Skip to content

Commit 5a8d659

Browse files
authored
Merge pull request #40 from lann/webcrypto-port-completion
ports/webcrypto: complete the polymorph:webcrypto@0.1.0 surface (#3)
2 parents 5af8c0f + 813d128 commit 5a8d659

23 files changed

Lines changed: 3245 additions & 172 deletions

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,5 @@ dist/
99
# trunk / Deno canary binaries.
1010
.shell-cache/
1111
*.tmp
12+
# ports/webcrypto conformance runner output (conformance/run.ts)
13+
ports/webcrypto/conformance/results-*.jsonl

‎ports/webcrypto/conformance/run.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
// The flagship gate: execute the consumer's REAL conformance suites
2+
// (`polymorph-webcrypto/conformance/guest-ct` and its signing sibling)
3+
// under deltic, with this port supplying every `polymorph:webcrypto/*`
4+
// interface and `wasi-shims` supplying WASI.
5+
//
6+
// deno task conformance [--only SUBSTRING] [--suite shared|signing] [--jspi]
7+
//
8+
// Shape follows ports/websocket/conformance/run.ts and
9+
// tools/smoke-tls/run.ts. Two suites, two envelope targets:
10+
//
11+
// suite | wasm | target key | missing
12+
// ---------+-----------------------------------+-----------------+----------------
13+
// shared | conformance_guest_ct | deltic | ["sha1-checked"]
14+
// signing | conformance_signing_guest_ct | deltic-signing | (see below)
15+
//
16+
// `missing` is the feature-tag scheduling list (ct-runner's `missing`,
17+
// upstream harness.mjs's): the features THIS target lacks, so cases gated
18+
// on them are scheduled out as `not-applicable` instead of failing.
19+
// `sha1-checked` is the one standing entry — no platform-backed provider
20+
// can serve it (src/sha1Checked.ts) — and the suite's `!sha1-checked`
21+
// decline case still runs, asserting the refusal works.
22+
//
23+
// NOTHING here writes into the consumer tree: it only reads the prebuilt
24+
// suite artifacts, and results are written under this directory.
25+
26+
import { Translator } from "../../../runtime/src/shim/mod.ts";
27+
import type { ComponentArtifacts } from "../../../runtime/src/embedder/mod.ts";
28+
import { runSuite } from "../../../ct-runner/src/mod.ts";
29+
import { wasiShims } from "../../../wasi-shims/src/mod.ts";
30+
import { setRsaPrivateKeyPolicy, webcryptoImports } from "../src/mod.ts";
31+
32+
const CE_ROOT = new URL("../../../", import.meta.url).pathname;
33+
const CONSUMER = "/home/lmartin/p/polymorph/polymorph-webcrypto";
34+
const SUITE_DIR = `${CONSUMER}/target/wasm32-wasip2/release`;
35+
36+
/** harness.mjs:33's per-case wall bound. */
37+
const CASE_TIMEOUT_MS = 60_000;
38+
39+
interface SuiteSpec {
40+
/** The lock identity: the wasm file stem (ct-runner normalizes `-` to `_`). */
41+
name: string;
42+
wasm: string;
43+
target: string;
44+
missing: string[];
45+
}
46+
47+
const SUITES: Readonly<Record<string, SuiteSpec>> = {
48+
shared: {
49+
name: "conformance-guest-ct",
50+
wasm: `${SUITE_DIR}/conformance_guest_ct.wasm`,
51+
target: "deltic",
52+
// No platform WebCrypto carries sha1dc; the port declines the
53+
// interface fail-closed (src/sha1Checked.ts).
54+
missing: ["sha1-checked"],
55+
},
56+
signing: {
57+
name: "conformance-signing-guest-ct",
58+
wasm: `${SUITE_DIR}/conformance_signing_guest_ct.wasm`,
59+
target: "deltic-signing",
60+
// Deno's `crypto.subtle` serves the gated RSA private-key mints, so
61+
// this port serves them too (see src/rsaSignature.ts's posture note):
62+
// nothing is declared missing here.
63+
missing: [],
64+
},
65+
};
66+
67+
interface Cli {
68+
/**
69+
* `--rsa-private decline`: take the reference's BROWSER posture — the
70+
* gated RSA private-key interfaces (`rsa-pss-sign`,
71+
* `rsassa-pkcs1-v15-sign`, `rsa-oaep-decrypt`) refuse with
72+
* `error.unsupported` — and declare the two matching features missing,
73+
* so the suite schedules their cases out and runs the `!rsa-sign` /
74+
* `!rsa-oaep-decrypt` decline cases instead. Default is `serve`
75+
* (src/rsaSignature.ts's posture note).
76+
*/
77+
rsaPrivate: "serve" | "decline";
78+
only?: string;
79+
jspi: boolean;
80+
out?: string;
81+
suites: string[];
82+
missing?: string[];
83+
}
84+
85+
function parseArgs(argv: string[]): Cli {
86+
const cli: Cli = { jspi: false, suites: [], rsaPrivate: "serve" };
87+
for (let i = 0; i < argv.length; i++) {
88+
switch (argv[i]) {
89+
case "--only":
90+
cli.only = argv[++i];
91+
break;
92+
case "--jspi":
93+
cli.jspi = true;
94+
break;
95+
case "--out":
96+
cli.out = argv[++i];
97+
break;
98+
case "--suite":
99+
cli.suites.push(argv[++i]);
100+
break;
101+
case "--rsa-private": {
102+
const value = argv[++i];
103+
if (value !== "serve" && value !== "decline") {
104+
throw new Error(`--rsa-private takes "serve" or "decline", got ${value}`);
105+
}
106+
cli.rsaPrivate = value;
107+
break;
108+
}
109+
case "--missing":
110+
cli.missing = argv[++i].split(",").filter((s) => s.length > 0);
111+
break;
112+
default:
113+
throw new Error(`unknown argument ${argv[i]}`);
114+
}
115+
}
116+
if (cli.suites.length === 0) cli.suites = ["shared", "signing"];
117+
for (const s of cli.suites) {
118+
if (!(s in SUITES)) throw new Error(`unknown suite '${s}' (known: ${Object.keys(SUITES).join(", ")})`);
119+
}
120+
return cli;
121+
}
122+
123+
async function loadArtifacts(wasm: string): Promise<ComponentArtifacts> {
124+
const shim = `${CE_ROOT}target/wasm32-unknown-unknown/release/translator_shim.wasm`;
125+
const translator = await Translator.create(await Deno.readFile(shim));
126+
const componentBytes = await Deno.readFile(wasm);
127+
const { plan, adapters } = translator.translate(componentBytes);
128+
return { plan, componentBytes, adapters };
129+
}
130+
131+
async function runOne(spec: SuiteSpec, cli: Cli): Promise<number> {
132+
const artifacts = await loadArtifacts(spec.wasm);
133+
const imports = { ...wasiShims({ cli: { env: {}, passthrough: false } }), ...webcryptoImports() };
134+
const out = cli.out ?? new URL(`./results-${spec.target}.jsonl`, import.meta.url).pathname;
135+
const lines: string[] = [];
136+
const started = performance.now();
137+
const counts = await runSuite(artifacts, {
138+
imports,
139+
target: spec.target,
140+
suiteName: spec.name,
141+
only: cli.only,
142+
missing: cli.missing ??
143+
(cli.rsaPrivate === "decline"
144+
? [...spec.missing, "rsa-sign", "rsa-oaep-decrypt"]
145+
: spec.missing),
146+
caseTimeoutMs: CASE_TIMEOUT_MS,
147+
jspi: cli.jspi,
148+
emit: (line) => lines.push(line),
149+
log: (msg) => console.error(msg),
150+
});
151+
await Deno.writeTextFile(out, lines.join("\n") + "\n");
152+
console.error(
153+
`\n[${spec.target}] ${counts.passed} passed | ${counts.failed} failed | ${counts.skipped} skipped | ` +
154+
`${counts.na} n/a (${counts.total} total) in ${((performance.now() - started) / 1000).toFixed(1)}s -> ${out}`,
155+
);
156+
return counts.failed;
157+
}
158+
159+
async function main() {
160+
const cli = parseArgs(Deno.args);
161+
setRsaPrivateKeyPolicy(cli.rsaPrivate);
162+
let failed = 0;
163+
for (const key of cli.suites) failed += await runOne(SUITES[key], cli);
164+
if (failed > 0) Deno.exitCode = 1;
165+
}
166+
167+
if (import.meta.main) await main();

‎ports/webcrypto/deno.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
},
88
"tasks": {
99
"test": "deno test --allow-read tests/",
10-
"check": "deno check src tests"
10+
"check": "deno check src tests conformance",
11+
"conformance": "deno run --allow-read --allow-write --allow-env conformance/run.ts"
1112
}
1213
}

