[PM-38767] Adopt cargo-run-bin for binary tool version pinning in desktop_native (#21169)

* [PM-38767] Adopt cargo-run-bin for binary tool version pinning in desktop_native

Align desktop_native's Rust tooling with bitwarden/sdk-internal.

Pin the desktop_native workspace's binary cargo tools (cargo-deny, cargo-sort,
cargo-udeps, cargo-llvm-cov, cargo-xwin) in [workspace.metadata.bin] and run
them via cargo-run-bin (`cargo bin <tool>`), bootstrapped once with
`cargo install cargo-run-bin --locked`. Replaces the cargo-tool-versions file
and the ad-hoc per-tool `cargo install` calls in CI and build.js. A
check-no-binstall guard enforces source-only installs (VULN-613).

Includes the PM-24643 improvement: a unified lint runner (--fix / --only) that
mirrors CI, exposed as `npm run lint:rust`. The lint.yml rust job is now a
per-check x OS matrix with per-check .bin caching and a stable `Rust lint`
aggregator job.

Pin the nightly toolchain the same way the SDK does, via a non-standard
`nightly-channel` key in rust-toolchain.toml. The shared Renovate preset this
repo already extends (github>bitwarden/renovate-config) matches that key in any
rust-toolchain.toml and updates it from a custom rust-nightly datasource, so no
renovate.json5 change is needed. This closes a real gap rather than a cosmetic
one: rustfmt.toml enables unstable options (wrap_comments, group_imports,
imports_granularity) whose output changes between nightlies, so a rolling local
nightly could format code that CI's pinned nightly then rejects. Both the stable
and nightly toolchains are now read from that one file by CI, prepare-env-rust,
lint-rust and the pre-commit hooks, so a Renovate bump can no longer leave a
stale literal behind in a workflow.

Dev/CI scripts are portable Node rather than the duplicated bash + PowerShell
pair, and rather than the SDK's bash equivalents: our Rust lint matrix includes
macos-14, so the SDK's `grep -oP` toolchain extraction and its Linux-only
component suffix can't be reused.
- scripts/prepare-env-rust.mjs   (was prepare-env-unix-rust.sh + -windows-rust.ps1)
- scripts/lint-rust.mjs          (the unified runner)
- scripts/check-no-binstall.mjs  (binstall guard)
- scripts/rust-toolchain.mjs     (reads channel / nightly-channel)

The cargo-deny (0.20.0) and cargo-xwin (0.23.0) bumps that landed on main while
this branch was open are carried into [workspace.metadata.bin].

NOTE: branch protection required-status-check names change with the matrix, from
`Run Rust lint on <os>` (3 checks) to `Rust <check> (<os>)` (15 checks); point
them at the new `Rust lint` aggregator job instead.

* [PM-38767] Keep cargo-xwin on PATH for the napi cross-build

cargoBuild() reaches cargo-xwin through `cargo bin`, but buildNapiModule() hands
off to the napi CLI, which spawns `cargo xwin` as a PATH cargo-subcommand we
can't redirect. Dropping the global `cargo install cargo-xwin` therefore broke
Windows cross-builds from macOS/Linux -- a path CI never exercises, since each
platform builds natively on its own runner.

Reinstate the global install, but read its version from [workspace.metadata.bin]
via a small pinnedBinVersion() helper, so the two call sites share one pin.

Also drop the cargo-xwin precheck in appx-cross-build.ps1: it carried its own
copy of 0.23.0 (covered by neither Renovate custom manager) and hard-errored
before `npm run build-native` could perform the install that satisfies it.

Fix a stale comment in Cargo.toml that pointed at the SDK's scripts/lint.sh
instead of this repo's scripts/lint-rust.mjs.

* [PM-38767] Fail the toolchain-resolve step when the reader errors

Match bitwarden/sdk-internal's shape for the resolve step. Its intermediate shell
variable is load-bearing, not stylistic: under `bash -e` an assignment adopts the
command substitution's exit status, so a failing reader fails the step. Inlining
`$(...)` into `echo` makes the status `tee`'s, which is always 0, so the step went
green while writing an empty toolchain -- dtolnay/rust-toolchain would then have
silently resolved something other than the pin, the exact drift this PR removes.

Also rename the step outputs to RUST_TOOLCHAIN / RUST_NIGHTLY_TOOLCHAIN to match
the SDK and the env var already consumed by lint-rust.mjs. The remaining
divergence, reading via Node instead of `grep -oP`, stays: this job also runs on
macos-14, whose BSD grep has no -P.

* [PM-38767] Correct the cargo-xwin subcommand-token rationale

The instruction was right but the reason was wrong. The `xwin` token is omitted
not because clap fails to strip it, but because cargo-run-bin supplies it: the
raw binary accepts both `cargo-xwin build` and `cargo-xwin xwin build`, while
`cargo bin cargo-xwin xwin build` becomes `xwin xwin` and fails with
"error: unrecognized subcommand 'xwin'".

Verified by cross-compiling for real on macOS with the exact form build.js uses:
  cargo bin cargo-xwin build --bin desktop_proxy --target=x86_64-pc-windows-msvc
produces target/x86_64-pc-windows-msvc/debug/desktop_proxy.exe, a PE32+ MS
Windows executable.

* [PM-38767] Address review: drop duplicate cargo-xwin build, last toolchain literal

cargoBuild() now dispatches `cargo xwin build ...` instead of `cargo bin
cargo-xwin build ...`. installTarget() already installs the version pinned in
[workspace.metadata.bin] globally, because the napi CLI spawns `cargo xwin`
itself and we can't redirect that, so the `cargo bin` route was building a second
copy of the same pinned version for no extra guarantee. It also removes a
security wrinkle: `cargo install --version --locked` is source-only, whereas
`cargo bin` falls through to cargo-binstall's prebuilt binaries when binstall is
on PATH (VULN-613).

test.yml no longer hardcodes `toolchain: 1.96.0`; it resolves from
rust-toolchain.toml like lint.yml, so that was the last place a stale literal
could survive a Renovate bump.

