Verify explicit VectorCraft duplex modes on a signed A4 queue

This commit is contained in:
Codex
2026-12-03 07:57:35 +01:00
parent ac2a5931aa
commit 1249aafafd
4 changed files with 402 additions and 0 deletions
+133
View File
@@ -0,0 +1,133 @@
$ErrorActionPreference = 'Stop'
if ($env:RUNNER_ENVIRONMENT -ne 'github-hosted' -or $env:RUNNER_OS -ne 'Windows') {
throw 'This capture requires a disposable GitHub-hosted Windows runner.'
}
$exe = [IO.Path]::Combine($env:CARGO_TARGET_DIR, 'debug', 'vectorcraft.exe')
if (!(Test-Path -LiteralPath $exe -PathType Leaf)) { throw "Missing application executable: $exe" }
$output = New-Item -ItemType Directory 'captured-duplex-a4'
$package = New-Item -ItemType Directory (Join-Path $env:RUNNER_TEMP 'konica-a4-duplex-package')
$cab = Join-Path $package.FullName 'kmmodel.cab'
# The same exact WHQL package examined in craft-libs #4958.
Invoke-WebRequest 'https://catalog.s.download.windowsupdate.com/d/msdownload/update/driver/drvs/2024/12/ee5c05ce-8868-4a0e-8057-f052afbc6450_8dd496baea495258d226709f6c31684c469baaf7.cab' -OutFile $cab
if ((Get-FileHash -LiteralPath $cab).Hash -ne '7823C2C01A7B51D887C2FA2C8CA7B66739580029B3E98D0B310326431D9C68DE') { throw 'CAB hash mismatch' }
expand.exe '-F:*' $cab $package.FullName
if ($LASTEXITCODE) { throw 'Could not expand the signed driver package' }
$catalog = Get-AuthenticodeSignature -LiteralPath (Join-Path $package.FullName 'kmmodel.cat')
$catalog | Select-Object Status,@{ Name = 'Signer'; Expression = { $_.SignerCertificate.Subject } } |
ConvertTo-Json | Set-Content -LiteralPath (Join-Path $output.FullName 'signature.json')
if ($catalog.Status -ne 'Valid' -or $catalog.SignerCertificate.Subject -notmatch 'CN=Microsoft Windows Hardware Compatibility Publisher,') {
throw 'Invalid WHQL catalog signature'
}
$model = 'KONICA MINOLTA A4 Multi Model PS-PPD Type 2'
$inf = Join-Path $package.FullName 'kmmodel.inf'
if (!(Select-String -LiteralPath $inf -Pattern $model -SimpleMatch -Quiet)) { throw 'Expected model absent from signed package' }
pnputil.exe /add-driver $inf
if ($LASTEXITCODE) { throw 'Could not stage the signed A4 model' }
$staged = @(Get-WindowsDriver -Online | Where-Object { [IO.Path]::GetFileName($_.OriginalFileName) -eq 'kmmodel.inf' -and $_.ProviderName -like '*KONICA*' })
if ($staged.Count -ne 1) { throw 'Expected exactly one installed Konica Minolta package' }
Start-Service Spooler
Add-PrinterDriver -Name $model -InfPath $staged[0].OriginalFileName
Get-PrinterDriver -Name $model | Select-Object Name,MajorVersion,Manufacturer,DataFile,InfPath |
ConvertTo-Json | Set-Content -LiteralPath (Join-Path $output.FullName 'driver.json')
$queue = "Craft QA duplex A4 $env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT"
$port = Join-Path $output.FullName 'incoming.prn'
$env:VECTORCRAFT_CAPTURE_QUEUE = $queue
$env:VECTORCRAFT_CAPTURE_REPORT = $output.FullName
# Read both stored tickets and driver capabilities in Windows PowerShell, where System.Printing is available.
$readDefaults = @'
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName System.Printing, ReachFramework
$name = $env:VECTORCRAFT_CAPTURE_QUEUE
$configuration = Get-PrintConfiguration -PrinterName $name
$server = [System.Printing.LocalPrintServer]::new()
$queue = $server.GetPrintQueue($name)
function Fingerprint($ticket) {
if (!$ticket) { return $null }
$stream = $ticket.GetXmlStream()
$hash = [Security.Cryptography.SHA256]::Create()
try { return [BitConverter]::ToString($hash.ComputeHash($stream)).Replace('-', '') }
finally { $hash.Dispose(); $stream.Dispose() }
}
try {
$queue.Refresh()
[ordered]@{
Color = $configuration.Color
Collate = $configuration.Collate
PaperSize = $configuration.PaperSize.ToString()
DuplexingMode = $configuration.DuplexingMode.ToString()
DefaultDuplex = [string]$queue.DefaultPrintTicket.Duplexing
UserDuplex = [string]$queue.UserPrintTicket.Duplexing
DefaultTicket = Fingerprint $queue.DefaultPrintTicket
UserTicket = Fingerprint $queue.UserPrintTicket
AdvertisedDuplex = @($queue.GetPrintCapabilities().DuplexingCapability | ForEach-Object { $_.ToString() } | Sort-Object)
} | ConvertTo-Json -Compress
} finally {
$queue.Dispose()
$server.Dispose()
}
'@
$reader = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($readDefaults))
function Snapshot($name) {
$result = powershell.exe -NoProfile -EncodedCommand $reader
if ($LASTEXITCODE) { throw 'Could not read the A4 queue defaults' }
$result | Set-Content -LiteralPath (Join-Path $output.FullName "$name.json")
$result
}
$portAdded = $false
$queueAdded = $false
try {
Add-PrinterPort -Name $port
$portAdded = $true
Add-Printer -Name $queue -PortName $port -DriverName $model
$queueAdded = $true
$installed = Get-Printer -Name $queue
if ($installed.Shared -or $installed.PortName -ne $port -or $installed.DriverName -ne $model) {
throw 'The printer is not exclusive to the private file port'
}
Set-PrintConfiguration -PrinterName $queue -PaperSize A4 -DuplexingMode TwoSidedLongEdge
$before = Snapshot 'defaults-before'
$settings = $before | ConvertFrom-Json
if ($settings.PaperSize -ne 'A4' -or $settings.DuplexingMode -ne 'TwoSidedLongEdge' -or
'TwoSidedLongEdge' -notin $settings.AdvertisedDuplex -or 'TwoSidedShortEdge' -notin $settings.AdvertisedDuplex) {
throw 'The isolated A4 queue did not expose both duplex edges and retain its long-edge default'
}
foreach ($case in 'simplex', 'long-edge', 'short-edge') {
if ((Test-Path -LiteralPath $port) -or (Get-PrintJob -PrinterName $queue)) { throw 'The private queue is not empty' }
$env:VECTORCRAFT_CAPTURE_CASE = $case
$stdOut = Join-Path $output.FullName "$case-stdout.txt"
$stdErr = Join-Path $output.FullName "$case-stderr.txt"
$child = Start-Process -FilePath $exe -ArgumentList '--qa-vector-print-duplex' -WindowStyle Hidden -Wait -PassThru -RedirectStandardOutput $stdOut -RedirectStandardError $stdErr
if ($child.ExitCode -ne 0) { throw "VectorCraft failed for $case (exit $($child.ExitCode)): $(Get-Content -Raw -LiteralPath $stdErr)" }
$reply = Get-Content -Raw -LiteralPath (Join-Path $output.FullName "$case.json") | ConvertFrom-Json
if ($reply.outcome -eq 'refused') {
if ((Test-Path -LiteralPath $port) -or (Get-PrintJob -PrinterName $queue)) { throw 'Queue activity after a claimed refusal' }
} elseif ($reply.outcome -eq 'submitted') {
$deadline = [DateTime]::UtcNow.AddSeconds(50)
$capture = Join-Path $output.FullName "$case.prn"
while ([DateTime]::UtcNow -lt $deadline) {
if ((Test-Path -LiteralPath $port -PathType Leaf) -and !(Get-PrintJob -PrinterName $queue)) {
try {
$file = [IO.File]::Open($port, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None)
try { $length = $file.Length } finally { $file.Dispose() }
if ($length -gt 0) { Move-Item -LiteralPath $port -Destination $capture; break }
} catch [IO.IOException] {}
}
Start-Sleep -Milliseconds 250
}
if (!(Test-Path -LiteralPath $capture)) { throw "No complete file arrived on the private port for $case" }
} else {
throw "Unexpected outcome for $($case): $($reply.message)"
}
if ((Snapshot "$case-defaults-after") -ne $before) { throw "Stored queue or user settings changed after $case" }
}
} finally {
if ($queueAdded) { Remove-Printer -Name $queue }
if ($portAdded) {
$localPort = Get-PrinterPort | Where-Object Name -eq $port
if ($localPort) { Remove-PrinterPort -InputObject $localPort }
}
Remove-PrinterDriver -Name $model
}
+61
View File
@@ -0,0 +1,61 @@
use std::{env, fs, path::PathBuf};
use serde_json::json;
use vectorcraft_engine::script::printing::{JobOptions, Sides};
use vectorcraft_ui_egui::print::{PrintJob, PrintService};
pub(crate) fn run() {
assert_eq!(env::var("RUNNER_ENVIRONMENT").as_deref(), Ok("github-hosted"));
let queue = env::var("VECTORCRAFT_CAPTURE_QUEUE").unwrap();
assert!(queue.starts_with("Craft QA duplex A4 "));
let case = env::var("VECTORCRAFT_CAPTURE_CASE").unwrap();
let sides = match case.as_str() {
"simplex" => Sides::OneSided,
"long-edge" => Sides::LongEdge,
"short-edge" => Sides::ShortEdge,
_ => panic!("unknown duplex capture case"),
};
let folder = PathBuf::from(env::var_os("VECTORCRAFT_CAPTURE_REPORT").unwrap());
let path = folder.join(format!("{case}-composed.pdf"));
let mut session = vectorcraft_engine::Session::new();
session.execute("file.new", &json!({ "width": 180, "height": 120 })).unwrap();
session.execute("artboard.new", &json!({ "x": 240, "y": 0, "width": 180, "height": 120 })).unwrap();
for (x, y, width, height) in [(12, 14, 28, 24), (335, 48, 65, 50)] {
session.execute("shape.rectangle", &json!({ "x": x, "y": y, "width": width, "height": height })).unwrap();
session.execute("paint.setFill", &json!({ "color": "#121212", "opacity": 80 })).unwrap();
session.execute("paint.setStroke", &json!({ "none": true })).unwrap();
}
let report = session
.execute("file.print", &json!({ "path": path, "settings": { "media": "a4", "autoRotate": false, "orientation": "portrait" } }))
.unwrap();
assert_eq!(report["pages"], 2);
let pdf = fs::read(&path).unwrap();
let job = PrintJob {
printer: Some(&queue),
title: "VectorCraft QA duplex artboards",
pdf: &pdf,
paper: None,
direct_pdf: false,
driver_settings: None,
options: JobOptions { color: None, duplex: Some(sides) },
grayscale_composed: false,
};
let service = crate::printing::SystemPrint::default();
let result = service.shared_print().unwrap()(&job);
let (outcome, message) = match result {
Ok(note) => ("submitted", note),
Err(error) if error.contains("nothing was sent") => ("refused", error),
Err(error) => ("error", error),
};
fs::write(
folder.join(format!("{case}.json")),
serde_json::to_string_pretty(&json!({
"outcome": outcome, "message": message,
"sharedDuplexAdvertised": craft::print::two_sided(&queue),
"duplexRequested": format!("{sides:?}")
}))
.unwrap(),
)
.unwrap();
}
+84
View File
@@ -0,0 +1,84 @@
"""Verify the duplex controls and rendered order of the signed A4 spool output."""
import json
import pathlib
import re
import subprocess
import sys
import tempfile
from PIL import Image
expected = {
"simplex": (False, None),
"long-edge": (True, False),
"short-edge": (True, True),
}
def read_job_control(raw):
features = re.findall(rb"^%%BeginFeature:\s*\*Duplex\s+([^\s]+)", raw, re.MULTILINE | re.IGNORECASE)
if features:
mapped = {
b"none": (False, None),
b"duplexnotumble": (True, False),
b"duplextumble": (True, True),
}
modes = {mapped.get(value.lower()) for value in features}
if len(modes) == 1 and None not in modes:
return modes.pop(), features
duplex = re.findall(rb"/Duplex\s+(true|false)(?=[\s/>])", raw, re.IGNORECASE)
tumble = re.findall(rb"/Tumble\s+(true|false)(?=[\s/>])", raw, re.IGNORECASE)
if duplex and all(value.lower() == duplex[-1].lower() for value in duplex):
on = duplex[-1].lower() == b"true"
if not on:
return (False, None), (duplex, tumble)
if tumble and all(value.lower() == tumble[-1].lower() for value in tumble):
return (True, tumble[-1].lower() == b"true"), (duplex, tumble)
pjl_duplex = re.findall(rb"@PJL\s+SET\s+DUPLEX\s*=\s*(ON|OFF)", raw, re.IGNORECASE)
pjl_binding = re.findall(rb"@PJL\s+SET\s+BINDING\s*=\s*(LONGEDGE|SHORTEDGE|LEFT|TOP)", raw, re.IGNORECASE)
if pjl_duplex:
on = pjl_duplex[-1].upper() == b"ON"
if not on:
return (False, None), (pjl_duplex, pjl_binding)
if pjl_binding:
return (True, pjl_binding[-1].upper() in (b"SHORTEDGE", b"TOP")), (pjl_duplex, pjl_binding)
raise AssertionError(f"Unresolved duplex controls {(features, duplex, tumble, pjl_duplex, pjl_binding)}")
def marker_ink(page):
with Image.open(page) as image:
return sum(min(pixel) < 225 for pixel in image.convert("RGB").getdata())
root = pathlib.Path(sys.argv[1])
load = lambda name: json.loads((root / name).read_text(encoding="utf-8-sig"))
before = load("defaults-before.json")
assert {"TwoSidedLongEdge", "TwoSidedShortEdge"} <= set(before["AdvertisedDuplex"]), before
assert before["DuplexingMode"] == "TwoSidedLongEdge", before
print("default snapshot", json.dumps(before))
with tempfile.TemporaryDirectory() as work:
work = pathlib.Path(work)
for mode, expected_controls in expected.items():
report = load(f"{mode}.json")
assert load(f"{mode}-defaults-after.json") == before, mode
source = root / f"{mode}.prn"
if report["outcome"] == "refused":
assert not source.exists(), report
print(mode, "refused before handoff", report["message"])
continue
assert report["outcome"] == "submitted", report
raw = source.read_bytes()
controls, evidence = read_job_control(raw)
assert controls == expected_controls, (mode, controls, evidence)
head = raw.find(b"%!")
assert 0 <= head < 4096, (mode, raw[:32])
ps = work / f"{mode}.ps"
ps.write_bytes(raw[head:])
subprocess.run(["gs", "-q", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-sDEVICE=png16m", "-r72",
f"-sOutputFile={work / mode}-%d.png", str(ps)], check=True)
ink = [marker_ink(page) for page in sorted(work.glob(f"{mode}-*.png"))]
assert len(ink) == 2 and ink[0] > 250 and 3 * ink[0] < ink[1] < 6 * ink[0], (mode, ink)
print(mode, "duplex", controls[0], "tumble", controls[1], "raw controls", evidence, "artboards", [1, 2], "marker pixels", ink, report["message"])
@@ -0,0 +1,124 @@
name: Verify VectorCraft duplex on signed A4 driver
on:
push:
branches: [verify/vectorcraft-job-duplex-a4-4859]
permissions:
contents: read
concurrency:
group: verify-vectorcraft-job-options-fixed-4859
cancel-in-progress: true
env:
SHARED_REV: 1d4231487ef21624ad7b7a5ddc92ff7a1fe79f65
WINPRINT_REV: 8ae097ef941b432b0e7671b1ec3a506800e65e57
CARGO_PROFILE_DEV_DEBUG: "0"
CARGO_PROFILE_DEV_OPT_LEVEL: "0"
CARGO_PROFILE_DEV_DEBUG_ASSERTIONS: "false"
CARGO_INCREMENTAL: "0"
CARGO_BUILD_JOBS: "2"
jobs:
windows:
runs-on: windows-2025
timeout-minutes: 75
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
ref: 0cbb7eee4f53174f33a0d7042e27608cfa2ea879
path: receipt-fixture
persist-credentials: false
- name: Choose an isolated build directory on Windows
shell: pwsh
run: |
$disk = Get-PSDrive -PSProvider FileSystem | Where-Object { $_.Free -gt 0 -and $_.Root -match '^[A-Za-z]:\\$' } | Sort-Object -Descending Free | Select-Object -First 1
"CARGO_TARGET_DIR=$(Join-Path $disk.Root "vector-print-duplex-$env:GITHUB_RUN_ID")" >> $env:GITHUB_ENV
- name: Resolve the staged app and shared receipts with the known Winprint observer
shell: python
run: |
import base64, json, os, pathlib, subprocess
previous = "77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
for name in ("Cargo.toml", "apps/vectorcraft-web/Cargo.toml"):
manifest = pathlib.Path(name)
manifest.write_text(manifest.read_text(encoding="utf-8").replace(previous, os.environ["SHARED_REV"]), encoding="utf-8")
home = pathlib.Path(os.environ["RUNNER_TEMP"]) / "vector-duplex-cargo"
os.environ["CARGO_HOME"] = str(home)
host = next(line[6:] for line in subprocess.check_output(["rustc", "-vV"], text=True).splitlines() if line.startswith("host: "))
graph = json.loads(subprocess.check_output(["cargo", "metadata", "--format-version", "1", "--filter-platform", host]))
for name in ("craft-print", "craft-pdf", "hayro"):
package, = (p for p in graph["packages"] if p["name"] == name)
assert package["source"].endswith("#" + os.environ["SHARED_REV"]), package["source"]
package, = (p for p in graph["packages"] if p["name"] == "winprint")
package_dir = pathlib.Path(package["manifest_path"]).parent
repo = pathlib.Path(subprocess.check_output(["git", "rev-parse", "--show-toplevel"], cwd=package_dir, text=True).strip())
head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
assert head == os.environ["WINPRINT_REV"], head
patch = base64.b64decode(pathlib.Path("receipt-fixture/.github/qa/receipt-winprint.patch.b64").read_bytes())
subprocess.run(["git", "apply", "--check"], cwd=repo, input=patch, check=True)
subprocess.run(["git", "apply"], cwd=repo, input=patch, check=True)
(home / "config.toml").write_text('[profile.dev.package."*"]\nopt-level = 0\n', encoding="utf-8")
with open(os.environ["GITHUB_ENV"], "a", encoding="utf-8") as env:
print("CARGO_HOME=" + str(home), file=env)
entry = pathlib.Path("apps/vectorcraft/src/main.rs")
source = entry.read_text(encoding="utf-8")
marker = "fn main() -> std::process::ExitCode {"
assert source.count(marker) == 1
probe = '''
if std::env::args_os().nth(1).is_some_and(|argument| argument == "--qa-vector-print-duplex") {
mod explicit_duplex_options {
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../.github/qa/explicit-duplex-options.rs"));
}
explicit_duplex_options::run();
return std::process::ExitCode::SUCCESS;
}
'''
entry.write_text(source.replace(marker, marker + probe, 1), encoding="utf-8")
- name: Build the normal application executable including its private print worker
shell: bash
run: cargo build --locked -p vectorcraft --bin vectorcraft
- name: Submit simplex and both duplex edges to the private signed A4 queue
shell: pwsh
run: ./.github/qa/capture-duplex-a4.ps1
- name: Save the exact executable for replay
if: always()
shell: pwsh
run: |
$compiled = [IO.Path]::Combine($env:CARGO_TARGET_DIR, 'debug', 'vectorcraft.exe')
if (Test-Path -LiteralPath $compiled -PathType Leaf) {
$replay = New-Item -ItemType Directory 'replay'
Copy-Item -LiteralPath $compiled -Destination $replay.FullName
}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: always()
with:
name: vectorcraft-duplex-a4-executable
compression-level: 1
path: replay/vectorcraft.exe
if-no-files-found: ignore
retention-days: 7
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: always()
with:
name: vectorcraft-duplex-a4-captures
path: captured-duplex-a4/
if-no-files-found: warn
retention-days: 7
inspect:
needs: windows
if: always()
runs-on: ubuntu-24.04
timeout-minutes: 12
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
persist-credentials: false
- uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0
with:
name: vectorcraft-duplex-a4-captures
path: prints
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
packages: ghostscript python3-pil
- name: Read native duplex binding and artboard order independently
run: /usr/bin/python3 .github/qa/inspect-duplex-a4.py prints