Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/maple-research/frontend/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
}
],
"security": {
"csp": "default-src 'self'; connect-src 'self' https://opensecret.cloud https://*.opensecret.cloud https://trymaple.ai https://*.trymaple.ai https://secretgpt.ai https://*.secretgpt.ai https://*.maple-ca8.pages.dev https://raw.githubusercontent.com localhost:* http://localhost:* http://0.0.0.0:* http://127.0.0.1:*; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; worker-src 'self' blob:; media-src 'self' blob: mediastream:"
"csp": "default-src 'self'; connect-src 'self' https://opensecret.cloud https://*.opensecret.cloud https://trymaple.ai https://*.trymaple.ai https://secretgpt.ai https://*.secretgpt.ai https://*.maple-ca8.pages.dev https://raw.githubusercontent.com https://attestations-dev.maple.ai https://attestations.maple.ai localhost:* http://localhost:* http://0.0.0.0:* http://127.0.0.1:*; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; worker-src 'self' blob:; media-src 'self' blob: mediastream:"
}
},
"bundle": {
Expand Down
7 changes: 6 additions & 1 deletion scripts/ci/build-sdk-publish.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ import subprocess
import sys

root, stage = map(Path, sys.argv[1:])
tracked = subprocess.check_output(["git", "-C", str(root), "ls-files", "-z", "sdk"])
# The SDK's tests compare its embedded trust inputs with these reviewed copies.
trust_anchors = ["scripts/ci/opensecret-release/dev-signing-key.pem",
"scripts/ci/opensecret-release/trusted_root.json"]
tracked = subprocess.check_output(["git", "-C", str(root), "ls-files", "-z", "sdk", *trust_anchors])
for raw in tracked.split(b"\0"):
if not raw:
continue
Expand Down Expand Up @@ -85,6 +88,8 @@ nix develop --no-update-lock-file ./sdk -c bash -euo pipefail -c '
bun --no-env-file pm pack --ignore-scripts --filename "${build_dir}/package.tgz"
python3 -I "${repo_root}/scripts/ci/check-sdk-package-consumers.py" \
"${build_dir}/sdk" "${build_dir}/package.tgz"
python3 -I "${repo_root}/scripts/ci/check-sdk-packed-release-evidence.py" \
"${build_dir}/sdk" "${build_dir}/package.tgz"
cp "${build_dir}/package.tgz" "${output_dir}/package.tgz"
;;
rust)
Expand Down
114 changes: 114 additions & 0 deletions scripts/ci/check-sdk-packed-release-evidence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Check that the packed SDK ships its release bundles exactly as published.

Each bundle under sdk/src/lib/releaseEvidence/published/ has its SHA-256 in a
.sha256 file beside it. This check confirms each file still matches its pin,
then finds the bundle's text in the packed ESM build and in the packed UMD
build and requires the same hash there, so the package verifies the published
bytes rather than a reformatted copy. It also confirms that no WebAssembly
ships. check-sdk-package-consumers.py loads both builds; tests in the SDK
verify the published bytes.