lint-rust.mjs now rejects `--only` with no value instead of silently running
every check.

Add root-level `lint:rust` / `lint:rust:fix` aliases: the runner lives in the
repo root's scripts/ and CI invokes it from there, so requiring a cd into
apps/desktop was surprising.

Verified by cross-compiling for real on macOS through the new dispatch form:
  cargo xwin build --bin desktop_proxy --target=x86_64-pc-windows-msvc
produces a PE32+ MS Windows executable.

* [PM-38767] Drop the now-unused cargo-run-bin bootstrap from build.js

Fallout from 11b9a8e090: once cargoBuild() switched from `cargo bin cargo-xwin`
to dispatching `cargo xwin`, nothing reachable from build.js invoked `cargo bin`
any more, so every Windows cross-build paid for a from-source
`cargo install cargo-run-bin` whose output was never used.

Remove it, and fold the "reached two different ways" comment back to one now that
both call sites reach cargo-xwin via PATH.

build.js consequently pins no cargo-run-bin version, so drop it from the Renovate
custom manager's fileMatch, along with the JS-array matchString whose only match
in the repo was that line (prepare-env-rust.mjs uses the CARGO_RUN_BIN_VERSION
const form, which has its own pattern). Verified the manager still matches
lint.yml, test.yml, prepare-env-rust.mjs and the devcontainer script, and no
longer matches build.js.

* [PM-38767] Address review: drop the comment about the absent cargo-xwin precheck

The neighbouring makemsix and osslsigncode prechecks exist because nothing
installs those tools for you; cargo-xwin needs no check because build-native
installs it. Documenting the absence of a check we never wrote is noise.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Andreas Coroiu
2026-08-11 13:50:25 +02:00
committed by GitHub
parent 6d434db340
commit b92de117da
20 changed files with 600 additions and 235 deletions

View File

@@ -61,13 +61,20 @@ if [ "$RUN_NPM_CI" = "yes" ]; then
fi
if [ "$SETUP_DESKTOP_NATIVE" = "yes" ]; then
# Install Rust nightly toolchain (required for desktop native module)
# Install the pinned Rust nightly toolchain (required for desktop native
# module). The pin lives in desktop_native/rust-toolchain.toml; rustfmt.toml
# enables unstable options whose output changes between nightlies, so a
# rolling nightly would disagree with CI.
echo "Installing Rust nightly toolchain..."
rustup toolchain install nightly
RUST_NIGHTLY_TOOLCHAIN="$(node scripts/rust-toolchain.mjs --nightly)"
rustup toolchain install "$RUST_NIGHTLY_TOOLCHAIN" -c rustfmt
# Install cargo tools for pre-commit hooks (optional but recommended)
echo "Installing cargo tools for pre-commit hooks..."
cargo install cargo-sort cargo-udeps cargo-deny
# Bootstrap cargo-run-bin for pre-commit hooks and lint-rust.mjs. The individual
# tools (cargo-sort, cargo-udeps, cargo-deny, ...) are pinned in
# apps/desktop/desktop_native/Cargo.toml under [workspace.metadata.bin] and
# built lazily on first `cargo bin <tool>`.
echo "Bootstrapping cargo-run-bin for cargo tools..."
cargo install cargo-run-bin --locked --version 1.7.4
# Build the desktop native module
echo "Building desktop native module..."

View File

