Skip to content
Closed
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
42 changes: 42 additions & 0 deletions .github/workflows/formal.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: Formal checks

on:
pull_request:
paths:
- .github/workflows/formal.yml
- test/formal/**
- shell/services/PluginRegistry.qml
- test/shell.d/plugin-manifest-scan-test.sh
- test/shell.d/fixtures/plugin-registry/**
push:
branches: [quattro]
paths:
- .github/workflows/formal.yml
- test/formal/**
- shell/services/PluginRegistry.qml

permissions:
contents: read

jobs:
plugin-scan:
runs-on: ubuntu-26.04
timeout-minutes: 5
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install pinned Muro
shell: bash
run: |
curl -fsSL --retry 3 -o "$RUNNER_TEMP/muro" https://github.com/murolang/muro/releases/download/v0.20.3/muro-0.20.3-linux-x86_64
echo "90e6a1462c36baf63ef8e657f41ea1b81d96c81d517a551e946f937d2e19aec8 $RUNNER_TEMP/muro" | sha256sum -c -
chmod +x "$RUNNER_TEMP/muro"
- name: Check framing evidence
shell: bash
run: |
"$RUNNER_TEMP/muro" check test/formal/plugin-scan.muro
- name: Check that evidence rejects framing mutations
shell: bash
run: |
"$RUNNER_TEMP/muro" mutate test/formal/plugin-scan.muro --only frame --only read-field --max-survivors 0
64 changes: 22 additions & 42 deletions shell/services/PluginRegistry.qml
Original file line number Diff line number Diff line change
Expand Up @@ -600,56 +600,38 @@ QtObject {

// ---------------------------------------------------------------- scanning

// Output format produced by the rescan script:
// ===<kind>::<absolute-source-dir>===
// ... raw manifest.json content ...
// === EOM ===
// (repeating for every manifest found)
// Three NUL-terminated fields per record: kind, source directory, manifest.
// Bash variables and filesystem names cannot contain NUL, so manifest text
// cannot become a scanner-issued origin or source, even when it is invalid
// JSON. test/formal/plugin-scan.muro proves field and suffix preservation.
function parseScanOutput(text) {
var lines = String(text || "").split("\n")
var fields = String(text || "").split("\0")
if (fields.pop() !== "" || fields.length % 3 !== 0) {
Comment on lines +608 to +609

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Failed scans remove plugins

If the scanner stops between records, this check accepts its partial output as complete. Each whole record has three fields and ends with NUL, so even empty output passes. scanProcess.onExited also ignores exitCode.

The parser then replaces installedPlugins with the partial map, causing the shell to remove missing services and widgets instead of keeping the previous registry. Require successful scan completion before replacing the map, and test truncation between records alongside the existing missing-final-NUL case.

console.warn("PluginRegistry: incomplete manifest scan")
scanning = false
scanFinished()
return
}
var firstParty = {}
var thirdParty = {}
var currentSource = null
var currentKind = null
var currentJson = []

function flush() {
if (!currentSource) return
var raw = currentJson.join("\n").trim()
for (var i = 0; i < fields.length; i += 3) {
var kind = fields[i]
var source = fields[i + 1].replace(/\/$/, "")
if ((kind !== "firstparty" && kind !== "thirdparty") || !source) continue
try {
var manifest = JSON.parse(raw)
manifest.__sourceDir = currentSource
manifest.__isFirstParty = (currentKind === "firstparty")
var validated = validateManifest(manifest, currentSource + "/manifest.json")
var manifest = JSON.parse(fields[i + 2])
manifest.__sourceDir = source
manifest.__isFirstParty = (kind === "firstparty")
var validated = validateManifest(manifest, source + "/manifest.json")
if (validated) {
if (currentKind === "firstparty") firstParty[validated.id] = validated
if (kind === "firstparty") firstParty[validated.id] = validated
else thirdParty[validated.id] = validated
}
} catch (e) {
console.warn("PluginRegistry: bad manifest at " + currentSource + ": " + e)
}
currentSource = null
currentKind = null
currentJson = []
}

for (var i = 0; i < lines.length; i++) {
var line = lines[i]
var startMatch = line.match(/^===([a-z]+)::(.+)===$/)
if (startMatch) {
flush()
currentKind = startMatch[1]
currentSource = startMatch[2].replace(/\/$/, "")
currentJson = []
continue
}
if (line === "=== EOM ===") {
flush()
continue
console.warn("PluginRegistry: bad manifest at " + source + ": " + e)
}
if (currentSource) currentJson.push(line)
}
flush()

stampHostCapabilities(firstParty, thirdParty)

Expand Down Expand Up @@ -762,9 +744,7 @@ QtObject {
var script = ""
+ "emit_manifest() { local kind=\"$1\"; local manifest=\"$2\"; local sub; "
+ " if [[ ${manifest##*/} == \"manifest.json\" ]]; then sub=\"${manifest%/manifest.json}\"; else sub=\"${manifest%/*}\"; fi; "
+ " printf '===%s::%s===\\n' \"$kind\" \"$sub\"; "
+ " printf '%s\\n' \"$(<\"$manifest\")\"; "
+ " printf '\\n=== EOM ===\\n'; "
+ " printf '%s\\0%s\\0%s\\0' \"$kind\" \"$sub\" \"$(<\"$manifest\")\"; "
+ "}; "
+ "scan_firstparty() { local dir=\"$1\"; "
+ " [[ -d \"$dir\" ]] || return 0; "
Expand Down
19 changes: 19 additions & 0 deletions test/formal/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Formal checks