Usage: check-sdk-packed-release-evidence.py <sdk-dir> <package.tgz>
"""

from __future__ import annotations

import ast
import hashlib
from pathlib import Path
import re
import sys
import tarfile

PUBLISHED = Path("src/lib/releaseEvidence/published")
UMD_BUILD = "package/dist/maple-sdk.umd.cjs"
ESM_BUILD = re.compile(r"package/dist/[^/]+\.js")
# A JavaScript string literal that starts a Sigstore bundle. The bundler
# emits the bundle text as one quoted literal; within it, a quote of the same
# kind only appears escaped.
BUNDLE_LITERAL = re.compile(r"""(['"])\{(?:(?!\1)[^\\\n]|\\.)*\1""")
BUNDLE_START = '{"mediaType":"application/vnd.dev.sigstore.bundle'


def sha256_hex(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()


def pinned_hashes(sdk_dir: Path) -> dict[str, str]:
"""The pinned hash of each published bundle, after checking the file."""
pins = {}
for bundle in sorted((sdk_dir / PUBLISHED).glob("*.sigstore.json")):
pin_file = bundle.with_name(bundle.name + ".sha256")
pinned = pin_file.read_text().split()[0]
actual = sha256_hex(bundle.read_bytes())
matches_pin = actual == pinned
if not matches_pin:
raise SystemExit(f"{bundle.name} does not match its pinned SHA-256")
pins[bundle.name] = pinned
if not pins:
raise SystemExit("No published release bundles found")
return pins


def embedded_bundle_hashes(source: str) -> set[str]:
"""Hashes of the bundle texts embedded as string literals in one build."""
hashes = set()
for match in BUNDLE_LITERAL.finditer(source):
literal = match.group(0)
names_bundle_media_type = "sigstore.bundle" in literal
if not names_bundle_media_type:
continue
# Python reads the escapes these literals use (\\, \', \", \n, \u)
# the same way JavaScript does; literal_eval runs no code.
text = ast.literal_eval(literal)
is_bundle = text.startswith(BUNDLE_START)
if is_bundle:
hashes.add(sha256_hex(text.encode("utf-8")))
return hashes


def read_builds(tarball: Path) -> tuple[str, str]:
"""The UMD build, and every ESM file joined, as text."""
umd = ""
esm_parts = []
with tarfile.open(tarball) as archive:
for member in archive.getmembers():
ships_wasm = member.name.endswith(".wasm")
if ships_wasm:
raise SystemExit(f"The package ships WebAssembly: {member.name}")
is_umd = member.name == UMD_BUILD
is_esm = ESM_BUILD.fullmatch(member.name) is not None
if not (is_umd or is_esm):
continue
text = archive.extractfile(member).read().decode("utf-8")
if is_umd:
umd = text
else:
esm_parts.append(text)
return umd, "\n".join(esm_parts)


def main() -> None:
expected_arguments = 3
arguments_missing = len(sys.argv) != expected_arguments
if arguments_missing:
raise SystemExit("usage: check-sdk-packed-release-evidence.py <sdk-dir> <package.tgz>")
sdk_dir = Path(sys.argv[1]).resolve()
tarball = Path(sys.argv[2]).resolve()
pins = pinned_hashes(sdk_dir)
umd, esm = read_builds(tarball)
for build_name, source in (("ESM", esm), ("UMD", umd)):
uses_webassembly = "WebAssembly" in source
if uses_webassembly:
raise SystemExit(f"The {build_name} build references WebAssembly")
embedded = embedded_bundle_hashes(source)
for bundle_name, pinned in pins.items():
shipped = pinned in embedded
if not shipped:
raise SystemExit(f"The {build_name} build does not carry {bundle_name} as published")
print(f"Packed release evidence passed: {len(pins)} published bundle(s) in ESM and UMD, no WebAssembly.")


if __name__ == "__main__":
main()
13 changes: 9 additions & 4 deletions scripts/ci/lanes.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def cache_store(label: str) -> str:
# What Research builds from the in-tree TypeScript SDK.
SDK_TS_BUILD = ("sdk/src/**", "!sdk/src/lib/test/**", "sdk/package.json", "sdk/bun.lock",
"sdk/bunfig.toml", "sdk/tsconfig*.json", "sdk/vite.config.ts", "sdk/.npmrc")
SDK_TS = ("sdk/src/**", "sdk/package.json", "sdk/bun.lock", "sdk/bunfig.toml",
SDK_TS = ("sdk/src/**", "sdk/test/fixtures/**", "sdk/package.json", "sdk/bun.lock", "sdk/bunfig.toml",
"sdk/tsconfig*.json", "sdk/vite.config.ts", "sdk/.npmrc", "sdk/flake.*")

AGENT = ("apps/maple-agent/**",)
Expand Down Expand Up @@ -317,9 +317,14 @@ def deny(manifest: str, component: str) -> str:
), runner=GITHUB, run="nix flake check --no-update-lock-file --print-build-logs", timeout=15, hook="repo"),

# The SDKs, proxy and container. build-sdk-publish.sh is the publishers' own builder.
Lane("sdk-ts", SDK_TS + ("sdk/.prettierrc.json", "sdk/eslint.config.js", "sdk/justfile", "sdk/.env.example",
"sdk/LICENSE.md", "scripts/ci/build-sdk-publish.sh",
"scripts/ci/check-sdk-package-consumers.py"),
# The SDK's tests compare its embedded release-approval trust inputs with the
# reviewed copies under opensecret-release/, so a change to either selects it.
Lane("sdk-ts", SDK_TS + ("sdk/.prettierrc.json", "sdk/.prettierignore", "sdk/eslint.config.js", "sdk/justfile",
"sdk/.env.example", "sdk/LICENSE.md", "scripts/ci/build-sdk-publish.sh",
"scripts/ci/check-sdk-package-consumers.py",
"scripts/ci/check-sdk-packed-release-evidence.py",
"scripts/ci/opensecret-release/dev-signing-key.pem",
"scripts/ci/opensecret-release/trusted_root.json"),
runner=GITHUB, run='./scripts/ci/build-sdk-publish.sh npm "$(mktemp -d)"', hook="sdk_ts"),
Lane("sdk-rust", ("sdk/rust/**", "sdk/rust-toolchain.toml", "sdk/flake.*", "scripts/ci/build-sdk-publish.sh",
"scripts/ci/sdk_crates_upload.py"),
Expand Down
9 changes: 9 additions & 0 deletions scripts/ci/test_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,14 @@ def test_typescript_sdk_selects_research_because_it_links_the_sdk(self):
# SDK tests are not Research build inputs.
self.assertNotIn("research-web", selected(["sdk/src/lib/test/ai.test.ts"], PR))

def test_reviewed_release_trust_inputs_select_the_typescript_sdk(self):
# The SDK lane compares its embedded copies with these reviewed files.
for path in ("scripts/ci/opensecret-release/dev-signing-key.pem",
"scripts/ci/opensecret-release/trusted_root.json"):
for event in (PR, PUSH):
with self.subTest(path=path, event=event):
self.assertIn("sdk-ts", selected([path], event))

def test_release_metadata_and_publisher_inputs_select_the_repo_lane(self):
for path in ("apps/maple-research/frontend/package.json", "apps/maple-research/frontend/src-tauri/Cargo.toml",
"apps/maple-research/frontend/src-tauri/tauri.conf.json", "proxy/justfile", ".github/CODEOWNERS",
Expand Down Expand Up @@ -581,6 +589,7 @@ def test_the_opensecret_selector_routes_each_lane(self):
(backend + "pcrDev.json", {"os-pcr"}, {"os-pcr"}),
(backend + "docs/nitro-deploy.md", set(), set()),
("sdk/test/integration/bootstrap.sql", {"os-sdk-e2e"}, {"os-sdk-e2e"}),
("sdk/test/fixtures/managed-key/manifest.json", {"sdk-ts", "os-sdk-e2e"}, {"sdk-ts", "os-sdk-e2e"}),
("scripts/ci/build_opensecret_eif.sh", {"os-eif", "repo"}, {"repo"}),
(".gitmodules", OPENSECRET_ALL, OPENSECRET_ALL - {"os-eif"}),
(backend + "Cargo.lock", OPENSECRET_ALL | {"deps-opensecret"}, OPENSECRET_ALL - {"os-eif"} | {
Expand Down
1 change: 1 addition & 0 deletions sdk/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
src/lib/releaseEvidence/published/
12 changes: 12 additions & 0 deletions sdk/bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
"fast-uri": "3.1.9"
},
"dependencies": {
"@freedomofpress/crypto-browser": "0.3.0",
"@freedomofpress/sigstore-browser": "git+https://github.com/MaplePrivacyLabs/sigstore-browser.git#b2b056000dec3e70f4fe5fd00f8ec2ae44758308",
"@peculiar/x509": "1.14.3",
"@stablelib/base64": "2.0.1",
"@stablelib/chacha20poly1305": "2.0.1",
Expand Down
6 changes: 6 additions & 0 deletions sdk/src/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,9 @@ declare module "*.der" {
const content: Uint8Array;
export default content;
}

// Vite and Bun both import a file's exact text with the ?raw suffix.
declare module "*?raw" {
const text: string;
export default text;
}
30 changes: 30 additions & 0 deletions sdk/src/lib/releaseEvidence/approvalKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { PcrEnvironment } from "../pcr";

/*
* Maple's release-approval public keys, one per environment, shipped with the
* SDK. These are the only keys that can approve a release; nothing fetched
* from the network, carried in a bundle or listed in a snapshot can add or
* replace one.
*
* The Dev key is the signing pipeline's reviewed key; a test compares it with
* scripts/ci/opensecret-release/dev-signing-key.pem. Production has no key
* yet, so Production verification fails as "approval-key-not-configured" and
* never falls back to the Dev key.
*/

const DEV_APPROVAL_KEY_PEM = `-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE2IpJwjrA1Uuk4p8F3B48EFZ16K1vwRrj
s3YrvgrucBNiHrSxDFyg0aVSHeuWlRXamXRW9UWxol/c6m/cu1St8sjBm1nUvSK0
Bh96GUQzovL4yGvEYriCf3BY0m2+GtZv
-----END PUBLIC KEY-----
`;

/** The environment's approval key as SPKI PEM, or undefined when it has none. */
export function approvalKeyPem(environment: PcrEnvironment): string | undefined {
switch (environment) {
case "development":
return DEV_APPROVAL_KEY_PEM;
case "production":
return undefined;
}
}
42 changes: 42 additions & 0 deletions sdk/src/lib/releaseEvidence/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { ReleaseEvidenceResult } from "./types";

/*
* Verified approvals held in memory, keyed by environment and PCR tuple. Only
* passes are stored; a 404, a timeout or a failed verification is never
* cached, so a later session always tries again.
*/

// A client meets one release per environment between updates, plus the
// occasional rollback; 32 leaves ample room while keeping the map small in a
// long-lived process.
const MAX_ENTRIES = 32;

const cache = new Map<string, ReleaseEvidenceResult>();

export function cacheKey(environment: string, pcr0: string, pcr1: string, pcr2: string): string {
return `${environment}:${pcr0}:${pcr1}:${pcr2}`;
}

export function getCachedPass(key: string): ReleaseEvidenceResult | undefined {
return cache.get(key);
}

export function storePass(key: string, result: ReleaseEvidenceResult): void {
const isPass = result.outcome === "pass";
if (!isPass) {
return;
}
cache.set(key, result);
// A Map iterates in insertion order, so the first key is the oldest. Each
// call adds at most one entry, so at most one has to go.
const overCapacity = cache.size > MAX_ENTRIES;
if (overCapacity) {
const oldest = cache.keys().next().value as string;
cache.delete(oldest);
}
}

/** Test hook: drop all cached passes. */
export function clearVerificationCache(): void {
cache.clear();
}
62 changes: 62 additions & 0 deletions sdk/src/lib/releaseEvidence/duplicateJsonKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* JSON.parse keeps the last of two members that share a name, so a document
* that names one member twice can be read differently by different parsers.
* Release evidence with a repeated member name is rejected before anything
* in it is trusted.
*
* JSON.parse checks the grammar first. Once it has accepted the text, every
* string and every structural character sits where the grammar puts it, so
* one pass over string and bracket tokens with a stack sees every member name
* in the object it belongs to. Nothing here parses JSON by hand.
*/

// One string token, escapes included, or one structural character.
const TOKEN = /"(?:[^"\\]|\\.)*"|[{}[\]:]/g;

/**
* Whether any object in the text names the same member twice. Escaped
* spellings of one name count as the same name, as they do for JSON.parse.
* Throws a SyntaxError when the text is not JSON.
*/
export function hasDuplicateJsonMember(text: string): boolean {
JSON.parse(text);
const tokens = text.match(TOKEN) ?? [];
// One entry per open container: the member names seen so far in an object,
// or undefined for an array.
const openContainers: (Set<string> | undefined)[] = [];
for (let index = 0; index < tokens.length; index += 1) {
const token = tokens[index];
const opensObject = token === "{";
if (opensObject) {
openContainers.push(new Set());
continue;
}
const opensArray = token === "[";
if (opensArray) {
openContainers.push(undefined);
continue;
}
const closesContainer = token === "}" || token === "]";
if (closesContainer) {
openContainers.pop();
continue;
}
// In JSON, only a member name is followed by a colon.
const isString = token.startsWith('"');
const followedByColon = tokens[index + 1] === ":";
const isMemberName = isString && followedByColon;
if (!isMemberName) {
continue;
}
// A member name only occurs inside an object, so the innermost open
// container is that object's set of names.
const namesInObject = openContainers[openContainers.length - 1] as Set<string>;
const name = JSON.parse(token) as string;
const repeated = namesInObject.has(name);
if (repeated) {
return true;
}
namesInObject.add(name);
}
return false;
}
Loading
Loading