Compare commits

...
Author SHA1 Message Date
skylartaylor 823627bfb6 nightly: enforce the signing guard and fix the review findings
- `nightly_compile_gui` calls `nightly_refuse_signing_env` before cargo, so an exported signing key
  cannot reach the compiler or a dependency build script.
- The candidate-workflow check reads the whole `push:` mapping by indentation, so a `paths` filter
  after a blank line is rejected; a negative fixture covers it.
- `profile_root::overlaps` keeps a non-UTF-8 component's exact bytes instead of folding it through
  `to_string_lossy`, and `private_subdirectory` refuses a regular file where a folder belongs.
- The Arch launcher passes a Launcher's `--profile-root` through, like `--launch-profile`.
- Packaging lint runs for `.github/nightly-signing-policy.json` changes.
- Windows: `nightly.ps1` builds into the `-TargetDir` it then reads; the signing fixture restores
  the caller's environment and drops its `cargo`/`git`/`Invoke-WebRequest` mocks.
- A start that created no window passes `false` for `unclean_notice_shown`, so an unclean record
  survives for the next launch to report instead of being deleted.
2026-11-25 00:59:23 +01:00
skylartaylor 809479c1d6 fix(nightly): keep Cargo.lock in cargo's order for the app's winsafe dependency
The nightly port added winsafe to the cadcraft app's dependency list by hand
and put it before winit, so the gate's `git diff --exit-code -- Cargo.lock`
failed after cargo rewrote the list in its sorted order. Move winsafe after
winresource, which is where cargo writes it.
2026-11-25 00:30:36 +01:00
skylartaylor 6c8118aa68 nightly: fix the batch 2A review findings (fmt, version line, assets, fence)
The Opus batch 2A review of nightly/cadcraft-flavor found five items; all are
fixed here, with tests, and nothing outside this channel changes.

1. rustfmt: `cargo fmt --all` (main.rs, nightly_session.rs, process_identity.rs,
   profile_root.rs, ui-egui chrome.rs/lib.rs), so the first `cargo xtask ci`
   step passes; `cargo fmt --all -- --check` is clean with rustfmt
   1.10.0-stable, the version hosted CI uses.
2. Version line: stable's `version_string()` is back to the exact clap form
   (`cadcraft <workspace version>`), so `launch_args::version_stops_parsing`
   passes again and the stable log line is unchanged. The Nightly identity moved
   to `nightly_version_line()` = `CADCraft <prepared> (nightly-v1)`, used by
   `prepare_launch`'s query (plain and Launcher forms) and, through
   `reported_version`, by the log. A unit test pins the kit's form and that the
   app name never gains a "Nightly".
3. `cargo xtask assets`: ATTRIBUTION.md rows for the six new files under
   `assets/app-icon/` (README, the nightly mark and its 1024 master, the .ico,
   the .icns and the provenance JSON). The rule was reproduced locally and
   reports no missing asset.
4. Deleted the dormant duplicates beside Dylan's enabled pair:
   `.github/workflows/nightly-dispatch.yml` and
   `docs/nightly-signing-policy.example.json`; `docs/releasing.md` now says
   there is no automatic transport yet. His `nightly.yml`, `nightly-sign.yml`
   and `.github/nightly-signing-policy.json` are untouched (no schedule, the
   five release managers).
5. `forbidden_roots()` now also fences stable's eframe storage folder per OS
   (`$XDG_DATA_HOME/ai.storyteller.cadcraft`,
   `~/Library/Application Support/ai.storyteller.cadcraft`,
   `%APPDATA%\ai.storyteller.cadcraft`), where stable's `app.ron` lives, with
   one assertion per OS in the existing fence tests.

Kit standards applied: the flat tar uses the standard layout -- `cadcraft` is
the launcher and `cadcraft-bin` the GUI (archive policy, archive tests and
launcher tests updated; a stub-`cargo` render of `nightly.sh` and the extracted
launcher were checked). The launcher passes `--launch-profile`,
`--profile-root`, `--version` and `-V` through once, and refuses a missing or
aliased `cadcraft-bin` instead of exec'ing it. The version line is
`<App> <version> (nightly-v1)`. The tar also ships
`assets/app-icon/cadcraft-nightly.png` rather than copying the stable 256 px
icon.

Optional nits taken: `nightly.ps1` drops the unread CADCRAFT_OVERRIDE_VERSION;
`nightly-signing-tests.ps1` gives its clean-build case the fixture's
CADCRAFT_BUILD_SHA/DATE and a `git` stub, so it reaches the mocked compiler
boundary instead of failing the source preflight; the no-build lint job also
renders the Arch handoff (`nightly-arch-tar-test.sh`).

Tests run here: `python3 packaging/nightly-tests.py` 77 tests OK,
`bash packaging/linux/nightly-arch-tar-test.sh` PASS, `bash -n` over the nine
launcher/packaging scripts, `cargo fmt --all -- --check` clean, and
`cargo check --locked -p cadcraft -p cadcraft-ui-egui --tests` plus
`cargo clippy --locked` (same crates, --all-targets) both clean at the QA-211
gate. pwsh, shellcheck and actionlint are not installed on this host, so the
PowerShell suites and the two linters were not re-run here.
2026-11-25 00:05:28 +01:00
skylartaylor 865ddf2a15 packaging(linux): start every nightly format with the flavor's launch profile
The Nightly flavor refuses to start without `--launch-profile nightly-v1
--profile-root <dir> -- <files>`, but every Linux nightly launcher still only
exported CADCRAFT_CONFIG_DIR and ran the binary bare, so an installed, AppImage,
Arch or Flatpak nightly could not start at all -- and the nightly tar had no
launcher, so an unpacked copy shared stable's settings folder and app.ron.