@@ -4,10 +4,37 @@
enabledManagers: ["cargo", "github-actions", "npm", "custom.regex"],
customManagers: [
{
// Pinned binary cargo tools declared in [workspace.metadata.bin]. These are
// not real dependency tables, so Renovate's native cargo manager ignores
// them. The `locked = true` field is the discriminator that keeps this regex
// from also matching [workspace.dependencies] entries of the same shape.
customType: "regex",
fileMatch: ["apps/desktop/desktop_native/cargo-tool-versions"],
matchStrings: ["(?<depName>[a-z][a-z0-9-]+)=(?<currentValue>[\\d.]+)"],
fileMatch: ["apps/desktop/desktop_native/Cargo\\.toml$"],
matchStrings: [
'(?<depName>[a-z][a-z0-9_-]*)\\s*=\\s*\\{\\s*version\\s*=\\s*"=?(?<currentValue>\\d+\\.\\d+\\.\\d+)"\\s*,\\s*locked\\s*=\\s*true',
],
datasourceTemplate: "crate",
versioningTemplate: "cargo",
},
{
// Bootstrap pin for cargo-run-bin across the CI workflows,
// scripts/prepare-env-rust.mjs, and the devcontainer. Keep these in sync.
// build.js is deliberately absent: it invokes cargo-xwin directly rather than
// through `cargo bin`, so it pins no cargo-run-bin version.
customType: "regex",
fileMatch: [
"^\\.github/workflows/.*\\.ya?ml$",
"scripts/prepare-env-rust\\.mjs$",
"\\.devcontainer/common/post-create-command\\.sh$",
],
matchStrings: [
"cargo install (?<depName>cargo-run-bin) --locked --version (?<currentValue>\\d+\\.\\d+\\.\\d+)",
// JS const form: const CARGO_RUN_BIN_VERSION = "x" (in scripts/prepare-env-rust.mjs).
'CARGO_RUN_BIN_VERSION\\s*=\\s*"(?<currentValue>\\d+\\.\\d+\\.\\d+)"',
],
depNameTemplate: "cargo-run-bin",
datasourceTemplate: "crate",
versioningTemplate: "cargo",
},
{
// Keep electronVersion in electron-builder.json in sync with the electron package.

View File

@@ -83,15 +83,25 @@ jobs:
run: npm run lint
rust:
name: Run Rust lint on ${{ matrix.os }}
name: Rust ${{ matrix.check.name }} (${{ matrix.os }})
runs-on: ${{ matrix.os || 'ubuntu-24.04' }}
strategy:
fail-fast: false
matrix:
os:
- ubuntu-24.04
- macos-14
- windows-2022
# Each check maps to `scripts/lint-rust.mjs --only <name>`. `nightly` pulls
# in the nightly toolchain (fmt, udeps); `cargo_bin` bootstraps cargo-run-bin
# and caches the tools it builds (sort, udeps, deny).
check:
- { name: fmt, nightly: true }
- { name: clippy }
- { name: sort, cargo_bin: true }
- { name: udeps, nightly: true, cargo_bin: true }
- { name: deny, cargo_bin: true }
steps:
- name: Checkout repo
@@ -99,17 +109,35 @@ jobs:
with:
persist-credentials: false
# Both toolchains come from desktop_native/rust-toolchain.toml so a Renovate
# bump can't leave a stale literal in this workflow. Read via Node rather
# than the `grep -oP` bitwarden/sdk-internal uses, because this job also runs
# on macos-14, whose BSD grep has no -P.
#
# Assign to variables before echoing: with `bash -e`, an assignment adopts the
# command substitution's exit status, so a failing reader fails the step.
# Inlining `$(...)` into `echo` would make the status `tee`'s instead, quietly
# emitting an empty toolchain.
- name: Resolve Rust toolchains
id: toolchain
run: |
RUST_TOOLCHAIN="$(node scripts/rust-toolchain.mjs)"
RUST_NIGHTLY_TOOLCHAIN="$(node scripts/rust-toolchain.mjs --nightly)"
echo "RUST_TOOLCHAIN=${RUST_TOOLCHAIN}" | tee -a "${GITHUB_OUTPUT}"
echo "RUST_NIGHTLY_TOOLCHAIN=${RUST_NIGHTLY_TOOLCHAIN}" | tee -a "${GITHUB_OUTPUT}"
- name: Install Rust
uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable
with:
toolchain: 1.96.0
toolchain: ${{ steps.toolchain.outputs.RUST_TOOLCHAIN }}
components: rustfmt, clippy
- name: Install Rust nightly
id: rust-nightly
if: matrix.check.nightly
uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable
with:
toolchain: nightly-2026-06-29
toolchain: ${{ steps.toolchain.outputs.RUST_NIGHTLY_TOOLCHAIN }}
components: rustfmt
- name: Check Rust version
@@ -118,35 +146,41 @@ jobs:
- name: Cache cargo registry
uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2.8.2
- name: Run cargo fmt
working-directory: ./apps/desktop/desktop_native
# Use the exact toolchain installed above (Renovate manages the version
# via the `with: toolchain:` input) so the invoked toolchain can never
# drift from the installed one. Passed through env rather than
# interpolated into the run script to satisfy the template-injection rule.
# Cache cargo-run-bin's built tools (.bin) separately from rust-cache. The
# tools depend only on their pinned versions (Cargo.toml) and the toolchain,
# not on Cargo.lock, so this key avoids rust-cache's lockfile rotation. Keyed
# per check so each one caches only the tools it builds.
- name: Cache cargo-run-bin tools
if: matrix.check.cargo_bin
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: apps/desktop/desktop_native/.bin
key: cargo-bin-${{ runner.os }}-${{ matrix.check.name }}-${{ hashFiles('apps/desktop/desktop_native/Cargo.toml', 'apps/desktop/desktop_native/rust-toolchain.toml') }}
restore-keys: |
cargo-bin-${{ runner.os }}-${{ matrix.check.name }}-
- name: Install cargo-run-bin
if: matrix.check.cargo_bin
run: cargo install cargo-run-bin --locked --version 1.7.4
# lint-rust.mjs runs the cargo-binstall guard (check-no-binstall.mjs) itself
# before any `cargo bin` invocation, so no separate step is needed here.
- name: Run lint --only ${{ matrix.check.name }}
# RUST_NIGHTLY_TOOLCHAIN pins the nightly invocations (fmt, udeps) to the
# toolchain actually installed above, so it can never drift from the
# resolved one. Passed through env rather than interpolated into the run
# script to satisfy the template-injection rule. Empty for the checks that
# don't need nightly; lint-rust.mjs then falls back to rust-toolchain.toml.
env:
RUST_NIGHTLY: ${{ steps.rust-nightly.outputs.name }}
run: cargo +"$RUST_NIGHTLY" fmt --check
RUST_NIGHTLY_TOOLCHAIN: ${{ steps.rust-nightly.outputs.name }}
run: node scripts/lint-rust.mjs --only ${{ matrix.check.name }}
- name: Run Clippy
working-directory: ./apps/desktop/desktop_native
run: cargo clippy --all-features --tests
env:
RUSTFLAGS: "-D warnings"
- name: Install cargo tool dependencies
run: ./scripts/prepare-env-unix-rust.sh
- name: Cargo sort
working-directory: ./apps/desktop/desktop_native
run: cargo sort --workspace --check
- name: Cargo udeps
working-directory: ./apps/desktop/desktop_native
env:
RUST_NIGHTLY: ${{ steps.rust-nightly.outputs.name }}
run: cargo +"$RUST_NIGHTLY" udeps --workspace --all-features --all-targets
- name: Run cargo deny
working-directory: ./apps/desktop/desktop_native
run: cargo deny --log-level error --all-features check all
rust-lint:
name: Rust lint
runs-on: ubuntu-24.04
needs: rust
if: always()
steps:
- name: Verify all Rust lint checks passed
if: ${{ needs.rust.result != 'success' }}
run: exit 1

View File

@@ -229,10 +229,19 @@ jobs:
with:
persist-credentials: false
# Resolved from desktop_native/rust-toolchain.toml, the single source of
# truth, so a Renovate bump can't leave a stale literal here. Assigned before
# echoing so a failure in the reader fails the step; see lint.yml.
- name: Resolve Rust toolchain
id: toolchain
run: |
RUST_TOOLCHAIN="$(node scripts/rust-toolchain.mjs)"
echo "RUST_TOOLCHAIN=${RUST_TOOLCHAIN}" | tee -a "${GITHUB_OUTPUT}"
- name: Install rust
uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable
with:
toolchain: 1.96.0
toolchain: ${{ steps.toolchain.outputs.RUST_TOOLCHAIN }}
components: llvm-tools
- name: Cache cargo registry
@@ -240,12 +249,15 @@ jobs:
with:
workspaces: "apps/desktop/desktop_native -> target"
- name: Install cargo-llvm-cov
run: cargo install cargo-llvm-cov --version 0.6.16
- name: Install cargo-run-bin
run: cargo install cargo-run-bin --locked --version 1.7.4
- name: Check cargo-binstall is not configured
run: node scripts/check-no-binstall.mjs
- name: Generate coverage
working-directory: ./apps/desktop/desktop_native
run: cargo llvm-cov --all-features --lcov --output-path lcov.info --workspace --no-cfg-coverage
run: cargo bin cargo-llvm-cov --all-features --lcov --output-path lcov.info --workspace --no-cfg-coverage
- name: Upload test coverage
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1

View File

@@ -1,4 +1,6 @@
target
# cargo-run-bin per-tool build cache
.bin
index.node
**/node_modules
**/.DS_Store

View File

@@ -99,3 +99,13 @@ print_stdout = "deny"
string_slice = "warn"
unused_async = "deny"
unwrap_used = "deny"
# Pinned binary cargo tools used by CI, scripts/lint-rust.mjs, and build.js.
# Bootstrap once with `cargo install cargo-run-bin --locked`, then invoke any
# tool via `cargo bin <tool> <args>`.
[workspace.metadata.bin]
cargo-deny = { version = "0.20.0", locked = true }
cargo-sort = { version = "2.0.2", locked = true }
cargo-udeps = { version = "0.1.57", locked = true }
cargo-llvm-cov = { version = "0.6.16", locked = true }
cargo-xwin = { version = "0.23.0", locked = true }

View File

@@ -18,6 +18,21 @@ const rustTargetsMap = {
// Ensure the dist directory exists
fs.mkdirSync(path.join(__dirname, "dist"), { recursive: true });
/**
* Read a tool version pinned in [workspace.metadata.bin] so nothing here carries a
* second copy of it. Kept as a local regex rather than importing scripts/*.mjs
* because this file is CommonJS.
* @param {string} tool Name of the tool as it appears in [workspace.metadata.bin].
*/
function pinnedBinVersion(tool) {
const cargoToml = fs.readFileSync(path.join(__dirname, "Cargo.toml"), "utf8");
const match = new RegExp(`^${tool}\\s*=\\s*\\{\\s*version\\s*=\\s*"=?([^"]+)"`, "m").exec(cargoToml);
if (!match) {
throw new Error(`Could not find '${tool}' in [workspace.metadata.bin] of desktop_native/Cargo.toml`);
}
return match[1];
}
const args = process.argv.slice(2); // Get arguments passed to the script
const mode = args.includes("--release") ? "release" : "debug";
const isRelease = mode === "release";
@@ -59,7 +74,15 @@ function cargoBuild(bin, target, release) {
const targetArg = target ? `--target=${target}` : "";
const releaseArg = release ? "--release" : "";
const args = ["build", "--bin", bin, releaseArg, targetArg]
// Use cross-compilation helper if necessary
// Use cross-compilation helper if necessary. Dispatch through cargo rather than
// `cargo bin cargo-xwin`: installTarget() has already installed the version
// pinned in [workspace.metadata.bin] globally, because buildNapiModule() needs
// cargo-xwin on PATH anyway (see the comment there). Reusing it avoids a second
// build of the same pinned version, and `cargo install --version --locked` is
// source-only, which `cargo bin` is not when cargo-binstall is on PATH.
//
// NOTE: this relies on installTarget() running first, which every path that can
// reach a Windows target does (both the `--target=` and `cross-platform` flows).
if (effectivePlatform(target) === "win32" && process.platform !== "win32") {
args.unshift("xwin")
}
@@ -117,9 +140,15 @@ function buildProcessIsolation() {
function installTarget(target) {
runCommand("rustup", ["target", "add", target]);
// Install cargo-xwin for cross-platform builds targeting Windows
// Cross-building for Windows needs cargo-xwin on PATH: buildNapiModule() hands
// off to the napi CLI, which spawns `cargo xwin` itself, and cargoBuild()
// dispatches the same way. Install the version pinned in Cargo.toml under
// [workspace.metadata.bin] so that stays the single source of truth for it.
//
// Nothing here goes through cargo-run-bin, so this deliberately does not
// bootstrap it; `cargo bin` is only used by the lint runner and CI.
if (target.includes('windows') && process.platform !== 'win32') {
runCommand("cargo", ["install", "--version", "0.23.0", "--locked", "cargo-xwin"]);
runCommand("cargo", ["install", "--version", pinnedBinVersion("cargo-xwin"), "--locked", "cargo-xwin"]);
// install tools needed for packaging Appx, only supported on macOS for now.
if (process.platform === "darwin") {
runCommand("brew", ["install", "iinuwa/msix-packaging-tap/msix-packaging", "osslsigncode"]);

View File

@@ -1,3 +0,0 @@
cargo-deny=0.20.0
cargo-sort=2.0.2
cargo-udeps=0.1.57

View File

@@ -2,3 +2,7 @@
channel = "1.96.0"
components = [ "rustfmt", "clippy" ]
profile = "minimal"
# The following is not part of the rust-toolchain.toml format,
# but is used by our Renovate config to manage nightly versions.
nightly-channel = "nightly-2026-06-29"

View File

@@ -23,6 +23,8 @@
"start": "cross-env ELECTRON_IS_DEV=0 ELECTRON_NO_UPDATER=1 electron ./build",
"build-native-macos": "cd desktop_native && ./autofill_provider/build.sh && node build.js cross-platform",
"build-native": "cd desktop_native && node build.js",
"lint:rust": "node ../../scripts/lint-rust.mjs",
"lint:rust:fix": "node ../../scripts/lint-rust.mjs --fix",
"build": "concurrently -n Main,Rend,Prel -c yellow,cyan \"npm run build:main\" \"npm run build:renderer\" \"npm run build:preload\"",
"build:dev": "concurrently -n Main,Rend,Prel -c yellow,cyan \"npm run build:main:dev\" \"npm run build:renderer:dev\" \"npm run build:preload:dev\"",
"build:preload": "cross-env NODE_ENV=production webpack --config webpack.config.js --config-name preload",

View File

@@ -91,13 +91,6 @@ if (!(Get-Command osslsigncode -ErrorAction SilentlyContinue)) {
Exit 1
}
if (!(Get-Command cargo-xwin -ErrorAction SilentlyContinue)) {
Write-Error "The `cargo-xwin` tool is required to cross-compile Windows native code."
Write-Error "You can install with cargo:"
Write-Error " cargo install --version 0.23.0 --locked cargo-xwin"
Exit 1
}
try {
# Resolve certificate file before we change directories.

View File

@@ -11,7 +11,9 @@ export default {
];
},
"apps/desktop/desktop_native/**/Cargo.toml": () => [
"node scripts/run-cargo-tool.mjs sort --workspace --check",
"node scripts/run-cargo-tool.mjs +nightly udeps --workspace --all-features --all-targets",
// cargo-sort and cargo-udeps are pinned in [workspace.metadata.bin] and run
// via cargo-run-bin (`cargo bin <tool>`); see scripts/lint-rust.mjs.
"node scripts/run-cargo-tool.mjs bin cargo-sort --workspace --check",
"node scripts/run-cargo-tool.mjs +nightly bin cargo-udeps --workspace --all-features --all-targets",
],
};

View File

@@ -17,6 +17,8 @@
"lint": "eslint . --cache --cache-strategy content && prettier --check .",
"lint:fix": "eslint . --cache --cache-strategy content --fix",
"lint:clear": "rimraf .eslintcache",
"lint:rust": "node scripts/lint-rust.mjs",
"lint:rust:fix": "node scripts/lint-rust.mjs --fix",
"prettier": "prettier --cache --write .",
"test": "jest",
"test:watch": "jest --clearCache && jest --watch",

View File

@@ -0,0 +1,83 @@
#!/usr/bin/env node
// Verifies that cargo-run-bin will NOT use cargo-binstall to fetch tool binaries.
//
// cargo-run-bin uses binstall when EITHER:
// 1. A `binstall` alias is defined in .cargo/config.toml at the project root, OR
// 2. `cargo-binstall` is available on PATH.
//
// We require source installs from crates.io so the tools we run match the source
// we audit. See VULN-613 for the dependency review of cargo-run-bin and the
// explicit caveat against enabling binstall.
//
// Returns true if neither path would trigger binstall. A repo-defined binstall
// alias always fails. In CI (GITHUB_ACTIONS=true) `cargo-binstall` on PATH also
// fails; locally it only warns -- devs may have binstall installed on their own
// machines and we don't try to police that. When run directly, exits 1 on failure.
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const DESKTOP_NATIVE = resolve(__dirname, "../apps/desktop/desktop_native");
function hasCommand(cmd) {
try {
if (process.platform === "win32") {
execFileSync("where", [cmd], { stdio: "ignore" });
} else {
// `command -v` is a portable POSIX shell builtin.
execFileSync("sh", ["-c", `command -v ${cmd}`], { stdio: "ignore" });
}
return true;
} catch {
return false;
}
}
export function checkNoBinstall() {
const config = resolve(DESKTOP_NATIVE, ".cargo/config.toml");
let ok = true;
// Match both inline form (`binstall = "..."`) and table form (`[alias.binstall]`).
if (
existsSync(config) &&
/^\s*(binstall\s*=|\[alias\.binstall\])/m.test(readFileSync(config, "utf8"))
) {
console.error("ERROR: .cargo/config.toml defines a 'binstall' alias.");
console.error(" cargo-run-bin would use cargo-binstall to fetch pre-built tool binaries");
console.error(
" from third-party mirrors (QuickInstall) instead of building from crates.io",
);
console.error(" sources. Remove the alias. See VULN-613 for context.");
ok = false;
}
if (hasCommand("cargo-binstall")) {
const msg =
"cargo-binstall is on PATH; cargo-run-bin will use it to fetch pre-built tool binaries";
if (process.env.GITHUB_ACTIONS === "true") {
console.error(`ERROR: ${msg}.`);
console.error(
" CI must build tools from source. Do not install cargo-binstall on the runner.",
);
console.error(" See VULN-613 for context.");
ok = false;
} else {
console.error(`WARN: ${msg} (your local machine).`);
console.error(
" CI builds tools from source, but your local 'cargo bin' invocations will use binstall.",
);
}
}
return ok;
}
// Run standalone (e.g. from CI) when invoked directly. argv[1] is undefined under
// `node -e`, where nothing was invoked directly, so guard before resolving it.
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
process.exit(checkNoBinstall() ? 0 : 1);
}

153
scripts/lint-rust.mjs Normal file
View File

@@ -0,0 +1,153 @@
#!/usr/bin/env node
// Unified lint/format runner for the Bitwarden desktop_native workspace.
// Mirrors the checks in .github/workflows/lint.yml so local runs match CI.
//
// Usage:
// node scripts/lint-rust.mjs Run every check (check-only).
// node scripts/lint-rust.mjs --fix Auto-fix where supported; still run check-only tools.
// node scripts/lint-rust.mjs --only <name> Run a single check. Composes with --fix.
//
// Available checks: fmt clippy sort udeps deny
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { checkNoBinstall } from "./check-no-binstall.mjs";
import { nightlyToolchain } from "./rust-toolchain.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const CWD = resolve(__dirname, "../apps/desktop/desktop_native");
const CHECKS = ["fmt", "clippy", "sort", "udeps", "deny"];
// Toolchain used by the checks that require nightly (fmt, udeps). rustfmt.toml
// enables unstable options (wrap_comments, group_imports, imports_granularity),
// whose output changes between nightlies, so this has to be the same pinned
// nightly CI uses or local `--fix` runs will produce formatting CI then rejects.
// CI passes the toolchain it actually installed via RUST_NIGHTLY_TOOLCHAIN;
// locally we read the same pin out of rust-toolchain.toml.
const NIGHTLY = `+${process.env.RUST_NIGHTLY_TOOLCHAIN || nightlyToolchain()}`;
let fix = false;
let only = "";
const argv = process.argv.slice(2);
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "--fix") {
fix = true;
} else if (arg === "--only") {
// Reject a missing value rather than falling back to "" (which would silently
// run every check when the caller asked for one).
only = argv[++i] ?? "";
if (!only) {
console.error("--only requires a check name");
console.error(`Available: ${CHECKS.join(" ")}`);
process.exit(2);
}
} else if (arg.startsWith("--only=")) {
only = arg.slice("--only=".length);
if (!only) {
console.error("--only requires a check name");
console.error(`Available: ${CHECKS.join(" ")}`);
process.exit(2);
}
} else if (arg === "-h" || arg === "--help") {
printHelp();
process.exit(0);
} else {
console.error(`Unknown argument: ${arg}`);
process.exit(2);
}
}
if (only && !CHECKS.includes(only)) {
console.error(`Unknown check: ${only}`);
console.error(`Available: ${CHECKS.join(" ")}`);
process.exit(2);
}
function printHelp() {
console.log(`Unified lint/format runner for the Bitwarden desktop_native workspace.
Mirrors the checks in .github/workflows/lint.yml so local runs match CI.
Usage:
node scripts/lint-rust.mjs Run every check (check-only).
node scripts/lint-rust.mjs --fix Auto-fix where supported; still run check-only tools.
node scripts/lint-rust.mjs --only <name> Run a single check. Composes with --fix.
Available checks: ${CHECKS.join(" ")}`);
}
function section(name) {
process.stdout.write(`\n\x1b[1;34m==> ${name}\x1b[0m\n`);
}
// Run a command in the workspace, inheriting stdio. Exits the process on failure.
function run(cmd, args, extraEnv = {}) {
const res = spawnSync(cmd, args, {
cwd: CWD,
stdio: "inherit",
env: { ...process.env, ...extraEnv },
});
if (res.error) {
console.error(`Failed to run ${cmd}: ${res.error.message}`);
process.exit(1);
}
if (res.status !== 0) {
process.exit(res.status ?? 1);
}
}
// Tools run via cargo-run-bin (sort, udeps, deny) need the `cargo bin` runner and
// must not fall through to cargo-binstall. Source installs only; see VULN-613.
function requireCargoBin() {
const probe = spawnSync("cargo", ["bin", "--version"], { stdio: "ignore" });
if (probe.error || probe.status !== 0) {
console.error("Required tool not found: cargo bin (cargo-run-bin)");
console.error("Install with: cargo install cargo-run-bin --locked");
console.error(
"(Binary tool versions are pinned in Cargo.toml under [workspace.metadata.bin].)",
);
process.exit(1);
}
if (!checkNoBinstall()) {
process.exit(1);
}
}
const runners = {
fmt() {
run("cargo", [NIGHTLY, "fmt", ...(fix ? [] : ["--check"])]);
},
clippy() {
// Pass `-D warnings` via RUSTFLAGS scoped to this command only (matching CI),
// rather than exporting it globally, so it does not leak into the from-source
// tool builds that `cargo bin` triggers for the other checks.
const args = fix
? ["clippy", "--fix", "--allow-dirty", "--allow-staged", "--all-features", "--tests"]
: ["clippy", "--all-features", "--tests"];
run("cargo", args, { RUSTFLAGS: "-D warnings" });
},
sort() {
requireCargoBin();
run("cargo", ["bin", "cargo-sort", "--workspace", ...(fix ? [] : ["--check"])]);
},
udeps() {
requireCargoBin();
run("cargo", [NIGHTLY, "bin", "cargo-udeps", "--workspace", "--all-features", "--all-targets"]);
},
deny() {
requireCargoBin();
run("cargo", ["bin", "cargo-deny", "--log-level", "error", "--all-features", "check", "all"]);
},
};
for (const check of CHECKS) {
if (only && only !== check) {
continue;
}
section(check);
runners[check]();
}

View File

@@ -0,0 +1,118 @@
#!/usr/bin/env node
// Prepares the environment for developing in Rust for the clients repo,
// specifically Desktop Native. Used by both developers locally and in CI, on
// every platform (replaces the former prepare-env-unix-rust.sh / -windows-rust.ps1).
//
// It installs the toolchains and bootstraps cargo-run-bin. The individual binary
// cargo tools (cargo-deny, cargo-sort, cargo-udeps, etc.) are pinned in
// apps/desktop/desktop_native/Cargo.toml under [workspace.metadata.bin] and built
// lazily on first use via `cargo bin <tool>` (see scripts/lint-rust.mjs).
import { execFileSync, spawnSync } from "node:child_process";
import { existsSync, unlinkSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { delimiter, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { nightlyToolchain } from "./rust-toolchain.mjs";
// Pinned bootstrap version of cargo-run-bin. Renovate-managed; keep in sync with
// the CI workflows and build.js.
const CARGO_RUN_BIN_VERSION = "1.7.4";
const __dirname = dirname(fileURLToPath(import.meta.url));
const DESKTOP_NATIVE = resolve(__dirname, "../apps/desktop/desktop_native");
// Run a command inheriting stdio; throws on failure.
function run(cmd, args, opts = {}) {
execFileSync(cmd, args, { stdio: "inherit", ...opts });
}
// Capture stdout of a command; returns "" on failure.
function capture(cmd, args, opts = {}) {
const res = spawnSync(cmd, args, { encoding: "utf8", ...opts });
return res.status === 0 && res.stdout ? res.stdout.trim() : "";
}
function hasCommand(cmd) {
const probe = spawnSync(cmd, ["--version"], { stdio: "ignore" });
return !probe.error && probe.status === 0;
}
async function installRustup() {
if (hasCommand("rustup")) {
return;
}
console.log("Installing Rust...");
if (process.platform === "win32") {
const arch = process.env.PROCESSOR_ARCHITECTURE === "ARM64" ? "aarch64" : "x86_64";
const initPath = join(tmpdir(), "rustup-init.exe");
const res = await fetch(`https://win.rustup.rs/${arch}`);
if (!res.ok) {
throw new Error(`Failed to download rustup-init.exe: ${res.status} ${res.statusText}`);
}
writeFileSync(initPath, Buffer.from(await res.arrayBuffer()));
try {
run(initPath, ["-y", "--default-toolchain", "stable"]);
} finally {
unlinkSync(initPath);
}
} else {
// Pipe the rustup installer through the shell, matching the documented one-liner.
const installer =
"curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable";
const res = spawnSync(installer, { stdio: "inherit", shell: true });
if (res.status !== 0) {
throw new Error("rustup installation failed");
}
}
}
// Ensure the cargo bin directory is on PATH for this process (and its children).
function ensureCargoOnPath() {
const cargoBin = join(process.env.CARGO_HOME || join(homedir(), ".cargo"), "bin");
if (existsSync(cargoBin) && !(process.env.PATH || "").split(delimiter).includes(cargoBin)) {
process.env.PATH = `${cargoBin}${delimiter}${process.env.PATH || ""}`;
}
}
function installToolchains() {
// Determine the desired toolchain (from rust-toolchain.toml) and ensure it's installed.
let activeToolchain = capture("rustup", ["show", "active-toolchain"], { cwd: DESKTOP_NATIVE });
// Keep only the first token (strip trailing parenthetical info).
activeToolchain = activeToolchain.split(/\s+/)[0] || "";
if (!activeToolchain) {
// No active toolchain yet: fall back to env override or default to stable.
activeToolchain = process.env.RUSTUP_TOOLCHAIN || "stable";
run("rustup", ["default", activeToolchain]);
}
// For building desktop_native.
run("rustup", ["toolchain", "install", activeToolchain]);
// For the checks that need nightly (fmt, udeps) in pre-commit hooks and CI.
// Pinned in rust-toolchain.toml rather than rolling `nightly`: rustfmt.toml
// enables unstable options whose output changes between nightlies, so a rolling
// toolchain would format code that CI's pinned nightly rejects.
run("rustup", ["toolchain", "install", nightlyToolchain(), "-c", "rustfmt"]);
run("rustup", ["show"]);
console.log();
}
// Bootstraps cargo-run-bin (the `cargo bin` runner) at the pinned version. The
// binary tools it runs are pinned in [workspace.metadata.bin] and built lazily.
function installCargoRunBin() {
const version = capture("cargo", ["bin", "--version"]);
if (version === `cargo-run-bin ${CARGO_RUN_BIN_VERSION}`) {
console.log(`cargo-run-bin ${CARGO_RUN_BIN_VERSION} is already installed.`);
} else {
console.log(`cargo-run-bin ${CARGO_RUN_BIN_VERSION} is not installed. Installing ...`);
run("cargo", ["install", "cargo-run-bin", "--locked", "--version", CARGO_RUN_BIN_VERSION]);
}
}
await installRustup();
ensureCargoOnPath();
installToolchains();
installCargoRunBin();

View File

@@ -1,68 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# This script prepares the environment for developing in Rust for the clients repo,
# specifically Desktop Native. This script is used by both developers locally, and
# in CI.
#
# NOTE: The cargo tools installed in this script, are installed to the default location
# (user's $HOME dir). If you prefer another location, please install the versions
# specified in apps/desktop/desktop_native/cargo-tool-versions, and ensure they are in your $PATH.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VERSIONS_FILE="${SCRIPT_DIR}/../apps/desktop/desktop_native/cargo-tool-versions"
# Ensures the active toolchain is installed, and that nightly is installed
# for the cargo tools
toolchain_is_installed() {
if ! command -v rustup >/dev/null 2>&1; then
echo "Installing Rust..."
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
fi
# Ensure cargo/rustup are on PATH
if [ -f "${HOME}/.cargo/env" ]; then
source "${HOME}/.cargo/env"
fi
# Determine desired toolchain and ensure it's installed.
ACTIVE_TOOLCHAIN="$(cd apps/desktop/desktop_native && rustup show active-toolchain 2>/dev/null || true)"
ACTIVE_TOOLCHAIN="${ACTIVE_TOOLCHAIN%% *}" # keep only the first token
if [ -z "${ACTIVE_TOOLCHAIN}" ]; then
# No active toolchain yet: fall back to env override or default to stable.
ACTIVE_TOOLCHAIN="${RUSTUP_TOOLCHAIN:-stable}"
rustup default "${ACTIVE_TOOLCHAIN}"
fi
# For building desktop_native
rustup toolchain install "${ACTIVE_TOOLCHAIN}"
# For the cargo tools used in pre-commit hooks and CI
rustup toolchain install nightly
rustup show
echo
}
# Checks version of tool and installs if needed
# Usage: maybe_install_cargo_tool <tool-name> <version>
# Note: cargo-* tools are invoked as "cargo <subcommand>", not as direct binaries
maybe_install_cargo_tool() {
local tool="$1"
local version="$2"
local version_cmd="cargo ${tool#cargo-}"
local version_pattern="${3:-${tool} ${version}}"
if ! $version_cmd --version 2>/dev/null | grep -q "^${version_pattern}"; then
echo "$tool $version is not installed. Installing ..."
cargo install "$tool" --version "$version" --force --locked
else
echo "$tool $version is already installed."
fi
}
toolchain_is_installed
while IFS='=' read -r tool version; do
maybe_install_cargo_tool "$tool" "$version"
done < "${VERSIONS_FILE}"

View File

@@ -1,103 +0,0 @@
#Requires -Version 5.1
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# This script prepares the environment for developing in Rust for the clients repo,
# specifically Desktop Native. This script is used by both developers locally, and
# in CI.
#
# NOTE: The cargo tools installed in this script, are installed to the default location
# (user's $HOME dir). If you prefer another location, please install the versions
# specified in apps/desktop/desktop_native/cargo-tool-versions, and ensure they are in your $PATH.
$versionsFile = Join-Path $PSScriptRoot "..\apps\desktop\desktop_native\cargo-tool-versions"
function Install-RustToolchain {
if (-not (Get-Command rustup -ErrorAction SilentlyContinue)) {
Write-Host "Installing Rust..."
$rustupUrl = if ($env:PROCESSOR_ARCHITECTURE -eq "ARM64") {
"https://win.rustup.rs/aarch64"
} else {
"https://win.rustup.rs/x86_64"
}
$rustupInit = Join-Path $env:TEMP "rustup-init.exe"
Invoke-WebRequest -Uri $rustupUrl -OutFile $rustupInit
& $rustupInit -y --default-toolchain stable
Remove-Item $rustupInit
}
# Ensure cargo/rustup are on PATH for the current session
$cargoHome = if ($env:CARGO_HOME) { $env:CARGO_HOME } else { Join-Path $env:USERPROFILE ".cargo" }
$cargoBin = Join-Path $cargoHome "bin"
if ((Test-Path $cargoBin) -and ($env:PATH -notlike "*$cargoBin*")) {
$env:PATH = "$cargoBin;$env:PATH"
}
# Determine desired toolchain and ensure it's installed.
Push-Location "apps/desktop/desktop_native"
try {
$activeToolchain = rustup show active-toolchain 2>$null
} catch {
$activeToolchain = $null
} finally {
Pop-Location
}
if ($activeToolchain) {
# Keep only the first token (strip trailing parenthetical info)
$activeToolchain = ($activeToolchain -split '\s+')[0]
}
if ([string]::IsNullOrEmpty($activeToolchain)) {
# No active toolchain yet: fall back to env override or default to stable.
$activeToolchain = if ($env:RUSTUP_TOOLCHAIN) { $env:RUSTUP_TOOLCHAIN } else { "stable" }
rustup default $activeToolchain
}
# For building desktop_native
rustup toolchain install $activeToolchain
# For the cargo tools used in pre-commit hooks and CI
rustup toolchain install nightly
rustup show
Write-Host
}
# Checks version of tool and installs if needed
# Usage: Install-CargoToolIfNeeded <tool-name> <version> [<version-pattern>]
# Note: cargo-* tools are invoked as "cargo <subcommand>", not as direct binaries
function Install-CargoToolIfNeeded {
param(
[string]$Tool,
[string]$Version,
[string]$VersionPattern = ""
)
# Strip "cargo-" prefix to get the cargo subcommand name
$subcommand = $Tool -replace "^cargo-", ""
if ([string]::IsNullOrEmpty($VersionPattern)) {
$VersionPattern = "$Tool $Version"
}
try {
$versionOutput = & cargo $subcommand --version 2>$null
} catch {
$versionOutput = $null
}
if ($versionOutput -and ($versionOutput -match ("^" + [regex]::Escape($VersionPattern)))) {
Write-Host "$Tool $Version is already installed."
} else {
Write-Host "$Tool $Version is not installed. Installing ..."
cargo install $Tool --version $Version --force --locked
}
}
Install-RustToolchain
Get-Content $versionsFile | ForEach-Object {
if ($_ -match "^([^=]+)=(.+)$") {
Install-CargoToolIfNeeded $Matches[1] $Matches[2]
}
}

View File

@@ -7,14 +7,18 @@ import { execSync } from "child_process";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
import { nightlyToolchain } from "./rust-toolchain.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const cwd = resolve(__dirname, "../apps/desktop/desktop_native");
const prepareScript =
process.platform === "win32"
? "scripts/prepare-env-windows-rust.ps1"
: "scripts/prepare-env-unix-rust.sh";
const prepareScript = "node scripts/prepare-env-rust.mjs";
const args = process.argv.slice(2).join(" ");
// Callers write `+nightly` for readability; resolve it to the pin in
// rust-toolchain.toml so pre-commit formatting matches CI. See lint-rust.mjs.
const args = process.argv
.slice(2)
.map((arg) => (arg === "+nightly" ? `+${nightlyToolchain()}` : arg))
.join(" ");
try {
execSync(`cargo ${args}`, { cwd, stdio: "inherit" });

View File

@@ -0,0 +1,57 @@
#!/usr/bin/env node
// Single source of truth for the Rust toolchains used by desktop_native. Both
// values live in apps/desktop/desktop_native/rust-toolchain.toml:
//
// channel - the stable toolchain (standard rust-toolchain.toml field,
// so `cargo` in that workspace honours it automatically)
// nightly-channel - the nightly toolchain used by the checks that need it
// (fmt, udeps). Not part of the rust-toolchain.toml format;
// it exists so Renovate can manage the nightly date.
//
// Both keys are updated by the shared Renovate preset this repo extends
// (github>bitwarden/renovate-config), which matches them in any
// rust-toolchain.toml. Nothing else should hardcode either value -- CI reads
// them from here so a Renovate bump can't leave a workflow literal behind.
//
// The equivalent in bitwarden/sdk-internal is a `grep -oP` in each workflow,
// which we can't reuse: our Rust lint matrix includes macos-14, whose BSD grep
// has no -P.
//
// Usage:
// node scripts/rust-toolchain.mjs Print the stable channel.
// node scripts/rust-toolchain.mjs --nightly Print the nightly channel.
//
// Also importable as { stableToolchain, nightlyToolchain }.
import { readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const TOOLCHAIN_FILE = resolve(__dirname, "../apps/desktop/desktop_native/rust-toolchain.toml");
// Anchored at line start so `channel` cannot also match `nightly-channel`.
const PATTERNS = {
stable: /^channel\s*=\s*"([^"]+)"/m,
nightly: /^nightly-channel\s*=\s*"([^"]+)"/m,
};
function read(key) {
const match = PATTERNS[key].exec(readFileSync(TOOLCHAIN_FILE, "utf8"));
if (!match) {
throw new Error(
`Could not find a '${key === "stable" ? "channel" : "nightly-channel"}' entry in ${TOOLCHAIN_FILE}`,
);
}
return match[1];
}
export const stableToolchain = () => read("stable");
export const nightlyToolchain = () => read("nightly");
// Run standalone when invoked directly. argv[1] is undefined under `node -e`,
// where nothing was invoked directly, so guard before resolving it.
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
console.log(process.argv.includes("--nightly") ? nightlyToolchain() : stableToolchain());
}