Merge pull request 'Support issue-linked demo source changes' (#35) from codex/demo-source-change-support into main
Reviewed-on: #35 Reviewed-by: bill <yebilly4@gmail.com>
This commit was merged in pull request #35.
This commit is contained in:
@@ -13,4 +13,5 @@ delivery/evidence/recovery-*.json text eol=lf
|
||||
# Keep the frozen upstream blobs and their provenance byte-identical on checkout.
|
||||
demo/tikzrefinery/** -text -whitespace
|
||||
demo/snapshot.json -text
|
||||
demo/source-change.json -text
|
||||
demo/ci/*.sh text eol=lf
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# Draft issue: Align the rectangle provider class with the suffix naming convention
|
||||
|
||||
**Draft only — this issue has not been published.** Use the real issue number in
|
||||
the branch, commit/PR links and `demo/source-change.json` after creation.
|
||||
|
||||
The verified TikZRefinery checkpoint declares `tkrRectangleShapeProvider`, while
|
||||
the recorded naming request is `tkrShapeProviderRectangle`. Make one coordinated
|
||||
source/documentation refactor in this DevOps copy, demonstrating issue → branch →
|
||||
reviewed merge → Jenkins build → versioned artifact.
|
||||
|
||||
The frozen input is upstream `f4e3193d49a98efcf2f16c2aa22d6085ebe70f36`, application
|
||||
baseline `0.1.4-alpha`. Keep `demo/snapshot.json` unchanged. Baseline Jenkins
|
||||
[build 2](https://ci.yebilly.me/job/tikzrefinery-demo/2/) passed eight suites and
|
||||
produced verified version 1.0.2. [Build 3](https://ci.yebilly.me/job/tikzrefinery-demo/3/)
|
||||
also passed after host maintenance. These are historical baseline evidence, not
|
||||
evidence that this refactor is already implemented.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- Rename the class and its matching `.h`/`.cpp` files. Update definitions,
|
||||
includes and both CMake target references.
|
||||
- Update current implementation documentation, the actual declaration note and
|
||||
current provider diagram. Review `code/README.md`, `documents/latex/tkrPluginDesign.tex`,
|
||||
`documents/assets/design-diagrams/current-provider-classes.tex` and its README.
|
||||
Explain that the coordinated rename is now implemented. Preserve historical
|
||||
evidence, original snapshot instructions and past prompt-log records.
|
||||
- Keep provider ID, plugin interface contract and `tkr_rectangle` library identity.
|
||||
The change is a naming refactor, with rectangle behavior preserved.
|
||||
- Record every changed/added/deleted imported file in `demo/source-change.json`,
|
||||
linked to this actual issue. The immutable upstream manifest remains intact.
|
||||
Stage the product diff and record together; the complete tracked-source gate passes.
|
||||
- All eight CTests pass; the real provider module loads. Both report editions
|
||||
build with checked references/diagram index. Source-generated architecture uses
|
||||
the new class name; inspect the current provider figure visually.
|
||||
- Billy performs a real review; Vincent merges. Run the artifact job from reviewed
|
||||
`main`, then record its actual commit, build URL, `1.0.N` delivery version,
|
||||
source-change proof, image identity and downloaded artifact verification.
|
||||
- Rehearse the interactive Windows package and retain the baseline as a clearly
|
||||
labelled fallback. Complete the walkthrough, explanations and questions within
|
||||
20 minutes.
|
||||
|
||||
Proposed pre-edit comment (publish personally at the demonstration):
|
||||
|
||||
> I will rename the rectangle provider class and matching files, update the two
|
||||
> CMake references and current documentation, and record the exact diff against
|
||||
> the frozen baseline. The module identity and rectangle behavior will stay the
|
||||
> same. Billy will review the PR before the merged source is built in Jenkins.
|
||||
|
||||
Do not mark the issue complete until the final reviewed build and artifact checks
|
||||
have actually passed. No issue number, peer approval or future build is presumed.
|
||||
+5
-4
@@ -35,10 +35,11 @@ Complete these steps before calling the walkthrough ready:
|
||||
- After that baseline passes, agree on the live issue/change and rehearse the
|
||||
feature-branch, review, merge and artifact-build sequence. Reserve the actual
|
||||
demonstration commit/push for the assessed workflow.
|
||||
- Preserve the original snapshot manifest. The current verifier deliberately
|
||||
rejects any changed imported byte. An intentional product increment needs an
|
||||
explicit, tested provenance record for its changed files; do not simply disable
|
||||
verification or continue claiming all files are unchanged from the original.
|
||||
- Preserve the original snapshot manifest. Review and merge the separate
|
||||
[source-change support](SOURCE_CHANGE_RUNBOOK.md), then verify its baseline
|
||||
behavior through Jenkins before preparing the product increment. The optional
|
||||
issue-linked record declares the exact derived tree; unlisted edits still fail.
|
||||
Do not disable verification or claim the changed source is an unchanged import.
|
||||
- Record the real demo issue URL, branch and expected behavior; those are pending.
|
||||
Baseline/fallback is build 2, version 1.0.2, at the job linked above. Retain its
|
||||
downloaded artifacts and [success record](evidence/jenkins-baseline-success-20261126.json).
|
||||
|
||||
@@ -22,6 +22,14 @@ issue-linked demo increment after the baseline pipeline is verified. It is not
|
||||
part of this import. Keep that increment and the import distinguishable in Git.
|
||||
Neither a repository rename nor a commit/push is performed by these scripts.
|
||||
|
||||
For that separate increment, use the [source-change runbook](SOURCE_CHANGE_RUNBOOK.md).
|
||||
The original manifest is pinned and remains unchanged. An optional issue-linked
|
||||
`source-change.json` declares exact replacement/addition/deletion identities;
|
||||
every unlisted byte still has to match upstream. Package metadata distinguishes
|
||||
`frozen-baseline` from `recorded-change`. The record establishes source identity,
|
||||
not issue existence or peer approval. The [demo issue draft](DEMO_ISSUE_DRAFT.md)
|
||||
is unpublished, and no product refactor is included in this support change.
|
||||
|
||||
## Build identities
|
||||
|
||||
The upstream `0.1.4-alpha` version and full source commit remain separate from
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
Title: Preserve frozen-source verification for the issue-linked demo change
|
||||
|
||||
The verified TikZRefinery import currently rejects every product edit, so the
|
||||
planned provider refactor cannot pass its source gate. Keep the original snapshot
|
||||
immutable and allow an explicit issue-linked record of changed file identities.
|
||||
Verify the entire derived tree and staged Git blobs, and carry that proof into
|
||||
Windows/Linux package metadata and Linux artifact verification.
|
||||
|
||||
Includes regression tests, a record generator, an unpublished demo issue draft
|
||||
and the remaining review/rehearsal steps. The product rename is reserved for the
|
||||
separate demonstration change.
|
||||
|
||||
Validation: 11 provenance regression tests passed, including real Git-index
|
||||
checks and synthetic saved-image provenance/tampering cases. A fresh Windows
|
||||
Release build passed all eight application suites; the portable application
|
||||
loaded its real provider and dependencies from its bundle. The original Jenkins
|
||||
1.0.2 download still passed checksum/OCI verification. The complete manual was
|
||||
built and affected pages visually checked. See
|
||||
`demo/evidence/source-change-support-20261127.json` for scope and limitations.
|
||||
A Jenkins build from the reviewed merge remains the next workflow check.
|
||||
@@ -0,0 +1,94 @@
|
||||
# Preparing the issue-linked demo increment
|
||||
|
||||
This support change follows maintenance PR #33, merged into `main` at
|
||||
`b6f7edd48bce87567432e97b5dffda7abec59523`. The provider refactor is still pending.
|
||||
The local PowerPoint remains under ignored `build/presentation/`; share it with
|
||||
Billy directly. This work does not regenerate that deck.
|
||||
|
||||
## Review the workflow support first
|
||||
|
||||
Review/merge the `codex/demo-source-change-support` changes through the normal
|
||||
protocol, then run the existing artifact job on reviewed `main`. It should still
|
||||
identify `frozen-baseline`, verify 435 indexed files and produce a new `1.0.N`
|
||||
artifact. The new scripts have local tests; an actual Jenkins run of this support
|
||||
revision is a separate remaining check. No PR-branch execution or Replay is needed.
|
||||
|
||||
Run the local regression checks from the repository root:
|
||||
|
||||
```powershell
|
||||
python -B demo/ci/test-source-provenance.py
|
||||
python -B demo/ci/verify-snapshot.py --require-tracked
|
||||
```
|
||||
|
||||
The first command uses one disposable local Git fixture, never a remote. It does
|
||||
not commit. `--require-tracked` checks the exact working files, Git blobs/modes,
|
||||
original manifest and optional change record. Stage intended product and record
|
||||
changes together when testing the eventual increment.
|
||||
|
||||
## Create the real issue and agree on the assessed change
|
||||
|
||||
The [issue draft](DEMO_ISSUE_DRAFT.md) is ready for Vincent/Billy to publish after
|
||||
review. An agent must receive explicit instructions before publishing it under a
|
||||
group member's account. Record its real URL; a syntactically valid URL alone does
|
||||
not prove issue existence, approval or implementation.
|
||||
|
||||
After support is merged and verified, branch from current reviewed `main`, using
|
||||
`codex/demo-issue-<actual-number>-provider-name`. Read the imported project's
|
||||
`AGENTS.md` and its referenced controlled sources before touching product files.
|
||||
Follow their change-impact and assistance-record requirements. Keep the issue,
|
||||
product refactor and demonstration commit separate from this preparation change.
|
||||
|
||||
## Record the intentional product diff
|
||||
|
||||
After making and reviewing the agreed edits, generate the record. Replace the
|
||||
placeholder URL with the actual issue URL; the placeholder will be rejected.
|
||||
|
||||
```powershell
|
||||
python -B demo/ci/record-source-change.py `
|
||||
--issue-url 'https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/issues/ACTUAL_NUMBER' `
|
||||
--change-id 'rectangle-provider-name' `
|
||||
--description 'Rename the rectangle provider class and files; align current documentation.'
|
||||
```
|
||||
|
||||
The helper creates only `demo/source-change.json`. It never edits product files,
|
||||
stages or commits. It refuses an existing record and rejects an unchanged tree.
|
||||
Review generated additions/deletions carefully: a content-changing file rename
|
||||
appears as a deletion and addition; Git can still display its rename similarity.
|
||||
The verifier also accepts an explicit `before` → different `after.path` rename.
|
||||
This first-increment format always compares directly with the original snapshot;
|
||||
it is not a general history of successive changes. A later record must account
|
||||
for the entire cumulative diff from the same baseline.
|
||||
|
||||
The record has schema version 1, the original full commit and manifest SHA-256,
|
||||
a change identifier, real project issue URL, description and nonempty `changes`.
|
||||
Each entry contains `before` (an original relative path or null) and `after`
|
||||
(null, or an object with `path`, `mode`, `git_blob`, `sha256`, `bytes`). Additions
|
||||
default to mode `100644`; review executable additions and their staged modes.
|
||||
Duplicate keys/entries, unsafe paths, collisions, invalid identities, unchanged
|
||||
records and altered baseline manifests are rejected. Unlisted source bytes still
|
||||
have to match the original exactly. Symlinks are rejected.
|
||||
|
||||
If further edits are needed, review and deliberately replace the generated record
|
||||
before regenerating it. Never rewrite `snapshot.json` to bless a changed tree.
|
||||
|
||||
## Build and present the real result
|
||||
|
||||
The existing job keeps reviewed-main ancestry, trusted-worker and sequential
|
||||
resource limits. Packaging re-verifies the source; Jenkins requires tracked
|
||||
provenance. Delivery metadata includes the complete validated change record and
|
||||
its hash, original baseline and actual downstream build identity. The optional
|
||||
record is also copied beside `upstream-snapshot.json` in the application bundle.
|
||||
The Windows helper carries the same source proof, while truthfully identifying
|
||||
itself as a command-line rehearsal.
|
||||
|
||||
For new Linux packages, `verify-artifacts.py` checks the declared source inventory,
|
||||
the saved OCI chain and the actual bundle's provenance/manifest/change record in
|
||||
the final COPY layer. Downloaded legacy packages remain transport/OCI checks only,
|
||||
explicitly labelled; they do not gain a source-change attestation retroactively.
|
||||
These hashes establish consistency, not a signature, external issue validation
|
||||
or proof that a binary behaves correctly. Preserve tests, review and build records.
|
||||
|
||||
Keep the actual rename commit/push for the agreed assessed workflow. Inspect the
|
||||
PR diff, have Billy review, merge, build from `main`, download/verify that build's
|
||||
artifacts, and update the demo script with the actual issue/commit/build/version.
|
||||
Rehearse timing and application use before calling the demonstration ready.
|
||||
@@ -16,7 +16,8 @@ $repository = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
|
||||
if ($DeliveryVersion -notmatch '^\d+\.\d+\.\d+$') { throw 'Use major.minor.changelist' }
|
||||
Push-Location $repository
|
||||
try {
|
||||
& $PythonExecutable demo/ci/verify-snapshot.py
|
||||
$sourceVerification = (& $PythonExecutable demo/ci/verify-snapshot.py) -join "`n" | ConvertFrom-Json
|
||||
$sourceVerification | ConvertTo-Json -Depth 12 | Write-Output
|
||||
$output = (New-Item -ItemType Directory -Force $OutputDirectory).FullName
|
||||
$build = if ($BuildDirectory) { [IO.Path]::GetFullPath($BuildDirectory) } else { Join-Path $output 'build' }
|
||||
$package = Join-Path $output "TikZRefinery-windows-$DeliveryVersion"
|
||||
@@ -39,17 +40,21 @@ try {
|
||||
Copy-Item "$QtKit/plugins/platforms/qoffscreen.dll" "$package/platforms"
|
||||
Copy-Item "$build/build-info.json" $package
|
||||
Copy-Item demo/snapshot.json "$package/upstream-snapshot.json"
|
||||
if ($null -ne $sourceVerification.source_change_record) {
|
||||
Copy-Item demo/source-change.json "$package/source-change.json"
|
||||
}
|
||||
Copy-Item demo/tikzrefinery/code/examples "$package/examples" -Recurse
|
||||
$downstream = (& git rev-parse HEAD).Trim()
|
||||
$state = (& git status --porcelain --untracked-files=normal) -join "`n"
|
||||
[ordered]@{
|
||||
delivery_version = $DeliveryVersion
|
||||
upstream_commit = 'f4e3193d49a98efcf2f16c2aa22d6085ebe70f36'
|
||||
application_baseline = '0.1.4-alpha'
|
||||
upstream_commit = $sourceVerification.upstream_commit
|
||||
application_baseline = $sourceVerification.application_baseline
|
||||
source_verification = $sourceVerification
|
||||
downstream_commit = $downstream
|
||||
downstream_modified = [bool]$state
|
||||
execution = 'Windows command-line rehearsal; not a Jenkins run'
|
||||
} | ConvertTo-Json | Set-Content "$package/delivery-info.json" -Encoding utf8
|
||||
} | ConvertTo-Json -Depth 12 | Set-Content "$package/delivery-info.json" -Encoding utf8
|
||||
& $PythonExecutable demo/ci/verify-snapshot.py
|
||||
Compress-Archive -LiteralPath $package -DestinationPath "$package.zip"
|
||||
Get-FileHash "$package.zip" -Algorithm SHA256 | Format-List
|
||||
|
||||
@@ -9,6 +9,10 @@ import subprocess
|
||||
import tarfile
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
import sys
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from source_provenance import verify_source
|
||||
|
||||
root = Path.cwd()
|
||||
out = root / 'build/demo'
|
||||
@@ -33,6 +37,7 @@ assert (out / 'artifacts/TikZRefinery-report.pdf').is_file()
|
||||
assert (out / 'architecture/html/index.html').is_file()
|
||||
snapshot = json.loads((root / 'demo/snapshot.json').read_text())
|
||||
jenkins = bool(os.environ.get('BUILD_URL'))
|
||||
source_verification = verify_source(root / 'demo', require_tracked=jenkins)
|
||||
try:
|
||||
downstream = run('git', 'rev-parse', 'HEAD')
|
||||
modified = bool(run('git', 'status', '--porcelain', '--untracked-files=normal'))
|
||||
@@ -47,6 +52,7 @@ record = dict(delivery_version=version, application_baseline=snapshot['applicati
|
||||
downstream_commit_or_parent=downstream, downstream_modified=modified,
|
||||
execution='Jenkins' if jenkins else 'SSH command-line rehearsal; not a Jenkins run',
|
||||
build_url=os.environ.get('BUILD_URL'), source_sha256=source_hashes,
|
||||
source_verification=source_verification,
|
||||
toolchain=json.loads((root / 'demo/toolchain.json').read_text()))
|
||||
bundle = out / 'application-bundle'
|
||||
bundle.mkdir(exist_ok=True)
|
||||
@@ -56,6 +62,11 @@ for source, destination in [(out/'native/TikZRefinery',bundle/'TikZRefinery'),
|
||||
(out/'native/build-info.json',bundle/'build-info.json'),
|
||||
(root/'demo/snapshot.json',bundle/'upstream-snapshot.json')]:
|
||||
shutil.copy2(source, destination)
|
||||
if source_verification['source_change_record'] is not None:
|
||||
shutil.copy2(root / 'demo/source-change.json', bundle / 'source-change.json')
|
||||
else:
|
||||
# This generated staging directory can survive a previous changed-source run.
|
||||
(bundle / 'source-change.json').unlink(missing_ok=True)
|
||||
(bundle / 'delivery-info.json').write_text(json.dumps(record, indent=2) + '\n')
|
||||
image = ('ssw590-tikzrefinery' if jenkins else 'ssw590-tikzrefinery-rehearsal') + ':' + version
|
||||
exists = subprocess.run(['docker','image','inspect',image], stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode == 0
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Record the current intentional tree diff; review it before staging or committing.
|
||||
|
||||
This creates metadata only. It never edits product source, stages files, verifies
|
||||
issue existence, or grants approval. A content-changing rename is a delete/add.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from source_provenance import BASELINE_SHA256, UPSTREAM_COMMIT, expected_files, identity, is_link, load_definition, verify_source
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--issue-url', required=True)
|
||||
parser.add_argument('--change-id', required=True)
|
||||
parser.add_argument('--description', required=True)
|
||||
args = parser.parse_args()
|
||||
demo = Path(__file__).resolve().parents[1]
|
||||
target = demo / 'source-change.json'
|
||||
try:
|
||||
manifest, existing, _, _ = load_definition(demo)
|
||||
if existing is not None:
|
||||
raise ValueError('Preserve existing source-change.json; inspect it before replacing it')
|
||||
source = demo / 'tikzrefinery'
|
||||
if is_link(source):
|
||||
raise ValueError('Source root must not be a link')
|
||||
actual = {}
|
||||
for path in sorted(source.rglob('*')):
|
||||
if is_link(path):
|
||||
raise ValueError(f'Source link rejected: {path}')
|
||||
if path.is_file():
|
||||
name = path.relative_to(source).as_posix()
|
||||
# Preserve original modes. New source/docs default to ordinary files;
|
||||
# review executable additions and their index modes explicitly.
|
||||
mode = manifest['files'].get(name, {}).get('mode', '100644')
|
||||
actual[name] = identity(path.read_bytes(), mode)
|
||||
changes = []
|
||||
for name in sorted(set(manifest['files']) | set(actual)):
|
||||
before, after = manifest['files'].get(name), actual.get(name)
|
||||
if before != after:
|
||||
changes.append(dict(before=name if before is not None else None,
|
||||
after=dict(path=name, **after) if after is not None else None))
|
||||
record = dict(schema_version=1, upstream_commit=UPSTREAM_COMMIT,
|
||||
baseline_manifest_sha256=BASELINE_SHA256, change_id=args.change_id,
|
||||
issue_url=args.issue_url, description=args.description, changes=changes)
|
||||
expected_files(manifest, record)
|
||||
with target.open('x', encoding='utf-8', newline='\n') as stream:
|
||||
stream.write(json.dumps(record, indent=2) + '\n')
|
||||
print(json.dumps(verify_source(demo), indent=2))
|
||||
except (ValueError, OSError) as error:
|
||||
parser.exit(1, f'Change recording failed: {error}\n')
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Verify an immutable import plus an optional downstream change record.
|
||||
|
||||
File identity is distinct from issue existence, peer approval and build success.
|
||||
Reviewed-main selection remains the Jenkins job's separate trust boundary.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
BASELINE_SHA256 = 'a86656744d5d700aa21834fc03b0a54dfe5b5fd4e8b32ccecc40c6ae7553df2d'
|
||||
UPSTREAM_COMMIT = 'f4e3193d49a98efcf2f16c2aa22d6085ebe70f36'
|
||||
APPLICATION_BASELINE = '0.1.4-alpha'
|
||||
ISSUE_PATTERN = r'https://git\.yebilly\.me/ssw590-group1/vpn-dns-gateway/issues/[1-9][0-9]*'
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def strict_json(data):
|
||||
def object_pairs(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
require(key not in result, f'Duplicate JSON key: {key}')
|
||||
result[key] = value
|
||||
return result
|
||||
return json.loads(data, object_pairs_hook=object_pairs)
|
||||
|
||||
|
||||
def identity(data, mode='100644'):
|
||||
return dict(mode=mode, bytes=len(data), sha256=hashlib.sha256(data).hexdigest(),
|
||||
git_blob=hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest())
|
||||
|
||||
|
||||
def is_link(path):
|
||||
return path.is_symlink() or getattr(path, 'is_junction', lambda: False)()
|
||||
|
||||
|
||||
def safe_path(name):
|
||||
require(isinstance(name, str) and bool(name), 'Expected a nonempty relative path')
|
||||
path = PurePosixPath(name)
|
||||
require(not path.is_absolute() and str(path) == name and '\\' not in name
|
||||
and all(part.casefold() not in {'.', '..', '.git'} and ':' not in part
|
||||
and not part.endswith((' ', '.')) for part in path.parts),
|
||||
f'Unsafe source path: {name}')
|
||||
return name
|
||||
|
||||
|
||||
def expected_files(manifest, change):
|
||||
"""Derive the complete expected tree without modifying the baseline manifest."""
|
||||
expected = dict(manifest['files'])
|
||||
if change is None:
|
||||
return expected
|
||||
require(isinstance(change, dict) and set(change) == {
|
||||
'schema_version', 'upstream_commit', 'baseline_manifest_sha256',
|
||||
'change_id', 'issue_url', 'description', 'changes'}, 'Invalid change record fields')
|
||||
require(type(change['schema_version']) is int and change['schema_version'] == 1,
|
||||
'Unsupported change schema')
|
||||
require(change['upstream_commit'] == UPSTREAM_COMMIT
|
||||
and change['baseline_manifest_sha256'] == BASELINE_SHA256,
|
||||
'Change record must reference the original baseline')
|
||||
require(isinstance(change['change_id'], str)
|
||||
and re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*', change['change_id'])
|
||||
and len(change['change_id']) <= 100, 'Invalid change identifier')
|
||||
require(isinstance(change['issue_url'], str)
|
||||
and re.fullmatch(ISSUE_PATTERN, change['issue_url']), 'Expected a project issue URL')
|
||||
require(isinstance(change['description'], str)
|
||||
and 1 <= len(change['description'].strip()) <= 2000, 'Invalid change description')
|
||||
require(isinstance(change['changes'], list) and bool(change['changes']), 'Empty change record')
|
||||
removed, replacements = set(), {}
|
||||
for row in change['changes']:
|
||||
require(isinstance(row, dict) and set(row) == {'before', 'after'}, 'Invalid change entry')
|
||||
before, after = row['before'], row['after']
|
||||
require(before is not None or after is not None, 'Empty change entry')
|
||||
if before is not None:
|
||||
safe_path(before)
|
||||
require(before in expected and before not in removed, f'Unknown/repeated original: {before}')
|
||||
removed.add(before)
|
||||
if after is not None:
|
||||
require(isinstance(after, dict) and set(after) == {
|
||||
'path', 'mode', 'git_blob', 'sha256', 'bytes'}, 'Invalid replacement identity')
|
||||
name = safe_path(after['path'])
|
||||
require(name not in replacements, f'Repeated replacement: {name}')
|
||||
require(isinstance(after['mode'], str) and after['mode'] in {'100644', '100755'}, 'Invalid file mode')
|
||||
require(type(after['bytes']) is int and after['bytes'] >= 0, 'Invalid byte count')
|
||||
for key, length in [('git_blob', 40), ('sha256', 64)]:
|
||||
require(isinstance(after[key], str) and re.fullmatch('[0-9a-f]{'+str(length)+'}', after[key]),
|
||||
f'Invalid {key}')
|
||||
replacement = {key: after[key] for key in ('mode', 'git_blob', 'sha256', 'bytes')}
|
||||
require(before != name or replacement != expected[before], f'No-op change: {name}')
|
||||
replacements[name] = replacement
|
||||
for name in removed:
|
||||
del expected[name]
|
||||
require(not (set(replacements) & set(expected)), 'Replacement collides with unchanged original')
|
||||
expected.update(replacements)
|
||||
require(expected != manifest['files'], 'Change record leaves the baseline tree unchanged')
|
||||
require(len({name.casefold() for name in expected}) == len(expected), 'Case-insensitive path collision')
|
||||
folded_names = {name.casefold() for name in expected}
|
||||
for name in expected:
|
||||
require(not any(str(parent).casefold() in folded_names for parent in PurePosixPath(name).parents),
|
||||
f'File/directory collision: {name}')
|
||||
return expected
|
||||
|
||||
|
||||
def load_definition(demo):
|
||||
manifest_path = demo / 'snapshot.json'
|
||||
require(not is_link(manifest_path), 'Baseline manifest must not be a link')
|
||||
data = manifest_path.read_bytes()
|
||||
require(hashlib.sha256(data).hexdigest() == BASELINE_SHA256, 'Original baseline manifest changed')
|
||||
manifest = strict_json(data)
|
||||
require(manifest['upstream_commit'] == UPSTREAM_COMMIT
|
||||
and manifest['application_baseline'] == APPLICATION_BASELINE, 'Wrong baseline identity')
|
||||
change_path = demo / 'source-change.json'
|
||||
require(not is_link(change_path), 'Change record must not be a link')
|
||||
change_data = change_path.read_bytes() if change_path.exists() else None
|
||||
change = strict_json(change_data) if change_data is not None else None
|
||||
require(change_data is None or change is not None, 'A present change record cannot be null')
|
||||
return manifest, change, change_data, expected_files(manifest, change)
|
||||
|
||||
|
||||
def verify_source(demo, require_tracked=False):
|
||||
demo = Path(demo).resolve()
|
||||
manifest, change, change_data, expected = load_definition(demo)
|
||||
source = demo / 'tikzrefinery'
|
||||
require(not is_link(source), 'Source root must not be a link')
|
||||
actual = set()
|
||||
for path in source.rglob('*'):
|
||||
require(not is_link(path), f'Source link rejected: {path}')
|
||||
if path.is_file():
|
||||
actual.add(path.relative_to(source).as_posix())
|
||||
else:
|
||||
require(path.is_dir(), f'Unexpected source entry: {path}')
|
||||
require(actual == set(expected), f'Source tree differs: missing={sorted(set(expected)-actual)}, '
|
||||
f'extra={sorted(actual-set(expected))}')
|
||||
for name, wanted in expected.items():
|
||||
require(identity((source / name).read_bytes(), wanted['mode']) == wanted,
|
||||
f'Source identity differs: {name}')
|
||||
if require_tracked:
|
||||
rows = subprocess.check_output(['git', 'ls-files', '--stage', '-z', '--',
|
||||
'demo/tikzrefinery', 'demo/snapshot.json', 'demo/source-change.json'],
|
||||
cwd=demo.parent).decode('utf-8').split('\0')
|
||||
tracked = {}
|
||||
for row in filter(None, rows):
|
||||
metadata, path = row.split('\t', 1)
|
||||
mode, blob, stage = metadata.split()
|
||||
require(stage == '0', f'Unresolved index entry: {path}')
|
||||
tracked[path] = (mode, blob)
|
||||
wanted_index = {'demo/tikzrefinery/' + name: (item['mode'], item['git_blob'])
|
||||
for name, item in expected.items()}
|
||||
wanted_index['demo/snapshot.json'] = ('100644', identity((demo / 'snapshot.json').read_bytes())['git_blob'])
|
||||
if change_data is not None:
|
||||
wanted_index['demo/source-change.json'] = ('100644', identity(change_data)['git_blob'])
|
||||
require(tracked == wanted_index, 'Git index differs from verified source/manifest/change record; '
|
||||
'stage the exact intended files, including new assets and the change record')
|
||||
return dict(result='passed', upstream_commit=UPSTREAM_COMMIT,
|
||||
application_baseline=APPLICATION_BASELINE, baseline_manifest_sha256=BASELINE_SHA256,
|
||||
source_state='frozen-baseline' if change is None else 'recorded-change',
|
||||
verified_files=len(expected), git_index_verified=require_tracked,
|
||||
source_change_record=change,
|
||||
source_change_sha256=hashlib.sha256(change_data).hexdigest() if change_data is not None else None)
|
||||
|
||||
|
||||
def verify_packaged_provenance(record, manifest):
|
||||
"""Check metadata consistency; this alone does not rebuild or retest a binary."""
|
||||
proof = record['source_verification']
|
||||
expected = expected_files(manifest, proof['source_change_record'])
|
||||
require(proof['result'] == 'passed' and proof['upstream_commit'] == UPSTREAM_COMMIT
|
||||
and proof['application_baseline'] == APPLICATION_BASELINE
|
||||
and proof['baseline_manifest_sha256'] == BASELINE_SHA256
|
||||
and proof['verified_files'] == len(expected), 'Invalid packaged source verification')
|
||||
changed = proof['source_change_record'] is not None
|
||||
require(proof['source_state'] == ('recorded-change' if changed else 'frozen-baseline'), 'Wrong source state')
|
||||
hashes = record['source_sha256']
|
||||
require(hashes['snapshot.json'] == BASELINE_SHA256, 'Wrong packaged baseline hash')
|
||||
require(record['upstream_commit'] == UPSTREAM_COMMIT
|
||||
and record['application_baseline'] == APPLICATION_BASELINE, 'Wrong package identity')
|
||||
require(type(proof['git_index_verified']) is bool, 'Invalid tracked-source flag')
|
||||
require(record['execution'] != 'Jenkins' or proof['git_index_verified'], 'Jenkins requires indexed source')
|
||||
if changed:
|
||||
require(isinstance(proof['source_change_sha256'], str)
|
||||
and re.fullmatch(r'[0-9a-f]{64}', proof['source_change_sha256'])
|
||||
and hashes['source-change.json'] == proof['source_change_sha256'], 'Wrong change record hash')
|
||||
else:
|
||||
require(proof['source_change_sha256'] is None and 'source-change.json' not in hashes,
|
||||
'Unexpected baseline change record')
|
||||
product_hashes = {name.removeprefix('tikzrefinery/'): value for name, value in hashes.items()
|
||||
if name.startswith('tikzrefinery/')}
|
||||
require(product_hashes == {name: item['sha256'] for name, item in expected.items()},
|
||||
'Packaged source inventory differs from declared tree')
|
||||
@@ -0,0 +1,278 @@
|
||||
"""Exercise real file/index boundaries in one disposable, local-only Git fixture."""
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import tarfile
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from source_provenance import (BASELINE_SHA256, UPSTREAM_COMMIT, expected_files, identity,
|
||||
strict_json, verify_packaged_provenance, verify_source)
|
||||
|
||||
REPOSITORY = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class SourceProvenanceTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
workspace = (REPOSITORY / 'work/demo-source-change-tests').resolve()
|
||||
workspace.mkdir(parents=True, exist_ok=True)
|
||||
cls.scratch = tempfile.TemporaryDirectory(prefix='fixture-', dir=workspace)
|
||||
cls.root = Path(cls.scratch.name).resolve()
|
||||
assert cls.root.is_relative_to(workspace) and cls.root != workspace
|
||||
cls.demo = cls.root / 'demo'
|
||||
cls.demo.mkdir()
|
||||
shutil.copyfile(REPOSITORY / 'demo/snapshot.json', cls.demo / 'snapshot.json')
|
||||
shutil.copytree(REPOSITORY / 'demo/tikzrefinery', cls.demo / 'tikzrefinery')
|
||||
(cls.demo / 'ci').mkdir()
|
||||
for name in ['source_provenance.py', 'record-source-change.py']:
|
||||
shutil.copyfile(REPOSITORY / 'demo/ci' / name, cls.demo / 'ci' / name)
|
||||
cls.manifest = strict_json((cls.demo / 'snapshot.json').read_bytes())
|
||||
cls.original = {name: (cls.demo / 'tikzrefinery' / name).read_bytes()
|
||||
for name in cls.manifest['files']}
|
||||
cls.git('init', '-q')
|
||||
cls.git('config', 'core.autocrlf', 'false')
|
||||
cls.git('add', '-f', 'demo')
|
||||
# Git for Windows may not infer executable bits. Restore pinned modes.
|
||||
for name, item in cls.manifest['files'].items():
|
||||
if item['mode'] == '100755':
|
||||
cls.git('update-index', '--chmod=+x', 'demo/tikzrefinery/' + name)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
# Absolute scratch target was validated under this task's workspace above.
|
||||
cls.scratch.cleanup()
|
||||
|
||||
@classmethod
|
||||
def git(cls, *args):
|
||||
return subprocess.check_output(['git', *args], cwd=cls.root, stderr=subprocess.STDOUT)
|
||||
|
||||
def setUp(self):
|
||||
self.record_path = self.demo / 'source-change.json'
|
||||
self.record_path.unlink(missing_ok=True)
|
||||
for path in (self.demo / 'tikzrefinery').rglob('*'):
|
||||
if path.is_file() and path.relative_to(self.demo / 'tikzrefinery').as_posix() not in self.original:
|
||||
path.unlink()
|
||||
for name, data in self.original.items():
|
||||
path = self.demo / 'tikzrefinery' / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
shutil.copyfile(REPOSITORY / 'demo/snapshot.json', self.demo / 'snapshot.json')
|
||||
self.git('add', '-f', '-A', 'demo')
|
||||
for name, item in self.manifest['files'].items():
|
||||
if item['mode'] == '100755':
|
||||
self.git('update-index', '--chmod=+x', 'demo/tikzrefinery/' + name)
|
||||
|
||||
def modification(self):
|
||||
name = 'README.md'
|
||||
data = self.original[name] + b'\nTest fixture change only.\n'
|
||||
(self.demo / 'tikzrefinery' / name).write_bytes(data)
|
||||
return self.record([dict(before=name, after=dict(path=name, **identity(data)))])
|
||||
|
||||
def record(self, changes):
|
||||
record = dict(schema_version=1, upstream_commit=UPSTREAM_COMMIT,
|
||||
baseline_manifest_sha256=BASELINE_SHA256, change_id='test-fixture',
|
||||
issue_url='https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/issues/999999',
|
||||
description='Synthetic local fixture; no published issue or product change.', changes=changes)
|
||||
self.record_path.write_text(json.dumps(record), encoding='utf-8')
|
||||
return record
|
||||
|
||||
def test_original_files_and_index(self):
|
||||
self.assertEqual(verify_source(self.demo, True)['verified_files'], 435)
|
||||
|
||||
def test_modified_source_requires_record(self):
|
||||
self.modification()
|
||||
self.record_path.unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'identity differs'):
|
||||
verify_source(self.demo)
|
||||
|
||||
def test_record_and_source_must_both_be_staged(self):
|
||||
self.modification()
|
||||
self.assertEqual(verify_source(self.demo)['source_state'], 'recorded-change')
|
||||
with self.assertRaisesRegex(ValueError, 'Git index differs'):
|
||||
verify_source(self.demo, True)
|
||||
self.git('add', '-f', 'demo/tikzrefinery/README.md')
|
||||
with self.assertRaisesRegex(ValueError, 'Git index differs'):
|
||||
verify_source(self.demo, True)
|
||||
self.git('add', '-f', 'demo/source-change.json')
|
||||
self.assertTrue(verify_source(self.demo, True)['git_index_verified'])
|
||||
self.record_path.write_bytes(self.record_path.read_bytes() + b'\n')
|
||||
with self.assertRaisesRegex(ValueError, 'Git index differs'):
|
||||
verify_source(self.demo, True)
|
||||
self.record_path.unlink()
|
||||
with self.assertRaises(ValueError):
|
||||
verify_source(self.demo, True)
|
||||
|
||||
def test_rename_add_delete(self):
|
||||
old, new = 'README.md', 'README-renamed.md'
|
||||
(self.demo / 'tikzrefinery' / old).rename(self.demo / 'tikzrefinery' / new)
|
||||
self.record([dict(before=old, after=dict(path=new, **self.manifest['files'][old]))])
|
||||
self.assertEqual(verify_source(self.demo)['verified_files'], 435)
|
||||
self.git('add', '-f', '-A', 'demo')
|
||||
self.assertTrue(verify_source(self.demo, True)['git_index_verified'])
|
||||
(self.demo / 'tikzrefinery' / new).unlink()
|
||||
added = self.demo / 'tikzrefinery/new.txt'
|
||||
added.write_bytes(b'new\n')
|
||||
self.record([dict(before=old, after=None), dict(before=None, after=dict(path='new.txt', **identity(b'new\n')))])
|
||||
self.assertEqual(verify_source(self.demo)['verified_files'], 435)
|
||||
|
||||
def test_missing_original_asset_rejected_even_if_on_disk(self):
|
||||
self.git('rm', '--cached', '-f', 'demo/tikzrefinery/documents/assets/loop-example/loop-boxes.dvi')
|
||||
self.assertEqual(verify_source(self.demo)['verified_files'], 435)
|
||||
with self.assertRaisesRegex(ValueError, 'Git index differs'):
|
||||
verify_source(self.demo, True)
|
||||
|
||||
def test_missing_extra_or_modified_unlisted_source_rejected(self):
|
||||
self.modification()
|
||||
path = self.demo / 'tikzrefinery/CHANGELOG.md'
|
||||
path.write_bytes(b'unlisted edit')
|
||||
with self.assertRaisesRegex(ValueError, 'identity differs'):
|
||||
verify_source(self.demo)
|
||||
path.unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'Source tree differs'):
|
||||
verify_source(self.demo)
|
||||
path.write_bytes(self.original['CHANGELOG.md'])
|
||||
(self.demo / 'tikzrefinery/extra.txt').write_bytes(b'extra')
|
||||
with self.assertRaisesRegex(ValueError, 'Source tree differs'):
|
||||
verify_source(self.demo)
|
||||
|
||||
def test_original_manifest_cannot_be_rewritten(self):
|
||||
self.modification()
|
||||
path = self.demo / 'snapshot.json'
|
||||
path.write_bytes(path.read_bytes() + b'\n')
|
||||
with self.assertRaisesRegex(ValueError, 'baseline manifest changed'):
|
||||
verify_source(self.demo)
|
||||
|
||||
def test_invalid_records_rejected(self):
|
||||
valid = self.modification()
|
||||
malformed = []
|
||||
for field, value in [('schema_version', True), ('issue_url', 'https://example.com/issues/1'),
|
||||
('baseline_manifest_sha256', '0'*64), ('changes', []), ('unknown', True)]:
|
||||
row = copy.deepcopy(valid)
|
||||
row[field] = value
|
||||
malformed.append(row)
|
||||
for path in ['../escape', '/escape', 'a\\b', 'a/../b', '.git/config', '.Git/config',
|
||||
'README.md/child', 'readme.md/child']:
|
||||
row = copy.deepcopy(valid)
|
||||
row['changes'][0]['after']['path'] = path
|
||||
# Preserve README as an unchanged original for the directory collision case.
|
||||
row['changes'][0]['before'] = None
|
||||
malformed.append(row)
|
||||
row = copy.deepcopy(valid)
|
||||
row['changes'] *= 2
|
||||
malformed.append(row)
|
||||
for after in [dict(path='README.md', **self.manifest['files']['README.md']),
|
||||
dict(path='CHANGELOG.md', **identity(b'collision')),
|
||||
dict(path='readme.md', **identity(b'case collision'))]:
|
||||
row = copy.deepcopy(valid)
|
||||
row['changes'][0]['after'] = after
|
||||
if after['path'] == 'readme.md':
|
||||
row['changes'][0]['before'] = None
|
||||
malformed.append(row)
|
||||
for row in malformed:
|
||||
with self.subTest(record=row), self.assertRaises(ValueError):
|
||||
expected_files(self.manifest, row)
|
||||
with self.assertRaisesRegex(ValueError, 'Duplicate JSON key'):
|
||||
strict_json('{"changes":[],"changes":[]}')
|
||||
self.record_path.write_text('null')
|
||||
with self.assertRaisesRegex(ValueError, 'cannot be null'):
|
||||
verify_source(self.demo)
|
||||
|
||||
def test_package_metadata_tracks_declared_tree(self):
|
||||
self.modification()
|
||||
proof = verify_source(self.demo)
|
||||
expected = expected_files(self.manifest, proof['source_change_record'])
|
||||
hashes = {'snapshot.json': BASELINE_SHA256, 'source-change.json': proof['source_change_sha256'],
|
||||
**{'tikzrefinery/' + name: item['sha256'] for name, item in expected.items()}}
|
||||
record = dict(source_verification=proof, source_sha256=hashes, upstream_commit=UPSTREAM_COMMIT,
|
||||
application_baseline='0.1.4-alpha', execution='local test fixture')
|
||||
verify_packaged_provenance(record, self.manifest)
|
||||
record['execution'] = 'Jenkins'
|
||||
with self.assertRaisesRegex(ValueError, 'indexed source'):
|
||||
verify_packaged_provenance(record, self.manifest)
|
||||
record['execution'] = 'local test fixture'
|
||||
hashes['tikzrefinery/README.md'] = '0'*64
|
||||
with self.assertRaisesRegex(ValueError, 'inventory differs'):
|
||||
verify_packaged_provenance(record, self.manifest)
|
||||
|
||||
def test_record_generator_and_overwrite_guard(self):
|
||||
self.modification()
|
||||
self.record_path.unlink()
|
||||
command = [sys.executable, '-B', str(self.demo / 'ci/record-source-change.py'),
|
||||
'--issue-url', 'https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/issues/999999',
|
||||
'--change-id', 'test-fixture', '--description', 'Synthetic local test only.']
|
||||
result = subprocess.run(command, capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(verify_source(self.demo)['source_state'], 'recorded-change')
|
||||
data = self.record_path.read_bytes()
|
||||
result = subprocess.run(command, capture_output=True, text=True)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(self.record_path.read_bytes(), data)
|
||||
|
||||
def test_saved_oci_bundle_provenance(self):
|
||||
# Synthetic transport fixture, not a real image, Jenkins run or behavior claim.
|
||||
for changed in [False, True]:
|
||||
with self.subTest(changed=changed):
|
||||
if changed:
|
||||
self.modification()
|
||||
proof = verify_source(self.demo)
|
||||
expected = expected_files(self.manifest, proof['source_change_record'])
|
||||
record = dict(delivery_version='9.9.9', execution='synthetic local test fixture',
|
||||
application_baseline='0.1.4-alpha', upstream_commit=UPSTREAM_COMMIT,
|
||||
source_verification=proof, source_sha256={
|
||||
'snapshot.json': BASELINE_SHA256,
|
||||
**{'tikzrefinery/' + name: value['sha256'] for name, value in expected.items()}})
|
||||
bundle_files = {'upstream-snapshot.json': (self.demo / 'snapshot.json').read_bytes()}
|
||||
if changed:
|
||||
record['source_sha256']['source-change.json'] = proof['source_change_sha256']
|
||||
bundle_files['source-change.json'] = self.record_path.read_bytes()
|
||||
bundle_files['delivery-info.json'] = json.dumps(record).encode()
|
||||
layer_stream = io.BytesIO()
|
||||
def add(tar, name, data):
|
||||
item = tarfile.TarInfo(name)
|
||||
item.size = len(data)
|
||||
tar.addfile(item, io.BytesIO(data))
|
||||
with tarfile.open(fileobj=layer_stream, mode='w') as layer:
|
||||
for name, data in bundle_files.items():
|
||||
add(layer, 'opt/tikzrefinery/' + name, data)
|
||||
blobs = {}
|
||||
def blob(data):
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
blobs['blobs/sha256/' + digest] = data
|
||||
return dict(digest='sha256:' + digest, size=len(data))
|
||||
image_manifest = dict(config=blob(b'{}'), layers=[blob(layer_stream.getvalue())])
|
||||
descriptor = blob(json.dumps(image_manifest).encode())
|
||||
record.update(application_image='synthetic-fixture:9.9.9', application_image_id=descriptor['digest'])
|
||||
artifacts = self.root / 'artifacts'
|
||||
artifacts.mkdir(exist_ok=True)
|
||||
archive_path = artifacts / 'TikZRefinery-9.9.9-linux-image.tar.gz'
|
||||
with tarfile.open(archive_path, 'w:gz') as archive:
|
||||
for name, data in {**blobs,
|
||||
'index.json': json.dumps(dict(manifests=[descriptor])).encode(),
|
||||
'manifest.json': json.dumps([dict(RepoTags=[record['application_image']])]).encode()}.items():
|
||||
add(archive, name, data)
|
||||
record['image_archive_sha256'] = hashlib.sha256(archive_path.read_bytes()).hexdigest()
|
||||
with zipfile.ZipFile(artifacts / 'TikZRefinery-9.9.9-architecture.zip', 'w') as docs:
|
||||
docs.writestr('html/index.html', 'Synthetic fixture')
|
||||
def write_record_and_sums():
|
||||
(artifacts / 'delivery-info.json').write_text(json.dumps(record))
|
||||
(artifacts / 'SHA256SUMS').write_text('\n'.join(
|
||||
hashlib.sha256(path.read_bytes()).hexdigest() + ' ' + path.name
|
||||
for path in sorted(artifacts.iterdir()) if path.name != 'SHA256SUMS') + '\n')
|
||||
write_record_and_sums()
|
||||
command = [sys.executable, '-B', str(REPOSITORY / 'demo/ci/verify-artifacts.py'), str(artifacts)]
|
||||
result = subprocess.run(command, capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
# Outer hashes are recalculated: only the actual image-bundle comparison catches this.
|
||||
record['downstream_commit_or_parent'] = 'tampered outer metadata'
|
||||
write_record_and_sums()
|
||||
self.assertNotEqual(subprocess.run(command, capture_output=True).returncode, 0)
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -7,15 +7,28 @@ import sys
|
||||
import tarfile
|
||||
import zipfile
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from source_provenance import BASELINE_SHA256, load_definition, strict_json, verify_packaged_provenance
|
||||
|
||||
folder = Path(sys.argv[1] if len(sys.argv) > 1 else 'build/demo/artifacts').resolve()
|
||||
actual_hashes = {}
|
||||
for line in (folder / 'SHA256SUMS').read_text().splitlines():
|
||||
expected, name = line.split(' ', 1)
|
||||
assert Path(name).name == name and re.fullmatch(r'[0-9a-f]{64}', expected)
|
||||
assert Path(name).name == name and name not in actual_hashes and re.fullmatch(r'[0-9a-f]{64}', expected)
|
||||
with (folder / name).open('rb') as stream:
|
||||
assert hashlib.file_digest(stream, 'sha256').hexdigest() == expected, name
|
||||
record = json.loads((folder / 'delivery-info.json').read_text())
|
||||
actual_hashes[name] = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
assert actual_hashes[name] == expected, name
|
||||
record = strict_json((folder / 'delivery-info.json').read_bytes())
|
||||
if 'source_verification' in record:
|
||||
baseline, _, _, _ = load_definition(Path(__file__).resolve().parents[1])
|
||||
verify_packaged_provenance(record, baseline)
|
||||
else:
|
||||
print('Legacy artifact: transport/OCI verification only; no new source-change proof is claimed.')
|
||||
version = record['delivery_version']
|
||||
assert re.fullmatch(r'\d+\.\d+\.\d+', version)
|
||||
assert {'delivery-info.json', f'TikZRefinery-{version}-linux-image.tar.gz',
|
||||
f'TikZRefinery-{version}-architecture.zip'} <= set(actual_hashes)
|
||||
assert record['image_archive_sha256'] == actual_hashes[f'TikZRefinery-{version}-linux-image.tar.gz']
|
||||
with tarfile.open(folder / f'TikZRefinery-{version}-linux-image.tar.gz', 'r:gz') as archive:
|
||||
compatibility = json.load(archive.extractfile('manifest.json'))[0]
|
||||
assert record['application_image'] in compatibility['RepoTags']
|
||||
@@ -34,6 +47,25 @@ with tarfile.open(folder / f'TikZRefinery-{version}-linux-image.tar.gz', 'r:gz')
|
||||
assert members[name].isfile(), name
|
||||
with archive.extractfile(name) as stream:
|
||||
assert 'sha256:' + hashlib.file_digest(stream, 'sha256').hexdigest() == reference['digest'], name
|
||||
if 'source_verification' in record:
|
||||
# application.Dockerfile's final filesystem layer is the complete bundle COPY.
|
||||
# Check actual packaged metadata without extracting files onto the workstation.
|
||||
with tarfile.open(fileobj=archive.extractfile(blob_name(manifest['layers'][-1]['digest'])), mode='r:*') as bundle:
|
||||
def bundled_bytes(name):
|
||||
member = bundle.getmember('opt/tikzrefinery/' + name)
|
||||
assert member.isfile(), name
|
||||
return bundle.extractfile(member).read()
|
||||
assert hashlib.sha256(bundled_bytes('upstream-snapshot.json')).hexdigest() == BASELINE_SHA256
|
||||
packaged_record = strict_json(bundled_bytes('delivery-info.json'))
|
||||
assert packaged_record == {key: value for key, value in record.items()
|
||||
if key not in {'application_image', 'application_image_id', 'image_archive_sha256'}}
|
||||
proof = record['source_verification']
|
||||
if proof['source_change_record'] is not None:
|
||||
change_bytes = bundled_bytes('source-change.json')
|
||||
assert hashlib.sha256(change_bytes).hexdigest() == proof['source_change_sha256']
|
||||
assert strict_json(change_bytes) == proof['source_change_record']
|
||||
else:
|
||||
assert 'opt/tikzrefinery/source-change.json' not in bundle.getnames()
|
||||
with zipfile.ZipFile(folder / f'TikZRefinery-{version}-architecture.zip') as docs:
|
||||
assert 'html/index.html' in docs.namelist()
|
||||
print(f'PASS: version {version}, artifact checksums, OCI manifest/config/{len(manifest["layers"])} layers and architecture ZIP')
|
||||
|
||||
+10
-37
@@ -1,45 +1,18 @@
|
||||
"""Verify the exact frozen source input, independent of either Git checkout."""
|
||||
"""Verify the frozen import or a precisely recorded, issue-linked downstream tree."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from source_provenance import verify_source
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--require-tracked', action='store_true',
|
||||
help='Also verify that the Git index contains every original blob.')
|
||||
help='Also verify source blobs and provenance records against the Git index.')
|
||||
args = parser.parse_args()
|
||||
|
||||
DEMO = Path(__file__).resolve().parents[1]
|
||||
SOURCE = DEMO / 'tikzrefinery'
|
||||
manifest = json.loads((DEMO / 'snapshot.json').read_text(encoding='utf-8'))
|
||||
expected = manifest['files']
|
||||
if args.require_tracked:
|
||||
index = subprocess.check_output(
|
||||
['git', 'ls-files', '--stage', '-z', '--', 'demo/tikzrefinery'], cwd=DEMO.parent)
|
||||
tracked = {}
|
||||
for row in index.decode('utf-8').split('\0'):
|
||||
if not row:
|
||||
continue
|
||||
metadata, path = row.split('\t', 1)
|
||||
mode, blob, stage = metadata.split()
|
||||
assert stage == '0', ('Unresolved snapshot index entry', path)
|
||||
tracked[path.removeprefix('demo/tikzrefinery/')] = (mode, blob)
|
||||
assert set(tracked) == set(expected), {
|
||||
'untracked_snapshot_files': sorted(set(expected) - set(tracked)),
|
||||
'unexpected_tracked_files': sorted(set(tracked) - set(expected))}
|
||||
for name, identity in expected.items():
|
||||
assert tracked[name] == (identity['mode'], identity['git_blob']), (
|
||||
'Git index differs from the frozen upstream blob', name)
|
||||
actual = {p.relative_to(SOURCE).as_posix() for p in SOURCE.rglob('*') if p.is_file()}
|
||||
assert actual == set(expected), {'missing': sorted(set(expected) - actual),
|
||||
'extra': sorted(actual - set(expected))}
|
||||
for name, identity in expected.items():
|
||||
data = (SOURCE / name).read_bytes()
|
||||
assert hashlib.sha256(data).hexdigest() == identity['sha256'], name
|
||||
git_blob = hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest()
|
||||
assert git_blob == identity['git_blob'], name
|
||||
print(json.dumps({'result': 'passed', 'upstream_commit': manifest['upstream_commit'],
|
||||
'application_baseline': manifest['application_baseline'],
|
||||
'verified_files': len(expected),
|
||||
'git_index_verified': args.require_tracked}, indent=2))
|
||||
try:
|
||||
print(json.dumps(verify_source(Path(__file__).resolve().parents[1], args.require_tracked), indent=2))
|
||||
except (ValueError, OSError) as error:
|
||||
parser.exit(1, f'Source verification failed: {error}\n')
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"date_eastern": "2026-11-27",
|
||||
"kind": "local preparation verification; not a Jenkins run",
|
||||
"branch": "codex/demo-source-change-support",
|
||||
"reviewed_parent": "b6f7edd48bce87567432e97b5dffda7abec59523",
|
||||
"maintenance_pr": 33,
|
||||
"maintenance_merge_verified": true,
|
||||
"upstream_source": {
|
||||
"result": "passed",
|
||||
"upstream_commit": "f4e3193d49a98efcf2f16c2aa22d6085ebe70f36",
|
||||
"application_baseline": "0.1.4-alpha",
|
||||
"baseline_manifest_sha256": "a86656744d5d700aa21834fc03b0a54dfe5b5fd4e8b32ccecc40c6ae7553df2d",
|
||||
"source_state": "frozen-baseline",
|
||||
"verified_files": 435,
|
||||
"git_index_verified": true,
|
||||
"source_change_record": null,
|
||||
"source_change_sha256": null
|
||||
},
|
||||
"original_product_and_snapshot_unchanged": true,
|
||||
"provenance_tests": {
|
||||
"result": "passed",
|
||||
"tests": 11,
|
||||
"failed": 0,
|
||||
"skipped": 0,
|
||||
"coverage": [
|
||||
"complete working tree",
|
||||
"real staged Git blobs/modes and provenance",
|
||||
"missing ignored asset",
|
||||
"unlisted/missing/extra source",
|
||||
"modify/rename/add/delete",
|
||||
"pinned manifest",
|
||||
"invalid/duplicate/unsafe/colliding change entries",
|
||||
"record generator and overwrite refusal",
|
||||
"synthetic baseline/changed OCI bundle and metadata tamper rejection"
|
||||
]
|
||||
},
|
||||
"windows": {
|
||||
"result": "passed",
|
||||
"execution": "Windows command-line rehearsal; not a Jenkins run",
|
||||
"delivery_version": "1.0.4",
|
||||
"downstream_modified": true,
|
||||
"application_tests": 8,
|
||||
"failures": 0,
|
||||
"portable_smoke_seconds": 5,
|
||||
"development_toolchain_absent_from_path": true,
|
||||
"observed_bundle_modules": [
|
||||
"Qt6Core.dll",
|
||||
"libgcc_s_seh-1.dll",
|
||||
"Qt6Widgets.dll",
|
||||
"Qt6Gui.dll",
|
||||
"libstdc++-6.dll",
|
||||
"libwinpthread-1.dll",
|
||||
"tkr_rectangle.dll"
|
||||
],
|
||||
"package_sha256": "f6886d32f2b934a93d5873934bfa365cb6980cbbbfa7827aabcd217f9c5e3a28"
|
||||
},
|
||||
"legacy_artifact": {
|
||||
"result": "passed",
|
||||
"real_jenkins_build": 2,
|
||||
"delivery_version": "1.0.2",
|
||||
"scope": "transport checksums, OCI configuration/eight layers and real COPY layer metadata; no new source-change attestation",
|
||||
"original_download_unchanged": true
|
||||
},
|
||||
"syntax": {
|
||||
"python_files": 9,
|
||||
"powershell": "build-windows.ps1 parser passed"
|
||||
},
|
||||
"manual": {
|
||||
"result": "passed",
|
||||
"pages": 222,
|
||||
"toolchain": "existing shared TinyTeX",
|
||||
"sequence": "six pdflatex passes, BibTeX, glossary/acronym/index twice",
|
||||
"visually_reviewed_physical_pages": [
|
||||
5,
|
||||
6,
|
||||
23,
|
||||
215,
|
||||
216
|
||||
],
|
||||
"unresolved_references": false,
|
||||
"missing_files": false,
|
||||
"preexisting_layout_and_duplicate_destination_warnings_retained": true,
|
||||
"sha256": "b5b786dde6c3af76a20b82e7d061f4bd9d688c64028ba5e6bc80d9285092180e"
|
||||
},
|
||||
"local_slide_draft": {
|
||||
"unchanged": true,
|
||||
"version_control": "ignored",
|
||||
"sha256": "df16455fa2a458875731493991f28cee1e4bf9f2304a2224b4365d892e4d418f"
|
||||
},
|
||||
"boundaries": {
|
||||
"product_refactor_implemented": false,
|
||||
"issue_published": false,
|
||||
"commit_created": false,
|
||||
"pushed": false,
|
||||
"new_cloud_build": false,
|
||||
"linux_container_build": false,
|
||||
"reason": "Docker Desktop was not running; Linux saved-image tests used explicit synthetic fixtures and the preserved historical download."
|
||||
},
|
||||
"remaining": [
|
||||
"review/commit/push support branch and peer-reviewed merge",
|
||||
"verify support through a real Jenkins baseline run on reviewed main",
|
||||
"publish the reviewed issue with explicit group authorization",
|
||||
"prepare the separate issue-linked provider rename and assessed commit/push",
|
||||
"real reviewed changed-source build, artifact download and final classroom rehearsal"
|
||||
],
|
||||
"cleanup": {
|
||||
"files_removed": 254,
|
||||
"bytes_reclaimed": 247851654.0,
|
||||
"mib_reclaimed": 236.37,
|
||||
"removed": "Current validation compiler/package outputs, duplicate legacy extraction, render images, test scratch and group-manual intermediates",
|
||||
"retained": "Final manual PDF, local slide draft and its sources, selected and raw verification evidence, original downloaded Jenkins archive, existing baseline Windows package, shared TinyTeX/minted cache, unrelated worktrees and preservation copies"
|
||||
}
|
||||
}
|
||||
@@ -140,3 +140,9 @@ Now that the baseline passes, the separate issue-linked product
|
||||
increment can be prepared. Retain artifacts and required grading evidence; remove
|
||||
only reproducible scratch from the current task. Never prune shared images,
|
||||
volumes, runner identities or older evidence during preparation.
|
||||
|
||||
The separate [source-change support](../SOURCE_CHANGE_RUNBOOK.md) preserves the
|
||||
immutable manifest while accepting an exact issue-linked downstream tree. After
|
||||
its review/merge, verify a new baseline run before the assessed product change.
|
||||
The job stays on reviewed `main`; preparation does not authorize PR-branch builds
|
||||
or publish the draft issue.
|
||||
|
||||
@@ -1524,3 +1524,51 @@ affected pages. Reproducible current-task render/compiler scratch is removed;
|
||||
protected outputs, evidence and unrelated work remain. No public port, firewall,
|
||||
credential, permission, pricing release selector, cloud plan or original frozen
|
||||
product source changed. Codex does not commit, push or publish project messages.
|
||||
|
||||
\section{Demo Source-Change Provenance Preparation}
|
||||
Date: November 27, 2026 Eastern; Tool: OpenAI Codex; Human: Vincent Sun.
|
||||
Vincent reported that Billy approved the maintenance PR and that its merge was
|
||||
created. Codex fetched and verified PR~33's merge at \texttt{b6f7edd}, then
|
||||
created the separate preparation branch
|
||||
\path{codex/demo-source-change-support}. Existing worktrees and unrelated work
|
||||
are preserved. The local presentation under \path{build/presentation/} is not
|
||||
regenerated; its recorded SHA-256 is checked before and after preparation.
|
||||
|
||||
The original 435-file import and its manifest remain unchanged. The verifier
|
||||
pins the original manifest hash and accepts either the frozen baseline or an
|
||||
explicit downstream change record with a project issue URL, exact file identities
|
||||
and the original upstream commit. It verifies the complete derived tree and,
|
||||
when requested, the Git index including the manifest and change record. Unlisted
|
||||
edits, missing assets, unsafe or colliding paths, duplicate records and altered
|
||||
baseline metadata are rejected. A URL's syntax does not prove that an issue
|
||||
exists or that its proposed change was reviewed. The existing reviewed-main
|
||||
selection and ancestry check remain separate Jenkins controls.
|
||||
|
||||
Packaging records baseline versus changed-source state and carries the validated
|
||||
record into delivery provenance. New Linux artifact checks compare that metadata
|
||||
with the bundle inside the saved image as well as the source inventory and OCI
|
||||
digests. Legacy artifacts keep explicitly labelled transport checks; no new
|
||||
attestation is retroactively assigned. Windows packaging includes the same source
|
||||
identity while retaining its truthful command-line rehearsal label. Regression
|
||||
tests use one disposable local Git fixture; synthetic issue/image values in those
|
||||
tests are not published project facts. A fresh Windows Release build passes all
|
||||
eight application suites and produces the updated package metadata.
|
||||
|
||||
Codex prepares the source-change runbook, generator, PR description and an
|
||||
unpublished issue draft for the coordinated provider-class rename. The actual
|
||||
product refactor and its assessed commit/push remain separate. The original
|
||||
source, canonical upstream PDFs, historical evidence, pricing environments and
|
||||
live services are unchanged. Docker Desktop is not running during this local
|
||||
preparation; no new cloud pipeline execution is claimed. After this support
|
||||
change is reviewed and merged, a real Jenkins run from main remains required,
|
||||
followed by the actual issue-linked increment and final rehearsal.
|
||||
|
||||
Selected local checks and limitations are recorded in:
|
||||
\begin{quote}\small
|
||||
\path{demo/evidence/source-change-support-20261127.json}
|
||||
\end{quote}
|
||||
Codex rebuilds the full
|
||||
group manual with the existing TinyTeX and visually checks affected pages.
|
||||
Only reproducible current-task scratch is removed; protected deliverables and
|
||||
required evidence remain. No commit, push, peer approval, issue publication or
|
||||
production deployment is performed by Codex in this preparation.
|
||||
|
||||
@@ -12,6 +12,7 @@ link each entry to the changed chapter, table, figure, or controlled artifact.
|
||||
\multicolumn{4}{l}{\small\itshape Document Update History (continued)}\\
|
||||
\toprule \textbf{Date / Version} & \textbf{Author Initials} & \textbf{Change} & \textbf{Changed At}\\ \midrule
|
||||
\endhead \bottomrule \endlastfoot
|
||||
November 27, 2026 / 6.4 demo provenance & VS, CDX & Verified maintenance PR~33's merge and prepared a separate source-change gate and package provenance for the assessed demo increment. Preserved the original 435-file snapshot, product source and local slide draft. Added regression checks, a record generator, an unpublished issue draft and review runbook; a fresh Windows build passed eight application suites. Reviewed-main Jenkins verification and the actual provider refactor remain pending. & \hyperref[Chapter:AIPromptLog]{AI log}\\
|
||||
November 26, 2026 / 6.4 host maintenance & VS, CDX & At Vincent's request, applied 20 host upgrades, rebooted into kernel 6.8.0-151 and repaired delivery-agent orphan reaping. Activated two compatible Jenkins sandbox security fixes and regenerated the workflow lock; themes are unchanged. Build~3 passed all eight tests and packaged 1.0.3; zero zombies remained. Cleared only 89.6\,MiB of APT cache, preserving evidence and recovery data. Updated current Hosts and maintenance records; Password hints are unchanged. & \hyperref[Chapter:HostsPasswords]{Hosts}, \hyperref[Chapter:AIPromptLog]{AI log}\\
|
||||
November 26, 2026 / 6.4 core and baseline proof & VS, CDX & After reviewed repair PR~32 merged, patched Jenkins core to 2.580.2 with fixed Java retained and a private stopped-home backup. Verified preserved settings and real build~2 on reviewed main: eight passing tests, both report editions, 25 source graphs and version 1.0.2. Downloaded the authenticated archive, resolved FDM's unsupported resume by restarting, and verified checksums and image layers locally. Updated current Hosts, recovery and demo runbooks; the issue-linked increment remains pending. & \hyperref[Chapter:HostsPasswords]{Hosts}, \hyperref[Chapter:AIPromptLog]{AI log}\\
|
||||
November 26, 2026 / 6.4 teammate tooling guide & VS, CDX & Prepared a standalone Windows TinyTeX setup guide for Billy and Claude. Covered existing-tool discovery, protected installation, explicit tool selection, project packages, current minted helpers, complete manual builds and troubleshooting. Checked official installer behavior and PowerShell syntax; no new compiler was installed on Vincent's computer. & \hyperref[Chapter:AIPromptLog]{AI log}\\
|
||||
|
||||
Reference in New Issue
Block a user