Every format now starts the GUI the flavor's way: the deb/rpm wrapper, the
AppImage AppRun (still a script, not a symlink), the Arch launcher, the Flatpak
wrapper, and a new launcher shipped inside the flat tar. The profile is
$XDG_DATA_HOME/cadcraft-nightly (inside the Flatpak's own sandbox folder), which
passes the fence. A plain version query and the Launcher's own query form are
passed through once, never doubled, so `--version` still answers without a
profile. The window identity the flavor selects is now the StartupWMClass every
nightly desktop entry names.

Also: isolate the renamed nightly CLI, which still read stable's settings folder;
let the flavor accept its own nightly Flatpak instance (FLATPAK_ID is set inside
the sandbox, so the blanket refusal made the bundle unusable) while keeping every
other instance refused; and make nightly-common.sh compare the exact
`CADCraft <version> (nightly-v1)` line and also run the Launcher's query form,
which must not create the root. The build now passes CADCRAFT_BUILD_CHANNEL and
CADCRAFT_VERSION explicitly (build.rs reads those, not the override).

Tests: new packaging/nightly-launcher-tests.py, wired into nightly-tests.py,
runs every launcher against a recorder; the archive and Arch tests cover the new
tar member.

Also drops the unused `APP_ID` const in main.rs, which the branch's
`cargo clippy --workspace --all-targets -- -D warnings` gate rejects.
2026-11-24 23:18:36 +01:00
skylartaylor b462abfdff packaging: add the isolated CADCraft nightly for Windows and macOS
The app-side flavor and the Windows/macOS producers, on top of Dylan's
nightly-linux-packaging branch: the Linux producer, the shared nightly helpers,
the release-ref callers and the policy, and the eframe persistence fix are his
(9bbbfb49) and stay as he wrote them. This commit adds what was missing for a
nightly to be a separate, isolated app on all three platforms.

App side: the `CADCRAFT_BUILD_CHANNEL=nightly-v1` build channel with its own
icon, version identity, product name and Windows AUMID; the Launcher's
`--launch-profile nightly-v1 --profile-root <abs> --` protocol with the early
`--version` answer in both forms, before logging, identity, IPC or any window;
the profile fences (stable roots, portable layout, install boundary, aliases,
`FLATPAK_ID`, and `CADCRAFT_CONFIG_DIR` accepted only when it names the profile
itself, so a Launcher wrapper can export it); one data-root hook so the settings
folder *and* eframe's `app.ron` are the profile, with autosave/Drawing Recovery,
logs, reports and the single-instance socket inside it; the session lease and
unclean-exit record finished from `on_exit` (macOS Cmd+Q); updater, control
server and agent surfaces off in this channel; the channel name in the window
title, drawn caption and About.

Windows: `packaging/windows/nightly.ps1` with `package.ps1 -Nightly
-BuildOnly` and `sign.ps1 -Required/-CheckOnly/-CheckBuildEnvironment`.
macOS: `nightly.sh`, `nightly-lib.sh`, `nightly-sign.sh`, `nightly-verify.sh`
and `nightly_plist.py`.
Shared: the `nightly-tests.py` runner over Dylan's release contracts plus the
archive, plist and macOS signing suites; the no-build `nightly-source-contract`
lint job; the dormant `nightly-dispatch.yml` (no schedule); the stable Linux key
file his tests read; and the nightly icon set with its provenance.
2026-11-24 22:30:27 +01:00
Dylan M. Taylor 9bbbfb49e9 packaging(nightly): port Linux nightly archive scripts, isolate eframe persistence, and exclude packaging from Sonar coverage 2026-11-24 16:18:40 -05:00
Dylan M. Taylor 9442ba19a0 fix(packaging): fix actionlint concurrency key and nightly Linux packaging review issues 2026-11-24 14:21:39 -05:00
Dylan M. Taylorandskylartaylor 22ed6624e5 ci(nightly): enable nightly workflows for supervised manual runs
Port Skylar's (@skylartaylor) supervised manual nightly enablement from
storytold/photocraft#16594 into CADCraft:

- Add .github/nightly-signing-policy.json (v3 policy adapted for
  storytold/cadcraft, repository ID 1408289866, CI workflow 380135820,
  SonarCloud project storytold_cadcraft; producer_workflow_id pending
  main registration).
- Add .github/workflows/nightly.yml and .github/workflows/nightly-sign.yml
  pinned to craft-common-actions@605d58766e8f536564da8fc81d3676ac86816dea
  for supervised manual workflow_dispatch runs by the reviewed release
  managers.
- Add docs/nightly-release-preparation.md and
  packaging/nightly-release-tests.py contract tests.

Credit to @skylartaylor for the original implementation in
storytold/photocraft#16594.

Co-authored-by: skylartaylor <[email protected]>
2026-11-24 14:14:41 -05:00
Dylan M. Taylor 29d7e73817 packaging(linux): support co-installable nightly packages 2026-11-24 13:33:35 -05:00
60 changed files with 5163 additions and 69 deletions
+16
View File
@@ -0,0 +1,16 @@
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
ga/qCA==
=3wGQ
-----END PGP PUBLIC KEY BLOCK-----
+107
View File
@@ -0,0 +1,107 @@
{
"schema": "craft-nightly-release-policy/v3",
"repository": "storytold/cadcraft",
"repository_id": 1408289866,
"producer_workflow_id": null,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "605d58766e8f536564da8fc81d3676ac86816dea",
"release_branch": "release",
"manual_actors": [
"bflatastic",
"dylanmtaylor",
"echelon",
"FredApps",
"skylartaylor"
],
"max_age_seconds": 86400,
"candidate_policy": {
"schema": "craft-nightly-candidate-policy/v3",
"epoch": "cadcraft-nightly-20261124-initial",
"repository": "storytold/cadcraft",
"branch": "main",
"required_workflows": [
{
"workflow_id": 380135820,
"workflow_path": ".github/workflows/ci.yml",
"jobs": [
{
"name": "gate / gate (ubuntu-24.04)",
"app_id": 15368,
"applicability": "required"
}
]
}
],
"sonar": {
"organization": "storytold",
"project": "storytold_cadcraft",
"app_id": 12526,
"check_name": "SonarCloud Code Analysis",
"details_url": "https://sonarcloud.io/dashboard?id=storytold_cadcraft&branch=main",
"issue_types": [
"VULNERABILITY"
],
"accepted_conditions": [
{
"metric": "new_security_rating",
"comparator": "GT",
"error_threshold": "1",
"maximum": "5"
}
],
"required_conditions": [
{
"metric": "new_reliability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_maintainability_rating",
"comparator": "GT",
"error_threshold": "1"
},
{
"metric": "new_coverage",
"comparator": "LT",
"error_threshold": "80"
},
{
"metric": "new_duplicated_lines_density",
"comparator": "GT",
"error_threshold": "3"
},
{
"metric": "new_security_hotspots_reviewed",
"comparator": "LT",
"error_threshold": "100"
}
],
"debt": []
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
"trust": {
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
}
},
"linux-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
"trust": {
"apple_team_id": "DJ6XS33FX8"
}
}
}
}
+42
View File
@@ -0,0 +1,42 @@
name: CADCraft release-ref nightly signer
# Enabled for supervised manual dispatch on release. Main/release contents must match.
# A reusable callee does not change context; this must be a real top-level release dispatch.
on:
workflow_dispatch:
inputs:
producer_run_id:
description: Exact untrusted producer Actions run ID
required: true
type: string
producer_run_attempt:
description: Exact untrusted producer Actions run attempt
required: true
type: string
permissions: {}
concurrency:
group: cadcraft-nightly-release
cancel-in-progress: false
jobs:
release:
# Actual context guards: official repository, manual dispatch, real release branch.
if: >-
github.repository == 'storytold/cadcraft' &&
github.event_name == 'workflow_dispatch' &&
github.ref == 'refs/heads/release' && github.ref_type == 'branch'
permissions:
contents: write
actions: read
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the existing release environment and export keys in its signing step.
+34
View File
@@ -0,0 +1,34 @@
name: CADCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
on:
workflow_dispatch:
permissions:
contents: read
jobs:
unsigned:
# Actual context guards only; no inherited/platform secrets.
if: >-
github.repository == 'storytold/cadcraft' &&
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
# no OIDC, attestation write, release environment or platform secrets in compilation.
permissions:
contents: read
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@605d58766e8f536564da8fc81d3676ac86816dea
with:
tooling-revision: 605d58766e8f536564da8fc81d3676ac86816dea
app-name: cadcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged #339 (bounded lineage compares), on top of the
# Linux/macOS signer (#342).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
+30 -2
View File
@@ -5,9 +5,9 @@ name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
pull_request:
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
workflow_dispatch:
permissions:
@@ -49,3 +49,31 @@ jobs:
- name: Build and check non-executable installer fixtures
shell: pwsh
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
nightly-source-contract:
name: Nightly source contracts (no build or signing)
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
steps:
- name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check the nightly scripts without running them
run: |
for script in packaging/nightly-common.sh packaging/linux/nightly.sh packaging/macos/nightly.sh \
packaging/macos/nightly-lib.sh packaging/macos/nightly-sign.sh packaging/macos/nightly-verify.sh; do
bash -n "$script"
done
shellcheck --version
shellcheck -x -P packaging packaging/nightly-common.sh packaging/linux/nightly.sh \
packaging/macos/nightly.sh packaging/macos/nightly-lib.sh packaging/macos/nightly-sign.sh packaging/macos/nightly-verify.sh
- name: Enforce the nightly serialization and synthetic packaging contracts
run: python3 packaging/nightly-tests.py
- name: Render the Arch Nightly handoff from stub binaries
run: bash packaging/linux/nightly-arch-tar-test.sh
+8
View File
@@ -9,3 +9,11 @@
*.swp
/apps/cadcraft-web/dist/
/.claude/worktrees/
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions):
# nightly_init refuses to build from a tree where these show up as changes.
/.nightly-tools
/.nightly-input
/craft-i18n
/craft-fonts
__pycache__/
+6
View File
@@ -45,6 +45,12 @@ Generated-in-code assets are original and have no file to list:
| `assets/app-icon/cadcraft-256.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-1024.png` | CADCraft contributors | generated | MIT OR Apache-2.0 | |
| `assets/app-icon/cadcraft-macos-512.png` | CADCraft contributors | generated (macOS margin variant) | MIT OR Apache-2.0 | |
| `assets/app-icon/README.md` | CADCraft contributors | original work for this repository | MIT OR Apache-2.0 | How each icon is generated and which mark each channel uses |
| `assets/app-icon/cadcraft-nightly.png` | CADCraft contributors | generated from `assets/app-icon/cadcraft-1024.png` | MIT OR Apache-2.0 | Nightly mark: same glyph, deeper background `#0c657b`; the Linux nightly tar's icon |
| `assets/app-icon/cadcraft-nightly-1024.png` | CADCraft contributors | generated from `assets/app-icon/cadcraft-1024.png` | MIT OR Apache-2.0 | 1024 master the nightly `.icns` is generated from |
| `assets/app-icon/cadcraft-nightly.ico` | CADCraft contributors | generated from `assets/app-icon/cadcraft-nightly-1024.png` | MIT OR Apache-2.0 | Windows nightly icon (16–256 px entries) for `build.rs` |
| `assets/app-icon/cadcraft-nightly.icns` | CADCraft contributors | generated from `assets/app-icon/cadcraft-nightly-1024.png` | MIT OR Apache-2.0 | macOS nightly bundle icon (`CFBundleIconFile cadcraft-nightly`) |
| `assets/app-icon/nightly-provenance.json` | CADCraft contributors | original work for this repository | MIT OR Apache-2.0 | The exact background transform that produced the nightly set |
| `packaging/macos/dmg/background.svg` | @XusBadia | original work for this repository (2026-10-08), "CADCraft macOS DMG window background"; derived from the CADCraft app icon (`assets/app-icon/`, referenced via `<image>`, not copied); text is outlined Inter / JetBrains Mono glyph paths (OFL fonts the project already uses); no third-party material modified | MIT OR Apache-2.0 (same as the code: `LICENSE-MIT`, `LICENSE-APACHE`) | Finder window background of the macOS DMG; `packaging/macos/dmg/generate.py` renders it to `background.tiff` (see `packaging/macos/dmg/README.md`) |
| `packaging/macos/dmg/background.tiff` | @XusBadia | Rendered from `packaging/macos/dmg/background.svg` by `packaging/macos/dmg/generate.py` | MIT OR Apache-2.0 (same as the code: `LICENSE-MIT`, `LICENSE-APACHE`) | 1x + 2x HiDPI TIFF for the macOS DMG window; includes the app icon (see its row) and LittleCMS's built-in sRGB profile ("No copyright, use freely") |
| `examples/apartment.dxf` | CADCraft contributors | sample drawing made with cadcraft-cli commands | MIT OR Apache-2.0 | Original |
Generated
+1
View File
@@ -677,6 +677,7 @@ dependencies = [
"windows",
"winit",
"winresource",
"winsafe",
"zbus",
]
+3
View File
@@ -77,6 +77,9 @@ windows = { version = "0.62", features = ["UI_ViewManagement"] }
# One CADCraft per sign-in: later launches hand their files over an AF_UNIX socket
# (single_instance.rs). Already in Cargo.lock through zbus.
uds_windows = "1.2.1"
# The Nightly build's own taskbar identity (process_identity.rs): the explicit
# AppUserModelID, which only a nightly launch sets.
winsafe = { version = "0.0.29", features = ["user", "shell"] }
[target.'cfg(target_os = "linux")'.dependencies]
hidapi = { version = "2.6.7", default-features = false, features = ["linux-native-basic-udev"] }
+46 -5
View File
@@ -1,23 +1,64 @@
//! Windows only: embed the app icon and version info into `cadcraft.exe`. Elsewhere a no-op.
//!
//! The build channel comes from `CADCRAFT_BUILD_CHANNEL`: `nightly-v1` compiles a Nightly build
//! with its own icon and version, `stable`/unset is the stable build, and anything else is refused
//! rather than silently producing a stable binary with a nightly name.
#[path = "src/build_channel.rs"]
mod build_channel;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=src/build_channel.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/cadcraft.ico");
println!("cargo:rerun-if-changed=../../assets/app-icon/cadcraft-nightly.ico");
println!("cargo:rerun-if-env-changed=CADCRAFT_REQUIRE_WINRES");
println!("cargo:rerun-if-env-changed=CADCRAFT_BUILD_SHA");
println!("cargo:rerun-if-env-changed=CADCRAFT_BUILD_CHANNEL");
println!("cargo:rerun-if-env-changed=CADCRAFT_VERSION");
println!("cargo:rustc-check-cfg=cfg(cadcraft_nightly_v1)");
let nightly = match std::env::var("CADCRAFT_BUILD_CHANNEL").as_deref() {
Ok("nightly-v1") => {
println!("cargo:rustc-cfg=cadcraft_nightly_v1");
true
}
// An empty value (an unset CI input) means the default stable build.
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
_ => {
eprintln!("unsupported CADCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
std::process::exit(1);
}
};
// The version the build reports: the prepared feed identity for a nightly (refused when it is
// missing or is not a nightly identity), the crate version otherwise.
let built_version = if nightly {
match std::env::var("CADCRAFT_VERSION") {
Ok(version) if build_channel::is_nightly_version(&version) => version,
_ => {
eprintln!("nightly-v1 requires an explicit CADCRAFT_VERSION feed identity");
std::process::exit(1);
}
}
} else {
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
};
println!("cargo:rustc-env=CADCRAFT_BUILT_VERSION={built_version}");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
if std::path::Path::new("../../assets/app-icon/cadcraft.ico").exists() {
res.set_icon("../../assets/app-icon/cadcraft.ico");
}
res.set("ProductName", "CADCraft")
.set("FileDescription", "CADCraft computer-aided design")
res.set_icon(build_channel::windows_icon_path(nightly))
.set("ProductName", if nightly { "CADCraft Nightly" } else { "CADCraft" })
.set("FileDescription", if nightly { "CADCraft Nightly computer-aided design" } else { "CADCraft computer-aided design" })
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) 2026 ArtCraft Team and the CADCraft contributors. MIT OR Apache-2.0.")
.set("OriginalFilename", "cadcraft.exe")
.set("InternalName", "cadcraft");
if nightly {
// The Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
res.set("ProductVersion", &built_version);
}
if let Err(e) = res.compile() {
if std::env::var_os("CADCRAFT_REQUIRE_WINRES").is_some() {
eprintln!("embedding Windows resources failed: {e}");
+53
View File
@@ -0,0 +1,53 @@
//! The build-time nightly identity shared by the build script and its pure regression tests.
pub fn is_nightly_version(version: &str) -> bool {
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
let base: Vec<_> = base.split('.').collect();
let parts: Vec<_> = suffix.split('.').collect();
base.len() == 3
&& base.iter().all(|s| digits(s))
&& parts.len() == 4
&& parts[0].len() == 8
&& digits(parts[0])
&& digits(parts[1])
&& digits(parts[2])
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
}
pub fn windows_icon_path(nightly: bool) -> &'static str {
if nightly { "../../assets/app-icon/cadcraft-nightly.ico" } else { "../../assets/app-icon/cadcraft.ico" }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
assert_eq!(windows_icon_path(false), "../../assets/app-icon/cadcraft.ico");
assert_eq!(windows_icon_path(true), "../../assets/app-icon/cadcraft-nightly.ico");
}
#[test]
fn explicit_feed_identity_is_required_for_a_nightly_build() {
assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345"));
for invalid in [
"",
"0.23.1",
"0.23.1-nightly",
"0.23.1-nightly.20261120",
"0.23.1-nightly.20261120.17.1.gABCDEF012345",
"0.23.1-nightly.20261120.17.1.gabcdef012345\n",
] {
assert!(!is_nightly_version(invalid), "{invalid:?}");
}
}
#[test]
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
for invalid in [
"../0.23.1-nightly.20261120.1.1.gabcdef012345",
"0.23.1-nightly.20261120.1.1.gabcdef012345/other",
"0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other",
] {
assert!(!is_nightly_version(invalid));
}
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
use crate::launch_profile::Profile;
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub const COMPILED: BuildFlavor = if cfg!(cadcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open CADCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable CADCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
pub fn version_query(args: &[OsString]) -> bool {
matches!(args, [arg] if arg == "--version" || arg == "-V")
}
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
match flavor {
BuildFlavor::Stable => stable.to_owned(),
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
assert!(!needs_native_error(BuildFlavor::Stable, true));
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.23.1"), "0.23.1");
assert_eq!(version(BuildFlavor::NightlyV1, "0.23.1"), "0.23.1 (nightly-v1)");
assert!(version_query(&["--version".into()]));
assert!(version_query(&["-V".into()]));
assert!(!version_query(&["--".into(), "--version".into()]));
assert!(!version_query(&[]));
}
}
+29
View File
@@ -71,6 +71,10 @@ impl Env {
fn from_vars_and_exe(var: impl Fn(&str) -> Option<OsString>, exe_dir: Option<&std::path::Path>) -> Env {
let mut vars = Env::from_vars(&var);
// The Nightly profile owns every data root before the first use (see [`apply_profile`]).
if Self::apply_profile(&mut vars, crate::launch_profile::current().root()) {
return vars;
}
// An explicit override (including blank, which disables settings) takes precedence.
if var(CONFIG_DIR).is_none()
&& let Some(exe) = exe_dir
@@ -87,6 +91,17 @@ impl Env {
vars
}
/// Point every data root this process resolves at the Nightly profile `root`: the settings folder
/// (logs, autosave and Drawing Recovery, workspace, plotters, LISP support, crash reports) and
/// eframe's own storage file, which would otherwise go to the stable user profile. `false` for a
/// stable launch, which then resolves its folders as before.
fn apply_profile(vars: &mut Env, root: Option<&std::path::Path>) -> bool {
let Some(root) = root else { return false };
vars.config_dir = Some(root.to_path_buf());
vars.portable_storage_file = Some(root.join("app.ron"));
true
}
/// [`Env::read`] with `var` looking a variable up.
pub(crate) fn from_vars(var: impl Fn(&str) -> Option<OsString>) -> Env {
let text = |k: &str| var(k).and_then(|v| v.into_string().ok()).filter(|v| !v.trim().is_empty());
@@ -124,6 +139,20 @@ mod tests {
use super::*;
use std::cell::RefCell;
/// The Nightly profile is the settings folder and eframe's storage file, before any portable
/// or platform resolution: no stable folder is read or written by a nightly launch.
#[test]
fn a_launch_profile_owns_the_settings_folder_and_the_eframe_storage_file() {
let profile = std::path::PathBuf::from("/nightly-data/profile");
let mut vars = Env::from_vars(|_| None);
// A stable launch keeps the platform resolution.
assert!(!Env::apply_profile(&mut vars, None));
assert!(!vars.portable_storage_file.as_ref().is_some_and(|f| f.ends_with("app.ron")));
assert!(Env::apply_profile(&mut vars, Some(&profile)));
assert_eq!(vars.config_dir, Some(profile.clone()));
assert_eq!(vars.portable_storage_file, Some(profile.join("app.ron")));
}
#[test]
fn portable_eframe_storage_is_a_file_inside_the_settings_directory() {
let exe = std::env::temp_dir().join(format!("cadcraft-env-portable-{}", std::process::id()));
+211
View File
@@ -0,0 +1,211 @@
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
//! Stable launches retain their original arguments and directory policy. No environment mutation.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
}
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old portable/config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::portable::probe)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
}
fn absolute() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\cadcraft" } else { "/nightly-data/profiles/cadcraft" }
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
for argv in [args(&[]), args(&["--new-window", "a.dxf"]), args(&["--", "--launch-profile", "file.dxf"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
}
}
#[test]
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
let mut argv = nightly();
argv.extend(args(&["--profile-root", "drawing with spaces.dxf"]));
let launch = parse(argv).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "drawing with spaces.dxf"]));
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
] {
assert!(parse(argv).is_err());
}
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-window", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
] {
assert!(!version_query(&argv), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+192 -18
View File
@@ -16,16 +16,23 @@
#[cfg(any(target_os = "macos", test))]
mod apple_events;
#[cfg(test)]
mod build_channel;
mod build_flavor;
mod control_server;
mod desktop_theme;
mod env;
#[cfg(any(target_os = "windows", test))]
mod graphics;
mod launch_args;
mod launch_profile;
mod logging;
#[cfg(target_os = "macos")]
mod native_menu;
mod nightly_session;
mod portable;
mod process_identity;
mod profile_root;
#[cfg(target_os = "macos")]
mod sheet;
mod single_instance;
@@ -34,6 +41,7 @@ mod system_animations;
mod workspace;
use cadcraft_engine::Session;
use cadcraft_ui_egui::os_window::{self, LaunchIdentity};
use cadcraft_ui_egui::switch::Switch;
use cadcraft_ui_egui::{CadApp, Pick, Services, i18n};
@@ -151,6 +159,11 @@ impl eframe::App for App {
self.persist_workspace(None);
self.cad.cancel_screenshots();
self.cad.shutdown_autosave();
// The host's last step, once: on macOS Cmd+Q ends the process here, after this, so the
// Nightly session record is finished by this hook and never by the code after `run_native`.
if let Some(at_exit) = self.cad.services.at_exit.take() {
at_exit();
}
}
/// Preferences (the interface theme) survive restarts; eframe saves the window state itself
/// (`persist_window`); egui state is not kept.
@@ -199,6 +212,8 @@ fn services() -> Services {
pick_pgp: Some(Box::new(|dir: Option<&str>| {
file_dialog(&Pick::Pgp(dir.unwrap_or_default().into())).pick_file().map(|p| p.to_string_lossy().to_string())
})),
// Set in `main` once the Nightly session record exists.
at_exit: None,
}
}
@@ -250,7 +265,8 @@ fn saved_window(app_ron: &str) -> bool {
/// unusable) is dropped first, so the window opens at its default size. `portable_file`: the
/// portable copy's settings file, read instead of the user profile's.
fn restores_window(portable_file: Option<&std::path::Path>) -> bool {
let Some(path) = portable_file.map(std::path::PathBuf::from).or_else(|| eframe::storage_dir(APP_ID).map(|dir| dir.join("app.ron"))) else {
let Some(path) = portable_file.map(std::path::PathBuf::from).or_else(|| eframe::storage_dir(os_window::app_id()).map(|dir| dir.join("app.ron")))
else {
return false;
};
let Ok(mut ron) = std::fs::read_to_string(&path) else { return false };
@@ -287,14 +303,14 @@ const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("CADCraft")
.with_title(os_window::name_for(os_window::identity()))
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
.with_title_shown(false)
.with_app_id(APP_ID),
.with_app_id(os_window::app_id()),
// The size, position and maximized state are kept between sessions (#2595); eframe keeps a
// restored window on the monitors that are connected now.
persist_window: true,
@@ -311,8 +327,6 @@ fn window_options(restoring: bool, stencil: u8) -> eframe::NativeOptions {
}
}
const APP_ID: &str = "ai.storyteller.cadcraft";
/// The key eframe saves the main window state under in its storage.
const WINDOW_KEY: &str = "window";
@@ -336,22 +350,118 @@ fn app_icon() -> Option<egui::IconData> {
eframe::icon_data::from_png_bytes(APP_ICON_PNG).map_err(|e| log::warn!("app icon: {e}")).ok()
}
/// The version this build reports: the prepared nightly identity, or the workspace version.
fn built_version() -> &'static str {
env!("CADCRAFT_BUILT_VERSION")
}
/// The stable line, exactly what clap prints for `--version`: `cadcraft <workspace version>`.
fn version_string() -> String {
format!("cadcraft {}", cadcraft_engine::build_version())
}
/// The Nightly identity line every nightly script checks: `<App> <version> (nightly-v1)`, with the
/// prepared nightly version embedded at build time. The app name never gains a "Nightly".
fn nightly_version_line() -> String {
format!("CADCraft {}", build_flavor::version(build_flavor::BuildFlavor::NightlyV1, built_version()))
}
/// The identity this build reports in its log: the Nightly line on that channel, stable's otherwise.
fn reported_version() -> String {
match build_flavor::COMPILED {
build_flavor::BuildFlavor::Stable => version_string(),
build_flavor::BuildFlavor::NightlyV1 => nightly_version_line(),
}
}
/// The reported line with the commit, for the log: a bug report's log names the build it came from.
fn log_version() -> String {
format!("{} ({})", reported_version(), option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev"))
}
/// Whether this start runs the isolated Nightly flavor.
fn is_nightly() -> bool {
launch_profile::current().is_nightly()
}
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(LaunchIdentity::NightlyV1))
}
/// A refused launch profile ends with a native dialog on a desktop, and with the reason on standard
/// error everywhere else (a headless runner must never wait for a modal).
fn report_launch_profile_error(error: &str) {
eprintln!("CADCraft launch profile: {error}");
let desktop_session = cfg!(windows)
|| cfg!(target_os = "macos")
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
if build_flavor::needs_native_error(build_flavor::COMPILED, desktop_session) {
if let Err(error) = initialize_nightly_process_identity() {
eprintln!("CADCraft launch profile: {error}");
return;
}
let _ = rfd::MessageDialog::new()
.set_title(os_window::name_for(LaunchIdentity::NightlyV1))
.set_description(error)
.set_level(rfd::MessageLevel::Error)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
}
/// Select the immutable launch profile before logging, updates, fonts or saved state, and answer
/// the version query before any of that: `None` means the query has been answered and the process
/// should return success without opening a window.
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<_> = std::env::args_os().skip(1).collect();
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, logging, IPC or any window.
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv))
{
use std::io::Write as _;
let _ = writeln!(std::io::stdout(), "{}", nightly_version_line());
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
std::process::exit(2)
});
let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable };
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
}
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
fn main() -> eframe::Result {
// A copy of this program started to read or write a DWG file does only that.
// A copy of this program started to read or write a DWG file does only that. It is started
// with `--dwg-worker` alone, so it is answered before the launch profile is required.
if let Some(code) = cadcraft_io::dwg_worker::serve_if_asked() {
std::process::exit(code);
}
let Some(arguments) = prepare_launch() else { return Ok(()) };
cadcraft_io::dwg_worker::use_own_worker();
// First, so every start-up record is captured; see `logging`.
let logger = logging::install();
// The update helper relaunches this binary after a self-update; it runs and exits here.
// The update helper relaunches this binary after a self-update; it runs and exits here. A
// nightly build is updated by the Launcher only, so it never finishes a stable helper.
#[cfg(not(target_arch = "wasm32"))]
if let Some(done) = craft_update::self_update::finish(&cadcraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
if !is_nightly()
&& let Some(done) = craft_update::self_update::finish(&cadcraft_ui_egui::UPDATE_APP, &arguments)
{
if let Err(e) = done {
eprintln!("CADCraft update helper failed: {e}");
std::process::exit(1);
@@ -361,14 +471,25 @@ fn main() -> eframe::Result {
// `--help` and `--version` print to standard output and exit 0. A usage error (an unknown or
// repeated flag, a missing or bad value, a bad CADCRAFT_CONTROL_PORT) names the argument on
// standard error and exits 2 before the window opens.
let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit());
let launch = launch_args::parse(launch_args::command(), arguments).unwrap_or_else(|e| e.exit());
let vars = env::Env::read();
let (control_port, sample, files) = (launch.control, launch.sample, launch.files);
// A nightly launch accepts no control server: the inherited CADCRAFT_CONTROL_PORT and the
// Launcher's agent link belong to the stable app, and a second unauthenticated surface over
// the nightly profile is not part of the protocol.
let control_port = if is_nightly() {
if control_port.is_some() {
eprintln!("CADCraft Nightly: the control server is off in this channel; the option is ignored");
}
None
} else {
control_port
};
// The log file lives under the settings directory; opened after the arguments, so `--version`
// leaves no file behind. Records logged until now are written to it first.
if let Some(logger) = logger {
match vars.config_dir.as_ref().map(|d| logger.attach_dir(&d.join(logging::LOG_DIR))) {
Some(Ok(path)) => log::info!("{} ({} {}), log file {}", version_string(), std::env::consts::OS, std::env::consts::ARCH, path.display()),
Some(Ok(path)) => log::info!("{} ({} {}), log file {}", log_version(), std::env::consts::OS, std::env::consts::ARCH, path.display()),
Some(Err(e)) => log::warn!("no log file: {e}"),
None => {
logger.stderr_only();
@@ -379,13 +500,32 @@ fn main() -> eframe::Result {
// A launch that only names files hands them to the CADCraft already running and exits.
let handed = single_instance::absolute(&files);
let may_hand_off = handed.is_some() && !launch.new_window && !files.is_empty() && control_port.is_none() && !sample;
let instance = match single_instance::claim(handed.as_deref().unwrap_or_default(), may_hand_off) {
let instance = match single_instance::claim(handed.as_deref().unwrap_or_default(), may_hand_off, launch_profile::current().root()) {
single_instance::Claim::HandedOff => return Ok(()),
single_instance::Claim::Primary(server) => Some(server),
single_instance::Claim::Alone => None,
};
install_io();
cadcraft_engine::settings_dir::set(vars.config_dir.clone());
// Nightly session health: the owner's lease and unclean-exit record live in the profile, and the
// record is finished on the way out (on macOS in `on_exit`, see `nightly_session`).
let (nightly_watch, previous_unclean) =
match nightly_session::Session::begin_with_health(launch_profile::current().root(), built_version(), option_env!("CADCRAFT_BUILD_SHA")) {
Ok((watch, unavailable)) => {
if unavailable {
log::warn!("another CADCraft Nightly holds this profile's session lease; this window keeps no health record");
}
let unclean = watch.as_ref().is_some_and(nightly_session::Session::previous_unclean);
(std::sync::Arc::new(std::sync::Mutex::new(watch)), unclean)
}
Err(error) => {
log::warn!("Nightly session state: {error}");
(std::sync::Arc::new(std::sync::Mutex::new(None)), false)
}
};
if previous_unclean {
log::warn!("the previous CADCraft Nightly ended without finishing its session record");
}
if let Some(dir) = &vars.config_dir {
cadcraft_ui_egui::fault::install_report_hook(dir.join(cadcraft_ui_egui::fault::REPORT_DIR));
}
@@ -402,12 +542,16 @@ fn main() -> eframe::Result {
if stencil == 0 {
log::warn!("CADCRAFT_STENCIL is off: the window has no stencil buffer; clipped layout viewports draw unclipped");
}
let persistence_path = vars
.portable_storage_file
.clone()
.or_else(|| std::env::var_os("CADCRAFT_CONFIG_DIR").and_then(|_| vars.config_dir.as_ref().map(|d| d.join("app.ron"))));
let mut options = eframe::NativeOptions {
// The crosshair is drawn by the app: present without a queue on Linux/BSD, where X11
// swapchains hold two frames back under vsync (`CADCRAFT_VSYNC=1` restores vsync).
wgpu_options: eframe::egui_wgpu::WgpuConfiguration::default().with_surface_config(surface),
persistence_path: vars.portable_storage_file.clone(),
..window_options(restores_window(vars.portable_storage_file.as_deref()), stencil)
persistence_path: persistence_path.clone(),
..window_options(restores_window(persistence_path.as_deref()), stencil)
};
if let Some(icon) = app_icon() {
options.viewport = options.viewport.with_icon(icon);
@@ -452,11 +596,19 @@ fn main() -> eframe::Result {
let apple_events = apple_events::AppleEvents::install();
#[cfg(target_os = "macos")]
let apple_events = &apple_events;
eframe::run_native(
"CADCraft",
// The exit hook's own handle: the app creator is a `move` closure, so the watch is cloned before it.
let exit_watch = std::sync::Arc::clone(&nightly_watch);
let result = eframe::run_native(
os_window::name_for(os_window::identity()),
options,
Box::new(move |cc| {
let mut app = CadApp::new(Session::empty(), services());
// The exit hook runs in `on_exit`: macOS ends the process inside AppKit's terminate after
// it, so nothing after `run_native` can be relied on there.
app.services.at_exit = Some(Box::new(move || nightly_session::finish_once(&exit_watch, previous_unclean)));
if previous_unclean {
app.set_status("CADCraft Nightly ended unexpectedly last time; your drawings were recovered where autosave had them.");
}
// File dialogs are sheets on macOS: a modal loop inside the event handler crashes the
// app when the dialog is resized (#1527).
#[cfg(target_os = "macos")]
@@ -489,7 +641,10 @@ fn main() -> eframe::Result {
// Autosave files (SAVEFILEPATH) default to `<settings dir>/autosave`.
if let Some(dir) = &vars.config_dir {
app.enable_autosave(&dir.join("autosave"));
app.enable_update_check();
// A nightly build is updated by the Launcher, never by the app's own update check.
if !is_nightly() {
app.enable_update_check();
}
// Startup LISP (acad.lsp, acaddoc.lsp) is read from `<settings>/support`; the
// folder is made so it is there to put them in.
let support = dir.join("support");
@@ -554,12 +709,20 @@ fn main() -> eframe::Result {
apple_events,
}))
}),
)
);
// The controlled return path: a start that created no window still finishes its record. On macOS
// a quit never reaches here, and the exit hook above has done it. No window ran, so no notice was
// shown: pass false and an unclean record survives for the next launch to report.
nightly_session::finish_once(&nightly_watch, false);
result
}
#[cfg(test)]
mod tests {
use super::{STENCIL_BITS, filters_for_save, follow_desktop, saved_window, stencil_bits, window_options, without_tiny_window};
use super::{
STENCIL_BITS, filters_for_save, follow_desktop, nightly_version_line, saved_window, stencil_bits, version_string, window_options,
without_tiny_window,
};
#[test]
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
@@ -642,6 +805,17 @@ mod tests {
assert_eq!(without_tiny_window("not ron"), None);
}
/// The two identity lines. Nightly prints the kit's `<App> <version> (nightly-v1)` -- the app
/// name never gains a "Nightly" -- while stable keeps exactly the line clap prints, which
/// `launch_args` asserts against its own `-V` output.
#[test]
fn the_version_lines_name_the_app_and_its_channel() {
let nightly = nightly_version_line();
assert_eq!(nightly, format!("CADCraft {} (nightly-v1)", super::built_version()));
assert!(!nightly.contains("Nightly "), "the version line must not rename the app: {nightly}");
assert_eq!(version_string(), format!("cadcraft {}", cadcraft_engine::build_version()));
}
/// View ▸ Theme ▸ System on Linux: winit reports no theme, so the desktop's answer stands in;
/// without one (or where winit answers and the desktop doesn't) the input is left alone.
#[test]
+287
View File
@@ -0,0 +1,287 @@
//! App-private Nightly session health, not telemetry or a Launcher protocol.
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write as _};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
const RECORD: &str = "nightly-session.json";
const LEASE: &str = "nightly-session.lock";
const MAX_METADATA_BYTES: usize = 256;
pub struct Session {
_lease: File,
path: PathBuf,
own_record: Vec<u8>,
previous_unclean: bool,
}
fn regular_or_missing(path: &Path) -> io::Result<bool> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
/// still runs for a start that created no window.
pub type Shared = Arc<Mutex<Option<Session>>>;
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
if let Some(watch) = watch
&& let Err(error) = watch.finish(unclean_notice_shown)
{
log::warn!("Nightly session state was left intact: {error}");
}
}
/// Replace `path` with `bytes` without ever writing through a symbolic link at the destination.
///
/// The engine's [`cadcraft_engine::atomic_write`] resolves a destination link so that its target is
/// replaced; a profile entry is not ours to redirect, so here a link at the destination is refused,
/// and the bytes are written to a fresh temporary in the same folder (created exclusively, so a
/// planted temporary cannot be followed either) before it is renamed over the destination.
fn write_atomic_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(metadata) if !metadata.file_type().is_file() => {
return Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory"));
}
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
let dir = path.parent().unwrap_or_else(|| Path::new("."));
for attempt in 0..32_u32 {
let temporary = dir.join(format!(".{}.{}-{attempt}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id()));
let mut file = match OpenOptions::new().write(true).create_new(true).open(&temporary) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
};
let written = file.write_all(bytes).and_then(|()| file.sync_all());
drop(file);
if let Err(error) = written {
let _ = std::fs::remove_file(&temporary);
return Err(error);
}
return match std::fs::rename(&temporary, path) {
Ok(()) => Ok(()),
Err(error) => {
let _ = std::fs::remove_file(&temporary);
Err(error)
}
};
}
Err(io::Error::other("no free temporary name for the Nightly session state"))
}
impl Session {
/// The warning belongs to this window: a busy secondary has no health-record coverage,
/// while Stable and a lease-owning Nightly window preserve their existing result.
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
let watch = Self::begin(root, version, commit)?;
let unavailable = root.is_some() && watch.is_none();
Ok((watch, unavailable))
}
/// `None` is stable or another owner of this profile. Neither case touches the record.
/// The supplied root must already be the validated private Nightly profile.
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
let Some(root) = root else { return Ok(None) };
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
}
let lease_path = root.join(LEASE);
regular_or_missing(&lease_path)?;
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
match lease.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
Err(std::fs::TryLockError::Error(error)) => return Err(error),
}
let path = root.join(RECORD);
let previous_unclean = regular_or_missing(&path)?;
let own_record = serde_json::to_vec(&serde_json::json!({
"schema_version": 1,
"channel": "nightly-v1",
"version": version,
"commit": commit.filter(|value| !value.is_empty()),
}))?;
// A raced destination link is refused, not followed ([`write_atomic_no_follow`]).
write_atomic_no_follow(&path, &own_record)?;
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
}
pub fn previous_unclean(&self) -> bool {
self.previous_unclean
}
/// Controlled return. If an earlier session's interruption was detected but no window showed
/// it yet (a renderer failure before the app callback, including the CPU-retry handoff), the
/// record is left for the next owner to report; otherwise this is [`Self::complete`].
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
if self.previous_unclean && !unclean_notice_shown {
return Ok(());
}
self.complete()
}
/// Controlled event-loop completion includes a handled startup error/CPU handoff, not only
/// exit0. Clear before releasing primary IPC so a successor cannot miss record ownership.
/// An unwind, abort, forced exit or killed process never calls this method.
pub fn complete(self) -> io::Result<()> {
if !regular_or_missing(&self.path)? {
return Ok(());
}
let mut current = Vec::new();
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
if current != self.own_record {
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
}
std::fs::remove_file(&self.path)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
loop {
let path =
std::env::temp_dir().join(format!("cadcraft-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&path) {
Ok(()) => return Self(path),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
}
}
}
impl Drop for Fixture {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).unwrap();
}
}
#[test]
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
let fixture = Fixture::new();
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
assert!(stable.is_none() && !warning);
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
assert!(!warning);
let first = first.unwrap();
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
let fixture = Fixture::new();
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
assert!(!first.previous_unclean());
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
first.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
assert!(!unfinished.previous_unclean());
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
assert!(next.previous_unclean());
next.complete().unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
let fixture = Fixture::new();
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
// Renderer initialization failed before the app callback: no notice was shown.
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
assert!(failed.previous_unclean());
failed.finish(false).unwrap();
// The CPU retry (or the next start) still sees the interruption and shows it.
let retry = Session::begin(Some(&fixture.0), "cpu-retry", None).unwrap().unwrap();
assert!(retry.previous_unclean());
retry.finish(true).unwrap();
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
// Without an earlier interruption, a handled failure still clears normally.
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
assert!(!clean.previous_unclean());
clean.finish(false).unwrap();
assert!(!fixture.0.join(RECORD).exists());
}
#[test]
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
let fixture = Fixture::new();
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
// The exit hook (macOS quit: the only path that runs there).
finish_once(&shared, false);
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
assert!(!successor.previous_unclean());
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
finish_once(&shared, false);
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
successor.complete().unwrap();
}
#[test]
fn cleanup_never_removes_an_unknown_changed_record() {
let fixture = Fixture::new();
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
assert!(watch.complete().is_err());
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
}
#[test]
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
let fixture = Fixture::new();
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
assert!(data["commit"].is_null(), "missing provenance must not be invented");
watch.complete().unwrap();
}
#[test]
#[cfg(unix)]
fn reserved_state_aliases_do_not_modify_external_files() {
let fixture = Fixture::new();
let external = fixture.0.join("stable-document");
std::fs::write(&external, b"stable bytes").unwrap();
for name in [LEASE, RECORD] {
let alias = fixture.0.join(name);
std::os::unix::fs::symlink(&external, &alias).unwrap();
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
std::fs::remove_file(alias).unwrap();
}
}
}
+28 -10
View File
@@ -3,21 +3,39 @@
use std::io::Write as _;
use std::path::{Path, PathBuf};
/// A marker must be a file. Prove the data folder is writable before selecting it.
pub(crate) fn directory_in(exe_dir: &Path) -> std::io::Result<Option<PathBuf>> {
if !exe_dir.join("portable.txt").is_file() {
return Ok(None);
}
let data = exe_dir.join("CADCraftData");
std::fs::create_dir_all(&data)?;
let probe = data.join(format!(".portable-write-test-{}", std::process::id()));
// A byte, not just an empty file: a full drive can still make the file and refuse its data.
/// The marker file a portable copy ships beside `cadcraft.exe`.
pub(crate) const PORTABLE_MARKER: &str = "portable.txt";
/// The settings folder a portable copy keeps beside the executable.
pub(crate) const PORTABLE_DATA_DIR: &str = "CADCraftData";
/// The marker path, when `dir` holds a marker file (not a directory of that name).
pub(crate) fn portable_marker(dir: &Path) -> Option<PathBuf> {
let marker = dir.join(PORTABLE_MARKER);
marker.is_file().then_some(marker)
}
/// Prove `dir` is writable with the one exclusive probe this app uses: a fresh file holding a byte
/// (a full drive can still create an empty file and refuse its data) and its flush, removed again.
/// The nightly profile check and the portable check share it, so both test the same thing.
pub(crate) fn probe(dir: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let probe = dir.join(format!(".portable-write-test-{}", std::process::id()));
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
let written = file.write_all(&[0]).and_then(|()| file.sync_all());
drop(file);
let removed = std::fs::remove_file(&probe);
written?;
removed?;
removed
}
/// A marker must be a file. Prove the data folder is writable before selecting it.
pub(crate) fn directory_in(exe_dir: &Path) -> std::io::Result<Option<PathBuf>> {
if portable_marker(exe_dir).is_none() {
return Ok(None);
}
let data = exe_dir.join(PORTABLE_DATA_DIR);
probe(&data)?;
Ok(Some(data))
}
+70
View File
@@ -0,0 +1,70 @@
//! Set the immutable nightly Windows identity before any native window or COM service.
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
use std::sync::OnceLock;
#[derive(Clone, Debug, thiserror::Error)]
pub enum IdentityError {
#[error("{0}")]
Configuration(String),
}
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
configure(nightly && cfg!(windows), app_id, |id| {
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
RESULT
.get_or_init(|| {
#[cfg(windows)]
{
winsafe::SetCurrentProcessExplicitAppUserModelID(id)
.map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
if actual != id {
return Err("the native Windows identity did not match the selected nightly channel".into());
}
Ok(())
}
#[cfg(not(windows))]
{
let _ = id;
Ok(())
}
})
.clone()
})
.map_err(IdentityError::Configuration)
}
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
if explicit_nightly { set(app_id) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stable_does_not_call_the_explicit_identity_api() {
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
}
#[test]
fn nightly_applies_the_supplied_identity_once() {
let calls = std::cell::Cell::new(0);
configure(true, "nightly-id", |id| {
assert_eq!(id, "nightly-id");
calls.set(calls.get() + 1);
Ok(())
})
.unwrap();
assert_eq!(calls.get(), 1);
}
#[test]
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
let started = std::cell::Cell::new(false);
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
assert_eq!(result.unwrap_err(), "native identity refused");
assert!(!started.get());
}
}
+607
View File
@@ -0,0 +1,607 @@
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
use std::ffi::OsString;
use crate::portable::{PORTABLE_DATA_DIR, portable_marker};
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
// CADCraft also builds for the BSDs (packaging/freebsd): nightly-v1 is Windows, macOS and
// Linux only, as the shared nightlies publish.
_ => Err("nightly-v1 is not defined for this operating system".into()),
}
}
fn ignores_case(self) -> bool {
self != Self::Linux
}
}
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(format!("{label} must be absolute and contain no parent traversal"));
}
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
/// is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
let mut parent = path;
let mut missing = Vec::new();
loop {
match std::fs::symlink_metadata(parent) {
Ok(_) => break,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
}
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
}
}
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
for part in missing.into_iter().rev() {
resolved.push(part);
}
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
// A component that is not valid UTF-8 keeps its exact bytes: a lossy comparison would fold two
// different names into the same replacement character and call them one folder.
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str();
match (platform.ignores_case(), value.to_str()) {
(true, Some(text)) => OsString::from(text.to_lowercase()),
_ => value.to_os_string(),
}
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
/// Every stable CADCraft data root of this platform, plus the install folders and the running
/// install ([`installation_boundary`]).
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("CADCraft")))
.collect::<Result<Vec<_>, _>>()?;
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` under
// `%APPDATA%\ai.storyteller.cadcraft\data`), outside the roaming `CADCraft` folder.
roots.push(required_base(env, "APPDATA")?.join(EFRAME_APP_ID));
// The MSI's per-machine folder (cadcraft.wxs). A custom install folder is not known
// here; the executable's own folder is fenced below.
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("CADCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("cadcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/cadcraft", "/usr/local/bin/cadcraft", "/opt/cadcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.cadcraft"));
// Stable's eframe storage folder (`eframe::storage_dir`: window state, Options profile,
// UI and autosave prefs in `app.ron`), which is not the XDG settings folder above.
roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(EFRAME_APP_ID));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/CADCraft"),
library.join("Caches/CADCraft"),
library.join("Caches/ai.storyteller.cadcraft"),
// Stable's eframe storage folder (`eframe::storage_dir`: `app.ron` in Application
// Support), beside the settings folder env.rs uses.
library.join("Application Support").join(EFRAME_APP_ID),
library.join("Preferences/CADCraft"),
library.join("Preferences/ai.storyteller.cadcraft.plist"),
library.join("Saved Application State/ai.storyteller.cadcraft.savedState"),
home.join("Applications/CADCraft.app"),
PathBuf::from("/Applications/CADCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
// A regular file in a folder's place is not a folder: the readers and sweepers that follow would
// fail halfway, so refuse it while the profile is still being validated.
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.file_type().is_dir() => {
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
Ok(child)
}
/// Every existing entry directly in the profile (logs, settings and so on) must resolve inside it,
/// so a link there cannot point Nightly's writes at another app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and resolved path.
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
// marker only counts beside a CADCraft executable, so an unrelated portable.txt higher up
// (in a user folder or at a drive root) does not refuse the profile.
path.ancestors().enumerate().any(|(depth, ancestor)| {
portable_marker(ancestor).is_some() && (depth == 0 || ["cadcraft.exe", "cadcraft"].iter().any(|exe| ancestor.join(exe).is_file()))
}) || path.components().any(|component| match component {
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
Component::Normal(name) => name == PORTABLE_DATA_DIR,
_ => false,
})
}
/// The writable hook is the app's existing exclusive probe (`portable::probe`). Keeping it injected
/// lets filesystem boundary tests exercise the real policy without starting the app or changing
/// global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
let chosen = canonical_future(root)?;
// The deb/rpm CLI wrapper exports CADCRAFT_CONFIG_DIR at the folder this launch already owns (the
// GUI wrappers name the profile through `--profile-root` instead), so that value is inert:
// `env::apply_profile` sets the settings folder from the profile, not from the variable. Any
// other value would redirect Nightly's settings folder, so it is refused.
if let Some(configured) = env("CADCRAFT_CONFIG_DIR").filter(|v| !v.is_empty()) {
let configured = canonical_future(&absolute(PathBuf::from(configured), "CADCRAFT_CONFIG_DIR")?)?;
if !configured.starts_with(&chosen) {
return Err("nightly-v1 cannot be combined with CADCRAFT_CONFIG_DIR outside its own profile".into());
}
}
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty())
{
// A Flatpak's data folder and runtime socket namespace belong to its app id. The nightly
// bundle has an id of its own ([`NIGHTLY_FLATPAK_ID`], named by
// `packaging/linux/flatpak-bundle.sh`), so its profile is already the sandbox's own; any
// other instance is the stable app's (or another app's), whose socket this profile must
// not inherit.
if id.to_string_lossy() != NIGHTLY_FLATPAK_ID {
return Err("nightly-v1 cannot inherit another Flatpak app's instance; launch through the native Launcher".into());
}
}
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
return Err("the nightly root must not use a portable CADCraft installation or its CADCraftData settings folder".into());
}
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
entries_stay_inside(&chosen)?;
// Drawing Recovery reads, adopts, overwrites and sweeps entries. Never let its alias leave this
// private profile, including toward a stable portable directory not in our known roots.
private_subdirectory(&chosen, AUTOSAVE, "recovery folder")?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
private_subdirectory(&confirmed, AUTOSAVE, "recovery folder")?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
/// The app id of the nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`): the one Flatpak
/// instance whose sandbox is this channel's own. The window identity ([`crate::os_window`]) and the
/// bundle id differ on purpose, as they do for stable.
pub const NIGHTLY_FLATPAK_ID: &str = "ai.storyteller.cadcraft.nightly";
/// The app id eframe derives stable's storage folder from ([`crate::main`]'s `persistence_path`).
/// A profile that sits there would overwrite stable's `app.ron`, so its folder is fenced too.
const EFRAME_APP_ID: &str = "ai.storyteller.cadcraft";
/// The subfolder autosave and Drawing Recovery write ([`crate::main`], `<settings>/autosave`).
pub const AUTOSAVE: &str = "autosave";
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("cadcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/cadcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
validate_for(
platform,
root,
|key| self.get(key),
Some(&self.exe),
|dir| {
let probe = dir.join("exclusive-test-probe");
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
drop(file);
std::fs::remove_file(probe)
},
)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
}
}
impl Drop for Fixture {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
}
}
#[test]
fn portable_settings_from_another_install_are_refused_before_any_probe() {
let fixture = Fixture::new();
let stable_install = fixture.root.join("stable portable install");
let stable_data = stable_install.join(PORTABLE_DATA_DIR);
std::fs::create_dir_all(&stable_data).unwrap();
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
let probed = std::cell::Cell::new(false);
let result = validate_for(
platform,
candidate,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
assert!(!probed.get(), "reject portable data before a writable probe");
assert!(!stable_data.join("nested nightly").exists());
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
}
}
let private = fixture.root.join("CADCraftData-backup-name/nightly");
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
}
#[cfg(unix)]
#[test]
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
let fixture = Fixture::new();
let stable = fixture.home().join(".local/state/cadcraft/autosave");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
let private = fixture.root.join(format!("nightly-{index}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&target, private.join(AUTOSAVE)).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err(), "autosave must not escape the private profile or follow a dangling alias");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-self");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&private, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_err(), "autosave cannot treat all profile settings as recovery entries");
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-private");
let recovery = private.join("private-recovery");
std::fs::create_dir_all(&recovery).unwrap();
std::os::unix::fs::symlink(&recovery, private.join(AUTOSAVE)).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok());
assert_eq!(std::fs::canonicalize(private.join(AUTOSAVE)).unwrap(), recovery);
}
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/cadcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join(AUTOSAVE), platform));
assert!(overlaps(&root.join(AUTOSAVE), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("cadcraft-other"), platform));
}
}
#[test]
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
let mut fixture = Fixture::new();
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("cadcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
// Stable's eframe storage folder holds `app.ron`, so a profile may not sit at or inside it.
let storage = data.join(EFRAME_APP_ID);
std::fs::create_dir_all(&storage).unwrap();
std::fs::write(storage.join("app.ron"), b"stable window state").unwrap();
for candidate in [storage.clone(), storage.join("nightly")] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
assert_eq!(std::fs::read(storage.join("app.ron")).unwrap(), b"stable window state");
let nightly = data.join("ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/CADCraft Nightly.app/Contents/MacOS/CADCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let library = fixture.home().join("Library");
for suffix in [
"Application Support/CADCraft",
"Application Support/ai.storyteller.cadcraft",
"Caches/CADCraft",
"Caches/ai.storyteller.cadcraft",
"Preferences/CADCraft",
"Saved Application State/ai.storyteller.cadcraft.savedState",
] {
let stable = library.join(suffix);
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
assert!(!stable.exists());
}
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
// The bundle path and the Library fences fold case on macOS.
let cased = library.join("application support/cadcraft/nightly");
assert!(fixture.check(Platform::Mac, &cased).is_err());
}
#[test]
fn windows_fences_roaming_local_and_both_install_folders() {
let mut fixture = Fixture::new();
fixture.env.insert("ProgramFiles".into(), fixture.root.join("program files").into_os_string());
for stable in [
fixture.root.join("roaming/CADCraft"),
fixture.root.join("roaming/ai.storyteller.cadcraft"),
fixture.root.join("local/CADCraft"),
fixture.root.join("program files/ArtCraft/CADCraft"),
] {
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{}", candidate.display());
}
// Windows folder names ignore case.
assert!(fixture.check(Platform::Windows, &stable.with_file_name("cadcraft")).is_err());
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
}
let valid = fixture.root.join("local/ArtCraftLauncher/nightly/profiles/cadcraft");
assert_eq!(fixture.check(Platform::Windows, &valid).unwrap(), valid);
}
#[test]
fn config_dir_and_flatpak_are_refused() {
let mut fixture = Fixture::new();
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("custom").into_os_string());
let private = fixture.root.join("nightly-config");
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
assert!(!private.exists());
fixture.env.remove("CADCRAFT_CONFIG_DIR");
for inherited in ["ai.storyteller.cadcraft", "org.freedesktop.other"] {
fixture.env.insert("FLATPAK_ID".into(), inherited.into());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("Flatpak"), "{inherited}");
assert!(!private.exists());
}
}
/// The nightly bundle runs under an app id of its own, so its sandbox data folder is this
/// channel's data root; that one instance is accepted, and its profile stays inside it.
#[test]
fn the_nightly_flatpaks_own_instance_accepts_its_own_profile() {
let mut fixture = Fixture::new();
fixture.env.insert("FLATPAK_ID".into(), NIGHTLY_FLATPAK_ID.into());
let private = fixture.home().join(".var/app/ai.storyteller.cadcraft.nightly/data/cadcraft-nightly");
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
// Stable's Flatpak folder is still fenced even inside the nightly instance.
let stable = fixture.home().join(".var/app/ai.storyteller.cadcraft");
assert!(fixture.check(Platform::Linux, &stable).unwrap_err().contains("overlap"));
}
/// A Linux Launcher wrapper exports `CADCRAFT_CONFIG_DIR` at the profile it launches; that is
/// the folder this launch already owns, so it must not refuse the profile. Anything else is
/// still a redirect.
#[test]
fn a_wrapper_naming_the_profile_in_config_dir_is_accepted() {
let mut fixture = Fixture::new();
let private = fixture.root.join("nightly-wrapper");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), private.clone().into_os_string());
assert_eq!(fixture.check(Platform::Linux, &private).unwrap(), private);
let inside = private.join("nested");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), inside.clone().into_os_string());
assert!(fixture.check(Platform::Linux, &inside).is_ok(), "a folder inside the profile is the profile's own");
fixture.env.insert("CADCRAFT_CONFIG_DIR".into(), fixture.root.join("elsewhere").into_os_string());
assert!(fixture.check(Platform::Linux, &private).unwrap_err().contains("CADCRAFT_CONFIG_DIR"));
}
#[test]
fn a_profile_that_cannot_be_written_is_refused_without_a_stable_fallback() {
let fixture = Fixture::new();
let private = fixture.root.join("nightly-unwritable");
let result = validate_for(Platform::Linux, &private, |key| fixture.get(key), Some(&fixture.exe), |_| Err(std::io::Error::other("read-only")));
assert!(result.unwrap_err().contains("not writable"));
assert!(private.exists(), "the profile was created before the probe, and nothing was written into stable");
assert!(!fixture.home().join(".config/cadcraft").exists());
}
#[cfg(unix)]
#[test]
fn a_dangling_entry_inside_the_profile_is_refused_before_writes() {
let fixture = Fixture::new();
let outside = fixture.root.join("outside");
std::fs::create_dir_all(&outside).unwrap();
let private = fixture.root.join("nightly-dangling");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(outside.join("missing"), private.join("logs")).unwrap();
let probed = std::cell::Cell::new(false);
let result = validate_for(
Platform::Linux,
&private,
|key| fixture.get(key),
Some(&fixture.exe),
|_| {
probed.set(true);
Ok(())
},
);
assert!(result.is_err());
assert!(!probed.get());
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
}
}
+10 -5
View File
@@ -100,25 +100,30 @@ pub fn absolute(paths: &[PathBuf]) -> Option<Vec<String>> {
/// Decide what this launch does. `files` are absolute ([`absolute`]); `may_hand_off` is false
/// when the launch asked for anything besides opening files, so it gets its own window.
pub fn claim(files: &[String], may_hand_off: bool) -> Claim {
/// `profile` is the Nightly profile root: its socket then lives in the profile, so a nightly launch
/// can never hand its files to a running stable CADCraft (and the reverse).
pub fn claim(files: &[String], may_hand_off: bool, profile: Option<&std::path::Path>) -> Claim {
#[cfg(windows)]
{
match socket_path() {
match socket_path(profile) {
Some(path) => claim_at(&path, files, may_hand_off),
None => Claim::Alone,
}
}
#[cfg(not(windows))]
{
let _ = (files, may_hand_off);
let _ = (files, may_hand_off, profile);
Claim::Alone
}
}
/// The socket in `%LOCALAPPDATA%\CADCraft`.
/// The socket in `%LOCALAPPDATA%\CADCraft`, or `<profile>\single-instance` for a Nightly launch.
#[cfg(windows)]
fn socket_path() -> Option<std::path::PathBuf> {
fn socket_path(profile: Option<&std::path::Path>) -> Option<std::path::PathBuf> {
let name = socket_name(std::env::var("SESSIONNAME").ok().as_deref());
if let Some(root) = profile {
return Some(root.join("single-instance").join(name));
}
std::env::var_os("LOCALAPPDATA").filter(|v| !v.is_empty()).map(|d| std::path::PathBuf::from(d).join("CADCraft").join(name))
}
+28
View File
@@ -0,0 +1,28 @@
# App icons
The stable icon is `cadcraft-1024.png` (the padded master). The packaging scripts derive the other
sizes from it:
| File | Where it goes |
|---|---|
| `cadcraft.ico` | `cadcraft.exe` resources and the MSI shortcuts (Windows) |
| `cadcraft.icns` | `CADCraft.app/Contents/Resources` (macOS) |
| `cadcraft-256.png` | the window and About icon on Linux, and the AppImage/menu entry |
| `hicolor/<size>/apps/ai.storyteller.cadcraft.png` | the freedesktop icon theme, so docks and menus find the app by its id |
## Nightly
The Nightly channel has its own icon, so a nightly window, taskbar button and bundle are not
mistaken for the stable app. It is the same mark — foreground unchanged, no badge — on a deeper
background, derived from the stable 1024 master (never an upscale):
| File | Where it goes |
|---|---|
| `cadcraft-nightly-1024.png` | the master the `.icns` is generated from |
| `cadcraft-nightly.png` | the Linux nightly tar (`cadcraft-nightly.png` beside the executable) |
| `cadcraft-nightly.ico` | `cadcraft.exe` of a nightly build (`build.rs`) |
| `cadcraft-nightly.icns` | `CADCraft Nightly.app/Contents/Resources`, `CFBundleIconFile cadcraft-nightly` |
`nightly-provenance.json` records the exact transform (which pixels changed, and from which
colour), so the nightly icon can be regenerated or reviewed against the stable one. Regenerating
either set is a deliberate change: check the result at 16 px before replacing a file.
Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

+24
View File
@@ -0,0 +1,24 @@
{
"schema": "craft-nightly-icon-provenance/v1",
"app": "cadcraft",
"channel": "nightly-v1",
"source": {
"master": "assets/app-icon/cadcraft-1024.png",
"note": "The stable 1024 master, padded as its designer made it; the nightly files are derived from it, never upscaled from a smaller icon."
},
"transform": {
"summary": "The app mark (near-black strokes, cream highlights and their antialiasing) is copied unchanged; only the background square is deepened.",
"background": {
"from": "#14a3c7",
"to": "#0c657b",
"rule": "A pixel whose channel distance from the stable background is at most 180 is scaled by 0.62; fully transparent pixels and every other colour are left as they were."
}
},
"outputs": {
"cadcraft-nightly.png": "256 px PNG of the icon the Linux tar carries as cadcraft-nightly.png",
"cadcraft-nightly-1024.png": "the padded 1024 master the icns is generated from",
"cadcraft-nightly.ico": "16, 24, 32, 48, 64, 128 and 256 px PNG entries, the Windows executable and window icon",
"cadcraft-nightly.icns": "icp4 icp5 icp6 ic07 ic08 ic09 ic10 PNG entries for the macOS bundle (CFBundleIconFile cadcraft-nightly)"
},
"not_done_here": "No badge, crescent or N was added, and the stable cadcraft.png/.ico/.icns files are untouched."
}
+7 -1
View File
@@ -536,7 +536,13 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) {
let left = Rect::from_min_size(r.min, vec2(300.0, r.height()));
p.rect_filled(left, 0.0, t.chrome_dark);
p.rect_filled(Rect::from_min_max(pos2(left.right(), r.top()), r.max), 0.0, t.chrome);
p.text(pos2(left.left() + 34.0, left.top() + 70.0), egui::Align2::LEFT_CENTER, crate::tl!("CADCraft"), egui::FontId::proportional(28.0), t.text);
p.text(
pos2(left.left() + 34.0, left.top() + 70.0),
egui::Align2::LEFT_CENTER,
crate::os_window::drawn_name(),
egui::FontId::proportional(28.0),
t.text,
);
p.text(
pos2(left.left() + 34.0, left.top() + 98.0),
egui::Align2::LEFT_CENTER,
+2 -1
View File
@@ -353,7 +353,8 @@ fn about(ctx: &egui::Context, open: &mut bool) {
1 => crate::credits::contributors_ui(ui),
2 => crate::credits::models_ui(ui),
_ => {
ui.heading(crate::tl!("CADCraft"));
// The channel name, so a Nightly bug report names the channel it came from.
ui.heading(crate::os_window::drawn_name());
ui.label(crate::tf!("Version {version}", version = env!("CARGO_PKG_VERSION")));
ui.label(crate::tl!("Computer-aided design and drafting: an open-source, clean-room CAD application written in pure Rust."));
ui.add_space(6.0);
+8
View File
@@ -62,6 +62,7 @@ pub mod menus;
pub mod modal;
pub mod opening;
pub mod options;
pub mod os_window;
pub mod palettes;
pub mod parametric;
pub mod plotstyles;
@@ -245,8 +246,15 @@ pub struct Services {
pub no_file_system: bool,
/// Pick a `.pgp` alias file, starting in the folder given (the last import's).
pub pick_pgp: Option<Box<dyn Fn(Option<&str>) -> Option<String>>>,
/// The app binary's last step as the app leaves, run once at the end of its `on_exit`. On
/// macOS every quit ends the process inside AppKit's terminate, after `on_exit`, so code
/// after `eframe::run_native` never runs there (the Nightly session record is finished here).
pub at_exit: Option<AtExitFn>,
}
/// Runs once when the app leaves ([`Services::at_exit`]).
pub type AtExitFn = Box<dyn FnOnce()>;
/// The file dialog to show: Open, Save with the suggested file name, APPLOAD's `.lsp` picker or
/// ALIASEDIT's `.pgp` picker, starting in the given folder (empty for the default one).
#[derive(Clone, Debug, PartialEq, Eq)]
+86
View File
@@ -0,0 +1,86 @@
//! The app id and the channel name every CADCraft OS window and caption carries, plus the
//! startup identity the desktop selects before any UI service exists.
//!
//! The identity is immutable once selected: a stable build and a nightly build never share a
//! window class, AUMID or app id, so docks, window rules and the taskbar keep them apart.
/// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon.
pub const APP_ID: &str = "ai.storyteller.cadcraft";
/// Immutable startup identity. The desktop selects it before any UI/runtime service is created.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LaunchIdentity {
Stable,
NightlyV1,
}
static IDENTITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
pub fn select_identity(identity: LaunchIdentity) -> Result<(), String> {
let value = match identity {
LaunchIdentity::Stable => 1,
LaunchIdentity::NightlyV1 => 2,
};
IDENTITY
.compare_exchange(0, value, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire)
.map(|_| ())
.map_err(|_| "the window launch identity was already selected".to_string())
}
pub fn identity() -> LaunchIdentity {
if IDENTITY.load(std::sync::atomic::Ordering::Acquire) == 2 { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }
}
pub const fn id_for(identity: LaunchIdentity) -> &'static str {
match identity {
LaunchIdentity::Stable => APP_ID,
LaunchIdentity::NightlyV1 => "ai.storyteller.cadcraft.nightly-v1",
}
}
pub fn app_id() -> &'static str {
id_for(identity())
}
pub const fn name_for(identity: LaunchIdentity) -> &'static str {
match identity {
LaunchIdentity::Stable => "CADCraft",
LaunchIdentity::NightlyV1 => "CADCraft Nightly",
}
}
/// The drawn caption for the window ([`crate::chrome`]): stable draws its name exactly as before.
pub fn drawn_name() -> &'static str {
name_for(identity())
}
/// Whether the stable-only services (updater, control server, agent links) may run this launch.
pub const fn stable_services_for(identity: LaunchIdentity) -> bool {
matches!(identity, LaunchIdentity::Stable)
}
pub fn stable_services_allowed() -> bool {
stable_services_for(identity())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nightly_identity_is_distinct_and_never_enables_stable_services() {
assert_eq!(id_for(LaunchIdentity::Stable), APP_ID);
assert_ne!(id_for(LaunchIdentity::NightlyV1), APP_ID);
assert_eq!(name_for(LaunchIdentity::Stable), "CADCraft");
assert_eq!(name_for(LaunchIdentity::NightlyV1), "CADCraft Nightly");
assert!(stable_services_for(LaunchIdentity::Stable));
assert!(!stable_services_for(LaunchIdentity::NightlyV1));
}
#[test]
fn the_window_id_differs_from_the_package_identity() {
// Two strings on purpose: the package/bundle id is `...cadcraft.nightly`, the window's is
// `...cadcraft.nightly-v1` (see the nightly contract).
assert_eq!(id_for(LaunchIdentity::NightlyV1), "ai.storyteller.cadcraft.nightly-v1");
}
}
+91
View File
@@ -0,0 +1,91 @@
# Windows, Linux and macOS release-ref nightly: supervised manual go-live
**Enabled for supervised manual runs, not yet qualified.** The producer (`nightly.yml`, main) and the
signer (`nightly-sign.yml`, release) keep only their exact context guards and run when one of the reviewed
manual actors dispatches them. There is no schedule yet. The installed policy
[`.github/nightly-signing-policy.json`](../.github/nightly-signing-policy.json) is the v3
policy. Once `nightly.yml` lands on `main`, populate `producer_workflow_id` before promoting the
policy to `release`, read with:
```bash
gh api repos/storytold/cadcraft/actions/workflows/nightly.yml --jq .id
```
The callers pass no platform secrets. The unsigned reusable caller's maximum OIDC/attestation
permissions are for its isolated attester; its compiler narrows to contents and Actions read
only, with no OIDC, attestation write, release environment or platform signing secrets.
Shared tooling is pinned to `605d58766e8f536564da8fc81d3676ac86816dea`, the craft-common-actions
main commit that merged [#339](https://github.com/storytold/craft-common-actions/pull/339) (bounded
lineage compares and an issue reread at the end of candidate admission) on top of
[#342](https://github.com/storytold/craft-common-actions/pull/342) (policy v3, the `platforms` input
and the Linux and macOS legs). Both callers name it in `uses` and `tooling-revision`. A pin is
reviewed source availability, not provider, queue, native signing or crypto qualification.
Existing stable workflows are unchanged.
**First runs.** The first runs are manual dispatches in this order: `nightly.yml` on main (only a
listed manual actor passes the producer's plan step), then `nightly-sign.yml` on `release` with that
producer run ID and attempt, by a listed manual actor.
**Manual actors.** `bflatastic`, `dylanmtaylor`, `echelon`, `FredApps` and `skylartaylor`, in the
producer's `manual-actors` and the policy's `manual_actors`. The list mirrors the release-managers
team (id 19837241), leaving out `echelon-robot`; update it by PR in both places when the team
changes.
**Admission timing.** The candidate check reads the newest CI run on the candidate commit and
main's latest finished Sonar analysis, so when to dispatch matters:
- The candidate must be main's latest finished Sonar analysis. Pick a quiet main, wait for its
CI and SonarCloud analysis to finish green, then dispatch the producer and, once it succeeds,
the signer, before another main push lands a newer analysis.
**Platform rows.** The producer caller lists
`platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'` on its single job: one producer
run builds every listed platform for one all-or-nothing release (one failed or
skipped platform stops that night's release, Windows included), and the release-ref signer admits
platforms only from the protected policy, so there is no separate Linux or macOS caller job and
the signer caller has no platform input.
## Installed policy values and their sources
Read on 2026-11-24; re-read anything that may have moved (and populate `producer_workflow_id` after `nightly.yml` lands on `main`) before the policy is promoted to `release`.
| Field | Value | Source |
|---|---|---|
| `repository_id` | `1408289866` | `gh api repos/storytold/cadcraft --jq .id` |
| `producer_workflow_id` | `null` (pending main registration) | `gh api repos/storytold/cadcraft/actions/workflows/nightly.yml --jq .id` once `nightly.yml` reaches `main` |
| `producer_tooling_revision`, `signer_tooling_revision`, `producer_workflow_ref` | `605d5876…` (craft-common-actions #339) | The callers' pin |
| `manual_actors` / `automatic_signer_actors` | the five release managers / `[]` | release-managers team (id 19837241) members who can push; equals the producer caller's `manual-actors` |
| `max_age_seconds`, `max_artifact_bytes` | `86400`, `2147483648` | Go-live checklist |
| `platforms` | three rows | StoryTold / Learning Machines stable signing identities (`windows-x86_64`, `linux-x86_64`, `macos-aarch64`) |
| `candidate_policy.required_workflows` | CI (`ci.yml`, workflow `380135820`), `gate / gate (ubuntu-24.04)` | Workflow list API and recent main push runs |
| `candidate_policy.sonar` | `storytold` / `storytold_cadcraft`, app `12526` | `sonar-project.properties`; the SonarCloud check on main commits |
| Sonar `issue_types` / `debt` | `VULNERABILITY`; `[]` | Refresh before promotion to `release` if any unresolved main vulnerabilities exist |
The candidate check refuses whenever main's unresolved vulnerability set differs from `debt`, whether
an issue is new or fixed, and whenever a required condition fails or a listed CI job is renamed. Refresh
those values in the same reviewed change that promotes the policy to `release`.
## Ownership and interface
- `.github/workflows/nightly.yml`: default-main registration of the unsigned producer, named
`CADCraft unsigned nightly`, enabled for manual dispatch by `manual-actors`; no signing secrets
may be passed or inherited.
- `.github/workflows/nightly-sign.yml`: top-level release registration, enabled for manual dispatch,
and identical on main and release after reviewed promotion. It rejects wrong repository/event/actual branch,
including same-name tags. Its constant whole-run concurrency (`cadcraft-nightly-release`) is distinct from stable,
cancellation is off and `queue: max` must be hosted-qualified. The caller itself passes no
credentials; only the shared callee's sign jobs bind the `release` environment.
- Shared reusable entrypoints are `nightly-unsigned.yml` and `nightly-release.yml` in
`storytold/craft-common-actions`. Both must resolve to a **real reviewed public immutable
commit**; the defining workflow SHA and tooling input must match.
- Ported from `storytold/photocraft#16594` (authored by `@skylartaylor`).
## Local regression checks
`python3 packaging/nightly-release-tests.py` verifies:
- Both callers share one immutable 40-hex commit pin in `uses` and `tooling-revision`.
- Both callers keep their exact context guards (every `if:` form and continuation line is read).
- No nightly schedule is registered.
- No cache actions, cache setup options, `environment:`, or `secrets` appear in the callers.
- Signer root serialization (`cadcraft-nightly-release`, `queue: max`, `cancel-in-progress: false`) stays literal.
- Manual actors are exactly the five release managers in both `nightly.yml` and `.github/nightly-signing-policy.json`.
- The installed policy's v3 schema, repository identity, platforms, bounds, required CI workflow, and SonarCloud project identity match the repository and callers.
+23
View File
@@ -9,3 +9,26 @@ This file describes how CADCraft is released.
- **Windows installer:** `packaging/windows/cadcraft.wxs` (WiX v5 + `WixToolset.UI.wixext`). Its wizard has a Shortcuts page: the Start Menu shortcut is always created, the desktop shortcut is opt-in (`DESKTOPSHORTCUT=1` for silent installs, `DESKTOPSHORTCUT=0` drops it on an upgrade; otherwise upgrades keep the previous choice).
- **File types:** `.dxf` and `.dwg` (macOS document types, Windows "Open with", Linux MIME types).
- **Local packaging test:** `packaging/macos/package.sh` (ad-hoc signed DMG), `packaging/linux/package.sh`, `packaging/web/package.sh`.
## Release-ref nightly
CADCraft's Windows, Linux and macOS nightly is documented in
[`nightly-release-preparation.md`](nightly-release-preparation.md). `.github/workflows/nightly.yml`
and `nightly-sign.yml` are enabled for **supervised manual runs only** by the reviewed release
managers: there is no schedule, and there is no automatic transport yet — a run is dispatched by
hand, and the completion step is manual too. No platform secret is granted to the producer. Stable `release.yml`, its triggers, environment and secrets are unchanged.
The signer-owned files (`.github/workflows/nightly-sign.yml`,
`.github/nightly-signing-policy.json`, `packaging/windows/sign.ps1`, the macOS nightly signing
scripts `nightly-sign.sh`/`nightly-verify.sh`/`nightly-lib.sh`/`import-cert.sh` and their
entitlements, `.github/nightly-linux-signing-key.asc`, and every transitive reusable pin) travel
on a reviewed `main` → `release` sync and are compared against the previous trusted release, not a
manifest from `main`. Nightlies share the existing Windows signing identity with stable, so a
suspected key compromise affects both channels: stop nightlies too, and have the identity's owner
revoke/rotate it.
Before the first run, the shared `craft-common-actions` caller must admit CADCraft (its jobs are
still gated on PhotoCraft), and the app-side flavor must be in the built channel: a nightly binary
is refused without `--launch-profile nightly-v1 --profile-root <dir>`, so every Launcher wrapper
must pass them (see the preparation doc).
+53 -7
View File
@@ -17,6 +17,12 @@ set -euo pipefail
. "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
HERE="$ROOT/packaging/linux"
APP_ID=ai.storyteller.cadcraft
FLATPAK_ID="$APP_ID"
# The remote indexes both app IDs on the stable ref branch; IDs isolate installations.
FLATPAK_BRANCH=stable
if [[ "${CADCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
FLATPAK_ID="$APP_ID.nightly"
fi
FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo
TEST=1
@@ -52,29 +58,69 @@ rm -rf "$WORK"
mkdir -p "$WORK/stage"
tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1
[[ -x "$WORK/stage/bin/cadcraft" ]] || { echo "error: $TARBALL has no bin/cadcraft" >&2; exit 1; }
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$APP_ID.yml"
if [[ "$FLATPAK_ID" != "$APP_ID" ]]; then
mv "$WORK/stage/bin/cadcraft" "$WORK/stage/bin/cadcraft-bin"
cat >"$WORK/stage/bin/cadcraft" <<'WRAPPER'
#!/bin/sh
# The bundled nightly starts the GUI with this channel's own launch profile. The sandbox's own
# data folder belongs to the nightly app id, so the profile stays inside it.
set -eu
case "${1-}" in
# The Launcher already named the profile (its version query does too); never pass it twice. A
# plain version query answers without touching any profile.
--launch-profile | --version | -V) exec /app/libexec/cadcraft "$@" ;;
esac
profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.var/app/ai.storyteller.cadcraft.nightly/data}"
exec /app/libexec/cadcraft \
--launch-profile nightly-v1 --profile-root "$profile_base/cadcraft-nightly" -- "$@"
WRAPPER
chmod 755 "$WORK/stage/bin/cadcraft"
sed -e "s|^Icon=$APP_ID$|Icon=$FLATPAK_ID|" \
-e "s|^Name=CADCraft$|Name=CADCraft Nightly|" \
-e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.cadcraft.nightly-v1|' \
-e '/^MimeType=/d' \
"$WORK/stage/share/applications/$APP_ID.desktop" >"$WORK/stage/share/applications/$FLATPAK_ID.desktop"
rm -f "$WORK/stage/share/applications/$APP_ID.desktop"
sed -e "s|<id>$APP_ID</id>|<id>$FLATPAK_ID</id>|g" \
-e "s|<name>CADCraft</name>|<name>CADCraft Nightly</name>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$FLATPAK_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$FLATPAK_ID</icon>|g" \
"$WORK/stage/share/metainfo/$APP_ID.metainfo.xml" >"$WORK/stage/share/metainfo/$FLATPAK_ID.metainfo.xml"
rm -f "$WORK/stage/share/metainfo/$APP_ID.metainfo.xml"
mv "$WORK/stage/share/mime/packages/$APP_ID.xml" "$WORK/stage/share/mime/packages/$FLATPAK_ID.xml"
rm -rf "$WORK/stage/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/cadcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
install -Dm644 "$NIGHTLY_ICON" \
"$WORK/stage/share/icons/hicolor/256x256/apps/$FLATPAK_ID.png"
sed -e "s|ai\.storyteller\.cadcraft|$FLATPAK_ID|g" \
-e 's|- install -Dm755 bin/cadcraft /app/bin/cadcraft|- install -Dm755 bin/cadcraft-bin /app/libexec/cadcraft\n - install -Dm755 bin/cadcraft /app/bin/cadcraft|' \
"$HERE/flatpak/$APP_ID.bundle.yml" >"$WORK/$FLATPAK_ID.yml"
else
cp "$HERE/flatpak/$APP_ID.bundle.yml" "$WORK/$FLATPAK_ID.yml"
fi
flatpak remote-add --user --if-not-exists flathub "$FLATHUB"
# --disable-rofiles-fuse: no FUSE in containers and CI runners.
flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --force-clean \
--default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml"
--default-branch="$FLATPAK_BRANCH" --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$FLATPAK_ID.yml"
OUT="$DIST/$BASENAME.flatpak"
# --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing.
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable
flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$FLATPAK_ID" "$FLATPAK_BRANCH"
echo "wrote $OUT"
if [[ "$OCI" = 1 ]]; then
OUT_OCI="$DIST/$BASENAME-oci"
rm -rf "$OUT_OCI"
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable
flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$FLATPAK_ID" "$FLATPAK_BRANCH"
echo "wrote OCI layout to $OUT_OCI"
fi
if [[ "$TEST" = 1 ]]; then
flatpak install --user -y --noninteractive --reinstall "$OUT"
flatpak info --user "$APP_ID"
flatpak run --command=cadcraft-cli "$APP_ID" --version
flatpak run --command=sh "$APP_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/256x256/apps'
flatpak info --user "$FLATPAK_ID"
flatpak run --command=cadcraft-cli "$FLATPAK_ID" --version
flatpak run --command=sh "$FLATPAK_ID" -c 'ls /app/share/applications /app/share/metainfo /app/share/mime/packages /app/share/icons/hicolor/*/apps'
fi
echo "==> done"
ls -lh "$OUT"
+8 -5
View File
@@ -3,7 +3,7 @@
# exports VERSION and NFPM_ARCH.
#
# nfpm package -f packaging/linux/nfpm.yaml -p deb -t dist/release/
name: cadcraft
name: ${NFPM_NAME}
arch: ${NFPM_ARCH}
platform: linux
version: ${VERSION}
@@ -55,12 +55,15 @@ overrides:
- xdg-desktop-portal
contents:
- src: ${STAGE}/usr/bin/cadcraft
dst: /usr/bin/cadcraft
- src: ${STAGE}/usr/bin/${NFPM_BIN}
dst: /usr/bin/${NFPM_BIN}
file_info: { mode: 0755 }
- src: ${STAGE}/usr/bin/cadcraft-cli
dst: /usr/bin/cadcraft-cli
- src: ${STAGE}/usr/bin/${NFPM_CLI}
dst: /usr/bin/${NFPM_CLI}
file_info: { mode: 0755 }
- src: ${STAGE}/usr/lib/
dst: /usr/lib/
type: tree
- src: ${STAGE}/usr/share/
dst: /usr/share/
type: tree
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# The Arch Nightly launcher: the GUI starts with this channel's own launch profile, so the AUR
# package never reads or writes stable's settings, window state or recovery files.
set -eu
real_bin="$(dirname "$0")/.cadcraft-nightly/cadcraft"
case "${1-}" in
# The Launcher already named the profile (its version query does too); never pass it twice. A
# plain version query answers without touching any profile.
--launch-profile | --profile-root | --version | -V) exec "$real_bin" "$@" ;;
esac
profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}"
exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_base/cadcraft-nightly" -- "$@"
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env bash
# Validate the staged Arch launcher without building or opening CADCraft.
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
work="$(mktemp -d)"
trap 'rm -rf "$work"' EXIT
stage="$work/source"
dst="$work/dist"
base=cadcraft-0.0.1-nightly.1-linux-x86_64
mkdir -p "$stage/bin" "$dst" "$work/extract"
# A local argv/env recorder stands in for the compiled binaries. It never opens a UI.
cat >"$stage/bin/cadcraft" <<'RECORDER'
#!/bin/sh
printf 'config=<%s>\n' "${CADCRAFT_CONFIG_DIR:-}"
for arg in "$@"; do
printf '<%s>\n' "$arg"
done
RECORDER
chmod 755 "$stage/bin/cadcraft"
cp "$stage/bin/cadcraft" "$stage/bin/cadcraft-cli"
bash "$HERE/nightly-arch-tar.sh" "$stage" "$work/stage" "$dst" "$base"
tar -xzf "$dst/$base.tar.gz" -C "$work/extract"
bin="$work/extract/$base/bin"
# Simulate the existing Arch bin-tree copy and public launcher rename.
mkdir -p "$work/installed"
cp -R "$bin" "$work/installed/bin"
bin="$work/installed/bin"
mv "$bin/cadcraft" "$bin/cadcraft-nightly"
mv "$bin/cadcraft-cli" "$bin/cadcraft-nightly-cli"
test ! -e "$stage/bin/.cadcraft-nightly"
cmp "$stage/bin/cadcraft" "$bin/.cadcraft-nightly/cadcraft"
cmp "$stage/bin/cadcraft-cli" "$bin/cadcraft-nightly-cli"
export HOME="$work/home with space"
unset XDG_DATA_HOME CADCRAFT_CONFIG_DIR
expect() {
expected="$1"
shift
actual=$(PATH="$bin:$PATH" cadcraft-nightly "$@")
if [[ "$actual" != "$expected" ]]; then
printf 'expected:\n%s\nactual:\n%s\n' "$expected" "$actual" >&2
exit 1
fi
}
# The launcher names the profile the flavor's way and keeps every argument after the delimiter.
launch() {
local profile="$1"
shift
printf 'config=<>\n<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s>\n<-->\n' "$profile"
for file in "$@"; do printf '<%s>\n' "$file"; done
}
expect "$(launch "$HOME/.local/share/cadcraft-nightly" 'sample.dxf')" sample.dxf
export XDG_DATA_HOME="$work/xdg with space"
expect "$(launch "$XDG_DATA_HOME/cadcraft-nightly" 'drawing with spaces.dxf' '--other-name.dxf')" \
'drawing with spaces.dxf' '--other-name.dxf'
# A version query answers with the plain argument, so it needs no profile at all.
expect "$(printf 'config=<>\n<--version>\n')" --version
expect "$(printf 'config=<>\n<-V>\n')" -V
# The Launcher's own form is passed through once, never doubled.
expect "$(printf 'config=<>\n<--launch-profile>\n<nightly-v1>\n<--profile-root>\n<%s>\n<--version>\n' "$work/launcher root")" \
--launch-profile nightly-v1 --profile-root "$work/launcher root" --version
# A CADCRAFT_CONFIG_DIR from an older wrapper is neither honoured nor rewritten: the profile is the
# launcher's, and the flavor refuses a variable outside it.
CADCRAFT_CONFIG_DIR="$work/explicit with space" \
expect "$(launch "$XDG_DATA_HOME/cadcraft-nightly" 'sample.dxf' | sed '1s|.*|config=<'"$work"'/explicit with space>|')" \
sample.dxf
echo "PASS: Arch Nightly handoff starts the flavor's profile and preserves launch arguments"
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Stage the CADCraft Nightly-only handoff for the Arch packager.
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
source_tree="$1"
work="$2"
destination="$3"
basename="$4"
stage="$work/$basename"
mkdir -p "$work"
cp -R "$source_tree" "$stage"
mkdir "$stage/bin/.cadcraft-nightly"
mv "$stage/bin/cadcraft" "$stage/bin/.cadcraft-nightly/cadcraft"
cp "$here/nightly-arch-launch.sh" "$stage/bin/cadcraft"
chmod 755 "$stage/bin/cadcraft"
tar -C "$work" -czf "$destination/$basename.tar.gz" "$basename"
echo "wrote $destination/$basename.tar.gz"
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
# The launcher inside CADCraft Nightly's flat tar. The tar's layout is the kit's: `cadcraft` is this
# script and `cadcraft-bin` the GUI beside it. An unpacked copy starts the GUI with this channel's
# own launch profile, so it never reads or writes stable's settings, window state or recovery files.
set -eu
here="$(dirname "$0")"
real_bin="$here/cadcraft-bin"
# Every path is resolved beside this script: there is no relative fallback, so a copy unpacked
# anywhere cannot be pointed at another program by its parent folder.
if [ ! -f "$real_bin" ] || [ -L "$real_bin" ]; then
echo "error: cadcraft-bin is missing beside $0" >&2
exit 2
fi
case "${1-}" in
# The Launcher already named the profile (its version query does too); never pass it twice. A
# plain version query answers without touching any profile.
--launch-profile | --profile-root | --version | -V) exec "$real_bin" "$@" ;;
esac
profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}"
exec "$real_bin" --launch-profile nightly-v1 --profile-root "$profile_base/cadcraft-nightly" -- "$@"
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env bash
# App-owned GUI-only nightly tar: no FUSE/AppImage, CLI, association or install hooks.
set -euo pipefail
ARCH=
while [[ $# -gt 0 ]]; do
case "$1" in
--arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;;
-h|--help) echo 'Usage: nightly.sh --arch x86_64'; exit 0 ;;
*) echo "unsupported nightly argument: $1" >&2; exit 2 ;;
esac
done
[[ "$ARCH" == x86_64 && "$(uname -s)" == Linux ]] || { echo 'only native Linux x86_64 nightly packaging is supported' >&2; exit 2; }
# shellcheck source=../nightly-common.sh
. "$(dirname "${BASH_SOURCE[0]}")/../nightly-common.sh"
nightly_init linux "$ARCH" x86_64-unknown-linux-gnu
OUTPUT="$DIST/cadcraft-$VERSION-linux-x86_64-nightly.tar.gz"
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive'
nightly_build_gui
STAGE="$NIGHTLY_WORK/stage"
mkdir -p "$STAGE"
# The kit's flat tar layout: `cadcraft` is the launcher people run and `cadcraft-bin` the GUI it
# starts with this channel's own profile, so an unpacked copy never writes stable's settings.
cp "$NIGHTLY_GUI" "$STAGE/cadcraft-bin"
chmod 755 "$STAGE/cadcraft-bin"
cp "$ROOT/packaging/linux/nightly-launch.sh" "$STAGE/cadcraft"
chmod 755 "$STAGE/cadcraft"
cp "$ROOT/assets/app-icon/cadcraft-nightly.png" "$STAGE/cadcraft-nightly.png"
nightly_copy_notices "$STAGE"
# The private mktemp cwd is the helper authority root, not a CLI path parent.
(cd "$NIGHTLY_WORK" && python3 "$ROOT/packaging/nightly-archive.py" linux stage archive.tar.gz)
nightly_publish_archive "$NIGHTLY_WORK/archive.tar.gz" "$OUTPUT"
+186 -9
View File
@@ -7,7 +7,7 @@
# $DIST/cadcraft-<version>-linux-<arch>.rpm Fedora, openSUSE, RHEL, ...
# $DIST/cadcraft-<version>-linux-<arch>.tar.gz plain FHS-style tree (bin/, share/)
#
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"]
# Usage: packaging/linux/package.sh [--skip-build] [--formats "appimage deb rpm tar"] [--arch-tar-dir DIRECTORY]
#
# Needs: cargo; nfpm for deb/rpm (https://nfpm.goreleaser.com); appimagetool for the AppImage
# (downloaded into $CARGO_TARGET_DIR if missing). Build on an old distro (CI: Ubuntu 22.04,
@@ -21,10 +21,16 @@ APP_ID=ai.storyteller.cadcraft
SKIP_BUILD=0
FORMATS="appimage deb rpm tar"
ARCH_TAR_DIR=
while [[ $# -gt 0 ]]; do
case "$1" in
--skip-build) SKIP_BUILD=1; shift ;;
--formats) FORMATS="$2"; shift 2 ;;
--arch-tar-dir)
[[ -n "${2:-}" ]] || { echo "error: --arch-tar-dir needs a directory" >&2; exit 2; }
ARCH_TAR_DIR="$2"
shift 2
;;
-h | --help) sed -n '2,17p' "$0"; exit 0 ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
@@ -40,9 +46,20 @@ case "$ARCH" in
*) echo "unsupported architecture $ARCH" >&2; exit 2 ;;
esac
export CADCRAFT_MAINTAINER="${CADCRAFT_MAINTAINER:-CADCraft maintainers <[email protected]>}"
IS_NIGHTLY=0
if [[ "${CADCRAFT_BUILD_CHANNEL:-}" == nightly-v1 || "$VERSION" == *-nightly* ]]; then
IS_NIGHTLY=1
export CADCRAFT_BUILD_CHANNEL=nightly-v1
export CADCRAFT_OVERRIDE_VERSION="$VERSION"
fi
BASENAME="cadcraft-$VERSION-linux-$ARCH"
echo "==> CADCraft $VERSION for Linux $ARCH ($FORMATS)"
if [[ -n "$ARCH_TAR_DIR" && "$IS_NIGHTLY" != 1 ]]; then
echo "error: --arch-tar-dir is only for Nightly builds" >&2
exit 2
fi
echo "==> CADCraft $VERSION for Linux $ARCH ($FORMATS, channel=${CADCRAFT_BUILD_CHANNEL:-stable})"
# The man-and-completions example writes cadcraft-cli's man pages and shell completions below. It
# is built in its own cargo run: built with the binaries, its dev-dependencies' features would be
@@ -66,6 +83,11 @@ install -Dm755 "$BIN/cadcraft" "$STAGE/usr/bin/cadcraft"
install -Dm755 "$BIN/cadcraft-cli" "$STAGE/usr/bin/cadcraft-cli"
"${CROSS_COMPILE:-}strip" "$STAGE/usr/bin/cadcraft" "$STAGE/usr/bin/cadcraft-cli" 2>/dev/null || true
install -Dm644 "$HERE/$APP_ID.desktop" "$STAGE/usr/share/applications/$APP_ID.desktop"
if [[ "$IS_NIGHTLY" = 1 ]]; then
sed -e 's|^StartupWMClass=.*|StartupWMClass=ai.storyteller.cadcraft.nightly-v1|' \
"$STAGE/usr/share/applications/$APP_ID.desktop" >"$STAGE/usr/share/applications/$APP_ID.desktop.tmp"
mv "$STAGE/usr/share/applications/$APP_ID.desktop.tmp" "$STAGE/usr/share/applications/$APP_ID.desktop"
fi
install -Dm644 "$HERE/$APP_ID.mime.xml" "$STAGE/usr/share/mime/packages/$APP_ID.xml"
mkdir -p "$STAGE/usr/share/metainfo"
sed -e "s/@VERSION@/$VERSION/g" -e "s/@DATE@/$CADCRAFT_BUILD_DATE/g" \
@@ -112,13 +134,120 @@ if has tar; then
echo "wrote $DIST/$BASENAME.tar.gz"
fi
# The Arch handoff keeps the same basename as the plain tarball in a separate directory.
# Flatpak, OCI and direct tar consumers still get the original binary, not this launcher.
if [[ -n "$ARCH_TAR_DIR" ]]; then
mkdir -p "$ARCH_TAR_DIR"
if [[ "$(cd "$ARCH_TAR_DIR" && pwd -P)" == "$(cd "$DIST" && pwd -P)" ]]; then
echo "error: the Arch tar directory must differ from the release directory" >&2
exit 2
fi
bash "$HERE/nightly-arch-tar.sh" "$STAGE/usr" "$WORK/arch-tar" "$ARCH_TAR_DIR" "$BASENAME"
fi
# ---- .deb / .rpm --------------------------------------------------------------------------------
if has deb || has rpm; then
command -v nfpm >/dev/null || { echo "error: nfpm not found (https://nfpm.goreleaser.com/install/)" >&2; exit 1; }
export VERSION
export NFPM_ARCH="$DEB_ARCH"
NFPM_STAGE="$STAGE"
export NFPM_NAME="cadcraft"
export NFPM_BIN="cadcraft"
export NFPM_CLI="cadcraft-cli"
if [[ "$IS_NIGHTLY" = 1 ]]; then
NIGHTLY_DESK_ID="$APP_ID.nightly-v1"
export NFPM_NAME="cadcraft-nightly"
export NFPM_BIN="cadcraft-nightly"
export NFPM_CLI="cadcraft-nightly-cli"
NFPM_STAGE="$WORK/nfpm-root"
rm -rf "$NFPM_STAGE"
cp -R "$STAGE" "$NFPM_STAGE"
install -Dm755 "$NFPM_STAGE/usr/bin/cadcraft" "$NFPM_STAGE/usr/lib/cadcraft-nightly/cadcraft"
cat >"$NFPM_STAGE/usr/bin/$NFPM_BIN" <<'WRAPPER'
#!/bin/sh
# Start the Nightly GUI the flavor's way: this channel's own launch profile, so an installed
# nightly never reads or writes stable's settings, window state or recovery files.
set -eu
case "${1-}" in
# The Launcher already named the profile (its version query does too); never pass it twice. A
# plain version query answers without touching any profile.
--launch-profile | --version | -V) exec /usr/lib/cadcraft-nightly/cadcraft "$@" ;;
esac
profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}"
exec /usr/lib/cadcraft-nightly/cadcraft \
--launch-profile nightly-v1 --profile-root "$profile_base/cadcraft-nightly" -- "$@"
WRAPPER
chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_BIN"
rm -f "$NFPM_STAGE/usr/bin/cadcraft"
install -m755 "$NFPM_STAGE/usr/bin/cadcraft-cli" "$NFPM_STAGE/usr/lib/cadcraft-nightly/cadcraft-cli"
cat >"$NFPM_STAGE/usr/bin/$NFPM_CLI" <<'CLI_WRAPPER'
#!/bin/sh
# The Nightly CLI keeps its settings (plotter configurations, support) in the same channel folder
# as the GUI. An explicitly empty CADCRAFT_CONFIG_DIR still means "no settings folder", and
# --config-dir still wins.
set -eu
if [ "${CADCRAFT_CONFIG_DIR+x}" != x ]; then
profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}"
CADCRAFT_CONFIG_DIR="$profile_base/cadcraft-nightly"
export CADCRAFT_CONFIG_DIR
fi
exec /usr/lib/cadcraft-nightly/cadcraft-cli "$@"
CLI_WRAPPER
chmod 755 "$NFPM_STAGE/usr/bin/$NFPM_CLI"
rm -f "$NFPM_STAGE/usr/bin/cadcraft-cli"
mv "$NFPM_STAGE/usr/share/doc/cadcraft" "$NFPM_STAGE/usr/share/doc/$NFPM_NAME"
sed -e "s#^Exec=cadcraft\([[:space:]]\|$\)#Exec=$NFPM_BIN\1#" \
-e "s|^TryExec=cadcraft$|TryExec=$NFPM_BIN|" \
-e "s|^Icon=$APP_ID$|Icon=$NIGHTLY_DESK_ID|" \
-e "s|^Name=CADCraft$|Name=CADCraft Nightly|" \
-e '/^MimeType=/d' \
"$NFPM_STAGE/usr/share/applications/$APP_ID.desktop" >"$NFPM_STAGE/usr/share/applications/$NIGHTLY_DESK_ID.desktop"
rm -f "$NFPM_STAGE/usr/share/applications/$APP_ID.desktop"
sed -e "s|<id>$APP_ID</id>|<id>$NIGHTLY_DESK_ID</id>|g" \
-e "s|<name>CADCraft</name>|<name>CADCraft Nightly</name>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$NIGHTLY_DESK_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$NIGHTLY_DESK_ID</icon>|g" \
-e "s|<binary>cadcraft</binary>|<binary>$NFPM_BIN</binary>|g" \
"$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml" >"$NFPM_STAGE/usr/share/metainfo/$NIGHTLY_DESK_ID.metainfo.xml"
rm -f "$NFPM_STAGE/usr/share/metainfo/$APP_ID.metainfo.xml"
rm -rf "$NFPM_STAGE/usr/share/mime"
rm -rf "$NFPM_STAGE/usr/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/cadcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
install -Dm644 "$NIGHTLY_ICON" \
"$NFPM_STAGE/usr/share/icons/hicolor/256x256/apps/$NIGHTLY_DESK_ID.png"
if [[ -d "$NFPM_STAGE/usr/share/man/man1" ]]; then
for man_file in "$NFPM_STAGE/usr/share/man/man1"/cadcraft-cli*.1; do
[[ -f "$man_file" ]] || continue
man_base="$(basename "$man_file")"
sed -e 's/cadcraft-cli/cadcraft-nightly-cli/g' -e 's/CADCRAFT-CLI/CADCRAFT-NIGHTLY-CLI/g' \
"$man_file" >"$man_file.tmp"
mv "$man_file.tmp" "$NFPM_STAGE/usr/share/man/man1/${NFPM_CLI}${man_base#cadcraft-cli}"
rm -f "$man_file"
done
fi
if [[ -f "$NFPM_STAGE/usr/share/bash-completion/completions/cadcraft-cli" ]]; then
sed -e 's/_cadcraft-cli/_cadcraft-nightly-cli/g' -e 's/cadcraft-cli/cadcraft-nightly-cli/g' \
"$NFPM_STAGE/usr/share/bash-completion/completions/cadcraft-cli" >"$NFPM_STAGE/usr/share/bash-completion/completions/$NFPM_CLI"
rm -f "$NFPM_STAGE/usr/share/bash-completion/completions/cadcraft-cli"
fi
if [[ -f "$NFPM_STAGE/usr/share/zsh/site-functions/_cadcraft-cli" ]]; then
sed -e 's/_cadcraft-cli/_cadcraft-nightly-cli/g' -e 's/cadcraft-cli/cadcraft-nightly-cli/g' \
"$NFPM_STAGE/usr/share/zsh/site-functions/_cadcraft-cli" >"$NFPM_STAGE/usr/share/zsh/site-functions/_$NFPM_CLI"
rm -f "$NFPM_STAGE/usr/share/zsh/site-functions/_cadcraft-cli"
fi
if [[ -f "$NFPM_STAGE/usr/share/fish/vendor_completions.d/cadcraft-cli.fish" ]]; then
sed -e 's/cadcraft-cli/cadcraft-nightly-cli/g' \
"$NFPM_STAGE/usr/share/fish/vendor_completions.d/cadcraft-cli.fish" >"$NFPM_STAGE/usr/share/fish/vendor_completions.d/$NFPM_CLI.fish"
rm -f "$NFPM_STAGE/usr/share/fish/vendor_completions.d/cadcraft-cli.fish"
fi
fi
# nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`.
sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
DROP_LIB_TREE=
# shellcheck disable=SC2016
[[ -d "$NFPM_STAGE/usr/lib" ]] || DROP_LIB_TREE='\|^ - src: \${STAGE}/usr/lib/|,+2d;'
# shellcheck disable=SC2016
sed "${DROP_LIB_TREE}s|\${STAGE}|$NFPM_STAGE|g;s|\${NFPM_BIN}|$NFPM_BIN|g;s|\${NFPM_CLI}|$NFPM_CLI|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml"
for fmt in deb rpm; do
if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi
done
@@ -128,10 +257,49 @@ fi
if has appimage; then
APPDIR="$WORK/CADCraft.AppDir"
cp -R "$STAGE" "$APPDIR"
ln -s usr/bin/cadcraft "$APPDIR/AppRun"
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
if [[ "$IS_NIGHTLY" = 1 ]]; then
APPIMAGE_ID="$APP_ID.nightly-v1"
cat >"$APPDIR/AppRun" <<'APPRUN'
#!/bin/sh
# The nightly AppImage runs this launcher rather than a symlink to the binary, so an extracted or
# integrated AppImage starts with this channel's own launch profile too.
set -eu
APPDIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
case "${1-}" in
# The Launcher already named the profile (its version query does too); never pass it twice. A
# plain version query answers without touching any profile.
--launch-profile | --version | -V) exec "$APPDIR/usr/bin/cadcraft" "$@" ;;
esac
profile_base="${XDG_DATA_HOME:-${HOME:?HOME is required}/.local/share}"
exec "$APPDIR/usr/bin/cadcraft" \
--launch-profile nightly-v1 --profile-root "$profile_base/cadcraft-nightly" -- "$@"
APPRUN
chmod 755 "$APPDIR/AppRun"
sed -e "s|^Icon=$APP_ID$|Icon=$APPIMAGE_ID|" \
-e "s|^Name=CADCraft$|Name=CADCraft Nightly|" \
-e '/^MimeType=/d' \
"$APPDIR/usr/share/applications/$APP_ID.desktop" >"$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop"
rm -f "$APPDIR/usr/share/applications/$APP_ID.desktop"
cp "$APPDIR/usr/share/applications/$APPIMAGE_ID.desktop" "$APPDIR/$APPIMAGE_ID.desktop"
sed -e "s|<id>$APP_ID</id>|<id>$APPIMAGE_ID</id>|g" \
-e "s|<name>CADCraft</name>|<name>CADCraft Nightly</name>|g" \
-e "s|<launchable type=\"desktop-id\">$APP_ID.desktop</launchable>|<launchable type=\"desktop-id\">$APPIMAGE_ID.desktop</launchable>|g" \
-e "s|<icon type=\"stock\">$APP_ID</icon>|<icon type=\"stock\">$APPIMAGE_ID</icon>|g" \
"$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml" >"$APPDIR/usr/share/metainfo/$APPIMAGE_ID.metainfo.xml"
rm -f "$APPDIR/usr/share/metainfo/$APP_ID.metainfo.xml"
rm -rf "$APPDIR/usr/share/icons/hicolor"
NIGHTLY_ICON="$ROOT/assets/app-icon/cadcraft-nightly.png"
[[ -f "$NIGHTLY_ICON" ]] || NIGHTLY_ICON="$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png"
install -Dm644 "$NIGHTLY_ICON" \
"$APPDIR/usr/share/icons/hicolor/256x256/apps/$APPIMAGE_ID.png"
cp "$NIGHTLY_ICON" "$APPDIR/$APPIMAGE_ID.png"
ln -s "$APPIMAGE_ID.png" "$APPDIR/.DirIcon"
else
ln -s usr/bin/cadcraft "$APPDIR/AppRun"
cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop"
cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png"
ln -s "$APP_ID.png" "$APPDIR/.DirIcon"
fi
TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}"
if [[ -z "$TOOL" ]]; then
@@ -153,11 +321,20 @@ if has appimage; then
# each AppImage on GitHub Releases. `latest` is the newest published release that is not a
# pre-release. A fork's builds point at its own releases through GITHUB_REPOSITORY.
REPO="${GITHUB_REPOSITORY:-storytold/cadcraft}"
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|cadcraft-*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=()
if [[ "$IS_NIGHTLY" = 0 ]]; then
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest|cadcraft-*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=(-u "$UPDATE_INFO")
else
# Nightly releases are GitHub pre-releases (`latest` only selects stable releases), so point
# zsync update metadata at pre-release tags rather than stable `latest`.
UPDATE_INFO="gh-releases-zsync|${REPO%%/*}|${REPO#*/}|latest-pre|cadcraft-*-linux-$ARCH.AppImage.zsync"
UPDATE_ARGS=(-u "$UPDATE_INFO")
fi
# Extract-and-run: works without FUSE (containers, CI). The output embeds the static runtime,
# so users don't need libfuse2 either. With zsyncmake on the host (CI installs the zsync
# package) appimagetool also writes the .zsync, into its working directory, hence the cd.
(cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream -u "$UPDATE_INFO" "$APPDIR" "$OUT")
(cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream "${UPDATE_ARGS[@]}" "$APPDIR" "$OUT")
echo "wrote $OUT"
if [[ -s "$OUT.zsync" ]]; then
echo "wrote $OUT.zsync"
+110
View File
@@ -0,0 +1,110 @@
# shellcheck shell=bash
# Shared checks for the Apple-silicon Nightly scripts (nightly.sh, nightly-sign.sh, nightly-verify.sh).
# Stable packaging (package.sh, verify.sh) does not source this file. The text checks take tool output
# as arguments, so packaging/macos/nightly_sign_tests.py runs them without macOS.
MAC_NIGHTLY_APP='CADCraft Nightly.app'
MAC_NIGHTLY_ID='ai.storyteller.cadcraft.nightly'
# The release environment's names, as stable release.yml passes them (packaging/macos/import-cert.sh).
MAC_NIGHTLY_SECRETS=(APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID)
mac_nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; }
# The exact prepared version from the feed asset name, or failure.
mac_nightly_version_from_asset() {
local name="$1" version
[[ "$name" =~ ^cadcraft-(.+)-macos-aarch64-nightly\.zip$ ]] || return 1
version="${BASH_REMATCH[1]}"
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || return 1
printf '%s\n' "$version"
}
# Every signing and notarization value is set, and the team is one Apple team ID. No ad-hoc fallback.
mac_nightly_require_secrets() {
local name
for name in "${MAC_NIGHTLY_SECRETS[@]}"; do
[[ -n "${!name:-}" ]] || mac_nightly_die "$name is not set: Nightly signing and notarization are required, with no ad-hoc fallback"
done
[[ "$APPLE_TEAM_ID" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'APPLE_TEAM_ID is not an Apple team ID'
if [[ -n "${NIGHTLY_APPLE_TEAM_ID:-}" && "$NIGHTLY_APPLE_TEAM_ID" != "$APPLE_TEAM_ID" ]]; then
mac_nightly_die 'the signing team differs from the reviewed Nightly team (NIGHTLY_APPLE_TEAM_ID)'
fi
}
# One line of `security find-identity -v -p codesigning`: the identity is a Developer ID Application of the team.
mac_nightly_identity_is_team() {
local line="$1" identity="$2" team="$3"
[[ "$line" == *" $identity "* && "$line" == *'"Developer ID Application: '*" ($team)\""* ]]
}
# `codesign -d --verbose=2` of the signed bundle: the Nightly identifier, a Developer ID Application of the
# team, a secure timestamp and the hardened runtime (the checks of verify.sh, made strict).
mac_nightly_check_signature() {
local details="$1" team="$2" ok=0
grep -Fqx "Identifier=$MAC_NIGHTLY_ID" <<<"$details" || { echo "error: the bundle is not signed as $MAC_NIGHTLY_ID" >&2; ok=1; }
grep -q '^Authority=Developer ID Application:' <<<"$details" || { echo 'error: not signed with a Developer ID Application identity' >&2; ok=1; }
grep -qx "TeamIdentifier=$team" <<<"$details" || { echo 'error: signed by a different team' >&2; ok=1; }
grep -q '^Timestamp=' <<<"$details" || { echo 'error: the signature has no secure timestamp' >&2; ok=1; }
grep -Eq '^CodeDirectory .*flags=0x[0-9a-f]+\([^)]*runtime' <<<"$details" || { echo 'error: not signed with the hardened runtime' >&2; ok=1; }
return "$ok"
}
# `spctl --assess --type execute -vv`: Gatekeeper accepts the bundle as notarized.
mac_nightly_check_assessment() {
grep -q 'accepted' <<<"$1" && grep -qx 'source=Notarized Developer ID' <<<"$1"
}
# Before anything is unpacked: every ZIP entry is a regular file or directory inside the one Nightly
# bundle, with no absolute path, `..`, backslash or empty component, and no link or special file.
mac_nightly_check_zip_entries() {
python3 -I - "$1" "$MAC_NIGHTLY_APP" <<'PY' || mac_nightly_die 'the archive has an entry outside the bundle, a link or a special file'
import stat, sys, zipfile
archive, app = sys.argv[1:]
with zipfile.ZipFile(archive) as z:
for info in z.infolist():
name = info.filename
parts = name.rstrip("/").split("/")
mode = info.external_attr >> 16
if (name.startswith("/") or "\\" in name or "\0" in name or parts[0] != app
or any(part in ("", ".", "..") for part in parts)
or stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR)):
sys.exit(f"refused entry: {name!r}")
PY
}
# An unpacked payload directory holds exactly the GUI-only Nightly bundle: one thin arm64 CADCraft
# executable, the Nightly identity and the exact version (no numeric fallback), no CLI, no links or special
# files, no document or URL types.
mac_nightly_check_bundle() {
local payload="$1" version="$2" app entries plist key value
app="$payload/$MAC_NIGHTLY_APP"
entries="$(ls -A "$payload")"
[[ "$entries" == "$MAC_NIGHTLY_APP" && -d "$app" && ! -L "$app" ]] || mac_nightly_die "the archive must hold exactly $MAC_NIGHTLY_APP"
[[ -z "$(find "$payload" ! -type f ! -type d -print -quit)" ]] || mac_nightly_die 'the bundle contains links or special files'
[[ "$(ls -A "$app/Contents/MacOS")" == CADCraft ]] || mac_nightly_die 'Contents/MacOS must hold only the CADCraft GUI (no CLI)'
[[ -f "$app/Contents/MacOS/CADCraft" && -x "$app/Contents/MacOS/CADCraft" ]] || mac_nightly_die 'missing executable GUI'
[[ "$(lipo -archs "$app/Contents/MacOS/CADCraft")" == arm64 ]] || mac_nightly_die 'the GUI must be thin arm64'
plist="$app/Contents/Info.plist"
for key in CFBundleIdentifier CFBundleExecutable CADCraftVersion; do
value="$(plutil -extract "$key" raw -o - "$plist")" || mac_nightly_die "Info.plist has no $key"
case "$key" in
CFBundleIdentifier) [[ "$value" == "$MAC_NIGHTLY_ID" ]] ;;
CFBundleExecutable) [[ "$value" == CADCraft ]] ;;
CADCraftVersion) [[ "$value" == "$version" ]] ;;
esac || mac_nightly_die "Info.plist $key is not the prepared Nightly identity"
done
for key in CFBundleDocumentTypes CFBundleURLTypes UTExportedTypeDeclarations UTImportedTypeDeclarations; do
if plutil -extract "$key" xml1 -o - "$plist" >/dev/null 2>&1; then mac_nightly_die "Nightly declares $key"; fi
done
}
# `stapler validate` asks Apple's CloudKit service, which sometimes drops the connection (error 68)
# though the ticket is there (verify.sh).
mac_nightly_validate_staple() {
local target="$1" attempt
for attempt in 1 2 3 4 5; do
xcrun stapler validate "$target" && return 0
[[ "$attempt" = 5 ]] || sleep $((attempt * 20))
done
return 1
}
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env bash
# Trusted signing step for the Apple-silicon Nightly, the stable release's macOS signing route
# (import-cert.sh, then package.sh's codesign, notarytool and stapler steps):
#
# nightly-sign.sh --arch aarch64 --input /abs/cadcraft-<version>-macos-aarch64-nightly.zip \
# --output /abs/<dir>/cadcraft-<version>-macos-aarch64-nightly.zip
#
# Input: the unsigned archive nightly.sh made. Output: the same bundle signed with the Developer ID and
# hardened runtime, notarized, with the ticket stapled into the bundle, zipped without extended
# attributes. Writes only that file, never replacing one; the temporary keychain and work directory
# are removed on every exit.
#
# Env (all required, no ad-hoc or unnotarized fallback): APPLE_CERTIFICATE, APPLE_CERTIFICATE_PASSWORD,
# KEYCHAIN_PASSWORD, APPLE_ID, APPLE_PASSWORD, APPLE_TEAM_ID; optional NIGHTLY_APPLE_TEAM_ID (must
# equal APPLE_TEAM_ID) and RUNNER_TEMP (work directory base).
#
# Never compiles, and never runs anything from the payload: the version query runs on the signed
# bundle in a job without secrets (nightly-verify.sh).
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=nightly-lib.sh
. "$HERE/nightly-lib.sh"
# shellcheck source=../nightly-common.sh
. "$HERE/../nightly-common.sh"
ARCH='' INPUT='' OUTPUT=''
while [[ $# -gt 0 ]]; do
case "$1" in
--arch | --input | --output)
[[ $# -ge 2 ]] || mac_nightly_die "missing $1 value"
case "$1" in --arch) ARCH="$2" ;; --input) INPUT="$2" ;; --output) OUTPUT="$2" ;; esac
shift 2 ;;
-h | --help) sed -n '2,18p' "$0"; exit 0 ;;
*) mac_nightly_die "unsupported argument: $1" ;;
esac
done
[[ "$ARCH" == aarch64 ]] || mac_nightly_die 'only --arch aarch64 is supported'
[[ "$INPUT" == /* && "$OUTPUT" == /* ]] || mac_nightly_die '--input and --output must be absolute paths'
NAME="$(basename -- "$INPUT")"
VERSION="$(mac_nightly_version_from_asset "$NAME")" || mac_nightly_die 'the input is not a prepared Nightly archive name'
[[ "$(basename -- "$OUTPUT")" == "$NAME" ]] || mac_nightly_die 'the output must keep the archive name'
[[ -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die 'the input must be a regular file'
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || mac_nightly_die 'refusing to replace an existing output'
[[ -d "$(dirname -- "$OUTPUT")" && ! -L "$(dirname -- "$OUTPUT")" ]] || mac_nightly_die 'the output directory must exist'
mac_nightly_require_secrets
[[ "$(uname -s)" == Darwin ]] || mac_nightly_die 'signing needs macOS (codesign, notarytool, stapler)'
BASE="${RUNNER_TEMP:-${TMPDIR:-/tmp}}"
WORK="$(mktemp -d "${BASE%/}/cadcraft-nightly-sign.XXXXXX")"
KEYCHAIN="$WORK/cadcraft-signing.keychain-db"
cleanup() {
if [[ -e "$KEYCHAIN" ]]; then security delete-keychain "$KEYCHAIN" >/dev/null 2>&1 || rm -f -- "$KEYCHAIN"; fi
rm -rf -- "$WORK"
}
trap cleanup EXIT
# ---- identity: import-cert.sh, into this run's private directory ------------------------------
# An empty GITHUB_ENV makes it print the identity instead of exporting it to later steps.
imported="$(GITHUB_ENV='' RUNNER_TEMP="$WORK" DIST="$WORK/dist" bash "$HERE/import-cert.sh")"
IDENTITY="$(sed -n 's/^MACOS_SIGN_IDENTITY=//p' <<<"$imported")"
[[ "$IDENTITY" =~ ^[0-9A-F]{40}$ && "$(sed -n 's/^MACOS_KEYCHAIN=//p' <<<"$imported")" == "$KEYCHAIN" ]] \
|| mac_nightly_die 'import-cert.sh did not import a signing identity'
mac_nightly_identity_is_team "$(security find-identity -v -p codesigning "$KEYCHAIN" | grep -F " $IDENTITY " || true)" "$IDENTITY" "$APPLE_TEAM_ID" \
|| mac_nightly_die "the imported identity is not a Developer ID Application of team $APPLE_TEAM_ID"
echo "==> CADCraft Nightly $VERSION for macOS (aarch64), identity: $IDENTITY"
# ---- the unsigned bundle ---------------------------------------------------------------------------
mac_nightly_check_zip_entries "$INPUT"
ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload"
mac_nightly_check_bundle "$WORK/payload" "$VERSION"
APP="$WORK/payload/$MAC_NIGHTLY_APP"
# ---- package.sh's signing and notarization, with a required Developer ID ---------------------------
sign() {
codesign --force --sign "$IDENTITY" --keychain "$KEYCHAIN" --timestamp "$@"
}
notarize() {
local file="$1" out id status
echo "==> notarizing $(basename "$file") (this can take a few minutes)"
out="$(xcrun notarytool submit "$file" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \
--team-id "$APPLE_TEAM_ID" --wait --timeout 1h --output-format json)" || true
echo "$out"
id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)"
status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)"
if [[ "$status" != "Accepted" ]]; then
if [[ -n "$id" ]]; then
# Capped: the shared signer bounds a step's output at 256 KiB.
xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" | head -c 131072 || true
fi
echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2
exit 1
fi
}
# Stapling and validating both look the ticket up in Apple's CloudKit service, which can drop the
# connection right after notarization (error 68), so retry the pair (package.sh).
staple() {
local file="$1" attempt
for attempt in 1 2 3 4 5; do
if xcrun stapler staple "$file" && xcrun stapler validate "$file"; then
return
fi
if [[ "$attempt" = 5 ]]; then
echo "error: stapling $(basename "$file") failed after $attempt attempts" >&2
exit 1
fi
echo "stapling $(basename "$file") failed (attempt $attempt); retrying in $((attempt * 20))s" >&2
sleep $((attempt * 20))
done
}
# Inside-out: the executable, then the bundle (no --deep on the final signature).
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/CADCraft"
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP"
codesign --verify --strict --deep --verbose=2 "$APP"
ditto -c -k --keepParent "$APP" "$WORK/notarize.zip"
notarize "$WORK/notarize.zip"
# The ticket goes into the bundle (Contents/CodeResources): the Launcher's extract restores no xattrs.
staple "$APP"
# ---- the final archive, checked as the Launcher unpacks it -----------------------------------------
ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$WORK/final.zip"
ditto -x -k --norsrc --noextattr "$WORK/final.zip" "$WORK/check"
mac_nightly_check_bundle "$WORK/check" "$VERSION"
CHECK="$WORK/check/$MAC_NIGHTLY_APP"
codesign --verify --strict --deep --verbose=2 "$CHECK"
mac_nightly_check_signature "$(codesign -d --verbose=2 "$CHECK" 2>&1)" "$APPLE_TEAM_ID" \
|| mac_nightly_die 'the signed bundle is not the required Developer ID signature'
mac_nightly_validate_staple "$CHECK" || mac_nightly_die 'no notarization ticket is stapled into the bundle'
# spctl's lookup can lag a few seconds behind notarytool's "Accepted" (verify.sh).
for attempt in 1 2 3 4 5; do
assessment="$(spctl --assess --type execute -vv "$CHECK" 2>&1)" || true
mac_nightly_check_assessment "$assessment" && break
[[ "$attempt" = 5 ]] || sleep 10
done
printf '%s\n' "$assessment"
mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized'
nightly_publish_archive "$WORK/final.zip" "$OUTPUT"
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# Check an Apple-silicon Nightly archive as the Launcher unpacks it, then ask the GUI its version.
# For a job without signing material (it refuses to run with any), after nightly-sign.sh:
#
# nightly-verify.sh --input /abs/cadcraft-<version>-macos-aarch64-nightly.zip --expect signed [--team ID]
# nightly-verify.sh --input /abs/cadcraft-<version>-macos-aarch64-nightly.zip --expect unsigned
#
# Both: the archive holds only the GUI-only Nightly bundle with the exact CADCraftVersion, unpacked
# without extended attributes. `signed` (the feed artifact): Developer ID of the team (--team, else
# NIGHTLY_APPLE_TEAM_ID), hardened runtime, secure timestamp, stapled ticket, Gatekeeper accepts it as
# notarized. `unsigned` (nightly.sh's compile output, e.g. pull-request CI) checks no signature.
# Last, the bundle's GUI answers its version query with an empty environment, both plainly and in the
# Launcher's form `--launch-profile nightly-v1 --profile-root <fresh dir> --version` (the shared producer
# smoke): each must exit 0 within 15 seconds, print exactly `CADCraft <version> (nightly-v1)` and
# write nothing to standard error.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=nightly-lib.sh
. "$HERE/nightly-lib.sh"
INPUT='' EXPECT='' TEAM="${NIGHTLY_APPLE_TEAM_ID:-}"
while [[ $# -gt 0 ]]; do
case "$1" in
--input | --expect | --team)
[[ $# -ge 2 ]] || mac_nightly_die "missing $1 value"
case "$1" in --input) INPUT="$2" ;; --expect) EXPECT="$2" ;; --team) TEAM="$2" ;; esac
shift 2 ;;
-h | --help) sed -n '2,15p' "$0"; exit 0 ;;
*) mac_nightly_die "unsupported argument: $1" ;;
esac
done
for name in "${MAC_NIGHTLY_SECRETS[@]}" MACOS_SIGN_IDENTITY MACOS_KEYCHAIN; do
[[ -z "${!name:-}" ]] || mac_nightly_die "refusing to run the payload with signing material in the environment ($name)"
done
[[ "$EXPECT" == signed || "$EXPECT" == unsigned ]] || mac_nightly_die '--expect must be signed or unsigned'
[[ "$EXPECT" == unsigned || "$TEAM" =~ ^[A-Z0-9]{10}$ ]] || mac_nightly_die 'a signed check needs the Apple team ID (--team or NIGHTLY_APPLE_TEAM_ID)'
[[ "$INPUT" == /* && -f "$INPUT" && ! -L "$INPUT" ]] || mac_nightly_die '--input must be an absolute regular file'
VERSION="$(mac_nightly_version_from_asset "$(basename -- "$INPUT")")" || mac_nightly_die 'the input is not a prepared Nightly archive name'
[[ "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || mac_nightly_die 'needs an Apple silicon Mac'
WORK="$(mktemp -d "${RUNNER_TEMP:-${TMPDIR:-/tmp}}/cadcraft-nightly-verify.XXXXXX")"
trap 'rm -rf -- "$WORK"' EXIT
mac_nightly_check_zip_entries "$INPUT"
ditto -x -k --norsrc --noextattr "$INPUT" "$WORK/payload"
mac_nightly_check_bundle "$WORK/payload" "$VERSION"
APP="$WORK/payload/$MAC_NIGHTLY_APP"
if [[ "$EXPECT" == signed ]]; then
codesign --verify --strict --deep --verbose=2 "$APP"
mac_nightly_check_signature "$(codesign -d --verbose=2 "$APP" 2>&1)" "$TEAM" \
|| mac_nightly_die 'the bundle is not the required Developer ID signature'
mac_nightly_validate_staple "$APP" || mac_nightly_die 'no notarization ticket is stapled into the bundle'
for attempt in 1 2 3 4 5; do
assessment="$(spctl --assess --type execute -vv "$APP" 2>&1)" || true
mac_nightly_check_assessment "$assessment" && break
[[ "$attempt" = 5 ]] || sleep 10
done
printf '%s\n' "$assessment"
mac_nightly_check_assessment "$assessment" || mac_nightly_die 'Gatekeeper does not accept the bundle as notarized'
fi
# macOS has no timeout(1): perl's alarm survives its exec and ends a query that hangs (a dialog, say).
query() {
local out
out="$(env -i HOME="$WORK/home" TMPDIR="$WORK/tmp/" PATH=/usr/bin:/bin \
/usr/bin/perl -e 'alarm 15; exec @ARGV or die' "$APP/Contents/MacOS/CADCraft" "$@" 2>"$WORK/stderr")" \
|| mac_nightly_die "the version query ($*) failed or did not finish within 15 s"
[[ ! -s "$WORK/stderr" ]] || mac_nightly_die "the version query ($*) wrote to standard error: $(head -c 2000 "$WORK/stderr")"
[[ "$out" == "CADCraft $VERSION (nightly-v1)" ]] || mac_nightly_die "the version query ($*) reports '$out', not CADCraft $VERSION (nightly-v1)"
}
mkdir -m 700 "$WORK/home" "$WORK/tmp" "$WORK/profile"
query --version
query --launch-profile nightly-v1 --profile-root "$WORK/profile" --version
echo "==> verified ($EXPECT): CADCraft $VERSION (nightly-v1), plain and in the Launcher's profile form"
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
# App-owned GUI-only Nightly for Apple silicon, compile step only (no signing material):
#
# $DIST/cadcraft-<version>-macos-aarch64-nightly.zip CADCraft Nightly.app, unsigned
#
# Usage: packaging/macos/nightly.sh --arch aarch64
#
# Required env (nightly-common.sh): CADCRAFT_BUILD_CHANNEL=nightly-v1, CADCRAFT_VERSION,
# CADCRAFT_BUILD_SHA, CADCRAFT_BUILD_DATE, absolute CARGO_TARGET_DIR and DIST; CRAFT_FONTS_DIR optional.
#
# Not publishable by itself: the trusted step (nightly-sign.sh) signs, notarizes and staples it. No CLI,
# DMG, document or URL types, and no stable package.sh. The bundle is not run here; the version query
# runs on the signed bundle (nightly-verify.sh).
set -euo pipefail
ARCH=
while [[ $# -gt 0 ]]; do
case "$1" in
--arch) [[ $# -ge 2 ]] || { echo 'missing --arch value' >&2; exit 2; }; ARCH="$2"; shift 2 ;;
-h|--help) sed -n '2,13p' "$0"; exit 0 ;;
*) echo "unsupported nightly argument: $1" >&2; exit 2 ;;
esac
done
[[ "$ARCH" == aarch64 && "$(uname -s)" == Darwin && "$(uname -m)" == arm64 ]] || { echo 'only native macOS aarch64 nightly packaging is supported' >&2; exit 2; }
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$HERE/../nightly-common.sh"
. "$HERE/nightly-lib.sh"
nightly_refuse_signing_env
nightly_init macos "$ARCH" aarch64-apple-darwin
# Keep in sync with LSMinimumSystemVersion in Info.plist.in (as package.sh).
export MACOSX_DEPLOYMENT_TARGET=11.0
OUTPUT="$DIST/cadcraft-$VERSION-macos-aarch64-nightly.zip"
[[ ! -e "$OUTPUT" && ! -L "$OUTPUT" ]] || nightly_die 'refusing to replace an existing nightly archive'
nightly_compile_gui
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/CADCraft"
chmod 755 "$APP/Contents/MacOS/CADCraft"
cp "$ROOT/assets/app-icon/cadcraft-nightly.icns" "$APP/Contents/Resources/cadcraft-nightly.icns"
nightly_copy_notices "$APP/Contents/Resources"
# The private mktemp cwd is the helper authority root: stage the template inside it.
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
--output "stage/$MAC_NIGHTLY_APP/Contents/Info.plist" --version "$VERSION" --source-commit "$CADCRAFT_BUILD_SHA")
plutil -lint "$APP/Contents/Info.plist"
printf 'APPL????' >"$APP/Contents/PkgInfo"
mac_nightly_check_bundle "$NIGHTLY_WORK/stage" "$VERSION"
# No resource forks, extended attributes or ACLs: the Launcher restores none, so nothing may depend on them.
ditto -c -k --norsrc --noextattr --noacl --keepParent "$APP" "$NIGHTLY_WORK/archive.zip"
nightly_publish_archive "$NIGHTLY_WORK/archive.zip" "$OUTPUT"
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Nightly metadata: run from a private owned build cwd with a staged template.
All file arguments must stay beneath that cwd; this is not native/signing acceptance.
"""
import argparse
import datetime
import os
from pathlib import Path
import plistlib
import re
import sys
# The shared helper location is fixed by this script, not by CLI file arguments.
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from nightly_paths import OwnedBuildRoot
MAX_TEMPLATE_BYTES = 256 * 1024
IDENTIFIER = "ai.storyteller.cadcraft.nightly"
ASSOCIATIONS = ("CFBundleDocumentTypes", "CFBundleURLTypes", "UTExportedTypeDeclarations", "UTImportedTypeDeclarations")
VERSION = re.compile(r"([0-9]+\.[0-9]+\.[0-9]+)-nightly\.([0-9]{8})\.[0-9]+\.[0-9]+\.g([0-9a-f]{12})\Z")
def render(template: bytes, version: str, commit: str) -> bytes:
match = VERSION.fullmatch(version)
if not match or not re.fullmatch(r"[0-9a-f]{40}", commit) or match[3] != commit[:12]:
raise ValueError("exact prepared Nightly version and matching source commit are required")
datetime.datetime.strptime(match[2], "%Y%m%d")
data = plistlib.loads(template)
if not isinstance(data, dict) or data.get("CFBundlePackageType") != "APPL":
raise ValueError("expected the app-owned application plist template")
for key in ASSOCIATIONS:
data.pop(key, None)
data.update(
CFBundleDisplayName="CADCraft Nightly",
CFBundleName="CADCraft Nightly",
CFBundleIdentifier=IDENTIFIER,
CFBundleExecutable="CADCraft",
CFBundleIconFile="cadcraft-nightly",
CFBundleShortVersionString=match[1],
CFBundleVersion=match[1],
CADCraftVersion=version,
CADCraftBuildCommit=commit,
)
return plistlib.dumps(data, fmt=plistlib.FMT_XML, sort_keys=False)
def write_plist(template: Path, destination: Path, version: str, commit: str) -> None:
with OwnedBuildRoot() as root:
content = render(root.read_bytes(template, MAX_TEMPLATE_BYTES), version, commit)
with root.create(destination) as stream:
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--template", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--version", required=True)
parser.add_argument("--source-commit", required=True)
args = parser.parse_args()
write_plist(args.template, args.output, args.version, args.source_commit)
if __name__ == "__main__":
main()
+202
View File
@@ -0,0 +1,202 @@
#!/usr/bin/env python3
"""Generated metadata/sentinel fixtures; no native binary, signature, archive or network."""
import importlib.util
import os
from pathlib import Path
import plistlib
import runpy
import sys
from unittest import mock
import tempfile
import unittest
HERE = Path(__file__).resolve().parent
SPEC = importlib.util.spec_from_file_location("photo_nightly_plist", HERE / "nightly_plist.py")
POLICY = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(POLICY)
COMMIT = "a" * 40
VERSION = "0.23.1-nightly.20261121.12345.1.g" + COMMIT[:12]
class NightlyMetadata(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name).resolve()
previous = Path.cwd()
os.chdir(self.root)
self.addCleanup(os.chdir, previous)
self.template = self.root / "Info.plist.in"
self.original = (HERE / "Info.plist.in").read_bytes()
self.template.write_bytes(self.original)
self.output = self.root / "Info.plist"
def test_nightly_transform_removes_associations_without_changing_stable_or_platform_metadata(self):
stable = plistlib.loads(self.original)
stable["CFBundleURLTypes"] = [{"CFBundleURLSchemes": ["generated-test-scheme"]}]
prepared = plistlib.dumps(stable)
self.template.write_bytes(prepared)
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
rendered = plistlib.loads(self.output.read_bytes())
for key in POLICY.ASSOCIATIONS:
self.assertNotIn(key, rendered)
self.assertNotEqual(rendered["CFBundleIdentifier"], stable["CFBundleIdentifier"])
self.assertEqual(rendered["CFBundleIdentifier"], "ai.storyteller.cadcraft.nightly")
self.assertEqual(rendered["CFBundleExecutable"], "CADCraft")
self.assertEqual(rendered["CADCraftVersion"], VERSION)
self.assertEqual(rendered["CADCraftBuildCommit"], COMMIT)
self.assertTrue(VERSION.startswith(rendered["CFBundleVersion"] + "-nightly."))
for key in ("LSMinimumSystemVersion", "LSApplicationCategoryType", "NSHighResolutionCapable", "NSHumanReadableCopyright"):
self.assertEqual(rendered[key], stable[key])
self.assertEqual(self.template.read_bytes(), prepared)
self.assertEqual((HERE / "Info.plist.in").read_bytes(), self.original)
def test_bad_identity_or_template_refuses_before_creating_output(self):
for version, commit in (("0.23.1", COMMIT), (VERSION, "b" * 40), (VERSION, "not-a-commit"), (VERSION.replace("20261121", "20261399"), COMMIT)):
with self.subTest(version=version, commit=commit):
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, self.output, version, commit)
self.assertFalse(self.output.exists())
self.assertEqual(self.template.read_bytes(), self.original)
self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "generated-not-an-app"}))
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
def test_cli_writes_the_requested_identity_without_replacing_the_template(self):
helper = HERE / "nightly_plist.py"
argv = [str(helper), "--template", str(self.template), "--output", str(self.output), "--version", VERSION, "--source-commit", COMMIT]
with mock.patch.object(sys, "argv", argv):
runpy.run_path(str(helper), run_name="__main__")
result = plistlib.loads(self.output.read_bytes())
self.assertEqual(result["CADCraftVersion"], VERSION)
self.assertEqual(result["CADCraftBuildCommit"], COMMIT)
self.assertEqual(self.template.read_bytes(), self.original)
def test_template_alias_or_nonfile_refuses_before_output(self):
alias = self.root / "template-alias"
alias.symlink_to(self.template)
for template in (alias, self.root, self.root / "missing-template"):
with self.subTest(template=template), self.assertRaises(ValueError):
POLICY.write_plist(template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
self.assertEqual(self.template.read_bytes(), self.original)
def test_failed_write_cleans_owned_output_but_preserves_a_replacement(self):
sentinel = b"generated replacement artifact"
for disposition in ("owned", "missing", "replacement"):
with self.subTest(disposition=disposition):
if self.output.exists():
self.output.unlink()
def fail_sync(_descriptor):
# macOS/Linux allow unlink of an open file: exercise the real
# cleanup ownership check, not a mocked inode comparison.
if disposition != "owned":
self.output.unlink()
if disposition == "replacement":
self.output.write_bytes(sentinel)
raise OSError("generated fsync failure")
with mock.patch.object(POLICY.os, "fsync", side_effect=fail_sync), self.assertRaises(OSError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
if disposition == "replacement":
self.assertEqual(self.output.read_bytes(), sentinel)
else:
self.assertFalse(self.output.exists())
self.assertEqual(self.template.read_bytes(), self.original)
def test_exclusive_output_preserves_existing_bytes_and_symlink_targets(self):
sentinel = b"generated owned sentinel, not an existing app or user file"
self.output.write_bytes(sentinel)
with self.assertRaises(FileExistsError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertEqual(self.output.read_bytes(), sentinel)
self.output.unlink()
external = self.root / "sentinel"
external.write_bytes(sentinel)
self.output.symlink_to(external)
with self.assertRaisesRegex(ValueError, "symlinks or aliases"):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertEqual(external.read_bytes(), sentinel)
self.assertTrue(self.output.is_symlink())
def test_template_outside_build_root_refuses_before_output(self):
with tempfile.TemporaryDirectory() as external:
template = Path(external) / "Info.plist.in"
template.write_bytes(self.original)
with self.assertRaises(ValueError):
POLICY.write_plist(template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
self.assertEqual(template.read_bytes(), self.original)
def test_output_outside_build_root_refuses_before_write(self):
with tempfile.TemporaryDirectory() as external:
output = Path(external) / "Info.plist"
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, output, VERSION, COMMIT)
self.assertFalse(output.exists())
def test_parent_traversal_refuses_even_to_an_owned_sibling(self):
with tempfile.TemporaryDirectory(dir=self.root.parent) as external:
output = Path("..") / Path(external).name / "Info.plist"
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, output, VERSION, COMMIT)
self.assertFalse((Path(external) / "Info.plist").exists())
def test_symlinked_output_parent_refuses(self):
with tempfile.TemporaryDirectory() as external:
alias = self.root / "alias"
alias.symlink_to(external, target_is_directory=True)
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, alias / "Info.plist", VERSION, COMMIT)
self.assertFalse((Path(external) / "Info.plist").exists())
def test_template_read_is_bounded_before_output(self):
self.template.write_bytes(plistlib.dumps({"CFBundlePackageType": "APPL", "fixture": "x" * 300000}))
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
def test_nonprivate_build_root_refuses(self):
self.root.chmod(0o755)
try:
with self.assertRaises(ValueError):
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
self.assertFalse(self.output.exists())
finally:
self.root.chmod(0o700)
def test_output_keeps_normal_new_file_permissions_inside_private_root(self):
previous = os.umask(0o022)
try:
reference = self.root / "reference"
reference.write_bytes(b"generated ordinary output")
POLICY.write_plist(self.template, self.output, VERSION, COMMIT)
finally:
os.umask(previous)
self.assertEqual(self.output.stat().st_mode & 0o777, reference.stat().st_mode & 0o777)
def test_open_parent_anchor_prevents_a_later_alias_redirect(self):
parent = self.root / "stage"
parent.mkdir()
retained = self.root / "retained-stage"
destination = parent / "Info.plist"
original = POLICY.OwnedBuildRoot._parent
with tempfile.TemporaryDirectory() as external:
def swap_after_parent_open(root, path):
descriptor, name = original(root, path)
if Path(path) == destination:
parent.rename(retained)
parent.symlink_to(external, target_is_directory=True)
return descriptor, name
with mock.patch.object(POLICY.OwnedBuildRoot, "_parent", swap_after_parent_open):
POLICY.write_plist(self.template, destination, VERSION, COMMIT)
self.assertFalse((Path(external) / "Info.plist").exists())
self.assertEqual(plistlib.loads((retained / "Info.plist").read_bytes())["CADCraftVersion"], VERSION)
if __name__ == "__main__":
unittest.main()
+425
View File
@@ -0,0 +1,425 @@
#!/usr/bin/env python3
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
real signature, notarization or Mac run."""
import base64
import importlib.util
import json
import os
from pathlib import Path
import plistlib
import shutil
import stat
import subprocess
import sys
import tempfile
import textwrap
import time
import unittest
import zipfile
HERE = Path(__file__).resolve().parent
SPEC = importlib.util.spec_from_file_location("photo_mac_nightly_plist", HERE / "nightly_plist.py")
PLIST = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(PLIST)
COMMIT = "b" * 40
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
ASSET = f"cadcraft-{VERSION}-macos-aarch64-nightly.zip"
APP = "CADCraft Nightly.app"
TEAM = "ABCDE12345"
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
SECRETS = {
"APPLE_CERTIFICATE": base64.b64encode(b"generated fixture, not a certificate").decode(),
"APPLE_CERTIFICATE_PASSWORD": "generated-fixture",
"KEYCHAIN_PASSWORD": "generated-fixture",
"APPLE_ID": "[email protected]",
"APPLE_PASSWORD": "generated-fixture",
"APPLE_TEAM_ID": TEAM,
}
# One stand-in for every Apple tool, dispatched on its own name. Each logs its argv as a JSON line.
SHIM = r"""
import json, os, plistlib, sys, zipfile
from pathlib import Path
name = Path(sys.argv[0]).name
args = sys.argv[1:]
with open(os.environ["SHIM_LOG"], "a") as log:
log.write(json.dumps([name] + args) + "\n")
team = os.environ.get("SHIM_TEAM", "")
if name == "uname":
print({"-s": "Darwin", "-m": "arm64"}.get(args[0], "Darwin"))
elif name == "lipo":
print("arm64")
elif name == "ditto":
paths = [a for a in args if not a.startswith("-")]
src, dst = paths
if "-x" in args:
with zipfile.ZipFile(src) as z:
for info in z.infolist():
target = Path(dst) / info.filename
if info.is_dir():
target.mkdir(parents=True, exist_ok=True)
continue
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(z.read(info))
mode = (info.external_attr >> 16) & 0o777
if mode:
target.chmod(mode)
else:
root = Path(src)
with zipfile.ZipFile(dst, "x") as z:
for path in sorted([root] + list(root.rglob("*"))):
arc = (Path(root.name) / path.relative_to(root)).as_posix()
if path.is_dir():
z.writestr(zipfile.ZipInfo(arc + "/"), b"")
else:
info = zipfile.ZipInfo(arc)
info.external_attr = (path.stat().st_mode & 0xFFFF) << 16
z.writestr(info, path.read_bytes())
elif name == "plutil":
if args[0] == "-lint":
sys.exit(0)
key, fmt, source = args[1], args[2], args[-1]
data = sys.stdin.read() if source == "-" else Path(source).read_bytes()
value = json.loads(data) if source == "-" else plistlib.loads(data)
if key not in value:
sys.exit(1)
print(value[key] if fmt == "raw" else "<present/>")
elif name == "security":
verb = args[0]
if verb == "create-keychain":
Path(args[-1]).write_bytes(b"keychain")
elif verb == "find-identity":
print(' 1) %s "Developer ID Application: Generated Fixture (%s)"' % (os.environ["SHIM_IDENTITY"], team))
print(" 1 valid identities found")
elif verb == "delete-keychain":
Path(args[-1]).unlink()
elif name == "codesign":
target = Path(args[-1])
if "--sign" in args and target.suffix == ".app":
(target / "Contents/_CodeSignature").mkdir(exist_ok=True)
(target / "Contents/_CodeSignature/CodeResources").write_bytes(b"sealed")
if "-d" in args:
sys.stderr.write("Executable=%s\nIdentifier=ai.storyteller.cadcraft.nightly\n"
"CodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1+7 location=embedded\n"
"Authority=Developer ID Application: Generated Fixture (%s)\n"
"Timestamp=23 Nov 2026 at 17:00:00\nTeamIdentifier=%s\n" % (target, team, team))
elif name == "xcrun":
if args[:2] == ["notarytool", "submit"]:
print(json.dumps({"id": "generated-id", "status": os.environ.get("SHIM_NOTARY", "Accepted")}))
elif args[:2] == ["stapler", "staple"]:
(Path(args[2]) / "Contents/CodeResources").write_bytes(b"ticket")
elif args[:2] == ["stapler", "validate"]:
sys.exit(0 if (Path(args[2]) / "Contents/CodeResources").is_file() else 1)
elif name == "spctl":
sys.stderr.write("%s: accepted\nsource=Notarized Developer ID\n" % args[-1])
elif name == "cargo":
sys.exit(1)
# sleep: the retry waits pass at once.
"""
TOOLS = ("uname", "lipo", "ditto", "plutil", "security", "codesign", "xcrun", "spctl", "cargo", "sleep")
class Fixture:
def __init__(self, test):
self.directory = tempfile.TemporaryDirectory()
test.addCleanup(self.directory.cleanup)
self.root = Path(self.directory.name).resolve()
self.bin = self.root / "bin"
self.bin.mkdir()
shim = self.bin / "shim.py"
shim.write_text(SHIM)
for tool in TOOLS:
path = self.bin / tool
path.write_text(f"#!{sys.executable}\nimport sys\nsys.argv[0] = {str(path)!r}\nexec(compile(open({str(shim)!r}).read(), 'shim', 'exec'), {{'__name__': '__main__'}})\n")
path.chmod(0o755)
self.log = self.root / "tools.log"
self.ran = self.root / "payload-ran"
self.temp = self.root / "runner-temp"
self.temp.mkdir()
self.dist = self.root / "unsigned"
self.dist.mkdir()
self.signed = self.root / "signed"
self.signed.mkdir()
self.input = self.dist / ASSET
self.output = self.signed / ASSET
# Every script runs from a directory with modules a Python helper must not import (-I).
self.cwd = self.root / "cwd"
self.cwd.mkdir()
self.hijacked = self.root / "hijacked"
for module in ("shutil", "zipfile", "stat"):
(self.cwd / f"{module}.py").write_text(f"open({str(self.hijacked)!r}, 'a').write({module!r})\n")
def add_entry(self, info, data=b""):
"""Append one raw entry to the input archive."""
with zipfile.ZipFile(self.input, "a") as z:
z.writestr(info, data)
def bundle(self, version=VERSION, extra=None, gui=None):
"""The archive nightly.sh makes: the real template through the real plist helper."""
stage = self.root / "stage"
shutil.rmtree(stage, ignore_errors=True)
app = stage / APP
(app / "Contents/MacOS").mkdir(parents=True)
(app / "Contents/Resources").mkdir()
exe = app / "Contents/MacOS/CADCraft"
exe.write_text(gui or f"#!/bin/sh\ntouch {self.ran}\necho 'CADCraft {version} (nightly-v1)'\n")
exe.chmod(0o755)
(app / "Contents/Resources/cadcraft-nightly.icns").write_bytes(b"generated icon")
rendered = PLIST.render((HERE / "Info.plist.in").read_bytes(), version, COMMIT)
(app / "Contents/Info.plist").write_bytes(rendered)
for relative, data in (extra or {}).items():
(app / relative).write_bytes(data)
(app / relative).chmod(0o755)
if self.input.exists():
self.input.unlink()
with zipfile.ZipFile(self.input, "x") as z:
for path in sorted([app] + list(app.rglob("*"))):
arc = (Path(APP) / path.relative_to(app)).as_posix()
info = zipfile.ZipInfo(arc + ("/" if path.is_dir() else ""))
info.external_attr = (path.stat().st_mode & 0xFFFF) << 16
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
return self.input
def env(self, **changes):
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
env.update(changes)
return {key: value for key, value in env.items() if value is not None}
def run(self, script, *args, **env):
if self.log.exists():
self.log.unlink()
return subprocess.run(["bash", str(HERE / script), *map(str, args)], env=self.env(**env), cwd=self.cwd,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120)
def sign(self, **env):
return self.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.input, "--output", self.output, **env)
def calls(self):
if not self.log.exists():
return []
return [json.loads(line) for line in self.log.read_text().splitlines()]
def lib(function, *args):
"""Run one nightly-lib.sh function; returns (exit status, stdout)."""
script = f'. {str(HERE / "nightly-lib.sh")!r}; {function} "$@"'
result = subprocess.run(["bash", "-c", script, "lib", *args], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
return result.returncode, result.stdout.strip()
DETAILS = (f"Identifier=ai.storyteller.cadcraft.nightly\nCodeDirectory v=20500 size=1 flags=0x10000(runtime) hashes=1\n"
f"Authority=Developer ID Application: Generated Fixture ({TEAM})\nAuthority=Developer ID Certification Authority\n"
f"Timestamp=23 Nov 2026\nTeamIdentifier={TEAM}\n")
class Checks(unittest.TestCase):
def test_the_version_comes_only_from_a_prepared_nightly_asset_name(self):
self.assertEqual(lib("mac_nightly_version_from_asset", ASSET), (0, VERSION))
for name in (f"cadcraft-0.23.1-macos-aarch64.zip", f"cadcraft-{VERSION}-macos-universal-nightly.zip",
f"cadcraft-{VERSION}-linux-x86_64-nightly.tar.gz", ASSET.replace(".g", ".x"), "../" + ASSET):
with self.subTest(name=name):
self.assertNotEqual(lib("mac_nightly_version_from_asset", name)[0], 0)
def test_signature_needs_every_part_of_the_developer_id_signature(self):
self.assertEqual(lib("mac_nightly_check_signature", DETAILS, TEAM)[0], 0)
for broken in (DETAILS.replace("flags=0x10000(runtime)", "flags=0x0(none)"),
DETAILS.replace("Timestamp=23 Nov 2026\n", "Signed Time=23 Nov 2026\n"),
"Identifier=cadcraft-1234\nSignature=adhoc\nTeamIdentifier=not set\n",
DETAILS.replace("ai.storyteller.cadcraft.nightly", "ai.storyteller.cadcraft"),
DETAILS.replace("ai.storyteller.cadcraft.nightly", "aiXstorytellerXcadcraftXnightly")):
with self.subTest(broken=broken):
self.assertNotEqual(lib("mac_nightly_check_signature", broken, TEAM)[0], 0)
self.assertNotEqual(lib("mac_nightly_check_signature", DETAILS, "ZZZZZ99999")[0], 0, "another team")
def test_gatekeeper_must_accept_the_bundle_as_notarized(self):
self.assertEqual(lib("mac_nightly_check_assessment", "x.app: accepted\nsource=Notarized Developer ID\n")[0], 0)
for text in ("x.app: accepted\nsource=Developer ID\n", "x.app: rejected\nsource=Unnotarized Developer ID\n"):
with self.subTest(text=text):
self.assertNotEqual(lib("mac_nightly_check_assessment", text)[0], 0)
def test_the_imported_identity_must_be_a_developer_id_of_the_team(self):
line = f' 1) {IDENTITY} "Developer ID Application: Generated Fixture ({TEAM})"'
self.assertEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, TEAM)[0], 0)
self.assertNotEqual(lib("mac_nightly_identity_is_team", line, IDENTITY, "ZZZZZ99999")[0], 0)
self.assertNotEqual(lib("mac_nightly_identity_is_team", line.replace("Developer ID Application", "Apple Development"), IDENTITY, TEAM)[0], 0)
class Sign(unittest.TestCase):
def setUp(self):
self.f = Fixture(self)
self.f.bundle()
self.unsigned = self.f.input.read_bytes()
def assert_refused_untouched(self, result, signed=False):
self.assertNotEqual(result.returncode, 0, result.stdout)
self.assertFalse(self.f.output.exists())
self.assertEqual(self.f.input.read_bytes(), self.unsigned)
self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step")
names = [call[0] for call in self.f.calls()]
self.assertNotIn("cargo", names)
if not signed:
self.assertNotIn("codesign", names)
self.assertNotIn("xcrun", names)
self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed")
def test_signs_notarizes_and_staples_without_running_the_payload(self):
result = self.f.sign()
self.assertEqual(result.returncode, 0, result.stdout)
self.assertFalse(self.f.hijacked.exists(), "helpers run isolated (python3 -I) beside the secrets")
calls = self.f.calls()
names = [call[0] for call in calls]
self.assertNotIn("cargo", names)
self.assertFalse(self.f.ran.exists(), "the payload must never run in the signing step")
self.assertEqual(self.f.input.read_bytes(), self.unsigned)
signs = [call for call in calls if call[0] == "codesign" and "--sign" in call]
self.assertEqual([Path(call[-1]).name for call in signs], ["CADCraft", APP], "inside-out: executable, then bundle")
for call in signs:
for flag in ("--force", "--timestamp", "runtime", str(HERE / "entitlements.plist"), IDENTITY):
self.assertIn(flag, call)
order = [" ".join(call[:3]) for call in calls]
submit = order.index("xcrun notarytool submit")
staple = order.index("xcrun stapler staple")
self.assertLess(max(i for i, call in enumerate(calls) if call[0] == "codesign" and "--sign" in call), submit)
self.assertLess(submit, staple)
final = [i for i, call in enumerate(calls) if call[0] == "ditto" and "-c" in call][-1]
self.assertLess(staple, final, "the final archive carries the stapled ticket")
self.assertIn("--noextattr", calls[final])
self.assertIn(["security", "delete-keychain"], [call[:2] for call in calls])
self.assertEqual(list(self.f.temp.iterdir()), [], "the work directory and keychain are removed")
with zipfile.ZipFile(self.f.output) as z:
names = set(z.namelist())
self.assertIn(f"{APP}/Contents/CodeResources", names, "stapled ticket inside the bundle")
self.assertIn(f"{APP}/Contents/_CodeSignature/CodeResources", names)
self.assertTrue(all(name.startswith(APP) for name in names))
mode = z.getinfo(f"{APP}/Contents/MacOS/CADCraft").external_attr >> 16
self.assertTrue(mode & stat.S_IXUSR)
def test_every_signing_and_notarization_secret_is_required(self):
for name in SECRETS:
with self.subTest(missing=name):
self.assert_refused_untouched(self.f.sign(**{name: None}))
self.assertEqual(self.f.calls(), [], "no tool runs before the configuration is complete")
self.assert_refused_untouched(self.f.sign(NIGHTLY_APPLE_TEAM_ID="ZZZZZ99999"))
self.assert_refused_untouched(self.f.sign(APPLE_TEAM_ID="not-a-team"))
def test_refuses_another_team_s_identity(self):
self.assert_refused_untouched(self.f.sign(SHIM_TEAM="ZZZZZ99999"))
def test_never_replaces_an_output_or_renames_the_asset(self):
self.f.output.write_bytes(b"generated existing artifact")
result = self.f.sign()
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.f.output.read_bytes(), b"generated existing artifact")
self.f.output.unlink()
renamed = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input, "--output", self.f.signed / "other.zip")
self.assertNotEqual(renamed.returncode, 0)
relative = self.f.run("nightly-sign.sh", "--arch", "aarch64", "--input", self.f.input.name, "--output", self.f.output)
self.assertNotEqual(relative.returncode, 0)
self.assertEqual(list(self.f.signed.iterdir()), [])
def test_refuses_a_payload_that_is_not_the_exact_gui_only_nightly(self):
cases = {
"cli": dict(extra={"Contents/MacOS/cadcraft-cli": b"generated cli"}),
"version": dict(version=VERSION.replace("4567", "4568")),
}
for label, change in cases.items():
with self.subTest(label=label):
self.f.bundle(**change)
self.unsigned = self.f.input.read_bytes()
self.assert_refused_untouched(self.f.sign())
def test_refuses_links_traversal_and_foreign_entries_before_unpacking(self):
link = zipfile.ZipInfo(f"{APP}/Contents/Resources/link")
link.external_attr = (stat.S_IFLNK | 0o777) << 16
fifo = zipfile.ZipInfo(f"{APP}/Contents/Resources/fifo")
fifo.external_attr = (stat.S_IFIFO | 0o644) << 16
for label, info in (("link", link), ("special", fifo), ("traversal", zipfile.ZipInfo(f"{APP}/../outside")),
("absolute", zipfile.ZipInfo("/tmp/outside")), ("foreign root", zipfile.ZipInfo("Other.app/x"))):
with self.subTest(label=label):
self.f.bundle()
self.f.add_entry(info, b"/etc/passwd")
self.unsigned = self.f.input.read_bytes()
result = self.f.sign()
self.assert_refused_untouched(result)
self.assertNotIn("ditto", [call[0] for call in self.f.calls()], "refused before unpacking")
def test_a_rejected_notarization_publishes_nothing_and_removes_the_keychain(self):
result = self.f.sign(SHIM_NOTARY="Invalid")
self.assert_refused_untouched(result, signed=True)
self.assertIn(["xcrun", "notarytool", "log"], [call[:3] for call in self.f.calls()])
self.assertNotIn(["xcrun", "stapler", "staple"], [call[:3] for call in self.f.calls()])
class Verify(unittest.TestCase):
def setUp(self):
self.f = Fixture(self)
def verify(self, *args, **env):
return self.f.run("nightly-verify.sh", "--input", self.f.input, *args, **{name: None for name in SECRETS}, **env)
def test_asks_the_gui_its_version_with_an_empty_environment(self):
self.f.bundle(gui=f"#!/bin/sh\n[ -z \"$INHERITED\" ] || exit 9\necho 'CADCraft {VERSION} (nightly-v1)'\n")
result = self.verify("--expect", "unsigned", INHERITED="generated")
self.assertEqual(result.returncode, 0, result.stdout)
self.f.bundle(gui="#!/bin/sh\necho 'CADCraft 0.23.1 (stable)'\n")
self.assertNotEqual(self.verify("--expect", "unsigned").returncode, 0)
def test_the_launcher_profile_form_must_answer_promptly_and_cleanly(self):
answer = f"echo 'CADCraft {VERSION} (nightly-v1)'"
# The shared producer smoke's exact form, with a fresh profile directory.
exact = ('#!/bin/sh\nif [ "$1" = --launch-profile ]; then\n'
' [ "$#" = 5 ] && [ "$2" = nightly-v1 ] && [ "$3" = --profile-root ] && [ -d "$4" ] && [ "$5" = --version ] || exit 7\n'
f'fi\n{answer}\n')
self.f.bundle(gui=exact)
result = self.verify("--expect", "unsigned")
self.assertEqual(result.returncode, 0, result.stdout)
hangs = f'#!/bin/sh\n[ "$1" != --launch-profile ] || exec /bin/sleep 60\n{answer}\n'
self.f.bundle(gui=hangs)
started = time.monotonic()
result = self.verify("--expect", "unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("within 15 s", result.stdout)
self.assertLess(time.monotonic() - started, 45, "a hanging query is ended, not waited for")
noisy = f'#!/bin/sh\n[ "$1" != --launch-profile ] || echo refusal >&2\n{answer}\n'
self.f.bundle(gui=noisy)
result = self.verify("--expect", "unsigned")
self.assertNotEqual(result.returncode, 0)
self.assertIn("standard error", result.stdout)
def test_a_signed_check_needs_the_signature_ticket_and_team(self):
self.f.bundle()
self.assertNotEqual(self.verify("--expect", "signed").returncode, 0, "no team to check against")
self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0, "no stapled ticket")
self.f.bundle(extra={"Contents/CodeResources": b"ticket"})
self.assertEqual(self.verify("--expect", "signed", "--team", TEAM).returncode, 0)
self.assertNotEqual(self.verify("--expect", "signed", "--team", TEAM, SHIM_TEAM="ZZZZZ99999").returncode, 0)
def test_refuses_to_run_the_payload_beside_signing_material(self):
self.f.bundle()
for name in ("APPLE_PASSWORD", "APPLE_CERTIFICATE", "MACOS_KEYCHAIN"):
with self.subTest(name=name):
result = self.f.run("nightly-verify.sh", "--input", self.f.input, "--expect", "unsigned",
**{**{key: None for key in SECRETS}, name: "generated"})
self.assertNotEqual(result.returncode, 0)
self.assertFalse(self.f.ran.exists())
self.assertEqual(self.f.calls(), [])
class Build(unittest.TestCase):
def test_compilation_refuses_signing_material_before_building(self):
f = Fixture(self)
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
with self.subTest(name=name):
result = f.run("nightly.sh", "--arch", "aarch64", **{**{key: None for key in SECRETS}, name: "generated"},
CADCRAFT_BUILD_CHANNEL="nightly-v1", CADCRAFT_VERSION=VERSION)
self.assertNotEqual(result.returncode, 0)
self.assertIn(name, result.stdout)
self.assertNotIn("cargo", [call[0] for call in f.calls()])
if __name__ == "__main__":
unittest.main()
+229
View File
@@ -0,0 +1,229 @@
#!/usr/bin/env python3
"""Synthetic app-owned archive/output tests; no native build or executable launch."""
import gzip
import importlib.util
import os
import runpy
import sys
from unittest import mock
from pathlib import Path
import subprocess
import tarfile
import tempfile
import unittest
HERE = Path(__file__).resolve().parent
SPEC = importlib.util.spec_from_file_location("photo_nightly_archive", HERE / "nightly-archive.py")
ARCHIVE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(ARCHIVE)
class ArchivePolicy(unittest.TestCase):
def setUp(self):
self.scratch = tempfile.TemporaryDirectory()
self.addCleanup(self.scratch.cleanup)
self.root = Path(self.scratch.name).resolve()
previous = Path.cwd()
os.chdir(self.root)
self.addCleanup(os.chdir, previous)
self.stage = self.root / "stage"
self.stage.mkdir()
self.output = self.root / "nightly.tar.gz"
self.required = {"cadcraft", "cadcraft-bin", "cadcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"}
for name in self.required:
(self.stage / name).write_bytes(b"generated fixture: " + name.encode())
(self.stage / "cadcraft").chmod(0o755)
def test_flat_regular_ustar_with_all_notices(self):
(self.stage / "OFL-Font.txt").write_text("generated fixture license", encoding="utf-8")
ARCHIVE.linux_archive(self.stage, self.output)
with tarfile.open(self.output) as archive:
self.assertEqual({m.name for m in archive}, self.required | {"OFL-Font.txt"})
self.assertTrue(all(m.isfile() and not m.pax_headers for m in archive))
self.assertEqual(archive.extractfile("cadcraft").read(), (self.stage / "cadcraft").read_bytes())
with gzip.open(self.output, "rb") as stream:
while (header := stream.read(512)) != bytes(512):
self.assertEqual(len(header), 512)
self.assertIn(header[156:157], {b"0", b"\0"})
self.assertEqual(header[257:263], b"ustar\0")
size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8)
stream.read(((size + 511) // 512) * 512)
def test_each_required_member_is_required_before_output(self):
for name in self.required:
with self.subTest(name=name):
content = (self.stage / name).read_bytes()
(self.stage / name).unlink()
with self.assertRaisesRegex(ValueError, "required"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
(self.stage / name).write_bytes(content)
def test_unexpected_cli_portable_or_installer_member_refuses(self):
for name in ["cadcraft-cli", "portable.txt", "cadcraft.desktop"]:
with self.subTest(name=name):
bad = self.stage / name
bad.write_bytes(b"generated fixture")
with self.assertRaisesRegex(ValueError, "unexpected"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
bad.unlink()
def test_symlink_refuses_before_output(self):
icon = self.stage / "cadcraft-nightly.png"
icon.unlink()
icon.symlink_to(self.stage / "README.md")
with self.assertRaisesRegex(ValueError, "regular file|symlinks or aliases"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
def test_directory_refuses_before_output(self):
icon = self.stage / "cadcraft-nightly.png"
icon.unlink()
icon.mkdir()
with self.assertRaisesRegex(ValueError, "regular file"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
def test_long_notice_refuses_before_output(self):
(self.stage / ("OFL-" + "x" * 100 + ".txt")).write_bytes(b"fixture")
with self.assertRaisesRegex(ValueError, "short regular"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
def test_case_colliding_notices_refuse_before_output(self):
for name in ["OFL-Font.txt", "OFL-font.txt"]:
(self.stage / name).write_bytes(b"fixture")
with self.assertRaisesRegex(ValueError, "case-colliding"):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
def test_cli_dispatches_only_the_supported_archive_kind(self):
helper = HERE / "nightly-archive.py"
with mock.patch.object(sys, "argv", [str(helper), "linux", str(self.stage), str(self.output)]):
runpy.run_path(str(helper), run_name="__main__")
with tarfile.open(self.output) as archive:
self.assertEqual({member.name for member in archive}, self.required)
refused = self.root / "refused.tar.gz"
for args in ([str(helper)], [str(helper), "unknown", str(self.stage), str(refused)]):
with self.subTest(args=args), mock.patch.object(sys, "argv", args):
with self.assertRaises(SystemExit):
runpy.run_path(str(helper), run_name="__main__")
self.assertFalse(refused.exists())
def test_existing_archive_is_unchanged(self):
self.output.write_bytes(b"owned earlier artifact")
with self.assertRaises(FileExistsError):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertEqual(self.output.read_bytes(), b"owned earlier artifact")
def test_archive_output_outside_build_root_refuses(self):
with tempfile.TemporaryDirectory() as external:
output = Path(external) / "nightly.tar.gz"
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(self.stage, output)
self.assertFalse(output.exists())
def test_archive_stage_outside_build_root_refuses(self):
with tempfile.TemporaryDirectory() as external:
stage = Path(external)
for name in self.required:
(stage / name).write_bytes(b"generated external fixture")
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(stage, self.output)
self.assertFalse(self.output.exists())
def test_archive_stage_alias_refuses(self):
alias = self.root / "stage-alias"
alias.symlink_to(self.stage, target_is_directory=True)
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(alias, self.output)
self.assertFalse(self.output.exists())
def test_archive_output_parent_alias_refuses(self):
with tempfile.TemporaryDirectory() as external:
alias = self.root / "output-alias"
alias.symlink_to(external, target_is_directory=True)
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(self.stage, alias / "nightly.tar.gz")
self.assertFalse((Path(external) / "nightly.tar.gz").exists())
def test_archive_parent_traversal_refuses(self):
with tempfile.TemporaryDirectory(dir=self.root.parent) as external:
output = Path("..") / Path(external).name / "nightly.tar.gz"
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(self.stage, output)
self.assertFalse((Path(external) / "nightly.tar.gz").exists())
def test_nonflat_member_name_refuses(self):
stage_root = os.path.realpath(self.stage)
with open(self.stage / "README.md", "rb") as incoming:
for bad in ("../escape", "/absolute", "nested/name", "x/../README.md", "", ".", ".."):
with self.subTest(name=bad), self.assertRaises(ValueError):
ARCHIVE.member_info(stage_root, bad, incoming)
def test_member_header_matches_what_gettarinfo_records(self):
stage_root = os.path.realpath(self.stage)
for name in sorted(self.required):
with self.subTest(name=name), open(self.stage / name, "rb") as incoming:
ours = ARCHIVE.member_info(stage_root, name, incoming)
with tarfile.open(fileobj=__import__("io").BytesIO(), mode="w") as reference:
theirs = reference.gettarinfo(fileobj=incoming, arcname=name)
self.assertEqual(ours.get_info(), theirs.get_info())
def test_member_read_budget_refuses_before_output(self):
(self.stage / "OFL-Large.txt").write_bytes(b"x" * 65)
with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64, create=True):
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
def test_member_growth_is_rechecked_before_copy_and_output_is_cleaned(self):
growing = self.stage / "OFL-Growing.txt"
growing.write_bytes(b"x" * 32)
original = ARCHIVE.member_info
def grow_before_stat(stage_root, name, incoming):
if name == growing.name:
growing.write_bytes(b"x" * 65)
return original(stage_root, name, incoming)
with mock.patch.object(ARCHIVE, "MAX_MEMBER_BYTES", 64), \
mock.patch.object(ARCHIVE, "member_info", grow_before_stat):
with self.assertRaises(ValueError):
ARCHIVE.linux_archive(self.stage, self.output)
self.assertFalse(self.output.exists())
class ExclusiveOutput(unittest.TestCase):
def setUp(self):
self.scratch = tempfile.TemporaryDirectory()
self.addCleanup(self.scratch.cleanup)
self.root = Path(self.scratch.name)
self.source = self.root / "input archive"
self.output = self.root / "final archive"
self.source.write_bytes(b"generated archive fixture" * 1024)
def publish(self):
return subprocess.run(["bash", "-c", 'set -euo pipefail; source "$1"; nightly_publish_archive "$2" "$3"', "test", str(HERE / "nightly-common.sh"), str(self.source), str(self.output)], capture_output=True, text=True, timeout=15)
def test_success_copies_exact_bytes(self):
result = self.publish()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.output.read_bytes(), self.source.read_bytes())
def test_existing_output_is_never_replaced(self):
self.output.write_bytes(b"existing artifact")
self.assertNotEqual(self.publish().returncode, 0)
self.assertEqual(self.output.read_bytes(), b"existing artifact")
def test_missing_source_does_not_leave_a_fake_empty_artifact(self):
self.source.unlink()
self.assertNotEqual(self.publish().returncode, 0)
self.assertFalse(self.output.exists())
if __name__ == "__main__":
unittest.main()
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""Flat Linux archive policy, invoked from its private owned build cwd.
The stage and archive must both remain under that independently chosen root.
No native build, platform signing, or malicious-same-UID sandbox is implied.
"""
import grp
import gzip
import os
import pathlib
import pwd
import re
import stat
import sys
import tarfile
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from nightly_paths import OwnedBuildRoot
APP_DOCS = {"README.md", "LICENSE", "LICENSE-MIT", "LICENSE-APACHE", "COPYRIGHT", "NOTICE", "ATTRIBUTION.md"}
MAX_MEMBER_BYTES = 512 * 1024 * 1024
MAX_TOTAL_BYTES = 1024 * 1024 * 1024
MAX_MEMBERS = 128
def notice(name):
return name in APP_DOCS or re.fullmatch(r"OFL-[A-Za-z0-9_.-]+\.txt", name) is not None
def checked_entries(root, stage):
entries = sorted(root.children(stage, MAX_MEMBERS), key=lambda item: item.name)
folded = set()
total = 0
for entry in entries:
name = entry.name
# `cadcraft` is the launcher and `cadcraft-bin` the GUI it starts with the private profile.
if name not in {"cadcraft", "cadcraft-bin", "cadcraft-nightly.png"} and not notice(name):
raise ValueError(f"unexpected nightly member: {name}")
if len(name.encode("utf-8")) > 100:
raise ValueError(f"nightly member must be a short regular file: {name}")
with root.reader(entry, MAX_MEMBER_BYTES) as stream:
total += os.fstat(stream.fileno()).st_size
if total > MAX_TOTAL_BYTES:
raise ValueError("nightly stage exceeds its read bound")
if name.casefold() in folded:
raise ValueError(f"case-colliding nightly member: {name}")
folded.add(name.casefold())
required = {"cadcraft", "cadcraft-bin", "cadcraft-nightly.png", "README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md"}
if not required.issubset({item.name for item in entries}):
raise ValueError("required GUI/icon/notices missing")
return entries
def member_info(stage_root, name, incoming):
"""Header for one stage file, built from the file this run opened rather than from the archive.
Members are flat names that resolve directly inside the stage they came from.
"""
if os.path.isabs(name) or os.path.basename(name) != name or name in ("", ".", ".."):
raise ValueError(f"nightly member name must be a flat file name: {name}")
destination = os.path.realpath(os.path.join(stage_root, name))
if not destination.startswith(stage_root + os.sep) or os.path.dirname(destination) != stage_root:
raise ValueError(f"nightly member resolves outside its stage: {name}")
status = os.fstat(incoming.fileno())
if not stat.S_ISREG(status.st_mode):
raise ValueError(f"nightly member must be a regular file: {name}")
# The same fields TarFile.gettarinfo records for a regular file.
info = tarfile.TarInfo(os.path.basename(destination))
info.type = tarfile.REGTYPE
info.mode = stat.S_IMODE(status.st_mode)
info.uid, info.gid = status.st_uid, status.st_gid
info.size = status.st_size
info.mtime = status.st_mtime
try:
info.uname = pwd.getpwuid(status.st_uid).pw_name
except KeyError:
pass
try:
info.gname = grp.getgrgid(status.st_gid).gr_name
except KeyError:
pass
return info
def verify_headers(root, output):
# Bounded ordinary headers, not a transparent PAX/GNU-normalizing reader.
total = 0
count = 0
with root.reader(output, MAX_TOTAL_BYTES) as incoming, gzip.GzipFile(fileobj=incoming) as stream:
while True:
header = stream.read(512)
if header == b"\0" * 512:
break
if len(header) != 512 or header[156:157] not in {b"0", b"\0"}:
raise ValueError("non-ordinary TAR record was emitted")
size = int(header[124:136].rstrip(b"\0 ").lstrip(b" ") or b"0", 8)
count += 1
total += size
if count > MAX_MEMBERS or size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES:
raise ValueError("archive exceeds its bounded member budget")
remaining = ((size + 511) // 512) * 512
while remaining:
chunk = stream.read(min(remaining, 1024 * 1024))
if not chunk:
raise ValueError("truncated TAR member")
remaining -= len(chunk)
def linux_archive(stage, output):
with OwnedBuildRoot() as root:
entries = checked_entries(root, stage)
stage_root = os.path.realpath(os.path.join(root.directory, stage))
total = 0
with root.create(output) as outgoing:
with tarfile.open(fileobj=outgoing, mode="w:gz", format=tarfile.USTAR_FORMAT) as archive:
for entry in entries:
with root.reader(entry, MAX_MEMBER_BYTES) as incoming:
info = member_info(stage_root, entry.name, incoming)
total += info.size
if info.size > MAX_MEMBER_BYTES or total > MAX_TOTAL_BYTES:
raise ValueError("nightly stage grew beyond its read bound")
archive.addfile(info, incoming)
outgoing.flush()
os.fsync(outgoing.fileno())
verify_headers(root, output)
if __name__ == "__main__":
if len(sys.argv) != 4 or sys.argv[1] != "linux":
raise SystemExit("usage: nightly-archive.py linux STAGE OUTPUT (from owned private build cwd)")
linux_archive(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3]))
+104
View File
@@ -0,0 +1,104 @@
# shellcheck shell=bash
# Shared setup for app-owned native nightly archives; stable packaging does not source this file.
nightly_die() { printf 'error: %s\n' "$*" >&2; exit 2; }
nightly_init() {
local os="$1" arch="$2" target="$3" date_digits
[[ "${CADCRAFT_BUILD_CHANNEL:-}" == nightly-v1 ]] || nightly_die 'CADCRAFT_BUILD_CHANNEL must be nightly-v1'
[[ "${CADCRAFT_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.[0-9]{8}\.[0-9]+\.[0-9]+\.g[0-9a-f]{12}$ ]] || nightly_die 'an exact prepared nightly version is required'
[[ "${CADCRAFT_BUILD_SHA:-}" =~ ^[0-9a-f]{40}$ ]] || nightly_die 'an exact source commit is required'
[[ "${CADCRAFT_VERSION##*.g}" == "${CADCRAFT_BUILD_SHA:0:12}" ]] || nightly_die 'version/source commit mismatch'
[[ "${CADCRAFT_BUILD_DATE:-}" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] || nightly_die 'the original run-created UTC date is required'
date_digits="${CADCRAFT_VERSION#*-nightly.}"
date_digits="${date_digits%%.*}"
[[ "${CADCRAFT_BUILD_DATE//-/}" == "$date_digits" ]] || nightly_die 'version/original-run date mismatch'
[[ "${CARGO_TARGET_DIR:-}" == /* && "$CARGO_TARGET_DIR" != / ]] || nightly_die 'an absolute owned CARGO_TARGET_DIR base is required'
[[ "${DIST:-}" == /* && "$DIST" != / ]] || nightly_die 'an absolute DIST output directory is required'
[[ "/$CARGO_TARGET_DIR/" != *'/../'* && "/$DIST/" != *'/../'* ]] || nightly_die 'output paths must not contain parent traversal'
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$CADCRAFT_BUILD_SHA" ]] || nightly_die 'prepared source is not the checked-out commit'
[[ -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'nightly packaging requires the frozen clean source'
if [[ -n "${CRAFT_FONTS_DIR:-}" && ! -d "$CRAFT_FONTS_DIR/fonts" ]]; then
nightly_die 'declared CRAFT_FONTS_DIR has no fonts directory'
fi
# env.sh retains the established notice copier. Required values above prohibit its stable fallbacks.
# shellcheck source=env.sh
. "$ROOT/packaging/env.sh"
export CARGO_TARGET_DIR="$CARGO_TARGET_DIR/nightly-v1/$os-$arch"
NIGHTLY_RUST_TARGET="$target"
mkdir -p "$CARGO_TARGET_DIR"
NIGHTLY_WORK="$(mktemp -d "$CARGO_TARGET_DIR/nightly-package.XXXXXX")"
trap 'rm -rf -- "$NIGHTLY_WORK"' EXIT
}
# Compile only: macOS runs the version query after signing. The flavor's `build.rs` compiles the
# channel from `CADCRAFT_BUILD_CHANNEL` and embeds `CADCRAFT_VERSION` (it does not read the
# PhotoCraft-style `CADCRAFT_OVERRIDE_VERSION`, so both are passed explicitly rather than inherited).
nightly_compile_gui() {
# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule).
nightly_refuse_signing_env
(cd "$ROOT" && CADCRAFT_BUILD_CHANNEL=nightly-v1 CADCRAFT_VERSION="$VERSION" \
cargo build --release --locked -p cadcraft --target "$NIGHTLY_RUST_TARGET")
NIGHTLY_GUI="$CARGO_TARGET_DIR/$NIGHTLY_RUST_TARGET/release/cadcraft"
[[ -f "$NIGHTLY_GUI" && ! -L "$NIGHTLY_GUI" ]] || nightly_die 'the owned GUI build did not produce a regular executable'
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$CADCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the build'
}
# The flavor prints exactly what it is -- `CADCraft <prepared version> (nightly-v1)` -- so the check
# compares that line, not a substring a stable binary could also print. The Launcher's query form is
# answered from the same parse, before any root is validated, so it must leave the root uncreated.
nightly_build_gui() {
nightly_compile_gui
local actual expected query_root
expected="CADCraft $VERSION (nightly-v1)"
actual="$("$NIGHTLY_GUI" --version)" || nightly_die 'side-effect-free nightly version verification failed'
[[ "$actual" == "$expected" ]] || nightly_die "the built identity is not the prepared nightly: $actual"
query_root="$NIGHTLY_WORK/launcher-query-profile"
actual="$("$NIGHTLY_GUI" --launch-profile nightly-v1 --profile-root "$query_root" --version)" \
|| nightly_die 'the Launcher version query did not answer'
[[ "$actual" == "$expected" ]] || nightly_die "the Launcher version query did not report the prepared identity: $actual"
[[ ! -e "$query_root" && ! -L "$query_root" ]] || nightly_die 'the Launcher version query touched the profile root'
[[ "$(git -C "$ROOT" rev-parse HEAD)" == "$CADCRAFT_BUILD_SHA" && -z "$(git -C "$ROOT" status --porcelain)" ]] || nightly_die 'source changed during the version query'
}
# Signing material never reaches compilation (the Windows -CheckBuildEnvironment rule).
nightly_refuse_signing_env() {
local name
# The signing names release.yml passes, for every platform, and import-cert.sh's outputs.
for name in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD KEYCHAIN_PASSWORD APPLE_ID APPLE_PASSWORD APPLE_TEAM_ID \
MACOS_SIGN_IDENTITY MACOS_KEYCHAIN WINDOWS_CERTIFICATE WINDOWS_CERTIFICATE_PASSWORD AZURE_TENANT_ID AZURE_CLIENT_ID \
AZURE_CLIENT_SECRET AZURE_SIGNING_ENDPOINT AZURE_SIGNING_ACCOUNT AZURE_CERT_PROFILE LINUX_SIGNING_KEY; do
[[ -z "${!name:-}" ]] || nightly_die "compilation must not receive signing configuration ($name); sign in the separate trusted step"
done
}
nightly_copy_notices() {
local destination="$1" required
for required in README.md LICENSE-MIT LICENSE-APACHE NOTICE ATTRIBUTION.md; do
[[ -f "$ROOT/$required" && ! -L "$ROOT/$required" ]] || nightly_die "missing regular app notice: $required"
done
copy_docs "$destination"
}
nightly_publish_archive() {
# Exclusive creation: never replace an existing artifact, even if another writer raced the preflight.
python3 -I - "$1" "$2" <<'PY'
import os, shutil, sys
source, destination = sys.argv[1:]
created = False
try:
# Open the input first: a missing source must not leave an empty final artifact.
with open(source, 'rb') as incoming:
with open(destination, 'xb') as output:
created = True
shutil.copyfileobj(incoming, output, length=1024 * 1024)
output.flush()
os.fsync(output.fileno())
except BaseException:
if created:
os.unlink(destination)
raise
PY
printf 'Nightly artifact: %s\n' "$2"
}
+161
View File
@@ -0,0 +1,161 @@
#!/usr/bin/env python3
"""Every Linux Nightly launcher starts the GUI the flavor's way; no build, no window.
The deb/rpm wrapper, the AppImage `AppRun` and the Flatpak wrapper are generated inside
package.sh/flatpak-bundle.sh; the plain tar and the Arch handoff ship a launcher file. All of them
must hand the binary the one protocol the flavor accepts -- `--launch-profile nightly-v1
--profile-root <dir> -- files...` -- and pass a version query through untouched.
"""
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
HERE = Path(__file__).resolve().parent
LINUX = HERE / "linux"
PROFILE = "cadcraft-nightly"
RECORDER = '#!/bin/sh\nfor arg in "$@"; do printf "<%s>\\n" "$arg"; done\n'
CONFIG_RECORDER = (
'#!/bin/sh\nprintf "config=%s\\n" "${CADCRAFT_CONFIG_DIR+<$CADCRAFT_CONFIG_DIR>}"\n'
'for arg in "$@"; do printf "<%s>\\n" "$arg"; done\n'
)
def heredoc(script, marker, needle):
"""The one heredoc body in `script` delimited by `marker` that contains `needle`."""
text = Path(script).read_text(encoding="utf-8")
bodies = []
start = 0
while (opening := text.find("<<'%s'" % marker, start)) != -1:
body_start = text.index("\n", opening) + 1
body_end = text.index("\n%s\n" % marker, body_start)
bodies.append(text[body_start:body_end] + "\n")
start = body_end + 1
matched = [body for body in bodies if needle in body]
if len(matched) != 1:
raise AssertionError(f"expected one {marker} heredoc with {needle!r} in {script}, found {len(matched)}")
return matched[0]
class Launcher(unittest.TestCase):
def setUp(self):
scratch = tempfile.TemporaryDirectory()
self.addCleanup(scratch.cleanup)
self.root = Path(scratch.name).resolve()
self.home = self.root / "home with space"
self.home.mkdir()
self.real = self.root / "cadcraft-real"
self.real.write_text(RECORDER, encoding="utf-8")
self.real.chmod(0o755)
def launcher(self, name, body):
path = self.root / name
path.write_text(body, encoding="utf-8")
path.chmod(0o755)
return path
def generated(self, script, marker, needle, replacement):
body = heredoc(script, marker, needle)
return self.launcher("cadcraft-nightly", body.replace(needle, str(replacement)))
def recording(self, launcher, *args, env=None):
environment = {"PATH": "/usr/bin:/bin", "HOME": str(self.home), **(env or {})}
result = subprocess.run([str(launcher), *args], capture_output=True, text=True, env=environment, timeout=60)
self.assertEqual(result.returncode, 0, result.stderr)
return [line[1:-1] for line in result.stdout.splitlines() if line.startswith("<")]
def profile_base(self, env=None, fallback=(".local", "share")):
return Path((env or {}).get("XDG_DATA_HOME") or self.home.joinpath(*fallback)) / PROFILE
def assert_starts_the_profile(self, launcher, env=None, fallback=(".local", "share")):
root = str(self.profile_base(env, fallback))
files = ["drawing.dxf", "with spaces and -- dashes.dxf"]
self.assertEqual(
self.recording(launcher, *files, env=env),
["--launch-profile", "nightly-v1", "--profile-root", root, "--", *files],
launcher,
)
self.assertEqual(self.recording(launcher, env=env), ["--launch-profile", "nightly-v1", "--profile-root", root, "--"])
for flag in ("--version", "-V"):
self.assertEqual(self.recording(launcher, flag, env=env), [flag], launcher)
query = ["--launch-profile", "nightly-v1", "--profile-root", str(self.root / "launcher root"), "--version"]
self.assertEqual(self.recording(launcher, *query, env=env), query, "a Launcher query is passed through once")
def test_the_plain_tar_launcher_starts_the_profile(self):
launcher = LINUX / "nightly-launch.sh"
(self.root / "cadcraft-bin").write_text(RECORDER, encoding="utf-8")
(self.root / "cadcraft-bin").chmod(0o755)
installed = self.launcher("cadcraft", launcher.read_text(encoding="utf-8"))
self.assert_starts_the_profile(installed)
self.assert_starts_the_profile(installed, {"XDG_DATA_HOME": str(self.root / "xdg with space")})
def test_the_tar_launcher_refuses_a_missing_or_aliased_gui(self):
launcher = self.launcher("cadcraft", (LINUX / "nightly-launch.sh").read_text(encoding="utf-8"))
for args in ([], ["--version"]):
with self.subTest(args=args):
result = subprocess.run([str(launcher), *args], capture_output=True, text=True, timeout=60, env={"PATH": "/usr/bin:/bin", "HOME": str(self.home)})
self.assertEqual(result.returncode, 2, result.stdout)
self.assertIn("cadcraft-bin is missing", result.stderr)
(self.root / "elsewhere").write_text(RECORDER, encoding="utf-8")
(self.root / "elsewhere").chmod(0o755)
(self.root / "cadcraft-bin").symlink_to(self.root / "elsewhere")
result = subprocess.run([str(launcher)], capture_output=True, text=True, timeout=60, env={"PATH": "/usr/bin:/bin", "HOME": str(self.home)})
self.assertEqual(result.returncode, 2, "an aliased GUI is not started")
def test_the_arch_launcher_starts_the_profile(self):
(self.root / ".cadcraft-nightly").mkdir()
shutil.copy(self.real, self.root / ".cadcraft-nightly" / "cadcraft")
installed = self.launcher("cadcraft-nightly", (LINUX / "nightly-arch-launch.sh").read_text(encoding="utf-8"))
self.assert_starts_the_profile(installed)
self.assert_starts_the_profile(installed, {"XDG_DATA_HOME": str(self.root / "xdg with space")})
def test_the_deb_and_rpm_wrapper_starts_the_profile(self):
generated = self.generated(LINUX / "package.sh", "WRAPPER", "/usr/lib/cadcraft-nightly/cadcraft", self.real)
self.assert_starts_the_profile(generated)
self.assert_starts_the_profile(generated, {"XDG_DATA_HOME": str(self.root / "xdg with space")})
def test_the_appimage_apprun_starts_the_profile(self):
appdir = self.root / "CADCraft.AppDir"
(appdir / "usr/bin").mkdir(parents=True)
shutil.copy(self.real, appdir / "usr/bin" / "cadcraft")
apprun = self.launcher("AppRun", heredoc(LINUX / "package.sh", "APPRUN", "$APPDIR/usr/bin/cadcraft"))
shutil.move(str(apprun), str(appdir / "AppRun"))
self.assert_starts_the_profile(appdir / "AppRun")
self.assert_starts_the_profile(appdir / "AppRun", {"XDG_DATA_HOME": str(self.root / "xdg with space")})
def test_the_nightly_cli_keeps_its_settings_in_the_profile(self):
body = heredoc(LINUX / "package.sh", "CLI_WRAPPER", "/usr/lib/cadcraft-nightly/cadcraft-cli")
cli = self.launcher("cadcraft-nightly-cli", body.replace("/usr/lib/cadcraft-nightly/cadcraft-cli", str(self.real)))
self.real.write_text(CONFIG_RECORDER, encoding="utf-8")
self.real.chmod(0o755)
# A downstream process sees the variable the CLI wrapper exported.
def recorded(*args, config=None, xdg=None):
environment = {"PATH": "/usr/bin:/bin", "HOME": str(self.home)}
if xdg is not None:
environment["XDG_DATA_HOME"] = xdg
if config is not None:
environment["CADCRAFT_CONFIG_DIR"] = config
result = subprocess.run([str(cli), *args], capture_output=True, text=True, env=environment, timeout=60)
self.assertEqual(result.returncode, 0, result.stderr)
lines = result.stdout.splitlines()
return lines[0], lines[1:]
base = Path(str(self.home / ".local" / "share")) / PROFILE
self.assertEqual(recorded("convert", "in.dxf"), (f"config=<{base}>", ["<convert>", "<in.dxf>"]))
self.assertEqual(recorded("convert", xdg=str(self.root / "xdg with space"))[0], f"config=<{self.root}/xdg with space/{PROFILE}>")
# An explicitly empty value still means "no settings folder", and an explicit one is kept.
self.assertEqual(recorded("run")[0], f"config=<{base}>")
self.assertEqual(recorded("run", config="")[0], "config=<>")
self.assertEqual(recorded("run", config=str(self.root / "explicit"))[0], f"config=<{self.root}/explicit>")
def test_the_flatpak_wrapper_starts_the_profile(self):
generated = self.generated(LINUX / "flatpak-bundle.sh", "WRAPPER", "/app/libexec/cadcraft", self.real)
# Inside the bundle XDG_DATA_HOME is the nightly app's own sandbox folder.
sandbox = self.home / ".var/app/ai.storyteller.cadcraft.nightly/data"
self.assert_starts_the_profile(generated, {"XDG_DATA_HOME": str(sandbox)})
self.assert_starts_the_profile(generated, fallback=(".var", "app", "ai.storyteller.cadcraft.nightly", "data"))
if __name__ == "__main__":
unittest.main()
+396
View File
@@ -0,0 +1,396 @@
#!/usr/bin/env python3
"""Local contract tests for CADCraft's nightly producer, signer, and policy."""
import copy
import json
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
# Each platform's one trust field in policy v3, and the public stable identity it must name.
NIGHTLY_TRUST = {
"windows-x86_64": ("publisher_subject",
"CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"),
"linux-x86_64": ("fingerprint", "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"),
"macos-aarch64": ("apple_team_id", "DJ6XS33FX8"),
}
# Mirrors the storytold release-managers team (id 19837241) minus echelon-robot.
# Update by PR, in the caller and the policy, when the team changes.
RELEASE_MANAGERS = ["bflatastic", "dylanmtaylor", "echelon", "FredApps", "skylartaylor"]
def assert_nightly_serialization(source):
"""Fail closed unless this app's plain root concurrency block retains its contract."""
lines = source.splitlines()
roots = [index for index, line in enumerate(lines) if line.startswith("concurrency:")]
if len(roots) != 1 or lines[roots[0]] != "concurrency:":
raise ValueError("one plain root concurrency block is required")
values = {}
for line in lines[roots[0] + 1:]:
if not line.strip() or line.lstrip().startswith("#"):
continue
if not line[0].isspace():
break
row = re.fullmatch(r" (group|cancel-in-progress): ([^#]+?)(?: +#.*)?", line)
if row is None or row[1] in values:
raise ValueError("malformed or duplicate nightly concurrency entry")
values[row[1]] = row[2].rstrip()
if values != {"group": "cadcraft-nightly-release", "cancel-in-progress": "false"}:
raise ValueError("nightly serialization must use its stable group and no cancellation")
def job_conditions(jobs):
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read)."""
lines = jobs.splitlines()
found = []
for index, line in enumerate(lines):
head = re.fullmatch(r" if:(?: (.*))?", line)
if head is None:
continue
value = (head[1] or "").strip()
continuation = []
for follow in lines[index + 1:]:
if follow.strip() and len(follow) - len(follow.lstrip(" ")) <= 4:
break
continuation.append(follow.strip())
indicator = value if re.fullmatch(r"[>|][+-]?", value) else None
parts = continuation if indicator else [value] + continuation
found.append((indicator, " ".join(part for part in parts if part)))
return found
def producer_platforms(source):
"""Read the one producer job's literal platform list; a narrow source guard, not YAML."""
rows = re.findall(r"(?m)^ platforms: (.*)$", source)
if len(rows) != 1:
raise ValueError("exactly one producer platform list is required")
literal = re.fullmatch(r"'(\[[^']*\])'", rows[0])
if literal is None:
raise ValueError("the platform list must be one single-quoted literal")
platforms = json.loads(literal[1])
if not isinstance(platforms, list) or json.dumps(platforms, separators=(",", ":")) != literal[1]:
raise ValueError("the platform list must be compact JSON")
if len(set(platforms)) != len(platforms) or not set(platforms) <= set(NIGHTLY_PLATFORMS):
raise ValueError("platforms must be distinct known nightly targets")
if "windows-x86_64" not in platforms:
raise ValueError("the Windows row stays in the producer")
return platforms
def reviewed_manual_actors(caller_source, policy):
"""The one reviewed manual-actor list, identical in the producer caller and the policy."""
rows = re.findall(r"(?m)^ manual-actors: '(\[[^']*\])'$", caller_source)
if len(rows) != 1:
raise ValueError("exactly one literal manual-actors list is required")
caller = json.loads(rows[0])
if caller != policy["manual_actors"]:
raise ValueError("caller and policy must grant the same actors in the same order")
if caller != RELEASE_MANAGERS:
raise ValueError("manual actors must be exactly the reviewed release managers")
if caller != sorted(caller, key=str.lower) or len({login.lower() for login in caller}) != len(caller):
raise ValueError("manual actors must be distinct and sorted case-insensitively")
if set(caller) & {login for login in policy["automatic_signer_actors"]}:
raise ValueError("manual and automatic actors overlap")
return caller
def caller_pin(name):
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$",
(ROOT / ".github/workflows" / name).read_text())[0]
class TrustedSourcePreparation(unittest.TestCase):
def test_one_producer_and_one_signer_job_carry_every_platform(self):
for name, job in (("nightly.yml", "unsigned"), ("nightly-sign.yml", "release")):
jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1]
with self.subTest(workflow=name):
self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), [job],
"a platform is a list entry, not a separately activatable job")
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
self.assertNotRegex(signer, r"(?m)^\s*platforms?:", "the release policy, not the caller, admits platforms")
def test_malformed_or_narrowed_platform_lists_are_rejected(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
current = "platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"macos-aarch64\"]'"
self.assertIn(current, source)
for new in ("platforms: '[\"linux-x86_64\"]'",
"platforms: '[\"linux-x86_64\",\"macos-aarch64\"]'",
"platforms: '[\"windows-x86_64\",\"linux-x86_64\",\"linux-x86_64\"]'",
"platforms: '[\"windows-x86_64\",\"macos-x86_64\"]'",
"platforms: '[\"windows-x86_64\",\"linux-arm64\"]'",
"platforms: '[\"windows-x86_64\", \"linux-x86_64\"]'",
"platforms: [\"windows-x86_64\",\"linux-x86_64\"]",
"platforms: ${{ vars.NIGHTLY_PLATFORMS }}",
"platforms: '{\"windows-x86_64\":1}'",
current + "\n " + current):
with self.subTest(change=new), self.assertRaises(ValueError):
producer_platforms(source.replace(current, new))
with self.assertRaises(ValueError):
producer_platforms(source.replace(" " + current + "\n", ""))
def test_continuation_lines_of_any_scalar_form_reach_the_guard_checks(self):
for name, workflow in (("nightly.yml", "nightly.yml"), ("nightly-sign.yml", "nightly-sign.yml")):
source = (ROOT / ".github/workflows" / workflow).read_text()
expected = NightlyEnabledCallers.GUARDS[name]
guard = re.search(r"(?m)^ if: >-\n(?: [^\n]*\n)+", source)[0]
for replacement in (guard + " || true\n", " if: " + expected + "\n || true\n"):
jobs = source.replace(guard, replacement).split("\njobs:\n", 1)[1]
with self.subTest(workflow=name, replacement=replacement[-30:]):
(indicator, expression), = job_conditions(jobs)
self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected)
def test_no_nightly_schedule_is_registered(self):
for name, event in (("nightly.yml", "workflow_dispatch"),
("nightly-sign.yml", "workflow_dispatch")):
source = (ROOT / ".github/workflows" / name).read_text()
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
triggers = [line for line in events.splitlines() if line.startswith(" ")
and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")]
with self.subTest(workflow=name):
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
def test_signer_serialization_contract_is_enforced(self):
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
def test_weakened_or_malformed_serialization_is_rejected(self):
source = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
for old, new in (
("cancel-in-progress: false", "cancel-in-progress: true"),
("cancel-in-progress: false", "cancel-in-progress: ${{ github.event_name == 'push' }}"),
("cancel-in-progress: false\n", ""),
("cancel-in-progress: false", "cancel-in-progress: false\n queue: max"),
("group: cadcraft-nightly-release", "group: ${{ github.run_id }}"),
("group: cadcraft-nightly-release", "group: release-${{ github.ref }}"),
("concurrency:\n", "concurrency: ${{ github.run_id }}\n"),
("concurrency:\n", " concurrency:\n"),
):
with self.subTest(change=new), self.assertRaises(ValueError):
assert_nightly_serialization(source.replace(old, new))
def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self):
for name in ("nightly.yml", "nightly-sign.yml"):
source = (ROOT / ".github/workflows" / name).read_text()
executable = "\n".join(line for line in source.splitlines()
if not line.lstrip().startswith("#"))
with self.subTest(workflow=name):
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
self.assertNotIn("secrets.", executable)
class NightlyTrustAnchors(unittest.TestCase):
"""The public stable identities each platform's signed nightly must carry."""
def setUp(self):
self.policy = json.loads(INSTALLED_POLICY.read_text())
def test_each_platform_row_names_its_fixed_artifact_kind_and_stable_identity(self):
self.assertEqual(set(self.policy["platforms"]), set(NIGHTLY_TRUST))
for platform, (field, value) in NIGHTLY_TRUST.items():
row = self.policy["platforms"][platform]
with self.subTest(platform=platform):
self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}",
"the artifact kind is fixed by platform, never a caller pattern")
self.assertEqual(row["trust"], {field: value}, "trust must be stable's public identity")
def test_trust_values_have_the_shapes_the_shared_signer_accepts(self):
rows = self.policy["platforms"]
self.assertRegex(rows["macos-aarch64"]["trust"]["apple_team_id"], r"^[A-Z0-9]{10}$")
self.assertRegex(rows["linux-x86_64"]["trust"]["fingerprint"], r"^[0-9A-F]{40}$")
subject = rows["windows-x86_64"]["trust"]["publisher_subject"]
self.assertTrue(0 < len(subject) <= 1024 and not set(subject) & {"\r", "\n", "\0"})
def test_both_callers_use_one_shared_pin_in_uses_and_tooling_revision(self):
pins = set()
for name, callee in (("nightly.yml", "nightly-unsigned.yml"), ("nightly-sign.yml", "nightly-release.yml")):
source = (ROOT / ".github/workflows" / name).read_text()
uses = re.findall(r"(?m)^ uses: storytold/craft-common-actions/\.github/workflows/"
+ re.escape(callee) + r"@(\S+)$", source)
tooling = re.findall(r"(?m)^ tooling-revision: (\S+)$", source)
with self.subTest(workflow=name):
self.assertEqual(len(uses), 1)
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
pins.update(uses)
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
class NightlyEnabledCallers(unittest.TestCase):
"""Producer and signer run only in their exact context, for the reviewed manual actor."""
GUARDS = {
"nightly.yml": "github.repository == 'storytold/cadcraft' && github.ref == 'refs/heads/main' && "
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
"github.event_name == 'workflow_dispatch')",
"nightly-sign.yml": "github.repository == 'storytold/cadcraft' && github.event_name == 'workflow_dispatch' && "
"github.ref == 'refs/heads/release' && github.ref_type == 'branch'",
}
def test_enabled_jobs_keep_exact_context_guards(self):
for name, expected in self.GUARDS.items():
jobs = (ROOT / ".github/workflows" / name).read_text().split("\njobs:\n", 1)[1]
guards = job_conditions(jobs)
with self.subTest(workflow=name):
self.assertEqual(len(guards), 1)
indicator, expression = guards[0]
self.assertEqual(indicator, ">-")
self.assertEqual(" ".join(expression.split()), expected, "guards may only change with review")
def test_manual_actors_are_the_release_managers_in_caller_and_policy(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
policy = json.loads(INSTALLED_POLICY.read_text())
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
def test_an_actor_outside_the_release_managers_is_refused(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
policy = json.loads(INSTALLED_POLICY.read_text())
caller = json.dumps(RELEASE_MANAGERS, separators=(",", ":"))
widened = sorted(RELEASE_MANAGERS + ["echelon-robot"], key=str.lower)
for change in ("caller", "policy", "both", "order", "case"):
mutated_source, mutated_policy = source, copy.deepcopy(policy)
if change in ("caller", "both"):
mutated_source = source.replace(caller, json.dumps(widened, separators=(",", ":")))
if change in ("policy", "both"):
mutated_policy["manual_actors"] = widened
if change == "order":
mutated_policy["manual_actors"] = list(reversed(RELEASE_MANAGERS))
if change == "case":
mutated_policy["manual_actors"] = [login.lower() for login in RELEASE_MANAGERS]
with self.subTest(change=change), self.assertRaises(ValueError):
reviewed_manual_actors(mutated_source, mutated_policy)
def push_block(source):
"""The whole `push:` mapping, blank lines and nested keys included.
A blank line does not end a YAML mapping, so the block is delimited by indentation rather than
by contiguous non-empty lines; a path filter after a blank line stays visible to the check.
"""
lines = source.splitlines()
for index, line in enumerate(lines):
if re.fullmatch(r" push:.*", line):
block = []
for follow in lines[index + 1:]:
if follow.strip() and not follow.startswith(" "):
break
block.append(follow)
return "\n".join(block)
return None
class NightlyInstalledPolicy(unittest.TestCase):
"""The installed v3 policy matches the callers, the repository and its documented sources."""
def setUp(self):
self.assertFalse(INSTALLED_POLICY.is_symlink())
self.policy = json.loads(INSTALLED_POLICY.read_text())
def test_exact_v3_fields_and_repository_identity(self):
expected = {"schema", "repository", "repository_id", "producer_workflow_id",
"producer_workflow_path", "producer_tooling_revision", "producer_workflow_ref",
"signer_workflow_path", "signer_tooling_revision", "release_branch", "manual_actors",
"automatic_signer_actors", "max_age_seconds", "candidate_policy",
"max_artifact_bytes", "platforms"}
self.assertEqual(set(self.policy), expected)
self.assertEqual(self.policy["schema"], "craft-nightly-release-policy/v3")
self.assertEqual(self.policy["repository"], "storytold/cadcraft")
self.assertEqual(self.policy["release_branch"], "release")
self.assertIs(type(self.policy["repository_id"]), int)
self.assertGreater(self.policy["repository_id"], 0)
# producer_workflow_id is null until nightly.yml lands on main, then a positive int.
producer_id = self.policy["producer_workflow_id"]
if producer_id is not None:
self.assertIs(type(producer_id), int)
self.assertGreater(producer_id, 0)
self.assertNotEqual(producer_id,
self.policy["candidate_policy"]["required_workflows"][0]["workflow_id"],
"the producer is not its own quality workflow")
def test_paths_and_tooling_match_the_callers(self):
pin = caller_pin("nightly.yml")
self.assertEqual(caller_pin("nightly-sign.yml"), pin)
self.assertEqual(self.policy["producer_workflow_path"], ".github/workflows/nightly.yml")
self.assertEqual(self.policy["signer_workflow_path"], ".github/workflows/nightly-sign.yml")
self.assertEqual(self.policy["producer_tooling_revision"], pin)
self.assertEqual(self.policy["signer_tooling_revision"], pin)
self.assertEqual(self.policy["producer_workflow_ref"],
"storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@" + pin)
def test_platforms_equal_the_producer(self):
built = producer_platforms((ROOT / ".github/workflows/nightly.yml").read_text())
self.assertEqual(built, list(NIGHTLY_PLATFORMS))
self.assertEqual(set(self.policy["platforms"]), set(built))
def test_bounds(self):
self.assertIs(type(self.policy["max_age_seconds"]), int)
self.assertTrue(0 < self.policy["max_age_seconds"] <= 604800)
self.assertIs(type(self.policy["max_artifact_bytes"]), int)
self.assertTrue(0 < self.policy["max_artifact_bytes"] <= 16 * 1024 ** 3)
def test_candidate_workflows_run_on_every_main_push(self):
candidate = self.policy["candidate_policy"]
self.assertEqual(set(candidate), {"schema", "epoch", "repository", "branch", "required_workflows", "sonar"})
self.assertEqual(candidate["schema"], "craft-nightly-candidate-policy/v3")
self.assertEqual((candidate["repository"], candidate["branch"]), ("storytold/cadcraft", "main"))
self.assertTrue(isinstance(candidate["epoch"], str) and 0 < len(candidate["epoch"]) <= 128)
rows = candidate["required_workflows"]
self.assertTrue(rows)
for row in rows:
with self.subTest(workflow=row["workflow_path"]):
self.assertEqual(set(row), {"workflow_id", "workflow_path", "jobs"})
self.assertIs(type(row["workflow_id"]), int)
self.assertNotEqual(row["workflow_path"], self.policy["producer_workflow_path"])
source = (ROOT / row["workflow_path"]).read_text()
push = push_block(source)
self.assertIsNotNone(push, "a required workflow must run on main pushes")
self.assertIn("branches: [main]", push)
self.assertNotRegex(push, r"(?m)^\s+paths(?:-ignore)?:", "a path filter would leave candidates without a run")
names = [job["name"] for job in row["jobs"]]
self.assertEqual(len(names), len(set(names)))
for job in row["jobs"]:
self.assertEqual(set(job), {"name", "app_id", "applicability"})
self.assertEqual((job["app_id"], job["applicability"]), (15368, "required"))
def test_a_path_filter_after_a_blank_line_is_still_rejected(self):
workflow = "on:\n push:\n branches: [main]\n\n paths: ['src/**']\n workflow_dispatch: {}\n"
block = push_block(workflow)
self.assertIsNotNone(block)
self.assertIn("branches: [main]", block)
self.assertRegex(block, r"(?m)^\s+paths(?:-ignore)?:")
for ignored in ("paths: ['src/**']", "paths-ignore: ['docs/**']"):
with self.subTest(ignored=ignored):
variant = workflow.replace(ignored.split(":")[0] + ": ['src/**']", ignored)
self.assertRegex(push_block(variant), r"(?m)^\s+paths(?:-ignore)?:",
"a quoted or unquoted filter must not hide behind a blank line")
def test_sonar_identity_and_reviewed_scope(self):
sonar = self.policy["candidate_policy"]["sonar"]
properties = dict(line.split("=", 1) for line in (ROOT / "sonar-project.properties").read_text().splitlines()
if line and not line.startswith("#"))
self.assertEqual(sonar["organization"], properties["sonar.organization"])
self.assertEqual(sonar["project"], properties["sonar.projectKey"])
self.assertEqual((sonar["app_id"], sonar["check_name"]), (12526, "SonarCloud Code Analysis"))
self.assertEqual(sonar["details_url"], "https://sonarcloud.io/dashboard?id=" + sonar["project"] + "&branch=main")
accepted = {"bugs": "BUG", "vulnerabilities": "VULNERABILITY", "code_smells": "CODE_SMELL",
"security_rating": "VULNERABILITY", "new_security_rating": "VULNERABILITY"}
self.assertEqual({accepted[c["metric"]] for c in sonar["accepted_conditions"]}, set(sonar["issue_types"]))
metrics = [c["metric"] for c in sonar["accepted_conditions"] + sonar["required_conditions"]]
self.assertEqual(len(metrics), len(set(metrics)))
keys = [item["key"] for item in sonar["debt"]]
self.assertEqual(len(keys), len(set(keys)))
for item in sonar["debt"]:
with self.subTest(issue=item["key"]):
self.assertEqual(set(item), {"key", "rule", "component", "type", "severity", "hash"})
self.assertTrue(item["component"].startswith(sonar["project"] + ":"))
self.assertIn(item["type"], sonar["issue_types"])
self.assertRegex(item["hash"], r"^[0-9a-f]{32}$")
if __name__ == "__main__":
unittest.main(verbosity=2)
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env python3
"""Run the existing synthetic packaging suites together; no app build or signing."""
import importlib.util
from pathlib import Path
import unittest
def main() -> int:
here = Path(__file__).resolve().parent
suite = unittest.TestSuite()
for name, relative in (
("photo_archive_suite", "nightly-archive-tests.py"),
("photo_launcher_suite", "nightly-launcher-tests.py"),
("photo_plist_suite", "macos/nightly_plist_tests.py"),
("photo_release_dispatch_suite", "nightly-release-tests.py"),
("photo_mac_sign_suite", "macos/nightly_sign_tests.py"),
):
spec = importlib.util.spec_from_file_location(name, here / relative)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
suite.addTests(unittest.defaultTestLoader.loadTestsFromModule(module))
return 0 if unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful() else 1
if __name__ == "__main__":
raise SystemExit(main())
+139
View File
@@ -0,0 +1,139 @@
"""POSIX packaging I/O rooted at a caller-owned private working directory.
The build launcher chooses cwd independently of file arguments (Linux uses its
mktemp directory). This is not a sandbox against root or a malicious same-UID
caller, and inode-check/unlink cleanup is not an atomic replacement-race primitive.
"""
import contextlib
import os
from pathlib import Path
import stat
def _component(name):
# A descriptor-relative open must name exactly one entry in its directory.
if not name or name in (".", "..") or os.path.basename(name) != name:
raise ValueError("build path components must be single names")
return os.path.basename(name)
class OwnedBuildRoot:
def __enter__(self):
self.directory = Path.cwd()
self.fd = os.open(".", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
info = os.fstat(self.fd)
if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) & 0o077:
os.close(self.fd)
raise ValueError("packaging cwd must be an owned private build directory")
return self
def __exit__(self, *_error):
os.close(self.fd)
def _relative(self, path):
path = Path(path)
try:
relative = path.relative_to(self.directory) if path.is_absolute() else path
except ValueError as error:
raise ValueError("path is outside the owned build directory") from error
if not relative.parts or ".." in relative.parts:
raise ValueError("empty or parent-traversing build path")
# Check an independently selected root, never the supplied filename's parent.
try:
parent = (self.directory / relative).parent.resolve(strict=True)
except OSError as error:
raise ValueError("build path parent must exist") from error
if not parent.is_relative_to(self.directory):
raise ValueError("resolved path escapes the owned build directory")
return relative
def _checked_parts(self, path):
relative = self._relative(path)
root = os.path.realpath(self.directory)
lexical = os.path.join(root, *relative.parts)
target = os.path.realpath(lexical)
if target == root or os.path.commonpath([root, target]) != root:
raise ValueError("resolved path escapes the owned build directory")
if target != lexical:
raise ValueError("build path must not pass through symlinks or aliases")
return [_component(part) for part in os.path.relpath(target, root).split(os.sep)]
def _parent(self, path):
parts = self._checked_parts(path)
current = os.dup(self.fd)
try:
for part in parts[:-1]:
next_fd = os.open(_component(part), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=current)
os.close(current)
current = next_fd
return current, parts[-1]
except OSError as error:
os.close(current)
raise ValueError("build path parents must be non-symlink directories") from error
@contextlib.contextmanager
def reader(self, path, limit):
parent, name = self._parent(path)
try:
try:
descriptor = os.open(_component(name), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
except OSError as error:
raise ValueError("build input must be a regular file without aliases") from error
finally:
os.close(parent)
info = os.fstat(descriptor)
if not stat.S_ISREG(info.st_mode) or info.st_size > limit:
os.close(descriptor)
raise ValueError("build input must be a regular file within its read bound")
with os.fdopen(descriptor, "rb") as stream:
yield stream
def read_bytes(self, path, limit):
with self.reader(path, limit) as stream:
data = stream.read(limit + 1)
if len(data) > limit:
raise ValueError("build input grew beyond its read bound")
return data
def children(self, path, limit):
relative = self._relative(path)
parent, name = self._parent(path)
try:
try:
descriptor = os.open(_component(name), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
except OSError as error:
raise ValueError("build stage must be a non-symlink directory") from error
finally:
os.close(parent)
try:
entries = []
with os.scandir(descriptor) as iterator:
for entry in iterator:
if len(entries) >= limit:
raise ValueError("too many build stage members")
entries.append(self.directory / relative / entry.name)
return entries
finally:
os.close(descriptor)
@contextlib.contextmanager
def create(self, path):
parent, name = self._parent(path)
name = _component(name)
try:
descriptor = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o666, dir_fd=parent)
info = os.fstat(descriptor)
identity = (info.st_dev, info.st_ino)
try:
with os.fdopen(descriptor, "wb") as stream:
yield stream
except BaseException:
try:
current = os.stat(name, dir_fd=parent, follow_symlinks=False)
if (current.st_dev, current.st_ino) == identity:
os.unlink(_component(name), dir_fd=parent)
except FileNotFoundError:
pass
raise
finally:
os.close(parent)
@@ -0,0 +1,95 @@
param([Parameter(Mandatory=$true)][string] $FixtureRoot)
. (Join-Path $PSScriptRoot 'nightly.ps1') -FunctionsOnly
function Assert([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } }
$spec = Get-NightlyArchiveSpec '0.23.1-nightly.20261120.17.1.gabcdef012345' 'x64'
Assert ($spec.Archive -eq 'cadcraft-0.23.1-nightly.20261120.17.1.gabcdef012345-windows-x86_64-nightly.zip') 'wrong nightly artifact name'
Assert ($spec.Executables.Count -eq 1 -and $spec.Executables[0] -eq 'cadcraft.exe') 'nightly must not ship the unqualified CLI'
Assert ($spec.AppId -eq 'ai.storyteller.cadcraft.nightly-v1') 'nightly identity is not distinct'
foreach ($arch in @('x86', 'arm64')) {
$refused = $false
try { Get-NightlyArchiveSpec '0.23.1' $arch | Out-Null } catch { $refused = $true }
Assert $refused 'unsupported target was accepted'
}
foreach ($bad in @('', '0.23.1', '../other', '0.23.1/elsewhere')) {
$refused = $false
try { Get-NightlyArchiveSpec $bad 'x64' | Out-Null } catch { $refused = $true }
Assert $refused 'unsafe artifact version was accepted'
}
Assert-NightlyFlavor 'CADCraft Nightly' 'CADCraft 0.23.1-nightly.20261120.17.1.gabcdef012345 (nightly-v1)' '0.23.1-nightly.20261120.17.1.gabcdef012345'
foreach ($pair in @(@('CADCraft', 'CADCraft 0.23.1 (nightly-v1)'), @('CADCraft Nightly', 'CADCraft 0.23.1'))) {
$refused = $false
try { Assert-NightlyFlavor $pair[0] $pair[1] '0.23.1-nightly.20261120.17.1.gabcdef012345' } catch { $refused = $true }
Assert $refused 'stable or mismatched build flavor was accepted'
}
$sha = 'abcdef0123456789abcdef0123456789abcdef01'
$good = '0.23.1-nightly.20261120.17.1.gabcdef012345'
Assert-NightlySource $good $sha '2026-11-20' $sha ''
$cases = @(
@('missing commit', $good, '', '2026-11-20', $sha, ''),
@('short commit', $good, 'abcdef012345', '2026-11-20', $sha, ''),
@('uppercase commit', $good, $sha.ToUpper(), '2026-11-20', $sha.ToUpper(), ''),
@('version names another commit', '0.23.1-nightly.20261120.17.1.g000000000000', $sha, '2026-11-20', $sha, ''),
@('missing date', $good, $sha, '', $sha, ''),
@('date differs from version', $good, $sha, '2026-11-21', $sha, ''),
@('other commit checked out', $good, $sha, '2026-11-20', ('0' * 40), ''),
@('dirty tree', $good, $sha, '2026-11-20', $sha, ' M apps/cadcraft/src/main.rs')
)
foreach ($case in $cases) {
$refused = $false
try { Assert-NightlySource $case[1] $case[2] $case[3] $case[4] $case[5] } catch { $refused = $true }
Assert $refused "source identity accepted: $($case[0])"
}
Write-Output 'nightly packaging spec, target/version refusal, source identity and flavor-binding tests passed'
# Exercise the SAME production notice copier with the real repository layout, then inspect a ZIP.
if (-not $FixtureRoot -or -not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'supply an owned absolute -FixtureRoot for the notices/ZIP regression' }
$testRoot = Join-Path $FixtureRoot ("nightly-notices-" + [Guid]::NewGuid().ToString('N'))
try {
$repo = Join-Path $testRoot 'app'
$fontRepo = Join-Path $testRoot 'craft-fonts'
$family = Join-Path $fontRepo 'fonts\ExampleFamily'
$stage = Join-Path $testRoot 'stage'
New-Item -ItemType Directory -Force -Path $repo, $family, $stage | Out-Null
$rootNames = @('README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md')
foreach ($name in $rootNames) { Set-Content -LiteralPath (Join-Path $repo $name) -Value "root-notice-$name" }
Set-Content -LiteralPath (Join-Path $family 'OFL.txt') -Value 'font-notice-example'
Copy-NightlyNotices $repo $fontRepo $stage
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) {
Assert (Test-Path -LiteralPath (Join-Path $stage $name)) "missing staged notice $name"
}
$zip = Join-Path $testRoot 'notices.zip'
Compress-Archive -Path (Join-Path $stage '*') -DestinationPath $zip
$archive = [IO.Compression.ZipFile]::OpenRead($zip)
try {
$names = @($archive.Entries | ForEach-Object { $_.FullName })
foreach ($name in @($rootNames) + @('OFL-ExampleFamily.txt')) { Assert ($name -in $names) "missing archived notice $name" }
foreach ($forbidden in @('portable.txt', 'cadcraft-cli.exe')) { Assert ($forbidden -notin $names) "unexpected payload $forbidden" }
$entry = $archive.GetEntry('OFL-ExampleFamily.txt')
$reader = [IO.StreamReader]::new($entry.Open())
try { Assert ($reader.ReadToEnd().Contains('font-notice-example')) 'wrong font license bytes in ZIP' } finally { $reader.Dispose() }
} finally { $archive.Dispose() }
} finally {
if (Test-Path -LiteralPath $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force }
}
Write-Output 'nightly mock-repository root and font notices are present in stage and ZIP'
# The source state comes from git itself: the checked-out commit, then a dirty tree.
$gitRoot = Join-Path $FixtureRoot ("nightly-source-" + [Guid]::NewGuid().ToString('N'))
try {
New-Item -ItemType Directory -Force -Path $gitRoot | Out-Null
git -C $gitRoot init -q; git -C $gitRoot -c user.name=fixture -c user.email=fixture@invalid commit -q --allow-empty -m fixture
if ($LASTEXITCODE -ne 0) { throw 'cannot create the git fixture' }
$head = (git -C $gitRoot rev-parse HEAD).Trim()
$state = Get-NightlySourceState $gitRoot
Assert ($state.Head -ceq $head -and -not $state.Status) 'clean checkout not reported as clean at HEAD'
$version = '0.23.1-nightly.20261120.17.1.g' + $head.Substring(0, 12)
Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status
Set-Content -LiteralPath (Join-Path $gitRoot 'untracked.txt') -Value 'dirty'
$state = Get-NightlySourceState $gitRoot
$refused = $false
try { Assert-NightlySource $version $head '2026-11-20' $state.Head $state.Status } catch { $refused = $true }
Assert $refused 'a dirty checkout was accepted'
} finally {
if (Test-Path -LiteralPath $gitRoot) { Remove-Item -LiteralPath $gitRoot -Recurse -Force }
}
Write-Output 'nightly source state is read from git and a dirty checkout is refused'
+104
View File
@@ -0,0 +1,104 @@
param(
[Parameter(Mandatory=$true)][string] $FixtureRoot,
[string] $PackagingRoot = $PSScriptRoot,
[switch] $PhaseGuardOnly
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PackagingRoot 'nightly.ps1') -FunctionsOnly
$sign = Join-Path $PackagingRoot 'sign.ps1'
$names = @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_TENANT_ID','AZURE_CLIENT_ID','AZURE_CLIENT_SECRET','AZURE_SIGNING_ENDPOINT','AZURE_SIGNING_ACCOUNT','AZURE_CERT_PROFILE')
function Clear-SigningFixtures { foreach ($name in $names) { [Environment]::SetEnvironmentVariable($name, $null) } }
function Assert-Policy([bool] $Value, [string] $Message) { if (-not $Value) { throw $Message } }
function Invoke-Refusal([scriptblock] $Operation, [string] $Message) {
$errorText = ''
try { & $Operation | Out-Null } catch { $errorText = $_.Exception.Message }
Assert-Policy ($errorText.Contains($Message)) "expected refusal: $Message; got: $errorText"
}
function global:cargo { $global:SigningFixtureCargoCalls++; throw 'FIXTURE_COMPILER_BOUNDARY' }
# The source preflight runs `git` in the real checkout; this fixture owns its own identity, so the
# stub answers for the fixture commit instead of whatever this working copy happens to be at.
function global:git {
param([Parameter(ValueFromRemainingArguments=$true)][object[]] $Arguments)
$joined = ($Arguments | ForEach-Object { "$_" }) -join ' '
if ($joined -match 'rev-parse HEAD$') { $global:LASTEXITCODE = 0; return ('a' * 40) }
if ($joined -match 'status --porcelain$') { $global:LASTEXITCODE = 0; return '' }
throw "the fixture must not run git: $joined"
}
function global:Invoke-WebRequest { throw 'fixture must not perform signing downloads' }
$global:SigningFixtureCargoCalls = 0
# The caller's own values, restored in `finally`: this script may run inside a developer's session.
$savedEnvironment = foreach ($name in ($names + @('CADCRAFT_VERSION', 'CADCRAFT_BUILD_SHA', 'CADCRAFT_BUILD_DATE'))) {
[pscustomobject]@{ Name = $name; Value = [Environment]::GetEnvironmentVariable($name) }
}
if (-not [IO.Path]::IsPathRooted($FixtureRoot)) { throw 'use an owned absolute FixtureRoot' }
$root = Join-Path $FixtureRoot ('signing-policy-' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $root | Out-Null
$version = '0.23.1-nightly.20261121.12345.1.gaaaaaaaaaaaa'
$env:CADCRAFT_VERSION = $version
# The preflight's other two identities: the fixture commit the version names, and its run date.
$env:CADCRAFT_BUILD_SHA = 'a' * 40
$env:CADCRAFT_BUILD_DATE = '2026-11-21'
function Invoke-Build([switch] $BuildOnly) {
$arguments = @{Arch='x64';Version=$version;Target='x86_64-pc-windows-msvc';TargetDir=$root;Dist=(Join-Path $root 'dist')}
if ($BuildOnly) { $arguments.BuildOnly = $true }
& (Join-Path $PackagingRoot 'nightly.ps1') @arguments
}
try {
Clear-SigningFixtures
Invoke-Refusal { Invoke-Build } 'requires -BuildOnly'
Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'default mode invoked Cargo'
Write-Output 'PASS: explicit-build-phase-required'
if ($PhaseGuardOnly) { return }
foreach ($name in @('WINDOWS_CERTIFICATE','WINDOWS_CERTIFICATE_PASSWORD','AZURE_CLIENT_SECRET')) {
Clear-SigningFixtures
[Environment]::SetEnvironmentVariable($name, 'generated-fixture-not-a-secret')
Invoke-Refusal { Invoke-Build -BuildOnly } 'Compilation must not receive signing credentials'
Assert-Policy ($global:SigningFixtureCargoCalls -eq 0) 'key-bearing compilation reached Cargo'
}
Write-Output 'PASS: credentials-rejected-before-compilation'
Clear-SigningFixtures
Invoke-Refusal { Invoke-Build -BuildOnly } 'FIXTURE_COMPILER_BOUNDARY'
Assert-Policy ($global:SigningFixtureCargoCalls -eq 1) 'clean compilation did not reach the mocked compiler boundary'
Assert-Policy (-not (Test-Path (Join-Path $root 'dist'))) 'mocked compilation produced an artifact'
Write-Output 'PASS: secret-free-build-reaches-only-mocked-boundary'
Clear-SigningFixtures
Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required'
$env:AZURE_CLIENT_SECRET = 'generated-partial-fixture'
Invoke-Refusal { & $sign -Required -CheckOnly } 'Nightly signing is required'
Write-Output 'PASS: required-signer-refuses-missing-and-partial-configuration'
Clear-SigningFixtures
$env:WINDOWS_CERTIFICATE = 'generated-presence-fixture-not-a-certificate'
& $sign -Required -CheckOnly
Clear-SigningFixtures
foreach ($name in $names | Where-Object { $_.StartsWith('AZURE_') }) { [Environment]::SetEnvironmentVariable($name, 'generated-presence-fixture') }
& $sign -Required -CheckOnly
Clear-SigningFixtures
Write-Output 'PASS: supported-configuration-presence-without-signing'
# Load the policy function without signing. These objects are not crypto evidence.
. $sign -CheckOnly
foreach ($value in @($null, [pscustomobject]@{Status='NotSigned';SignerCertificate='fixture'}, [pscustomobject]@{Status='HashMismatch';SignerCertificate='fixture'}, [pscustomobject]@{Status='Valid';SignerCertificate=$null})) {
Invoke-Refusal { Assert-AuthenticodeSignature $value } 'valid Authenticode signature'
}
Assert-AuthenticodeSignature ([pscustomobject]@{Status='Valid';SignerCertificate='generated-public-certificate-placeholder'})
Write-Output 'PASS: required-signature-policy-rejects-invalid-or-missing-signer'
$file = Join-Path $root 'owned-sentinel.exe'
[IO.File]::WriteAllText($file, 'generated sentinel, not a real executable')
$before = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash
& $sign -Files $file
Assert-Policy ((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash -ceq $before) 'optional stable policy changed unsigned bytes'
Write-Output 'PASS: stable-optional-policy-preserves-owned-bytes'
} finally {
# Put back exactly what the caller had (an unset variable is restored as unset), and drop the
# command mocks: a `function global:` binding outlives this script and outranks the real program.
foreach ($entry in $savedEnvironment) { [Environment]::SetEnvironmentVariable($entry.Name, $entry.Value) }
foreach ($mock in @('cargo', 'git', 'Invoke-WebRequest')) {
Remove-Item -LiteralPath "function:global:$mock" -ErrorAction SilentlyContinue
}
Remove-Item -LiteralPath $root -Recurse -Force
}
+132
View File
@@ -0,0 +1,132 @@
<# First nightly target only: Windows x86_64 GUI ZIP. No MSI, CLI, portable marker or association registration. #>
param(
[string] $Arch = 'x64',
[string] $Version,
[string] $Target,
[string] $TargetDir,
[string] $Dist,
[switch] $SkipBuild,
[switch] $BuildOnly,
[switch] $FunctionsOnly
)
$ErrorActionPreference = 'Stop'
function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) {
if ($Arch -ne 'x64') { throw 'nightly-v1 supports only Windows x86_64' }
if (-not $Version -or $Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' }
return @{
Archive = "cadcraft-$Version-windows-x86_64-nightly.zip"
UnsignedArchive = "cadcraft-$Version-windows-x86_64-nightly.unsigned.zip"
Executables = @('cadcraft.exe')
Channel = 'nightly-v1'
AppId = 'ai.storyteller.cadcraft.nightly-v1'
}
}
# The same source identity the Linux helper enforces (nightly-common.sh): the version names the
# commit being built, the date is the original run's, and the tree is clean.
function Assert-NightlySource([string] $Version, [string] $Sha, [string] $BuildDate, [string] $Head, [string] $Status) {
if ($Sha -cnotmatch '^[0-9a-f]{40}\z') { throw 'an exact source commit is required (CADCRAFT_BUILD_SHA)' }
if ($Version -cnotmatch '^\d+\.\d+\.\d+-nightly\.\d{8}\.\d+\.\d+\.g[0-9a-f]{12}\z') { throw 'invalid nightly artifact version' }
if ($Version.Substring($Version.Length - 12) -cne $Sha.Substring(0, 12)) { throw 'version/source commit mismatch' }
if ($BuildDate -cnotmatch '^\d{4}-\d{2}-\d{2}\z') { throw 'the original run-created UTC date is required (CADCRAFT_BUILD_DATE)' }
$versionDate = ($Version -split '-nightly\.', 2)[1].Substring(0, 8)
if ($BuildDate.Replace('-', '') -cne $versionDate) { throw 'version/original-run date mismatch' }
if ($Head -cne $Sha) { throw 'prepared source is not the checked-out commit' }
if ($Status) { throw 'nightly packaging requires the frozen clean source' }
}
function Get-NightlySourceState([string] $RepositoryRoot) {
$head = git -C $RepositoryRoot rev-parse HEAD
if ($LASTEXITCODE -ne 0) { throw 'cannot read the checked-out commit' }
$status = git -C $RepositoryRoot status --porcelain
if ($LASTEXITCODE -ne 0) { throw 'cannot read the source tree status' }
return @{ Head = "$head".Trim(); Status = ($status | Out-String).Trim() }
}
function Assert-NightlyFlavor([string] $ProductName, [string] $VersionOutput, [string] $ExpectedVersion) {
if ($ProductName -ne 'CADCraft Nightly' -or $VersionOutput -cne "CADCraft $ExpectedVersion (nightly-v1)") {
throw 'the executable is not the compiled nightly-v1 flavor'
}
}
function Copy-NightlyNotices([string] $RepositoryRoot, [string] $FontRepository, [string] $Destination) {
foreach ($name in 'README.md', 'LICENSE', 'LICENSE-MIT', 'LICENSE-APACHE', 'NOTICE', 'ATTRIBUTION.md') {
$source = Join-Path $RepositoryRoot $name
if (Test-Path -LiteralPath $source) { Copy-Item -LiteralPath $source -Destination $Destination }
}
if ($FontRepository) {
$fonts = Join-Path $FontRepository 'fonts'
if (-not (Test-Path -LiteralPath $fonts -PathType Container)) { throw 'CRAFT_FONTS_DIR has no fonts directory for the bundled notices' }
foreach ($family in Get-ChildItem -LiteralPath $fonts -Directory) {
$license = Join-Path $family.FullName 'OFL.txt'
if (Test-Path -LiteralPath $license) { Copy-Item -LiteralPath $license -Destination (Join-Path $Destination "OFL-$($family.Name).txt") }
}
}
}
if ($FunctionsOnly) { return }
if (-not $env:CADCRAFT_VERSION -or $Version -cne $env:CADCRAFT_VERSION) { throw 'nightly-v1 requires explicit CADCRAFT_VERSION, not the Cargo version fallback' }
$Spec = Get-NightlyArchiveSpec $Version $Arch
if ($SkipBuild) { throw 'nightly-v1 forbids -SkipBuild; the executable flavor must be built in this operation' }
if ($Target -ne 'x86_64-pc-windows-msvc') { throw 'nightly-v1 target must be x86_64-pc-windows-msvc' }
if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final archives are produced in the separate trusted signing job' }
# No key values may enter compilation. This produces an internal intermediate, not a feed artifact.
& (Join-Path $PSScriptRoot 'sign.ps1') -CheckBuildEnvironment
$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$Source = Get-NightlySourceState $Root
Assert-NightlySource $Version $env:CADCRAFT_BUILD_SHA $env:CADCRAFT_BUILD_DATE $Source.Head $Source.Status
$oldChannel = $env:CADCRAFT_BUILD_CHANNEL
try {
# `build.rs` reads CADCRAFT_VERSION (already required above), not a PhotoCraft-style override.
$env:CADCRAFT_BUILD_CHANNEL = 'nightly-v1'
$env:CADCRAFT_REQUIRE_WINRES = '1'
$env:CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS = '-C target-feature=+crt-static'
# Into the directory the archive steps read (`$TargetDir`), not Cargo's default.
cargo build --release --locked -p cadcraft --target $Target --target-dir $TargetDir
if ($LASTEXITCODE -ne 0) { throw "nightly cargo build failed: $LASTEXITCODE" }
} finally {
$env:CADCRAFT_BUILD_CHANNEL = $oldChannel
}
$Source = Get-NightlySourceState $Root
try { Assert-NightlySource $Version $env:CADCRAFT_BUILD_SHA $env:CADCRAFT_BUILD_DATE $Source.Head $Source.Status }
catch { throw "source changed during the build: $_" }
$Exe = Join-Path $TargetDir "$Target\release\cadcraft.exe"
$pe = [System.IO.File]::ReadAllBytes($Exe)
if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' }
$offset = [BitConverter]::ToInt32($pe, 0x3C)
if ($offset -lt 0 -or $offset -gt $pe.Length - 0x5E) { throw 'invalid nightly PE header offset' }
if ([BitConverter]::ToUInt16($pe, $offset + 4) -ne 0x8664 -or [BitConverter]::ToUInt16($pe, $offset + 0x5C) -ne 2) {
throw 'nightly executable must be x86_64 Windows GUI'
}
$VersionInfo = (Get-Item -LiteralPath $Exe).VersionInfo
$ProductName = $VersionInfo.ProductName
if ($VersionInfo.ProductVersion -cne $Version) { throw 'nightly PE ProductVersion differs from the feed identity' }
# Check the embedded build flavor before invoking even the side-effect-free version query.
if ($ProductName -ne 'CADCraft Nightly') { throw 'nightly executable is missing the embedded build flavor' }
$VersionOutput = (& $Exe --version | Out-String).Trim()
if ($LASTEXITCODE -ne 0) { throw 'nightly --version query failed' }
Assert-NightlyFlavor $ProductName $VersionOutput $Version
$Stage = Join-Path $TargetDir 'windows-package\nightly-v1-x86_64'
if (Test-Path -LiteralPath $Stage) { Remove-Item -LiteralPath $Stage -Recurse -Force }
New-Item -ItemType Directory -Force -Path $Stage | Out-Null
Copy-Item -LiteralPath $Exe -Destination (Join-Path $Stage 'cadcraft.exe')
# Signing happens only in the separate trusted step, using sign.ps1 -Required.
# The intermediate's filename cannot satisfy the feed-ready archive contract.
Copy-NightlyNotices $Root $env:CRAFT_FONTS_DIR $Stage
if ((Get-ChildItem -LiteralPath $Stage -Filter '*.exe').Count -ne 1 -or (Test-Path (Join-Path $Stage 'portable.txt'))) {
throw 'nightly stage contains an unexpected executable or portable fallback marker'
}
New-Item -ItemType Directory -Force -Path $Dist | Out-Null
$Zip = Join-Path $Dist $Spec.UnsignedArchive
if (Test-Path -LiteralPath $Zip) { throw 'Nightly output already exists; refusing to replace prepared artifact bytes' }
Compress-Archive -Path (Join-Path $Stage '*') -DestinationPath $Zip
$Archive = [System.IO.Compression.ZipFile]::OpenRead($Zip)
try {
$Names = @($Archive.Entries | ForEach-Object { $_.FullName })
if ('cadcraft.exe' -notin $Names -or 'cadcraft-cli.exe' -in $Names -or 'portable.txt' -in $Names) {
throw 'nightly ZIP payload violates the GUI-only profile contract'
}
} finally { $Archive.Dispose() }
Write-Output "Nightly build intermediate (not publishable): $Zip ($VersionOutput)"
+16 -1
View File
@@ -23,11 +23,15 @@
#>
param(
[ValidateSet('x64', 'x86', 'arm64')] [string] $Arch = 'x64',
[switch] $SkipBuild
[switch] $SkipBuild,
[switch] $Nightly,
[switch] $BuildOnly
)
$ErrorActionPreference = 'Stop'
if ($BuildOnly -and -not $Nightly) { throw '-BuildOnly is only for secret-free nightly compilation' }
$Root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
function Invoke-Native([string] $What, [scriptblock] $Block) {
Write-Output "==> $What"
& $Block
@@ -52,12 +56,20 @@ $Dist = if ($env:DIST) { $env:DIST } else { Join-Path $Root 'dist\release' }
$TargetDir = if ($env:CARGO_TARGET_DIR) { $env:CARGO_TARGET_DIR } else { Join-Path $Root 'target' }
New-Item -ItemType Directory -Force -Path $Dist | Out-Null
# Nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both.
if (-not $env:CADCRAFT_BUILD_SHA) { $env:CADCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) }
if (-not $env:CADCRAFT_BUILD_DATE) { $env:CADCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') }
Write-Output "CADCraft $Version for Windows $Arch ($Target)"
# A nightly build is a separate channel: it delegates to nightly.ps1 before any stable packaging.
if ($Nightly) {
& (Join-Path $PSScriptRoot 'nightly.ps1') -Arch $Arch -Version $Version -Target $Target -TargetDir $TargetDir -Dist $Dist -SkipBuild:$SkipBuild -BuildOnly:$BuildOnly
return
}
if (-not $SkipBuild) {
$env:CADCRAFT_BUILD_CHANNEL = 'stable'
# Static CRT: no VC++ redistributable needed. Scoped to the target so host build scripts and
# proc-macros are unaffected.
$flagVar = 'CARGO_TARGET_' + ($Target.ToUpper() -replace '-', '_') + '_RUSTFLAGS'
@@ -85,6 +97,9 @@ foreach ($check in @(@('cadcraft.exe', 2), @('cadcraft-cli.exe', 3))) {
if ($h.Subsystem -ne $check[1]) { throw "$($check[0]) has PE subsystem $($h.Subsystem), expected $($check[1])" }
Write-Output "ok $($check[0]): $Arch, PE subsystem $($h.Subsystem)"
}
if ((Get-Item -LiteralPath (Join-Path $Bin 'cadcraft.exe')).VersionInfo.ProductName -eq 'CADCraft Nightly') {
throw 'a nightly executable cannot be packaged as stable'
}
$Stage = Join-Path $TargetDir "windows-package\$Arch"
Remove-Item -Recurse -Force $Stage -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $Stage | Out-Null
+37 -5
View File
@@ -9,7 +9,9 @@
AZURE_SIGNING_ENDPOINT (e.g. https://eus.codesigning.azure.net),
AZURE_SIGNING_ACCOUNT, AZURE_CERT_PROFILE
With neither, it prints a warning and leaves the files unsigned (exit code 0), so test builds
still produce installers.
still produce installers. Nightly callers require signing with -Required and can check signing
configuration with -Required -CheckOnly. Compilation uses the separate -CheckBuildEnvironment
mode, without importing signing keys.
This is the one place to adapt when the signing setup changes (an HSM/cloud key, a different
timestamp server, ...). Optional overrides: WINDOWS_TIMESTAMP_URL, SIGNTOOL (path to signtool.exe).
@@ -18,8 +20,11 @@
pwsh packaging/windows/sign.ps1 dist/cadcraft.exe dist/Designcraft.msi
#>
param(
[Parameter(Mandatory = $true, ValueFromRemainingArguments = $true)]
[string[]] $Files
[Parameter(Position = 0, ValueFromRemainingArguments = $true)]
[string[]] $Files,
[switch] $Required,
[switch] $CheckOnly,
[switch] $CheckBuildEnvironment
)
$ErrorActionPreference = 'Stop'
@@ -27,6 +32,12 @@ function Write-Warn([string] $Message) {
if ($env:GITHUB_ACTIONS) { Write-Output "::warning::$Message" } else { Write-Warning $Message }
}
function Assert-AuthenticodeSignature($Signature) {
if (-not $Signature -or [string]$Signature.Status -cne 'Valid' -or -not $Signature.SignerCertificate) {
throw 'Required signing must produce a valid Authenticode signature and signer certificate'
}
}
function Find-SignTool {
if ($env:SIGNTOOL) { return $env:SIGNTOOL }
$onPath = Get-Command signtool.exe -ErrorAction SilentlyContinue
@@ -44,11 +55,29 @@ function Invoke-SignTool([string[]] $Arguments) {
if ($LASTEXITCODE -ne 0) { throw "signtool $($Arguments[0]) failed with exit code $LASTEXITCODE" }
}
$Files = $Files | ForEach-Object { (Resolve-Path $_).Path }
$haveCert = [bool]$env:WINDOWS_CERTIFICATE
$azureVars = 'AZURE_TENANT_ID', 'AZURE_CLIENT_ID', 'AZURE_CLIENT_SECRET', 'AZURE_SIGNING_ENDPOINT', 'AZURE_SIGNING_ACCOUNT', 'AZURE_CERT_PROFILE'
if ($CheckBuildEnvironment) {
# Signing material must never reach compilation. Prints nothing when the environment is clean.
if ($Required -or $CheckOnly -or $Files) { throw '-CheckBuildEnvironment is separate from signing' }
$names = @('WINDOWS_CERTIFICATE', 'WINDOWS_CERTIFICATE_PASSWORD') + $azureVars
if ($names | Where-Object { [Environment]::GetEnvironmentVariable($_) }) {
throw 'Compilation must not receive signing credentials; use a separate trusted signing step'
}
return
}
$haveCert = [bool]$env:WINDOWS_CERTIFICATE
$haveAzure = -not ($azureVars | Where-Object { -not [Environment]::GetEnvironmentVariable($_) })
if ($Required -and -not $haveCert -and -not $haveAzure) {
throw 'Nightly signing is required: configure WINDOWS_CERTIFICATE or the complete existing Azure signing configuration'
}
if ($CheckOnly) {
if ($Files) { throw '-CheckOnly does not sign files' }
return
}
if (-not $Files) { throw 'At least one file is required for signing' }
$Files = $Files | ForEach-Object { (Resolve-Path $_).Path }
if (-not $haveCert -and -not $haveAzure) {
Write-Warn "Windows signing secrets not set (WINDOWS_CERTIFICATE or AZURE_*): leaving unsigned: $($Files -join ', ')"
exit 0
@@ -89,6 +118,9 @@ try {
Invoke-SignTool ($common + @('/tr', $ts, '/dlib', $dlib.FullName, '/dmdf', $metadata) + $Files)
}
Invoke-SignTool (@('verify', '/pa', '/v') + $Files)
if ($Required) {
foreach ($file in $Files) { Assert-AuthenticodeSignature (Get-AuthenticodeSignature -LiteralPath $file) }
}
}
finally {
Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
+1
View File
@@ -1,2 +1,3 @@
sonar.projectKey=storytold_cadcraft
sonar.organization=storytold
sonar.coverage.exclusions=packaging/**