‎ports/webcrypto/src/aead.ts‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
// table, not a Deno `crypto.subtle` gap: Deno serves AES-CBC/CTR too).
66

77
import { decryptFailure, errInvalidKey, errInvalidNonce, errNotExtractable, errNotPermitted, errOther, errUnsupported, notPermitted, platformCall } from "./errors.ts";
8+
import { importPlatformKeyJwk, jwkKeyBytes, jwkMaterial, requireStrictBase64url } from "./platform.ts";
89
import { asBufferSource, collectByteStream, unwrappedJwk } from "./util.ts";
910
import { deriveKeyFrom, type DeriveInput } from "./derivation.ts";
1011
import {
@@ -242,9 +243,22 @@ export const aesGcm = {
242243
const bits = aesBits(variant);
243244
const policy = optionsOf(options);
244245
const usages = platformUsages(policy);
245-
const key = await platformCall("AES-GCM import jwk", () =>
246-
subtle.importKey("jwk", JSON.parse(jwk), { name: "AES-GCM", length: bits }, policy.extractable, usages));
247-
return new AeadKey(key as CryptoKey, bits, policy);
246+
// `jwkMaterial` strips the consumer-policy members and every platform
247+
// refusal becomes `invalid-key` (reference: js/jco/webcrypto.js:2570).
248+
const material = jwkMaterial(jwk);
249+
requireStrictBase64url(material.k);
250+
const key = await importPlatformKeyJwk(
251+
`${variant} JWK`,
252+
material,
253+
{ name: "AES-GCM", length: bits },
254+
policy.extractable,
255+
usages,
256+
);
257+
const gotBits = jwkKeyBytes(material.k) * 8;
258+
if (gotBits !== bits) {
259+
errInvalidKey(`JWK carries a ${gotBits}-bit key; ${variant} requires ${bits}`);
260+
}
261+
return new AeadKey(key, bits, policy);
248262
},
249263
generateKey: async (variant: string, options: AeadKeyOptions): Promise<AeadKey> => {
250264
const bits = aesBits(variant);

0 commit comments

Comments
 (0)