Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 106 additions & 18 deletions .github/scripts/check-ci-gates-listed.sh
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
#!/usr/bin/env bash
# Every gate CI runs must appear in CONTRIBUTING.md §1's "run these before
# pushing" block. The paragraph under that block promises the workflow is
# the source of truth when the two disagree; this is what makes the promise
# hold. It also holds §7's "Required checks" list to the jobs
# pushing" block, with the toolchain and flags CI gives it, and every gate
# §1 lists must be one CI runs (#858). The paragraph under that block
# promises the workflow is the source of truth when the two disagree; this
# is what makes the promise hold. It also holds §7's "Required checks" list to the jobs
# `required-green` needs, which drifted twice with nothing comparing them
# (#509, #861). Usage: check-ci-gates-listed.sh [ci.yml] [CONTRIBUTING.md]
set -euo pipefail
Expand All @@ -28,17 +29,33 @@ plumbing=(

# One record per `run:` key, separated by \037 (a tab is IFS whitespace, so
# an empty name between two would vanish): kind (line or block), the step's
# name (empty when it has none), the line number, and for a single-line
# value the command with YAML's quoting and folding undone. A step's keys
# can come in any order, so a step is printed once it ends, when its name is
# name (empty when it has none), the line number, for a single-line value
# the command with YAML's quoting and folding undone, and then the step's
# RUSTUP_TOOLCHAIN, RUSTFLAGS and RUSTDOCFLAGS, from its own `env:` or the
# nearest enclosing one (the job's, the workflow's). A step's keys can come
# in any order, so a step is printed once it ends, when its name and env are
# known. This is a reader for the YAML this repository writes, not a YAML
# parser: flow mappings and anchors are not steps here.
records="$(awk '
function indent(s) { match(s, /^ */); return RLENGTH }
# The value of env var `v` the step keyed at `k` sees: its own, or the
# nearest enclosing mapping'"'"'s.
function envof(k, v, j) {
for (j = k; j >= 0; j--) if ((j, v) in env) return env[j, v]
return ""
}
function flush(k) {
if (has_run[k]) printf "%s\037%s\037%d\037%s\n", kind[k], name[k], line[k], value[k]
if (has_run[k]) printf "%s\037%s\037%d\037%s\037%s\037%s\037%s\n", kind[k], name[k], line[k], value[k],
envof(k, "RUSTUP_TOOLCHAIN"), envof(k, "RUSTFLAGS"), envof(k, "RUSTDOCFLAGS")
has_run[k] = 0; name[k] = ""
}
# A mapping that ended takes its env with it.
function drop_env(deeper_than, key, parts) {
for (key in env) {
split(key, parts, SUBSEP)
if (parts[1] + 0 > deeper_than) delete env[key]
}
}
function unquote(v, q) {
q = substr(v, 1, 1)
if ((q == "\"" || q == "\047") && substr(v, length(v), 1) == q) {
Expand Down Expand Up @@ -74,13 +91,30 @@ records="$(awk '
{
# A line less indented than a pending step ends it.
for (j in has_run) if (has_run[j] && ind < j + 0) flush(j)
drop_env(ind)
}
# An entry of an `env:` mapping: NAME: value.
env_k >= 0 && ind > env_k {
v = substr(raw, ind + 1)
if (match(v, /^[A-Za-z_][A-Za-z0-9_]*:/)) {
key = substr(v, 1, RLENGTH - 1)
v = substr(v, RLENGTH + 1); sub(/^[ \t]+/, "", v)
env[env_k, key] = unquote(decomment(v))
}
next
}
{ env_k = -1 }
match(raw, /^ *- /) {
k = RLENGTH
flush(k)
drop_env(k - 1)
rest = substr(raw, k + 1)
}
!match(raw, /^ *- /) { k = ind; rest = substr(raw, ind + 1) }
rest ~ /^env:[ \t]*(#.*)?$/ {
env_k = k
next
}
rest ~ /^name:/ {
v = rest; sub(/^name:[ \t]*/, "", v)
name[k] = unquote(decomment(v))
Expand All @@ -101,7 +135,7 @@ records="$(awk '
if (cont_k >= 0 && kind[cont_k] == "line") value[cont_k] = unquote(decomment(value[cont_k]))
for (j in has_run) flush(j)
}
' cont_k=-1 "$ci")"
' cont_k=-1 env_k=-1 "$ci")"

is_plumbing() {
local p
Expand All @@ -111,9 +145,14 @@ is_plumbing() {
return 1
}

# CI's msrv job sets RUSTUP_TOOLCHAIN from Cargo.toml's rust-version; §1
# writes that toolchain out, as `cargo +1.85 …`.
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
msrv="$(sed -n 's/^rust-version *= *"\(.*\)"/\1/p' "$root/Cargo.toml" | head -1)"

status=0
ci_cmds=""
while IFS=$'\037' read -r kind name lineno cmd; do
while IFS=$'\037' read -r kind name lineno cmd toolchain rustflags rustdocflags; do
[ -z "$kind" ] && continue
if [ -n "$name" ] && is_plumbing "$name"; then
continue
Expand All @@ -125,25 +164,51 @@ while IFS=$'\037' read -r kind name lineno cmd; do
continue
fi
cmd="$(sed -E 's/[[:space:]]+/ /g; s/^ //; s/ $//' <<<"$cmd")"
# What CI gives a cargo step is part of its gate, so §1 must say it too
# (#858): `RUSTDOCFLAGS='-D warnings'` is what makes the docs job fail on
# a broken intra-doc link, and the toolchain is what makes the msrv job a
# check of the MSRV. Both used to be stripped from §1 before comparing,
# so §1 could drop either and tools/preflight.sh then ran a weaker gate.
# RUSTDOCFLAGS is written only where rustdoc runs (`cargo doc`,
# `cargo rustdoc`, `cargo test`'s doctests), since the docs job's env
# reaches its script steps too, where it changes nothing.
case "$cmd" in
"cargo "* | .github/scripts/* | tools/*)
"cargo "*)
case "$toolchain" in
"") ;;
'${{ steps.msrv.outputs.msrv }}')
cmd="cargo +$msrv ${cmd#cargo }" ;;
*'${{'*)
echo "::error::$where runs under RUSTUP_TOOLCHAIN=$toolchain, which $(basename "$0") cannot resolve to the toolchain CONTRIBUTING.md §1 must name"
status=1 ;;
*)
cmd="cargo +$toolchain ${cmd#cargo }" ;;
esac
sub="${cmd#cargo }"
case "$sub" in +*) sub="${sub#* }" ;; esac
case "$sub" in
doc | "doc "* | rustdoc | "rustdoc "* | test | "test "*)
[ -n "$rustdocflags" ] && cmd="RUSTDOCFLAGS='$rustdocflags' $cmd" ;;
esac
[ -n "$rustflags" ] && cmd="RUSTFLAGS='$rustflags' $cmd"
;;
esac
case "$cmd" in
"cargo "* | "RUSTFLAGS="* | "RUSTDOCFLAGS="* | .github/scripts/* | tools/*)
ci_cmds="$ci_cmds$cmd"$'\n' ;;
*)
echo "::error::$where runs \`$cmd\`, which is neither a gate (cargo …, .github/scripts/…, tools/…) nor a step in the plumbing list in $(basename "$0")"
status=1 ;;
esac
done <<<"$records"

cargo_count="$(grep -c '^cargo ' <<<"$ci_cmds" || true)"
cargo_count="$(grep -Ec "^(RUST[A-Z]*FLAGS='[^']*' )*cargo " <<<"$ci_cmds" || true)"
script_count="$(grep -Ec '^(\.github/scripts/|tools/)' <<<"$ci_cmds" || true)"

# CONTRIBUTING §1: the shared extraction in extract-gates.sh (#368), plus
# the normalisations this comparison alone needs — the RUSTDOCFLAGS prefix
# and a `+toolchain` selector removed, because `cargo +1.85 check` in the
# doc is `cargo check` under RUSTUP_TOOLCHAIN in the workflow.
doc_cmds="$("$(dirname "${BASH_SOURCE[0]}")/extract-gates.sh" "$doc" \
| sed -E -e "s/^RUSTDOCFLAGS='-D warnings' //" \
-e 's/^cargo \+[^ ]+ /cargo /')"
# CONTRIBUTING §1: the shared extraction in extract-gates.sh (#368), as
# written. The CI side above carries the step's toolchain and flags, so the
# two compare whole (#858).
doc_cmds="$("$(dirname "${BASH_SOURCE[0]}")/extract-gates.sh" "$doc")"

while IFS= read -r cmd; do
[ -z "$cmd" ] && continue
Expand All @@ -153,6 +218,29 @@ while IFS= read -r cmd; do
fi
done <<<"$ci_cmds"

# …and the other way: a gate §1 lists must be one CI runs, or §1 and
# tools/preflight.sh keep a gate CI dropped (#858). §1's setup lines are
# not gates; tools/preflight.sh skips the same ones. Two gates run in CI
# other than as a step of their own, and each is held to what runs it: the
# deny job uses cargo-deny's action, and the zizmor job runs zizmor inside
# its retry function, so that line must appear in ci.yml as written.
ci_code="$(grep -v '^[[:space:]]*#' "$ci")"
while IFS= read -r cmd; do
[ -z "$cmd" ] && continue
case "$cmd" in
"git clone "* | "cd "* | "cargo install "* | "cargo insta "*) continue ;;
esac
grep -Fxq -- "$cmd" <<<"$ci_cmds" && continue
case "$cmd" in
"cargo deny check")
grep -Fq 'uses: EmbarkStudios/cargo-deny-action@' <<<"$ci_code" && continue ;;
"pipx run zizmor"*)
grep -Fq -- "$cmd" <<<"$ci_code" && continue ;;
esac
echo "::error::CONTRIBUTING.md §1 lists \`$cmd\` but CI does not run it, or runs it with another toolchain or flags"
status=1
done <<<"$doc_cmds"

# zizmor is pinned in the workflow; the doc must name the same pin.
pin="$(grep -o 'zizmor==[0-9.]*' "$ci" | head -1 || true)"
if [ -n "$pin" ] && ! grep -Fq -- "$pin" "$doc"; then
Expand Down
33 changes: 21 additions & 12 deletions .github/scripts/check-skill-snippets.sh
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
# Any other Rust tag fails rather than being skipped, and so does a fence the
# extraction cannot place: this matched only an unindented, bare ```rust, so a
# broken ```rust,no_run block or one indented under a list item passed (#657).
# A tag is skipped only by saying ,ignore.
# A tag is skipped only by saying ,ignore. All of this holds for a fence of
# tildes too: ~~~rust is compiled and ~~~rust,no_run fails (#860).
#
# Compiles, does not run: the stub `myapp` here is `fn main() {}`, and the
# recipes' runtime claims are exercised against a real application when the
Expand Down Expand Up @@ -73,21 +74,26 @@ EOF
# written. Fails, naming the line, on a Rust tag that is neither `rust` nor
# `rust,ignore`, and on a fence left open at the end.
#
# A fence is any run of three or more backticks at any indentation, closed
# by a run at least as long with nothing after it, as CommonMark has it. The
# content of a non-Rust fence is passed over, so a ```rust line inside a
# ```text example opens nothing. A block indented under a list item has
# that indentation removed. No regex intervals: BSD awk lacks them.
# A fence is any run of three or more backticks or three or more tildes at
# any indentation, closed by a run of the same character at least as long
# with nothing after it, as CommonMark has it. GitHub renders ~~~rust as
# Rust, and reading backticks alone left such a block neither compiled nor
# refused (#860). The content of a non-Rust fence is passed over, so a
# ```rust line inside a ```text or ~~~text example opens nothing, and a
# fence of the other character inside a block is content. A block indented
# under a list item has that indentation removed. No regex intervals: BSD
# awk lacks them.
extract() {
awk -v dir="$2" -v short="${2#"$tmp"/}" -v index_file="$tmp/index" '
function fence_len(s, n) { n = 0; while (substr(s, n + 1, 1) == "`") n++; return n }
function run_len(s, c, n) { n = 0; while (substr(s, n + 1, 1) == c) n++; return n }
{
match($0, /^[ \t]*/)
lead = RLENGTH
rest = substr($0, lead + 1)
ticks = fence_len(rest)
ch = substr(rest, 1, 1)
ticks = (ch == "`" || ch == "~") ? run_len(rest, ch) : 0
}
infence && ticks >= flen && rest ~ /^`+[ \t]*$/ {
infence && ch == fch && ticks >= flen && substr(rest, ticks + 1) ~ /^[ \t]*$/ {
if (out != "") close(out)
infence = 0; out = ""; next
}
Expand All @@ -102,14 +108,17 @@ extract() {
ticks >= 3 {
info = substr(rest, ticks + 1)
sub(/^[ \t]+/, "", info); sub(/[ \t]+$/, "", info)
if (index(info, "`") > 0) next # an inline code span, not a fence
infence = 1; flen = ticks; findent = lead; out = ""; opened = NR
# A backtick in a backtick fence'"'"'s info string makes it an inline
# code span; a tilde fence'"'"'s info string may hold anything.
if (ch == "`" && index(info, "`") > 0) next
infence = 1; fch = ch; flen = ticks; findent = lead; out = ""; opened = NR
lang = tolower(info); sub(/[ ,{].*$/, "", lang)
if (lang != "rust" && lang != "rs") next
tag = tolower(info); gsub(/[ \t]/, "", tag)
if (tag == "rust,ignore") next
if (tag != "rust") {
printf "::error file=%s,line=%d::```%s is neither ```rust (compiled) nor ```rust,ignore (skipped)\n", FILENAME, NR, info > "/dev/stderr"
f = ch ch ch
printf "::error file=%s,line=%d::%s%s is neither %srust (compiled) nor %srust,ignore (skipped)\n", FILENAME, NR, f, info, f, f > "/dev/stderr"
bad = 1
next
}
Expand Down
110 changes: 100 additions & 10 deletions .github/scripts/check-unsafe-blocks.sh
Original file line number Diff line number Diff line change
@@ -1,18 +1,33 @@
#!/usr/bin/env bash
# .github/scripts/check-unsafe-blocks.sh — assert that the count of `unsafe {`
# blocks in the codebase matches the number documented in SECURITY.md (#706).
# .github/scripts/check-unsafe-blocks.sh — assert that the `unsafe` code in
# the crates is exactly the count of blocks SECURITY.md documents (#706).
#
# SECURITY.md promises that unsafe is confined to a specific, audited count
# of blocks. This check ensures the documentation and implementation cannot
# drift when unsafe blocks are added or removed.
# drift when unsafe code is added or removed.
#
# Usage: .github/scripts/check-unsafe-blocks.sh [SECURITY.md]
# What is counted is every `unsafe` keyword in the Rust sources, outside
# comments and string and character literals: one followed by `{` is a
# block, and any other (`unsafe impl`, `unsafe fn`, `unsafe trait`,
# `unsafe extern`, `#[unsafe(…)]`) is unsafe code that is not a block.
# SECURITY.md speaks of blocks alone, so the blocks must match its count and
# there must be no other. This counted lines holding `unsafe {`, so an
# `unsafe impl Send` passed at the old count, and two blocks on one line
# counted as one, so only a wrong count passed (#864).
#
# Usage: .github/scripts/check-unsafe-blocks.sh [SECURITY.md [SRC_DIR ...]]
# SRC_DIR defaults to crates/*/src; tools/unsafe-gate-selftest/ passes its
# own.
set -euo pipefail

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$root"

doc="${1:-SECURITY.md}"
[ "$#" -gt 0 ] && shift
if [ "$#" -eq 0 ]; then
set -- crates/*/src
fi

if [ ! -f "$doc" ]; then
echo "::error::document not found: $doc" >&2
Expand Down Expand Up @@ -47,12 +62,87 @@ PY
exit 1
}

actual="$(grep -rn 'unsafe {' crates/*/src | wc -l | tr -d ' ')"
# One line per `unsafe` keyword: `block <file>:<line>` or `other <file>:<line>`.
sites="$(python3 - "$@" <<'PY'
import os, re, sys

if [ "$actual" -ne "$documented" ]; then
echo "::error::unsafe block count mismatch: $doc documents $documented, but crates/*/src contains $actual:" >&2
grep -rn 'unsafe {' crates/*/src | sed 's/^/ /' >&2
exit 1
# A Rust lexer just deep enough to tell code from comments and literals:
# `// unsafe {` and "unsafe {" are not unsafe code, and a count that read
# them would let a real block hide behind such a mention.
CHAR = re.compile(r"'(?:\\(?:u\{[0-9a-fA-F_]+\}|x[0-9a-fA-F]{2}|.)|[^\\'\n])'")
RAW = re.compile(r'(?:br|cr|r)(#*)"')
WORD = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")

def blank(s):
return "".join(c if c == "\n" else " " for c in s)

def code_only(src):
"""`src` with every comment and literal blanked, its newlines kept."""
out = []
i, n = 0, len(src)
while i < n:
c = src[i]
if src.startswith("//", i):
j = src.find("\n", i)
j = n if j < 0 else j
elif src.startswith("/*", i):
# Block comments nest in Rust.
depth, j = 1, i + 2
while j < n and depth:
if src.startswith("/*", j):
depth += 1; j += 2
elif src.startswith("*/", j):
depth -= 1; j += 2
else:
j += 1
elif m := RAW.match(src, i):
close = '"' + m.group(1)
j = src.find(close, m.end())
j = n if j < 0 else j + len(close)
elif c == '"':
j = i + 1
while j < n and src[j] != '"':
j += 2 if src[j] == "\\" else 1
j += 1
elif c == "'" and (m := CHAR.match(src, i)):
j = m.end()
elif m := WORD.match(src, i):
# A whole identifier at once, so the `r` ending `bar"` cannot
# start a raw string; `b"…"` leaves `b` here and the string next.
out.append(m.group(0)); i = m.end()
continue
else:
out.append(c); i += 1
continue
out.append(blank(src[i:j])); i = j
return "".join(out)

files = []
for top in sys.argv[1:]:
for d, _, names in os.walk(top):
files += [os.path.join(d, f) for f in names if f.endswith(".rs")]
for path in sorted(files):
code = code_only(open(path, encoding="utf-8").read())
for m in re.finditer(r"\bunsafe\b(\s*\{)?", code):
line = code.count("\n", 0, m.start()) + 1
print("block" if m.group(1) else "other", f"{path}:{line}")
PY
)"

blocks="$(printf '%s\n' "$sites" | command grep -c '^block ' || true)"
others="$(printf '%s\n' "$sites" | command grep -c '^other ' || true)"

status=0
if [ "$others" -ne 0 ]; then
echo "::error::$doc counts unsafe blocks alone, but $* holds $others other unsafe item(s); remove them, or document them in $doc and count them in this gate:" >&2
printf '%s\n' "$sites" | sed -n 's/^other / /p' >&2
status=1
fi
if [ "$blocks" -ne "$documented" ]; then
echo "::error::unsafe block count mismatch: $doc documents $documented, but $* contains $blocks:" >&2
printf '%s\n' "$sites" | sed -n 's/^block / /p' >&2
status=1
fi
[ "$status" -eq 0 ] || exit 1

echo "unsafe blocks: $doc documents $documented, matching $actual in crates/*/src"
echo "unsafe blocks: $doc documents $documented, matching $blocks in $*, with no other unsafe code"
Loading
Loading