Verify DRM Playback Without Leaking Keys or Tokens
A green DRM test can leave the content key in its log, HAR and trace, in base64url where a hex grep never finds it. Test four licence cases with ClearKey and ffmpeg-encrypted media, redact inside the logger, scan every artifact in every encoding, and know what only a real CDM can prove.

A DRM test goes green. The licence request returned 200, the key status went to usable and the video played for twelve seconds. The artifacts from that run hold the content key three times in the application log, three times in the HAR file and 13 more times inside the Playwright trace. A grep for the key the job generated, a 32-character hex string, matches no file at all. ClearKey licences carry keys as base64url; that form matches 12 files across the run's five cases, and still misses the trace, whose zip entries are compressed.
Part 5 of the streaming and CTV quality series opens one row of the contract table from part 1: entitlement, observed through the licence response and the EME key statuses. Part 3 timed the licence request as one startup milestone. Here the content of that request is the subject: which cases a licence test must cover, and how to keep the secrets they need out of everything the CI job keeps.
LAB-FAKE-, and no key value appears here.Four licence outcomes with four right answers
A test that asserts only "playback started" passes the first row and cannot tell the other three apart.
| Case | Licence server says | Player should | Viewer should see |
|---|---|---|---|
| Entitled | 200 with the key, then 200 on each renewal | Install the key, play, renew before the licence lapses | Uninterrupted video |
| Not entitled | 403 not_entitled | Stop after one attempt | A message naming the fix, such as an upgrade |
| Licence service down | 503, or no response | Retry with backoff while the installed key still plays, up to the licence's lapse time | Nothing, if the outage ends in time |
| Entitlement ended | 401 entitlement_expired on renewal | Close the key session | Playback stops with a rent-again prompt |
The retry rule is where the rows split. A 403 is still a 403 on the fifth attempt, and each retry delays the message the viewer is waiting for. A 503 during renewal is the opposite: the installed key stays valid for a while, so the right reaction is one the viewer never notices. Fix the mapping from server reason to error code, message and action first, and assert the mapping, not the status code.
Encrypt synthetic media with keys made for one run
In a scratch directory, pin Playwright, generate throwaway secrets, and encrypt a 40-second testsrc2 clip:
npm init -y
npm i [email protected]
openssl rand -hex 16 > key.hex # content key, this run only
openssl rand -hex 16 > kid.hex # key ID
openssl rand -hex 32 > signing.hex # signs the lab's entitlement tokens
mkdir -p media
ffmpeg -hide_banner -loglevel error -y \
-f lavfi -i testsrc2=size=640x360:rate=30:duration=40 \
-c:v libx264 -profile:v main -preset veryfast -g 60 -keyint_min 60 -sc_threshold 0 -b:v 600k \
-movflags frag_keyframe+empty_moov+default_base_moof \
-encryption_scheme cenc-aes-ctr -encryption_key "$(cat key.hex)" -encryption_kid "$(cat kid.hex)" \
media/video.mp4
The mp4 muxer's encryption_scheme accepts none or cenc-aes-ctr, with key and key ID in hex; the movflags make a fragmented file MSE can take. To prove the output is encrypted, decode it twice: without the key, ffmpeg printed 4,278 lines of decoder errors; with the mov demuxer's -decryption_key, none:
ffmpeg -hide_banner -v error -i media/video.mp4 -f null - 2>&1 | wc -l
ffmpeg -hide_banner -v error -decryption_key "$(cat key.hex)" -i media/video.mp4 -f null - 2>&1 | wc -l
4278
0
A byte search of the file found:
pssh boxes: 0, KID bytes: 1, key bytes: 0
The key ID sits in the file in the clear, for anyone who downloads the media: an identifier, not a secret. With no pssh box, Chromium fired no encrypted event in any run, so the page builds its own initialisation data in the keyids format, a kids array of base64url key IDs.
A licence endpoint behind an entitlement token
The lab server serves the page and media, hands the page its session, and answers POST /licence. The token is an HMAC-signed claim set: viewer, entitled titles, expiry. Every refusal carries a machine-readable reason, because a status code alone cannot choose a message.
// Local origin for the lab: the page, the encrypted media, and a ClearKey
// licence endpoint behind an entitlement token. Every log line goes through
// the same redact() the page uses.
import { createServer } from "node:http";
import { readFile, appendFile } from "node:fs/promises";
import { createHmac, timingSafeEqual } from "node:crypto";
import { redact } from "./redact.mjs";
const b64url = (buf) => Buffer.from(buf).toString("base64url");
const TYPES = { ".html": "text/html", ".mjs": "text/javascript", ".mp4": "video/mp4" };
const FILES = { "/": "player.html", "/redact.mjs": "redact.mjs", "/media/video.mp4": "media/video.mp4" };
export function lab({ keyHex, kidHex, signingKey, logFile, naive = false, title = "title-42" }) {
const KEYS = { [b64url(Buffer.from(kidHex, "hex"))]: b64url(Buffer.from(keyHex, "hex")) };
const state = { down: false, ttlMs: 10_000, session: null };
const log = (entry) => {
const e = { t: Date.now(), ...entry };
return appendFile(logFile, JSON.stringify(naive ? e : redact(e)) + "\n");
};
const sign = (claims) => {
const body = b64url(JSON.stringify(claims));
return `LAB-FAKE-${body}.${b64url(createHmac("sha256", signingKey).update(body).digest())}`;
};
const verify = (header = "") => {
const m = /^Bearer LAB-FAKE-([\w-]+)\.([\w-]+)$/.exec(header);
if (!m) return null;
const want = createHmac("sha256", signingKey).update(m[1]).digest();
const got = Buffer.from(m[2], "base64url");
if (got.length !== want.length || !timingSafeEqual(got, want)) return null;
return JSON.parse(Buffer.from(m[1], "base64url"));
};
const licence = async (req, res) => {
const send = (status, body) => {
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(body));
log({ evt: "licence", status, reason: body.error ?? "ok", authorization: req.headers.authorization });
};
if (state.down) return send(503, { error: "licence_unavailable" });
const claims = verify(req.headers.authorization);
if (!claims) return send(401, { error: "invalid_token" });
if (claims.exp < Date.now()) return send(401, { error: "entitlement_expired" });
if (!claims.ent.includes(title)) return send(403, { error: "not_entitled", title });
let chunks = "";
for await (const c of req) chunks += c;
const { kids = [], type } = JSON.parse(chunks);
const keys = kids.filter((kid) => KEYS[kid]).map((kid) => ({ kty: "oct", kid, k: KEYS[kid] }));
if (keys.length === 0) return send(400, { error: "unknown_kid" });
send(200, { licence: { keys, type }, renewAfterMs: state.ttlMs / 2, expiresInMs: state.ttlMs });
};
const server = createServer(async (req, res) => {
const path = req.url.split("?")[0];
if (req.method === "POST" && path === "/licence") return licence(req, res);
if (path === "/session") {
return res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(state.session));
}
const file = FILES[path];
if (!file) return res.writeHead(404).end();
res.writeHead(200, { "content-type": TYPES[file.slice(file.lastIndexOf("."))] });
res.end(await readFile(file));
});
return new Promise((ok) => server.listen(0, "localhost", () => ok({ server, state, sign })));
}
EME defines the ClearKey licence as a JSON Web Key Set: entries with kty oct, the key in k and the key ID in kid, both base64url, plus an optional type. It has no lifetime field, so the server wraps it in an envelope with renewAfterMs and expiresInMs. A ten-second licence would be absurd in production; here it forces two renewals into a twelve-second run.
Drive the key session from the page
The page attaches ClearKey MediaKeys, appends the file through MSE and calls generateRequest(). Everything after the CDM's message event is application code: licence fetch, retry policy, renewal timer, and the decision to close.
<!doctype html>
<meta charset="utf-8">
<video id="v" muted playsinline width="640"></video>
<script type="module">
import { redact, fingerprint } from "/redact.mjs";
const video = document.getElementById("v");
const t0 = performance.now();
const enc = new TextEncoder(), dec = new TextDecoder();
window.__log = [];
window.start = async ({ naive = false, honourExpiry = true }) => {
// The page gets its token the way the app does, from its own backend, so the
// test never passes a secret through page.evaluate().
const { token, kid } = await (await fetch("/session", { cache: "no-store" })).json();
const log = (evt, fields = {}) => {
const e = { t: Math.round(performance.now() - t0), evt, ct: +video.currentTime.toFixed(2), ...fields };
const out = naive ? e : redact(e);
window.__log.push(out);
console.log(JSON.stringify(out));
};
const stop = (error) => { window.__error = error; log("user-error", error); };
// Retry only what can succeed later: network failures and 5xx. A 401/403
// will not change on retry, and the viewer is waiting for the message.
const DELAYS = [1000, 1000, 2000, 2000, 2000];
async function fetchLicence(body, purpose, deadline = Infinity) {
for (let attempt = 1; ; attempt++) {
let res;
try {
res = await fetch("/licence", { method: "POST", body,
headers: { authorization: `Bearer ${token}`, "content-type": "application/json" } });
} catch (err) { res = { ok: false, status: 0, json: async () => ({ error: String(err) }) }; }
const payload = await res.json();
log("licence-response", { purpose, attempt, status: res.status, reason: payload.error ?? "ok",
headers: { authorization: `Bearer ${token}` }, body: payload });
if (res.ok) return payload;
const retryable = res.status === 0 || res.status >= 500;
const wait = DELAYS[attempt - 1];
if (!retryable || wait === undefined || performance.now() + wait > deadline) return { failed: res.status, error: payload.error };
await new Promise((r) => setTimeout(r, wait));
}
}
const ACTIONS = {
not_entitled: { code: "DRM-403-NOT-ENTITLED", message: "This title is not in your plan.", action: "show-upgrade" },
entitlement_expired: { code: "DRM-401-EXPIRED", message: "Your rental has ended.", action: "offer-rent-again" },
invalid_token: { code: "DRM-401-SIGNED-OUT", message: "Please sign in again.", action: "sign-in" },
};
const fail = (r, phase) => ACTIONS[r.error] ?? { code: `DRM-${r.failed}-UNAVAILABLE`, phase,
message: "We can't reach the licence service. Try again shortly.", action: "retry-later" };
const access = await navigator.requestMediaKeySystemAccess("org.w3.clearkey", [{ initDataTypes: ["keyids"],
videoCapabilities: [{ contentType: 'video/mp4; codecs="avc1.4d401e"' }] }]);
const keys = await access.createMediaKeys();
await video.setMediaKeys(keys);
const session = keys.createSession("temporary");
session.closed.then((reason) => log("session-closed", { reason }));
session.addEventListener("keystatuseschange", () => {
const statuses = [];
session.keyStatuses.forEach((status, id) => statuses.push([fingerprint(btoa(String.fromCharCode(...new Uint8Array(id)))
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")), status]));
log("keystatuses", { statuses, expiration: String(session.expiration) });
});
let expiryTimer, renewTimer;
const install = async (payload) => {
await session.update(enc.encode(JSON.stringify(payload.licence)));
clearTimeout(expiryTimer); clearTimeout(renewTimer);
const deadline = performance.now() + payload.expiresInMs;
renewTimer = setTimeout(() => renew(deadline), payload.renewAfterMs);
expiryTimer = setTimeout(() => {
if (!honourExpiry) return log("licence-lapsed-ignored");
stop({ code: "DRM-LICENCE-LAPSED", message: "Playback paused: licence could not be renewed.", action: "retry-later" });
session.close();
}, payload.expiresInMs);
};
let request;
const renew = async (deadline) => {
const r = await fetchLicence(request, "renewal", deadline);
if (!r.failed) return install(r);
if (r.failed === 0 || r.failed >= 500) return; // the expiry timer decides
if (!honourExpiry) return log("renewal-refused-ignored", { status: r.failed });
clearTimeout(expiryTimer);
stop(fail(r, "renewal"));
session.close();
};
session.addEventListener("message", async (ev) => {
request = ev.message;
log("licence-request", { messageType: ev.messageType, request: JSON.parse(dec.decode(ev.message)) });
const r = await fetchLicence(request, "initial");
if (r.failed) return stop(fail(r, "initial"));
await install(r);
video.play();
});
for (const type of ["playing", "waiting", "waitingforkey", "encrypted", "ended", "error"]) {
video.addEventListener(type, (e) => log(type, type === "encrypted" ? { initDataType: e.initDataType } : {}));
}
setInterval(() => log("tick", { readyState: video.readyState }), 2000);
const ms = new MediaSource();
video.src = URL.createObjectURL(ms);
await new Promise((r) => ms.addEventListener("sourceopen", r, { once: true }));
const sb = ms.addSourceBuffer('video/mp4; codecs="avc1.4d401e"');
sb.appendBuffer(await (await fetch("/media/video.mp4")).arrayBuffer());
await new Promise((r) => sb.addEventListener("updateend", r, { once: true }));
ms.endOfStream();
await session.generateRequest("keyids", enc.encode(JSON.stringify({ kids: [kid] })));
};
</script>
Three ClearKey behaviours shape this code. In every session the CDM raised exactly one message, a license-request; EME also defines license-renewal, but this CDM never sent one, so the page renews on its own timer and passes each licence to update() on the same session. EME states that the ClearKey expiration attribute is always NaN, so the lifetime must come from the envelope. And the expired key status requires an expiration earlier than the current time, which NaN never is: a ClearKey session cannot report expired. Expiry is something the page enforces by closing the session, or not at all.
fetchLicence holds the retry rule: network failures and 5xx are retried after 1, 1, 2, 2 and 2 seconds, renewal retries stop before the licence would lapse, and a 401 or 403 returns at once. A renewal lost to 5xx leaves the decision to the expiry timer, because the key is valid until then.
Five sessions against one licence server
The runner gives each case a fresh context with a HAR and a trace, and flips the server's down flag for the outage. A fifth case, expired-ignored, switches the page's enforcement off to show what ClearKey does alone.
// Runs the five licence cases in Playwright's Chromium and writes every
// artifact a CI job would keep. Usage: node run.mjs naive|hardened
import { chromium } from "playwright";
import { mkdir, readFile, writeFile, rm } from "node:fs/promises";
import { lab } from "./server.mjs";
const mode = process.argv[2] ?? "hardened";
const naive = mode === "naive";
const read = async (f) => (await readFile(f, "utf8")).trim();
const [keyHex, kidHex, signingKey] = await Promise.all(["key.hex", "kid.hex", "signing.hex"].map(read));
const kid = Buffer.from(kidHex, "hex").toString("base64url");
const ARTIFACTS = {
naive: { har: { content: "embed" }, trace: { screenshots: false, snapshots: true } },
hardened: { har: { content: "omit", urlFilter: /\/media\// }, trace: { screenshots: false, snapshots: false } },
}[mode];
const cases = [
{ name: "allowed", ent: ["title-42"], runMs: 13_000 },
{ name: "denied", ent: [], runMs: 3_000 },
{ name: "outage", ent: ["title-42"], runMs: 13_000, outage: [4_000, 7_500] },
{ name: "expired", ent: ["title-42"], runMs: 20_000, expMs: 12_000 },
{ name: "expired-ignored", ent: ["title-42"], runMs: 20_000, expMs: 12_000, honourExpiry: false },
];
await rm(`artifacts/${mode}`, { recursive: true, force: true });
const browser = await chromium.launch();
console.log(`mode=${mode} chromium=${browser.version()}`);
for (const c of cases) {
const dir = `artifacts/${mode}/${c.name}`;
await mkdir(dir, { recursive: true });
const { server, state, sign } = await lab({ keyHex, kidHex, signingKey, naive, logFile: `${dir}/server.log` });
const origin = `http://localhost:${server.address().port}`;
const context = await browser.newContext({ recordHar: { path: `${dir}/network.har`, ...ARTIFACTS.har } });
await context.tracing.start(ARTIFACTS.trace);
const page = await context.newPage();
const consoleLines = [];
page.on("console", (m) => consoleLines.push(m.text()));
await page.goto(origin);
const token = sign({ sub: "viewer-1", ent: c.ent, exp: Date.now() + (c.expMs ?? 600_000) });
const started = Date.now();
state.session = { token, kid };
await page.evaluate((a) => window.start(a), { naive, honourExpiry: c.honourExpiry ?? true });
if (c.outage) {
setTimeout(() => (state.down = true), c.outage[0] - (Date.now() - started));
setTimeout(() => (state.down = false), c.outage[1] - (Date.now() - started));
}
await page.waitForTimeout(c.runMs);
const log = await page.evaluate(() => window.__log);
await context.tracing.stop({ path: `${dir}/trace.zip` });
await context.close();
server.close();
await writeFile(`${dir}/events.jsonl`, log.map((e) => JSON.stringify(e)).join("\n") + "\n");
await writeFile(`${dir}/console.log`, consoleLines.join("\n") + "\n");
const pick = (evt) => log.filter((e) => e.evt === evt);
const lic = pick("licence-response").map((e) => `${e.purpose[0]}${e.attempt}:${e.status}@${(e.t / 1000).toFixed(1)}s`);
const statuses = pick("keystatuses").map((e) => e.statuses.map(([, s]) => s).join("+") || "(none)");
const err = pick("user-error")[0];
const last = log.at(-1);
console.log(`\n[${c.name}]`);
console.log(` licence ${lic.join(" ")}`);
console.log(` keystatus ${statuses.join(" -> ")} expiration=${pick("keystatuses")[0]?.expiration ?? "-"}`);
console.log(` playback playing=${pick("playing").length} waitingforkey=${pick("waitingforkey").length} currentTime=${last.ct}s at ${(last.t / 1000).toFixed(1)}s`);
console.log(` user error ${err ? `${err.code} "${err.message}" action=${err.action}` : "none"}`);
const closed = pick("session-closed")[0];
if (closed) console.log(` session closed (${closed.reason}) at ${(closed.t / 1000).toFixed(1)}s`);
for (const e of [...pick("licence-lapsed-ignored"), ...pick("renewal-refused-ignored")]) console.log(` ignored ${e.evt} at ${(e.t / 1000).toFixed(1)}s`);
}
await browser.close();
node run.mjs naive > naive.stdout 2>&1; cp naive.stdout artifacts/naive/run.stdout
node run.mjs hardened > hardened.stdout 2>&1; cp hardened.stdout artifacts/hardened/run.stdout
Each mode takes about 70 seconds of real-time playback. The runner's output goes into the artifact folder too, because a CI log is an artifact. The hardened run printed:
mode=hardened chromium=151.0.7922.34
[allowed]
licence i1:[email protected] r1:[email protected] r1:[email protected]
keystatus usable -> usable -> usable expiration=NaN
playback playing=1 waitingforkey=1 currentTime=11.98s at 12.0s
user error none
[denied]
licence i1:[email protected]
keystatus expiration=-
playback playing=0 waitingforkey=1 currentTime=0s at 2.0s
user error DRM-403-NOT-ENTITLED "This title is not in your plan." action=show-upgrade
[outage]
licence i1:[email protected] r1:[email protected] r2:[email protected] r3:[email protected] r4:[email protected]
keystatus usable -> usable expiration=NaN
playback playing=1 waitingforkey=1 currentTime=11.97s at 12.0s
user error none
[expired]
licence i1:[email protected] r1:[email protected] r1:[email protected] r1:[email protected]
keystatus usable -> usable -> usable -> (none) expiration=NaN
playback playing=1 waitingforkey=2 currentTime=15.17s at 20.0s
user error DRM-401-EXPIRED "Your rental has ended." action=offer-rent-again
session closed (closed-by-application) at 15.0s
[expired-ignored]
licence i1:[email protected] r1:[email protected] r1:[email protected] r1:[email protected]
keystatus usable -> usable -> usable expiration=NaN
playback playing=1 waitingforkey=1 currentTime=20.01s at 20.0s
user error none
ignored renewal-refused-ignored at 15.0s
The naive run printed the same outcomes, with timings at most a tenth of a second apart.
Entitled. One licence, two renewals, each usable. In all ten sessions across both modes, a waitingforkey fired 17 to 51 milliseconds in, before the first licence response and before play(). An alert on every waitingforkey fires on every encrypted start.
Not entitled. One 403, no retry, and DRM-403-NOT-ENTITLED with the upgrade action. Assert on that error object; there is no frozen video to assert on.
Outage. Down from 4.0 to 7.5 seconds. Renewals at 5, 6 and 7 seconds got 503; the one at 9 got a licence. No waiting followed the first playing, and the viewer saw nothing. Absence of errors would also pass a player that never renews, so assert the attempts and their outcome from the log.
Expired. Entitlement ended at 12 seconds; the 15-second renewal got 401 entitlement_expired. The page showed the rent-again message and closed the session, whose closed promise resolved with closed-by-application. Key statuses went empty, a second waitingforkey fired, and currentTime stopped at 15.17 with readyState 2, about 0.17 seconds after the close. Assert a stop within a margin, not at an exact time.
Expired, enforcement off. Same 401, and playback ran on to 20 seconds, when the run ended, decrypting with a key the server had refused to renew. EME gives a CDM the expired status for this; ClearKey cannot use it, so a passing test proves the page's policy, not the CDM's.
Redact before the log line exists
Page and server pass every entry through one function before it is stored, printed or written. Post-processing is too late: in the naive run, the trace's main entry held the key in three console messages and in the value the test read back with page.evaluate().
// Shared by the page and the licence server. Runs on every log entry before it
// is written anywhere, including the console, so traces never see the raw value.
const DROP = new Set(["authorization", "token", "k", "keys", "licence", "license", "body", "request", "headers"]);
const B64URL_16 = /\b[A-Za-z0-9_-]{22}\b/g; // a 16-byte value, base64url, no padding
const HEX_16 = /\b[0-9a-fA-F]{32}\b/g; // the same value as hex
const BEARER = /Bearer\s+[A-Za-z0-9._~+\/=-]+/g;
const LAB_TOKEN = /LAB-FAKE-[A-Za-z0-9._-]+/g;
// FNV-1a: a small lab-only correlation tag, not a cryptographic privacy boundary.
export const fingerprint = (s) => {
let h = 0x811c9dc5;
for (const c of s) h = Math.imul(h ^ c.charCodeAt(0), 0x01000193) >>> 0;
return "fp:" + h.toString(16).padStart(8, "0");
};
const scrub = (s) =>
s.replace(BEARER, "Bearer [REDACTED]").replace(LAB_TOKEN, "[REDACTED-TOKEN]")
.replace(B64URL_16, (m) => fingerprint(m)).replace(HEX_16, (m) => fingerprint(m));
export function redact(value, key = "") {
if (DROP.has(key.toLowerCase())) return "[REDACTED]";
if (key === "kid" || key === "kids") return [].concat(value).map((v) => fingerprint(String(v)));
if (typeof value === "string") return scrub(value);
if (Array.isArray(value)) return value.map((v) => redact(v));
if (value && typeof value === "object") {
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redact(v, k)]));
}
return value;
}
The drop list removes fields known to carry secrets. The value patterns catch secrets inside strings, such as an error that quotes a header. A 16-byte key prints as 32 hex characters or, with padding dropped as RFC 4648 allows, 22 base64url characters; matching both forms catches it in any field. Key IDs become an FNV-1a fingerprint (fp:4a7efe84 here), so lines about one key still join. This 32-bit non-cryptographic hash can collide and permits guessing from known IDs. Do not treat it as anonymisation or use it for viewer identity; use short-lived random aliases or a reviewed keyed pseudonym scheme when correlation is required in production.
Over-redaction is the cost. The first drop list included message, the EME event field, and blanked the viewer-facing text of every error: "message":"[REDACTED]". Assert that the fields support needs survive. A redacted outage renewal:
{"t":5035,"evt":"licence-response","ct":5,"purpose":"renewal","attempt":1,"status":503,"reason":"licence_unavailable","headers":"[REDACTED]","body":"[REDACTED]"}
Scan for every secret in every encoding
The scan reads every file and every zip entry, and searches for each secret as lower- and upper-case hex, base64url, base64 and raw bytes. The LAB-FAKE- prefix finds every token minted during the run without storing any.
// Searches every artifact, and every entry inside every zip, for each lab
// secret in each encoding it can take on the wire. Exit 1 on any hit.
// Usage: node scan.mjs artifacts/hardened
import { readdir, readFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { join } from "node:path";
const dir = process.argv[2];
const hex = (f) => readFile(f, "utf8").then((s) => s.trim());
const forms = (name, bytes) => [
[`${name}/hex`, Buffer.from(bytes.toString("hex"))],
[`${name}/HEX`, Buffer.from(bytes.toString("hex").toUpperCase())],
[`${name}/base64url`, Buffer.from(bytes.toString("base64url"))],
[`${name}/base64`, Buffer.from(bytes.toString("base64"))],
[`${name}/raw`, bytes],
];
const signing = await hex("signing.hex");
const needles = [
...forms("key", Buffer.from(await hex("key.hex"), "hex")),
...forms("kid", Buffer.from(await hex("kid.hex"), "hex")),
["token", Buffer.from("LAB-FAKE-")],
["signing-key", Buffer.from(signing)],
];
async function* walk(d) {
for (const e of await readdir(d, { withFileTypes: true })) {
const p = join(d, e.name);
if (e.isDirectory()) yield* walk(p);
else if (p.endsWith(".zip")) {
for (const entry of execFileSync("unzip", ["-Z1", p], { encoding: "utf8" }).split("\n").filter(Boolean)) {
yield [`${p}!${entry}`, execFileSync("unzip", ["-p", p, entry], { maxBuffer: 1 << 28 })];
}
} else yield [p, await readFile(p)];
}
}
let files = 0, hits = 0;
for await (const [name, buf] of walk(dir)) {
files++;
const found = needles.map(([label, n]) => {
let count = 0;
for (let i = buf.indexOf(n); i !== -1; i = buf.indexOf(n, i + 1)) count++;
return count ? `${label}x${count}` : null;
}).filter(Boolean);
if (found.length) { hits += found.length; console.log(`LEAK ${name.slice(dir.length + 1)} ${found.join(" ")}`); }
}
console.log(`${files} files and zip entries scanned, ${needles.length} needles, ${hits ? `${hits} leak finding(s)` : "0 leaks"}`);
process.exit(hits ? 1 : 0);
Against the naive artifacts it exits 1. The entitled case's lines, then the run's summary:
LEAK allowed/console.log key/base64urlx3 kid/base64urlx4 tokenx3
LEAK allowed/events.jsonl key/base64urlx3 kid/base64urlx4 tokenx3
LEAK allowed/network.har key/base64urlx3 kid/base64urlx7 tokenx5
LEAK allowed/server.log tokenx3
LEAK allowed/trace.zip!trace.trace key/base64urlx12 kid/base64urlx16 tokenx12
LEAK allowed/trace.zip!trace.network tokenx3
LEAK allowed/trace.zip!resources/93bac8a010467dd15e386c3d1e6f0bfa57a57583.json kid/base64urlx1 tokenx1
LEAK allowed/trace.zip!resources/969e21a56fa069fcbb0b5866c5ab478dc55a3331.mp4 kid/rawx1
LEAK allowed/trace.zip!resources/901f98224826dcb6b29ec99b99ffc4d2ee44ad7e.json kid/base64urlx1
LEAK allowed/trace.zip!resources/6d17ff6ffcf5d37314f52a26851c72b9f6c03d2b.json key/base64urlx1 kid/base64urlx1
64 files and zip entries scanned, 12 needles, 94 leak finding(s)
Every key hit is base64url. A hex-only grep would have passed:
KEY_HEX=$(cat key.hex)
KEY_B64URL=$(xxd -r -p key.hex | base64 | tr '+/' '-_' | tr -d '=')
echo "files with hex key: $(grep -rl "$KEY_HEX" artifacts/naive | wc -l | tr -d ' ') files with base64url key: $(grep -rl -- "$KEY_B64URL" artifacts/naive | wc -l | tr -d ' ')"
files with hex key: 0 files with base64url key: 12
Neither grep reaches the trace, where most hits are. The kid/raw hit in the .mp4 resource is the media itself, captured by the trace.
Hardened mode records the HAR with content: "omit" and a media-only urlFilter, and the trace with snapshots: false, which Playwright documents as also turning off network recording; that trade-off is covered in retaining CI artifacts that explain failures. The first hardened run still failed:
LEAK allowed/trace.zip!trace.trace kid/base64urlx1 tokenx1
LEAK denied/trace.zip!trace.trace kid/base64urlx1 tokenx1
LEAK expired/trace.zip!trace.trace kid/base64urlx1 tokenx1
LEAK expired-ignored/trace.zip!trace.trace kid/base64urlx1 tokenx1
LEAK outage/trace.zip!trace.trace kid/base64urlx1 tokenx1
36 files and zip entries scanned, 12 needles, 10 leak finding(s)
The token reached the trace through the test itself: that runner passed it to the page as an argument, and the trace records each evaluateExpression call with its arguments. The fix delivers it the way a real app gets it, from its backend:
// Before: the token is an argument, and the trace records every argument.
await page.evaluate((a) => window.start(a), { token, kid, naive, honourExpiry: c.honourExpiry ?? true });
// After: the lab server hands the page its session, as the app's backend would.
state.session = { token, kid };
await page.evaluate((a) => window.start(a), { naive, honourExpiry: c.honourExpiry ?? true });
The hardened scan then exited 0:
36 files and zip entries scanned, 12 needles, 0 leaks
It proves absence only for the values it was given. Run it before the upload step and fail the job on exit 1.
Where ClearKey stops standing in for a real CDM
ClearKey exercises the application's half: licence protocol, entitlement decisions, retry and renewal, error mapping and logging. EME's own description of ClearKey marks where it stops.
- Robustness. Only the empty string, defined as accepting any ability to decrypt and decode. A test cannot request, or be refused, a hardware-backed level.
- Output protection.
getStatusForPolicy()should always resolveusable, whateverminHdcpVersionis asked for.output-restricteddid not appear in any run; HDCP needs the real device and display. - Expiry.
expirationis alwaysNaN, so duration rules are only as strong as the page. - Device identity.
distinctiveIdentifier: "required"is unsupported. EME requires distinctive identifiers in key system messages to be encrypted with a timestamp or nonce, so real messages always differ. - Licence format. EME calls licences and messages key-system-specific. ClearKey's licence is readable JSON with the key inside; for Widevine, PlayReady or FairPlay, check the key search against that system's format. The token search carries over unchanged.
Nor did the lab produce the hardware-context-reset close reason. Keep device-only checks in a smaller matrix with your DRM provider's test licences, and run the ClearKey suite on every pull request.
Questions about testing the licence path
Is a key ID a secret?
No; it is in the clear in the media. Log a fingerprint anyway, so a viewer ID beside it does not record who watched what.
Should a 401 from the licence server be retried?
Once, after refreshing the token, if tokens can expire before entitlements do. A fresh token that still gets 401 means the entitlement ended; stop. Never retry a 403.
Does this change with Shaka Player or dash.js in place of raw EME?
The cases, redaction and scan carry over. The token moves into the player's request hooks and errors into its error events; check what those error objects hold before logging them whole, since a request URL or headers can carry the token.
Specifications behind the licence tests
- W3C Encrypted Media Extensions, Clear Key. Robustness, distinctive identifier,
getStatusForPolicy()andexpirationrules, and the licence request and licence formats. - EME, MediaKeyStatus.
expiredrequiring an expiration earlier than the current time;output-restrictedandoutput-downscaled. - EME, MediaKeySessionClosedReason.
closed-by-applicationfor an explicitclose(), andhardware-context-reset. - EME, getStatusForPolicy(). The HDCP policy expressed as
minHdcpVersion. - EME, Wait for Key. The
waitingforkeyevent andreadyStateat or belowHAVE_CURRENT_DATAwhile playback is blocked on a key. - EME, encrypt distinctive identifiers. Distinctive identifiers in key system messages encrypted with a timestamp or nonce.
- W3C "keyids" Initialization Data Format. The
kidsarray of base64url key IDs used as initialisation data. - RFC 4648, section 5. The URL-safe base64 alphabet and omitting padding when the length is known.
- FFmpeg formats, mov/mp4 muxer.
encryption_schemewithcenc-aes-ctr, andencryption_keyandencryption_kidin hex. - FFmpeg formats, mov/mp4 demuxer.
decryption_keyfor decrypting CENC files, used to prove the lab media is encrypted. - Playwright Browser API, newContext.
recordHarwithcontent: "omit"andurlFilter. - Playwright Tracing API.
snapshots.domcapturing DOM snapshots and network activity.
Add one leak gate and one refusal test today
- Search your last DRM run's artifacts, inside every zip entry, for the test key and token in base64url as well as hex. Any match makes the scan a required step before upload.
- Write the 403 case first: one licence request, no retry, and an error carrying a code, a message and an action.
- If your test hands a token to the browser through a
page.evaluate()argument, move it behind a backend call and re-scan. - Keep the outage case's redacted event log with each run; the diff checker compares two runs' renewal attempts line by line.
- Mark every rule that relies on CDM enforcement (duration, HDCP, robustness) as device-only in part 1's contract table.