From c0dd6c81a5fc6dc35cdb28b3c42305c9737387ea Mon Sep 17 00:00:00 2001 From: skylartaylor Date: Mon, 23 Nov 2026 15:27:42 +0100 Subject: [PATCH] Check the Windows Nightly source identity and widen the profile fences nightly.ps1 now enforces what the Linux helper does: an exact 40-hex commit, a version naming that commit, the original run date, and a clean checkout of it before and after the build. package.ps1 no longer defaults those for Nightly. The profile root also refuses the default MSI install folders, folders under a portable copy and the stable Flatpak data folder, and every existing entry in the profile must resolve inside it. An empty build channel means stable. --- .gitignore | 5 + apps/photocraft/build.rs | 3 +- apps/photocraft/src/profile_root.rs | 145 ++++++++++++++++++-- packaging/windows/nightly-package-tests.ps1 | 41 +++++- packaging/windows/nightly.ps1 | 26 ++++ packaging/windows/package.ps1 | 7 +- 6 files changed, 215 insertions(+), 12 deletions(-) diff --git a/.gitignore b/.gitignore index 0e71c973d8..7f91efd6ac 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,8 @@ target/ /craft-fonts *.log __pycache__/ + +# Checked out inside the workspace by the shared nightly workflows (craft-common-actions). +/.nightly-tools +/.nightly-input +/craft-i18n diff --git a/apps/photocraft/build.rs b/apps/photocraft/build.rs index 0f5455057c..a4bcba0756 100644 --- a/apps/photocraft/build.rs +++ b/apps/photocraft/build.rs @@ -17,7 +17,8 @@ fn main() { println!("cargo:rustc-cfg=photocraft_nightly_v1"); true } - Ok("stable") | Err(std::env::VarError::NotPresent) => false, + // An empty value (an unset CI input) means the default stable build. + Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false, _ => { eprintln!("unsupported PHOTOCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)"); std::process::exit(1); diff --git a/apps/photocraft/src/profile_root.rs b/apps/photocraft/src/profile_root.rs index fb80c9b1ca..8e515c65d9 100644 --- a/apps/photocraft/src/profile_root.rs +++ b/apps/photocraft/src/profile_root.rs @@ -95,7 +95,17 @@ fn installation_boundary(platform: Platform, exe: &Path) -> Result Option, exe: &Path) -> Result, String> { let mut roots = match platform { Platform::Windows => { - ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join("Photocraft"))).collect::, _>>()? + let mut roots = + ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join("Photocraft"))).collect::, _>>()?; + // The MSI's default per-user and per-machine folders (install-policy.wxi). A custom + // install folder is not known here; the executable's own folder is fenced below. + roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("PhotoCraft")); + 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("PhotoCraft")); + } + } + roots } Platform::Linux => { let mut roots = @@ -104,6 +114,8 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("photocraft"))) .collect::, _>>()?; roots.extend(["/usr/bin/photocraft", "/usr/local/bin/photocraft", "/opt/photocraft"].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.photocraft")); roots } Platform::Mac => { @@ -132,7 +144,7 @@ pub fn agent_directory(root: &Path) -> Result { private_subdirectory(root, "AgentFiles", "default agent folder") } -fn private_subdirectory(root: &Path, name: &str, label: &str) -> Result { +fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { 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) { @@ -141,15 +153,34 @@ fn private_subdirectory(root: &Path, name: &str, label: &str) -> Result 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 { - portable_marker(path).is_some() - || 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, - }) + // A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a + // marker only counts beside a PhotoCraft 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 || ["photocraft.exe", "photocraft"].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. Keeping it injected lets filesystem @@ -197,6 +228,7 @@ fn validate_for( } // Existing aliases under the profile must not redirect the default agent workspace elsewhere. agent_directory(&chosen)?; + entries_stay_inside(&chosen)?; // Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this // private profile, including toward a Stable portable directory not in our known roots. private_subdirectory(&chosen, "Recovery", "recovery folder")?; @@ -214,6 +246,7 @@ fn validate_for( } agent_directory(&confirmed)?; private_subdirectory(&confirmed, "Recovery", "recovery folder")?; + entries_stay_inside(&confirmed)?; writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; Ok(confirmed) } @@ -514,6 +547,102 @@ mod tests { assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/photocraft")).is_ok()); } + #[test] + fn windows_default_msi_install_folders_are_fenced() { + let mut fixture = Fixture::new(); + let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()); + let per_user = local.join("Programs").join("ArtCraft").join("PhotoCraft"); + assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap")); + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + let base = fixture.root.join(format!("machine {key}")); + fixture.env.insert(key.into(), base.clone().into_os_string()); + let machine = base.join("ArtCraft").join("PhotoCraft"); + assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap")); + assert!(!machine.exists()); + } + let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("photocraft"); + assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not PhotoCraft's install"); + } + + #[test] + fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() { + let fixture = Fixture::new(); + let portable = fixture.root.join("D/PC"); + std::fs::create_dir_all(&portable).unwrap(); + std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap(); + std::fs::write(portable.join("photocraft.exe"), b"stable portable executable, never run").unwrap(); + for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { + for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] { + let probed = std::cell::Cell::new(false); + let result = validate_for( + platform, + &candidate, + |key| fixture.get(key), + Some(&fixture.exe), + None, + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.unwrap_err().contains("portable")); + assert!(!probed.get()); + assert!(!candidate.exists()); + } + } + // A portable.txt that no PhotoCraft executable sits beside is someone else's file. + let unrelated = fixture.root.join("user folder"); + std::fs::create_dir_all(&unrelated).unwrap(); + std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap(); + assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/photocraft")).is_ok()); + } + + #[test] + fn linux_fences_the_stable_flatpak_data_folder() { + let fixture = Fixture::new(); + let flatpak = fixture.home().join(".var/app/ai.storyteller.photocraft"); + for candidate in [flatpak.clone(), flatpak.join("data/nightly")] { + assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap")); + } + assert!(!flatpak.exists()); + assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok()); + } + + #[cfg(unix)] + #[test] + fn any_profile_entry_alias_must_stay_inside_the_profile() { + let fixture = Fixture::new(); + let stable = fixture.home().join(".config/photocraft/Presets"); + std::fs::create_dir_all(&stable).unwrap(); + std::fs::write(stable.join("stable-preset"), b"stable preset bytes").unwrap(); + for name in ["Presets", "logs", "settings.json"] { + let private = fixture.root.join(format!("nightly-{name}")); + std::fs::create_dir(&private).unwrap(); + std::os::unix::fs::symlink(&stable, private.join(name)).unwrap(); + let probed = std::cell::Cell::new(false); + let result = validate_for( + Platform::Linux, + &private, + |key| fixture.get(key), + Some(&fixture.exe), + None, + |_| { + probed.set(true); + Ok(()) + }, + ); + assert!(result.is_err(), "{name} must not lead outside the profile"); + assert!(!probed.get()); + } + let private = fixture.root.join("nightly-inside"); + std::fs::create_dir_all(private.join("real-presets")).unwrap(); + std::fs::write(private.join("settings.json"), b"{}").unwrap(); + std::os::unix::fs::symlink(private.join("real-presets"), private.join("Presets")).unwrap(); + assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine"); + assert_eq!(std::fs::read(stable.join("stable-preset")).unwrap(), b"stable preset bytes"); + assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1); + } + #[test] fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() { let mut fixture = Fixture::new(); diff --git a/packaging/windows/nightly-package-tests.ps1 b/packaging/windows/nightly-package-tests.ps1 index de820fdc61..f5768849ec 100644 --- a/packaging/windows/nightly-package-tests.ps1 +++ b/packaging/windows/nightly-package-tests.ps1 @@ -21,7 +21,25 @@ foreach ($pair in @(@('PhotoCraft', 'PhotoCraft 0.23.1 (nightly-v1)'), @('PhotoC 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' } -Write-Output 'nightly packaging spec, target/version refusal and flavor-binding tests passed' +$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/photocraft/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' } @@ -54,3 +72,24 @@ try { 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' diff --git a/packaging/windows/nightly.ps1 b/packaging/windows/nightly.ps1 index b951895477..5eaa20263d 100644 --- a/packaging/windows/nightly.ps1 +++ b/packaging/windows/nightly.ps1 @@ -23,6 +23,27 @@ function Get-NightlyArchiveSpec([string] $Version, [string] $Arch) { } } +# 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 (PHOTOCRAFT_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 (PHOTOCRAFT_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 'PhotoCraft Nightly' -or $VersionOutput -cne "PhotoCraft $ExpectedVersion (nightly-v1)") { throw 'the executable is not the compiled nightly-v1 flavor' @@ -54,6 +75,8 @@ if (-not $BuildOnly) { throw 'Nightly compilation requires -BuildOnly; final arc # 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:PHOTOCRAFT_BUILD_SHA $env:PHOTOCRAFT_BUILD_DATE $Source.Head $Source.Status $oldChannel = $env:PHOTOCRAFT_BUILD_CHANNEL $oldVersionOverride = $env:PHOTOCRAFT_OVERRIDE_VERSION try { @@ -67,6 +90,9 @@ try { $env:PHOTOCRAFT_BUILD_CHANNEL = $oldChannel $env:PHOTOCRAFT_OVERRIDE_VERSION = $oldVersionOverride } +$Source = Get-NightlySourceState $Root +try { Assert-NightlySource $Version $env:PHOTOCRAFT_BUILD_SHA $env:PHOTOCRAFT_BUILD_DATE $Source.Head $Source.Status } +catch { throw "source changed during the build: $_" } $Exe = Join-Path $TargetDir "$Target\release\photocraft.exe" $pe = [System.IO.File]::ReadAllBytes($Exe) if ($pe.Length -lt 64) { throw 'truncated nightly PE executable' } diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 833b74adfb..5d4279a005 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -55,8 +55,11 @@ $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 -if (-not $env:PHOTOCRAFT_BUILD_SHA) { $env:PHOTOCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } -if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +# Nightly requires the prepared commit and original run date explicitly; nightly.ps1 checks both. +if (-not $Nightly) { + if (-not $env:PHOTOCRAFT_BUILD_SHA) { $env:PHOTOCRAFT_BUILD_SHA = (git -C $Root rev-parse HEAD 2>$null) } + if (-not $env:PHOTOCRAFT_BUILD_DATE) { $env:PHOTOCRAFT_BUILD_DATE = (Get-Date).ToUniversalTime().ToString('yyyy-MM-dd') } +} Write-Output "PhotoCraft $Version for Windows $Arch ($Target)"