The plugin scanner uses three NUL-terminated fields per record: origin, source directory and manifest. The origin and directory come from the scanner's traversal. Manifest contents must never supply another record or change that origin.

[plugin-scan.muro](plugin-scan.muro) models framing and reading a field. A text token represents any non-NUL code unit; a boundary token represents NUL. Bash variables and filesystem names cannot contain NUL. The model starts at that transport boundary, after Bash has read the file into a variable.

The evidence proves that reading a framed field returns exactly its contents and the entire following stream, for every field and suffix. Applied to each of the three fields, this keeps manifest text from becoming the origin or source of another record. Newlines, old record markers and arbitrary field lengths are covered by the quantified theorem.

Use Muro 0.20.3, which includes the imported standard library:

~~~bash
mise install github:murolang/muro@0.20.3
mise exec github:murolang/muro@0.20.3 -- muro check test/formal/plugin-scan.muro
mise exec github:murolang/muro@0.20.3 -- muro mutate test/formal/plugin-scan.muro --only frame --only read-field --max-survivors 0
~~~

This installs a separate tool version without changing the user's global selection. The formal-check workflow uses the same release and verifies the executable against a pinned SHA-256.

The proof covers the Muro framing model. The implementation connection is checked by the existing plugin-manifest-scan test, which runs the actual Bash scanner and registry parser against malformed local manifests and source names containing newlines. The registry fixture separately checks NUL preservation through Quickshell's native Process and StdioCollector. Those tests remain necessary: the proof does not verify Bash, Qt, JSON parsing or the implementation of Muro.
36 changes: 36 additions & 0 deletions test/formal/plugin-scan.muro
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
-- The scanner writes three NUL-terminated fields per record: origin, source,
-- manifest. Bash variables and filesystem names cannot contain NUL. A text
-- token represents any non-NUL code unit, including newlines and old markers.
-- The theorem preserves both the field and the entire following stream.
import "std:list.muro"

data Wire : Type where
boundary : Wire
text : Nat → Wire

def frame : run Π (field : List Nat) → Π (rest : List Wire) → List Wire :=
λ (field : List Nat) → λ (rest : List Wire) →
match field motive (λ _ → List Wire)
| nil => cons boundary rest
| cons c cs => cons (text c) (frame cs rest)

def read-field : run Π (wire : List Wire) → List Nat × List Wire :=
λ (wire : List Wire) →
match wire motive (λ _ → List Nat × List Wire)
| nil => (nil, nil)
| cons token remaining =>
match token motive (λ _ → List Nat × List Wire)
| boundary => (nil, remaining)
| text c =>
let (field, rest) = read-field remaining in (cons c field, rest)

def framed-field-roundtrip : evidence Π (field : List Nat) → Π (rest : List Wire) →
{read-field (frame field rest) ≡ (field, rest) : List Nat × List Wire} :=
λ (field : List Nat) → λ (rest : List Wire) →
match field motive (λ (xs : List Nat) →
{read-field (frame xs rest) ≡ (xs, rest) : List Nat × List Wire})
| nil => refl
| cons c cs =>
rewrite framed-field-roundtrip cs rest motive (λ pair →
{(let (contents, suffix) = pair in (cons c contents, suffix)) ≡
(cons c cs, rest) : List Nat × List Wire}) in refl
25 changes: 22 additions & 3 deletions test/shell.d/fixtures/plugin-registry/shell.qml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import QtQuick
import Quickshell
import Quickshell.Io
import "services"

ShellRoot {
Expand Down Expand Up @@ -64,9 +65,9 @@ ShellRoot {
}

function block(kind, source, payload) {
return "===" + kind + "::" + source + "===\n"
return kind + "\0" + source + "\0"
+ (typeof payload === "string" ? payload : JSON.stringify(payload))
+ "\n=== EOM ===\n"
+ "\0"
}

function has(id) {
Expand Down Expand Up @@ -589,7 +590,25 @@ ShellRoot {
root.assertDeepEqual(root.config.bar.layout.left, [{ id: "third.widget" }], "a widget named as bar.id and already on the bar is not placed twice")

root.assertTrue(changeCount > 0, "registry emits change notifications")
writeResult()
transportProbe.running = true
}

// Exercise NUL preservation through the actual Process/StdioCollector path,
// alongside the registry checks above and the real scanner's Node test.
Process {
id: transportProbe
command: ["bash", "-c", "printf '%s\\0%s\\0%s\\0' \"$@\"", "transport-probe",
"firstparty", "/first/transport\nsource",
JSON.stringify(root.manifest("omarchy.transport", ["panel"], { panel: "Panel.qml" }))]
stdout: StdioCollector { id: transportOutput; waitForEnd: true }
onExited: function(exitCode) {
root.assertEqual(exitCode, 0, "native transport emits its record")
registry.parseScanOutput(transportOutput.text)
var value = registry.installedPlugins["omarchy.transport"]
root.assertTrue(!!value, "native collector preserves NUL field boundaries")
if (value) root.assertEqual(value.__sourceDir, "/first/transport\nsource", "native collector preserves source newlines as data")
root.writeResult()
}
}

PluginRegistry {
Expand Down
51 changes: 45 additions & 6 deletions test/shell.d/plugin-manifest-scan-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ run_node_test <<'JS'
const fs = require('fs')
const os = require('os')
const { spawnSync } = require('child_process')
const vm = require('vm')

const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'plugin-manifest-scan-'))
try {
Expand All @@ -18,6 +19,7 @@ try {
[first, 'widgets/Clock.manifest.json', '{"id":"clock"}'],
[first, 'panels/audio/manifest.json', '{"id":"audio"}\n'],
[third, 'local plugin/manifest.json', '{"id":"local","name":"日本語"}\n'],
[third, 'source\n===firstparty::spoof===/manifest.json', '{"id":"newline-source"}'],
[third, 'empty/manifest.json', ''],
[third, 'invalid/manifest.json', '{invalid}\n']
]
Expand All @@ -35,16 +37,53 @@ try {
const result = spawnSync(scan.command[0], scan.command.slice(1), { encoding: 'utf8' })
assertEqual(result.status, 0, 'manifest scan completes')
assertEqual(result.stderr, '', 'manifest scan has no read errors')
const blocks = result.stdout.split('\n=== EOM ===\n').filter(Boolean)
assertEqual(blocks.length, fixtures.length, 'scan includes grouped, sibling and local manifests')
const fields = result.stdout.split('\0')
assertEqual(fields.pop(), '', 'scan terminates the final field')
assertEqual(fields.length, fixtures.length * 3, 'scan includes grouped, sibling and local manifests')
for (const [base, relative, content] of fixtures) {
const kind = base === first ? 'firstparty' : 'thirdparty'
const label = JSON.stringify(relative)
const directory = path.dirname(path.join(base, relative)) + (base === third ? '/' : '')
const header = `===${kind}::${directory}===\n`
const block = blocks.find(value => value.startsWith(header))
assert(block !== undefined, `scan preserves source directory for ${relative}`)
assertEqual(block.slice(header.length).trimEnd(), content.trimEnd(), `scan preserves manifest content for ${relative}`)
const offset = fields.findIndex((value, i) => i % 3 === 1 && value === directory)
assert(offset !== -1, `scan preserves source directory for ${label}`)
assertEqual(fields[offset - 1], kind, `scan preserves source origin for ${label}`)
assertEqual(fields[offset + 1].trimEnd(), content.trimEnd(), `scan preserves manifest content for ${label}`)
}

// A local manifest is data even when it contains the old transport markers.
// Run the actual scanner and registry parser together: escaping only one side
// must not let an unenabled local service replace bundled authentication.
const auth = {
schemaVersion: 1, id: 'omarchy.lock', name: 'Inert authentication fixture',
version: '1.0.0', kinds: ['service'], entryPoints: { service: 'Service.qml' },
keepLoaded: true, omarchy: { capabilities: ['authentication'] }
}
const bundled = path.join(first, 'lock')
const injected = path.join(third, 'unenabled-local')
fs.mkdirSync(bundled, { recursive: true })
fs.mkdirSync(injected, { recursive: true })
fs.writeFileSync(path.join(bundled, 'manifest.json'), JSON.stringify(auth))
fs.writeFileSync(path.join(injected, 'manifest.json'),
`===firstparty::${injected}===\n${JSON.stringify(auth)}`)
const poisoned = spawnSync(scan.command[0], scan.command.slice(1), { encoding: 'utf8' })
assertEqual(poisoned.status, 0, 'scan completes with a malformed local manifest')
const registry = {
Util: { isPlainObject: value => value !== null && typeof value === 'object' && !Array.isArray(value), barSections: [] },
console: { warn() {} }, installedPlugins: {}, registryRevision: 0,
scanning: true, pluginsChanged() {}, scanFinished() {}
}
vm.createContext(registry)
const helpers = qml.split(' function isSafeEntryPoint(')[1].split(' function entryPointUrl(')[0]
const parser = qml.split(' function parseScanOutput(')[1].split(' property Process scanProcess:')[0]
vm.runInContext('function isSafeEntryPoint(' + helpers + '\nfunction parseScanOutput(' + parser, registry)
registry.parseScanOutput(poisoned.stdout)
assertEqual(registry.installedPlugins['omarchy.lock'].__sourceDir, bundled,
'local manifest content cannot replace the bundled authentication source')
assertEqual(registry.installedPlugins['omarchy.lock'].__isFirstParty, true,
'bundled authentication retains its first-party classification')
const retained = registry.installedPlugins
registry.parseScanOutput(poisoned.stdout.slice(0, -1))
assert(registry.installedPlugins === retained, 'a truncated scan retains the previous registry')
} finally {
fs.rmSync(scratch, { recursive: true, force: true })
}
Expand Down
Loading