{"title":"Verify DRM Playback Without Leaking Keys or Tokens","excerpt":"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.","canonicalUrl":"https://automationtester.in/blog/automation-tutorials/verify-drm-playback-without-logging-secrets","category":{"name":"Automation Tutorials","slug":"automation-tutorials"},"tags":["streaming","drm","encrypted-media-extensions","playwright","security-testing","video-testing"],"author":{"name":"Shashank Rawlani","url":"https://shashank.rawlani.com","linkedin":"https://www.linkedin.com/in/shashankrawlani/"},"datePublished":"2026-11-25T13:30:00.000Z","dateModified":"2026-11-25T13:30:00.000Z","coverImage":{"url":"https://ik.imagekit.io/automationtester/automationtester-in/blog/covers/v3/verify-drm-playback-without-logging-secrets.webp","alt":"A player pane with a green ringed node sends an arc to a server panel and gets a green key back. Green flows feed three panels of green and grey pills, one zipped. Dashed orange paths beside them end in key outlines that stop short."},"contentHtml":"<div class=\"callout callout-info\"><strong>Quick answer:</strong> Test four licence cases, each with its own correct outcome: an entitled viewer plays and renews; a 403 stops after one attempt with a message naming the fix; an outage is retried while the installed key keeps playing; a refused renewal closes the key session. ClearKey and ffmpeg-encrypted synthetic media run all four in headless Chromium. Redact inside the logger, then scan every artifact, including each entry in the trace zip, for every secret in hex, base64url, base64 and raw bytes. ClearKey carries keys as base64url, so a grep for the hex you generated finds nothing. Output protection, robustness and CDM-enforced expiry still need a real CDM on the device.</div>\n\n<p>A DRM test goes green. The licence request returned 200, the key status went to <code>usable</code> 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.</p>\n\n<p>Part 5 of the streaming and CTV quality series opens one row of the contract table from <a href=\"/blog/automation-tutorials/streaming-quality-model-beyond-video-starts\">part 1</a>: entitlement, observed through the licence response and the EME key statuses. <a href=\"/blog/automation-tutorials/measure-video-startup-time-percentiles\">Part 3</a> 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.</p>\n\n<div class=\"callout callout-warning\"><strong>Versions checked on 2026-11-18:</strong> Playwright 1.62.1 with its bundled Chromium 151.0.7922.34, Node.js 26.12.1 and ffmpeg 9.0.1, on macOS arm64. No player library: the page drives EME and MSE directly. The EME text cited is the W3C Working Draft of 8 November 2026. Every key, key ID, signing key and token is a throwaway generated for one run, tokens start with <code>LAB-FAKE-</code>, and no key value appears here.</div>\n\n<h2 id=\"drm-four-outcomes\">Four licence outcomes with four right answers</h2>\n\n<p>A test that asserts only \"playback started\" passes the first row and cannot tell the other three apart.</p>\n\n<table>\n<thead><tr><th>Case</th><th>Licence server says</th><th>Player should</th><th>Viewer should see</th></tr></thead>\n<tbody>\n<tr><td>Entitled</td><td>200 with the key, then 200 on each renewal</td><td>Install the key, play, renew before the licence lapses</td><td>Uninterrupted video</td></tr>\n<tr><td>Not entitled</td><td>403 <code>not_entitled</code></td><td>Stop after one attempt</td><td>A message naming the fix, such as an upgrade</td></tr>\n<tr><td>Licence service down</td><td>503, or no response</td><td>Retry with backoff while the installed key still plays, up to the licence's lapse time</td><td>Nothing, if the outage ends in time</td></tr>\n<tr><td>Entitlement ended</td><td>401 <code>entitlement_expired</code> on renewal</td><td>Close the key session</td><td>Playback stops with a rent-again prompt</td></tr>\n</tbody>\n</table>\n\n<p>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.</p>\n\n<h2 id=\"drm-throwaway-media\">Encrypt synthetic media with keys made for one run</h2>\n\n<p>In a scratch directory, pin Playwright, generate throwaway secrets, and encrypt a 40-second <code>testsrc2</code> clip:</p>\n\n<pre><code class=\"language-bash\">npm init -y\nnpm i playwright@1.62.1\nopenssl rand -hex 16 &gt; key.hex       # content key, this run only\nopenssl rand -hex 16 &gt; kid.hex       # key ID\nopenssl rand -hex 32 &gt; signing.hex   # signs the lab's entitlement tokens\nmkdir -p media\nffmpeg -hide_banner -loglevel error -y \\\n  -f lavfi -i testsrc2=size=640x360:rate=30:duration=40 \\\n  -c:v libx264 -profile:v main -preset veryfast -g 60 -keyint_min 60 -sc_threshold 0 -b:v 600k \\\n  -movflags frag_keyframe+empty_moov+default_base_moof \\\n  -encryption_scheme cenc-aes-ctr -encryption_key \"$(cat key.hex)\" -encryption_kid \"$(cat kid.hex)\" \\\n  media/video.mp4</code></pre>\n\n<p>The mp4 muxer's <code>encryption_scheme</code> accepts <code>none</code> or <code>cenc-aes-ctr</code>, with key and key ID in hex; the <code>movflags</code> 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 <code>-decryption_key</code>, none:</p>\n\n<pre><code class=\"language-bash\">ffmpeg -hide_banner -v error -i media/video.mp4 -f null - 2&gt;&amp;1 | wc -l\nffmpeg -hide_banner -v error -decryption_key \"$(cat key.hex)\" -i media/video.mp4 -f null - 2&gt;&amp;1 | wc -l</code></pre>\n\n<pre><code class=\"language-text\">    4278\n       0</code></pre>\n\n<p>A byte search of the file found:</p>\n\n<pre><code class=\"language-text\">pssh boxes: 0, KID bytes: 1, key bytes: 0</code></pre>\n\n<p>The key ID sits in the file in the clear, for anyone who downloads the media: an identifier, not a secret. With no <code>pssh</code> box, Chromium fired no <code>encrypted</code> event in any run, so the page builds its own initialisation data in the <code>keyids</code> format, a <code>kids</code> array of base64url key IDs.</p>\n\n<h2 id=\"drm-licence-endpoint\">A licence endpoint behind an entitlement token</h2>\n\n<p>The lab server serves the page and media, hands the page its session, and answers <code>POST /licence</code>. 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.</p>\n\n<pre><code class=\"language-javascript\">// Local origin for the lab: the page, the encrypted media, and a ClearKey\n// licence endpoint behind an entitlement token. Every log line goes through\n// the same redact() the page uses.\nimport { createServer } from \"node:http\";\nimport { readFile, appendFile } from \"node:fs/promises\";\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\nimport { redact } from \"./redact.mjs\";\n\nconst b64url = (buf) =&gt; Buffer.from(buf).toString(\"base64url\");\nconst TYPES = { \".html\": \"text/html\", \".mjs\": \"text/javascript\", \".mp4\": \"video/mp4\" };\nconst FILES = { \"/\": \"player.html\", \"/redact.mjs\": \"redact.mjs\", \"/media/video.mp4\": \"media/video.mp4\" };\n\nexport function lab({ keyHex, kidHex, signingKey, logFile, naive = false, title = \"title-42\" }) {\n  const KEYS = { [b64url(Buffer.from(kidHex, \"hex\"))]: b64url(Buffer.from(keyHex, \"hex\")) };\n  const state = { down: false, ttlMs: 10_000, session: null };\n  const log = (entry) =&gt; {\n    const e = { t: Date.now(), ...entry };\n    return appendFile(logFile, JSON.stringify(naive ? e : redact(e)) + \"\\n\");\n  };\n\n  const sign = (claims) =&gt; {\n    const body = b64url(JSON.stringify(claims));\n    return `LAB-FAKE-${body}.${b64url(createHmac(\"sha256\", signingKey).update(body).digest())}`;\n  };\n  const verify = (header = \"\") =&gt; {\n    const m = /^Bearer LAB-FAKE-([\\w-]+)\\.([\\w-]+)$/.exec(header);\n    if (!m) return null;\n    const want = createHmac(\"sha256\", signingKey).update(m[1]).digest();\n    const got = Buffer.from(m[2], \"base64url\");\n    if (got.length !== want.length || !timingSafeEqual(got, want)) return null;\n    return JSON.parse(Buffer.from(m[1], \"base64url\"));\n  };\n\n  const licence = async (req, res) =&gt; {\n    const send = (status, body) =&gt; {\n      res.writeHead(status, { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" }).end(JSON.stringify(body));\n      log({ evt: \"licence\", status, reason: body.error ?? \"ok\", authorization: req.headers.authorization });\n    };\n    if (state.down) return send(503, { error: \"licence_unavailable\" });\n    const claims = verify(req.headers.authorization);\n    if (!claims) return send(401, { error: \"invalid_token\" });\n    if (claims.exp &lt; Date.now()) return send(401, { error: \"entitlement_expired\" });\n    if (!claims.ent.includes(title)) return send(403, { error: \"not_entitled\", title });\n    let chunks = \"\";\n    for await (const c of req) chunks += c;\n    const { kids = [], type } = JSON.parse(chunks);\n    const keys = kids.filter((kid) =&gt; KEYS[kid]).map((kid) =&gt; ({ kty: \"oct\", kid, k: KEYS[kid] }));\n    if (keys.length === 0) return send(400, { error: \"unknown_kid\" });\n    send(200, { licence: { keys, type }, renewAfterMs: state.ttlMs / 2, expiresInMs: state.ttlMs });\n  };\n\n  const server = createServer(async (req, res) =&gt; {\n    const path = req.url.split(\"?\")[0];\n    if (req.method === \"POST\" &amp;&amp; path === \"/licence\") return licence(req, res);\n    if (path === \"/session\") {\n      return res.writeHead(200, { \"content-type\": \"application/json\", \"cache-control\": \"no-store\" }).end(JSON.stringify(state.session));\n    }\n    const file = FILES[path];\n    if (!file) return res.writeHead(404).end();\n    res.writeHead(200, { \"content-type\": TYPES[file.slice(file.lastIndexOf(\".\"))] });\n    res.end(await readFile(file));\n  });\n  return new Promise((ok) =&gt; server.listen(0, \"localhost\", () =&gt; ok({ server, state, sign })));\n}</code></pre>\n\n<p>EME defines the ClearKey licence as a JSON Web Key Set: entries with <code>kty</code> <code>oct</code>, the key in <code>k</code> and the key ID in <code>kid</code>, both base64url, plus an optional <code>type</code>. It has no lifetime field, so the server wraps it in an envelope with <code>renewAfterMs</code> and <code>expiresInMs</code>. A ten-second licence would be absurd in production; here it forces two renewals into a twelve-second run.</p>\n\n<h2 id=\"drm-page-session\">Drive the key session from the page</h2>\n\n<p>The page attaches ClearKey <code>MediaKeys</code>, appends the file through MSE and calls <code>generateRequest()</code>. Everything after the CDM's <code>message</code> event is application code: licence fetch, retry policy, renewal timer, and the decision to close.</p>\n\n<pre><code class=\"language-html\">&lt;!doctype html&gt;\n&lt;meta charset=\"utf-8\"&gt;\n&lt;video id=\"v\" muted playsinline width=\"640\"&gt;&lt;/video&gt;\n&lt;script type=\"module\"&gt;\nimport { redact, fingerprint } from \"/redact.mjs\";\n\nconst video = document.getElementById(\"v\");\nconst t0 = performance.now();\nconst enc = new TextEncoder(), dec = new TextDecoder();\nwindow.__log = [];\n\nwindow.start = async ({ naive = false, honourExpiry = true }) =&gt; {\n  // The page gets its token the way the app does, from its own backend, so the\n  // test never passes a secret through page.evaluate().\n  const { token, kid } = await (await fetch(\"/session\", { cache: \"no-store\" })).json();\n  const log = (evt, fields = {}) =&gt; {\n    const e = { t: Math.round(performance.now() - t0), evt, ct: +video.currentTime.toFixed(2), ...fields };\n    const out = naive ? e : redact(e);\n    window.__log.push(out);\n    console.log(JSON.stringify(out));\n  };\n  const stop = (error) =&gt; { window.__error = error; log(\"user-error\", error); };\n\n  // Retry only what can succeed later: network failures and 5xx. A 401/403\n  // will not change on retry, and the viewer is waiting for the message.\n  const DELAYS = [1000, 1000, 2000, 2000, 2000];\n  async function fetchLicence(body, purpose, deadline = Infinity) {\n    for (let attempt = 1; ; attempt++) {\n      let res;\n      try {\n        res = await fetch(\"/licence\", { method: \"POST\", body,\n          headers: { authorization: `Bearer ${token}`, \"content-type\": \"application/json\" } });\n      } catch (err) { res = { ok: false, status: 0, json: async () =&gt; ({ error: String(err) }) }; }\n      const payload = await res.json();\n      log(\"licence-response\", { purpose, attempt, status: res.status, reason: payload.error ?? \"ok\",\n        headers: { authorization: `Bearer ${token}` }, body: payload });\n      if (res.ok) return payload;\n      const retryable = res.status === 0 || res.status &gt;= 500;\n      const wait = DELAYS[attempt - 1];\n      if (!retryable || wait === undefined || performance.now() + wait &gt; deadline) return { failed: res.status, error: payload.error };\n      await new Promise((r) =&gt; setTimeout(r, wait));\n    }\n  }\n\n  const ACTIONS = {\n    not_entitled: { code: \"DRM-403-NOT-ENTITLED\", message: \"This title is not in your plan.\", action: \"show-upgrade\" },\n    entitlement_expired: { code: \"DRM-401-EXPIRED\", message: \"Your rental has ended.\", action: \"offer-rent-again\" },\n    invalid_token: { code: \"DRM-401-SIGNED-OUT\", message: \"Please sign in again.\", action: \"sign-in\" },\n  };\n  const fail = (r, phase) =&gt; ACTIONS[r.error] ?? { code: `DRM-${r.failed}-UNAVAILABLE`, phase,\n    message: \"We can't reach the licence service. Try again shortly.\", action: \"retry-later\" };\n\n  const access = await navigator.requestMediaKeySystemAccess(\"org.w3.clearkey\", [{ initDataTypes: [\"keyids\"],\n      videoCapabilities: [{ contentType: 'video/mp4; codecs=\"avc1.4d401e\"' }] }]);\n  const keys = await access.createMediaKeys();\n  await video.setMediaKeys(keys);\n  const session = keys.createSession(\"temporary\");\n  session.closed.then((reason) =&gt; log(\"session-closed\", { reason }));\n  session.addEventListener(\"keystatuseschange\", () =&gt; {\n    const statuses = [];\n    session.keyStatuses.forEach((status, id) =&gt; statuses.push([fingerprint(btoa(String.fromCharCode(...new Uint8Array(id)))\n      .replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\")), status]));\n    log(\"keystatuses\", { statuses, expiration: String(session.expiration) });\n  });\n\n  let expiryTimer, renewTimer;\n  const install = async (payload) =&gt; {\n    await session.update(enc.encode(JSON.stringify(payload.licence)));\n    clearTimeout(expiryTimer); clearTimeout(renewTimer);\n    const deadline = performance.now() + payload.expiresInMs;\n    renewTimer = setTimeout(() =&gt; renew(deadline), payload.renewAfterMs);\n    expiryTimer = setTimeout(() =&gt; {\n      if (!honourExpiry) return log(\"licence-lapsed-ignored\");\n      stop({ code: \"DRM-LICENCE-LAPSED\", message: \"Playback paused: licence could not be renewed.\", action: \"retry-later\" });\n      session.close();\n    }, payload.expiresInMs);\n  };\n  let request;\n  const renew = async (deadline) =&gt; {\n    const r = await fetchLicence(request, \"renewal\", deadline);\n    if (!r.failed) return install(r);\n    if (r.failed === 0 || r.failed &gt;= 500) return; // the expiry timer decides\n    if (!honourExpiry) return log(\"renewal-refused-ignored\", { status: r.failed });\n    clearTimeout(expiryTimer);\n    stop(fail(r, \"renewal\"));\n    session.close();\n  };\n\n  session.addEventListener(\"message\", async (ev) =&gt; {\n    request = ev.message;\n    log(\"licence-request\", { messageType: ev.messageType, request: JSON.parse(dec.decode(ev.message)) });\n    const r = await fetchLicence(request, \"initial\");\n    if (r.failed) return stop(fail(r, \"initial\"));\n    await install(r);\n    video.play();\n  });\n\n  for (const type of [\"playing\", \"waiting\", \"waitingforkey\", \"encrypted\", \"ended\", \"error\"]) {\n    video.addEventListener(type, (e) =&gt; log(type, type === \"encrypted\" ? { initDataType: e.initDataType } : {}));\n  }\n  setInterval(() =&gt; log(\"tick\", { readyState: video.readyState }), 2000);\n\n  const ms = new MediaSource();\n  video.src = URL.createObjectURL(ms);\n  await new Promise((r) =&gt; ms.addEventListener(\"sourceopen\", r, { once: true }));\n  const sb = ms.addSourceBuffer('video/mp4; codecs=\"avc1.4d401e\"');\n  sb.appendBuffer(await (await fetch(\"/media/video.mp4\")).arrayBuffer());\n  await new Promise((r) =&gt; sb.addEventListener(\"updateend\", r, { once: true }));\n  ms.endOfStream();\n\n  await session.generateRequest(\"keyids\", enc.encode(JSON.stringify({ kids: [kid] })));\n};\n&lt;/script&gt;</code></pre>\n\n<p>Three ClearKey behaviours shape this code. In every session the CDM raised exactly one <code>message</code>, a <code>license-request</code>; EME also defines <code>license-renewal</code>, but this CDM never sent one, so the page renews on its own timer and passes each licence to <code>update()</code> on the same session. EME states that the ClearKey <code>expiration</code> attribute is always <code>NaN</code>, so the lifetime must come from the envelope. And the <code>expired</code> key status requires an expiration earlier than the current time, which <code>NaN</code> never is: a ClearKey session cannot report <code>expired</code>. Expiry is something the page enforces by closing the session, or not at all.</p>\n\n<p><code>fetchLicence</code> 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.</p>\n\n<h2 id=\"drm-five-sessions\">Five sessions against one licence server</h2>\n\n<p>The runner gives each case a fresh context with a HAR and a trace, and flips the server's <code>down</code> flag for the outage. A fifth case, <code>expired-ignored</code>, switches the page's enforcement off to show what ClearKey does alone.</p>\n\n<pre><code class=\"language-javascript\">// Runs the five licence cases in Playwright's Chromium and writes every\n// artifact a CI job would keep. Usage: node run.mjs naive|hardened\nimport { chromium } from \"playwright\";\nimport { mkdir, readFile, writeFile, rm } from \"node:fs/promises\";\nimport { lab } from \"./server.mjs\";\n\nconst mode = process.argv[2] ?? \"hardened\";\nconst naive = mode === \"naive\";\nconst read = async (f) =&gt; (await readFile(f, \"utf8\")).trim();\nconst [keyHex, kidHex, signingKey] = await Promise.all([\"key.hex\", \"kid.hex\", \"signing.hex\"].map(read));\nconst kid = Buffer.from(kidHex, \"hex\").toString(\"base64url\");\n\nconst ARTIFACTS = {\n  naive: { har: { content: \"embed\" }, trace: { screenshots: false, snapshots: true } },\n  hardened: { har: { content: \"omit\", urlFilter: /\\/media\\// }, trace: { screenshots: false, snapshots: false } },\n}[mode];\n\nconst cases = [\n  { name: \"allowed\", ent: [\"title-42\"], runMs: 13_000 },\n  { name: \"denied\", ent: [], runMs: 3_000 },\n  { name: \"outage\", ent: [\"title-42\"], runMs: 13_000, outage: [4_000, 7_500] },\n  { name: \"expired\", ent: [\"title-42\"], runMs: 20_000, expMs: 12_000 },\n  { name: \"expired-ignored\", ent: [\"title-42\"], runMs: 20_000, expMs: 12_000, honourExpiry: false },\n];\n\nawait rm(`artifacts/${mode}`, { recursive: true, force: true });\nconst browser = await chromium.launch();\nconsole.log(`mode=${mode} chromium=${browser.version()}`);\nfor (const c of cases) {\n  const dir = `artifacts/${mode}/${c.name}`;\n  await mkdir(dir, { recursive: true });\n  const { server, state, sign } = await lab({ keyHex, kidHex, signingKey, naive, logFile: `${dir}/server.log` });\n  const origin = `http://localhost:${server.address().port}`;\n  const context = await browser.newContext({ recordHar: { path: `${dir}/network.har`, ...ARTIFACTS.har } });\n  await context.tracing.start(ARTIFACTS.trace);\n  const page = await context.newPage();\n  const consoleLines = [];\n  page.on(\"console\", (m) =&gt; consoleLines.push(m.text()));\n  await page.goto(origin);\n\n  const token = sign({ sub: \"viewer-1\", ent: c.ent, exp: Date.now() + (c.expMs ?? 600_000) });\n  const started = Date.now();\n  state.session = { token, kid };\n  await page.evaluate((a) =&gt; window.start(a), { naive, honourExpiry: c.honourExpiry ?? true });\n  if (c.outage) {\n    setTimeout(() =&gt; (state.down = true), c.outage[0] - (Date.now() - started));\n    setTimeout(() =&gt; (state.down = false), c.outage[1] - (Date.now() - started));\n  }\n  await page.waitForTimeout(c.runMs);\n\n  const log = await page.evaluate(() =&gt; window.__log);\n  await context.tracing.stop({ path: `${dir}/trace.zip` });\n  await context.close();\n  server.close();\n  await writeFile(`${dir}/events.jsonl`, log.map((e) =&gt; JSON.stringify(e)).join(\"\\n\") + \"\\n\");\n  await writeFile(`${dir}/console.log`, consoleLines.join(\"\\n\") + \"\\n\");\n\n  const pick = (evt) =&gt; log.filter((e) =&gt; e.evt === evt);\n  const lic = pick(\"licence-response\").map((e) =&gt; `${e.purpose[0]}${e.attempt}:${e.status}@${(e.t / 1000).toFixed(1)}s`);\n  const statuses = pick(\"keystatuses\").map((e) =&gt; e.statuses.map(([, s]) =&gt; s).join(\"+\") || \"(none)\");\n  const err = pick(\"user-error\")[0];\n  const last = log.at(-1);\n  console.log(`\\n[${c.name}]`);\n  console.log(`  licence     ${lic.join(\" \")}`);\n  console.log(`  keystatus   ${statuses.join(\" -&gt; \")}  expiration=${pick(\"keystatuses\")[0]?.expiration ?? \"-\"}`);\n  console.log(`  playback    playing=${pick(\"playing\").length} waitingforkey=${pick(\"waitingforkey\").length} currentTime=${last.ct}s at ${(last.t / 1000).toFixed(1)}s`);\n  console.log(`  user error  ${err ? `${err.code} \"${err.message}\" action=${err.action}` : \"none\"}`);\n  const closed = pick(\"session-closed\")[0];\n  if (closed) console.log(`  session     closed (${closed.reason}) at ${(closed.t / 1000).toFixed(1)}s`);\n  for (const e of [...pick(\"licence-lapsed-ignored\"), ...pick(\"renewal-refused-ignored\")]) console.log(`  ignored     ${e.evt} at ${(e.t / 1000).toFixed(1)}s`);\n}\nawait browser.close();</code></pre>\n\n<pre><code class=\"language-bash\">node run.mjs naive &gt; naive.stdout 2&gt;&amp;1; cp naive.stdout artifacts/naive/run.stdout\nnode run.mjs hardened &gt; hardened.stdout 2&gt;&amp;1; cp hardened.stdout artifacts/hardened/run.stdout</code></pre>\n\n<p>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:</p>\n\n<pre><code class=\"language-text\">mode=hardened chromium=151.0.7922.34\n\n[allowed]\n  licence     i1:200@0.0s r1:200@5.0s r1:200@10.0s\n  keystatus   usable -&gt; usable -&gt; usable  expiration=NaN\n  playback    playing=1 waitingforkey=1 currentTime=11.98s at 12.0s\n  user error  none\n\n[denied]\n  licence     i1:403@0.0s\n  keystatus     expiration=-\n  playback    playing=0 waitingforkey=1 currentTime=0s at 2.0s\n  user error  DRM-403-NOT-ENTITLED \"This title is not in your plan.\" action=show-upgrade\n\n[outage]\n  licence     i1:200@0.0s r1:503@5.0s r2:503@6.0s r3:503@7.0s r4:200@9.0s\n  keystatus   usable -&gt; usable  expiration=NaN\n  playback    playing=1 waitingforkey=1 currentTime=11.97s at 12.0s\n  user error  none\n\n[expired]\n  licence     i1:200@0.0s r1:200@5.0s r1:200@10.0s r1:401@15.0s\n  keystatus   usable -&gt; usable -&gt; usable -&gt; (none)  expiration=NaN\n  playback    playing=1 waitingforkey=2 currentTime=15.17s at 20.0s\n  user error  DRM-401-EXPIRED \"Your rental has ended.\" action=offer-rent-again\n  session     closed (closed-by-application) at 15.0s\n\n[expired-ignored]\n  licence     i1:200@0.0s r1:200@5.0s r1:200@10.0s r1:401@15.0s\n  keystatus   usable -&gt; usable -&gt; usable  expiration=NaN\n  playback    playing=1 waitingforkey=1 currentTime=20.01s at 20.0s\n  user error  none\n  ignored     renewal-refused-ignored at 15.0s</code></pre>\n\n<p>The naive run printed the same outcomes, with timings at most a tenth of a second apart.</p>\n\n<p><strong>Entitled.</strong> One licence, two renewals, each <code>usable</code>. In all ten sessions across both modes, a <code>waitingforkey</code> fired 17 to 51 milliseconds in, before the first licence response and before <code>play()</code>. An alert on every <code>waitingforkey</code> fires on every encrypted start.</p>\n\n<p><strong>Not entitled.</strong> One 403, no retry, and <code>DRM-403-NOT-ENTITLED</code> with the upgrade action. Assert on that error object; there is no frozen video to assert on.</p>\n\n<p><strong>Outage.</strong> 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 <code>waiting</code> followed the first <code>playing</code>, 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.</p>\n\n<p><strong>Expired.</strong> Entitlement ended at 12 seconds; the 15-second renewal got 401 <code>entitlement_expired</code>. The page showed the rent-again message and closed the session, whose <code>closed</code> promise resolved with <code>closed-by-application</code>. Key statuses went empty, a second <code>waitingforkey</code> fired, and <code>currentTime</code> stopped at 15.17 with <code>readyState</code> 2, about 0.17 seconds after the close. Assert a stop within a margin, not at an exact time.</p>\n\n<p><strong>Expired, enforcement off.</strong> 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 <code>expired</code> status for this; ClearKey cannot use it, so a passing test proves the page's policy, not the CDM's.</p>\n\n<h2 id=\"drm-redact-at-source\">Redact before the log line exists</h2>\n\n<p>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 <code>page.evaluate()</code>.</p>\n\n<pre><code class=\"language-javascript\">// Shared by the page and the licence server. Runs on every log entry before it\n// is written anywhere, including the console, so traces never see the raw value.\nconst DROP = new Set([\"authorization\", \"token\", \"k\", \"keys\", \"licence\", \"license\", \"body\", \"request\", \"headers\"]);\nconst B64URL_16 = /\\b[A-Za-z0-9_-]{22}\\b/g;          // a 16-byte value, base64url, no padding\nconst HEX_16 = /\\b[0-9a-fA-F]{32}\\b/g;                // the same value as hex\nconst BEARER = /Bearer\\s+[A-Za-z0-9._~+\\/=-]+/g;\nconst LAB_TOKEN = /LAB-FAKE-[A-Za-z0-9._-]+/g;\n\n// FNV-1a: a small lab-only correlation tag, not a cryptographic privacy boundary.\nexport const fingerprint = (s) =&gt; {\n  let h = 0x811c9dc5;\n  for (const c of s) h = Math.imul(h ^ c.charCodeAt(0), 0x01000193) &gt;&gt;&gt; 0;\n  return \"fp:\" + h.toString(16).padStart(8, \"0\");\n};\n\nconst scrub = (s) =&gt;\n  s.replace(BEARER, \"Bearer [REDACTED]\").replace(LAB_TOKEN, \"[REDACTED-TOKEN]\")\n   .replace(B64URL_16, (m) =&gt; fingerprint(m)).replace(HEX_16, (m) =&gt; fingerprint(m));\n\nexport function redact(value, key = \"\") {\n  if (DROP.has(key.toLowerCase())) return \"[REDACTED]\";\n  if (key === \"kid\" || key === \"kids\") return [].concat(value).map((v) =&gt; fingerprint(String(v)));\n  if (typeof value === \"string\") return scrub(value);\n  if (Array.isArray(value)) return value.map((v) =&gt; redact(v));\n  if (value &amp;&amp; typeof value === \"object\") {\n    return Object.fromEntries(Object.entries(value).map(([k, v]) =&gt; [k, redact(v, k)]));\n  }\n  return value;\n}</code></pre>\n\n<p>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 (<code>fp:4a7efe84</code> 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.</p>\n\n<p>Over-redaction is the cost. The first drop list included <code>message</code>, the EME event field, and blanked the viewer-facing text of every error: <code>\"message\":\"[REDACTED]\"</code>. Assert that the fields support needs survive. A redacted outage renewal:</p>\n\n<pre><code class=\"language-json\">{\"t\":5035,\"evt\":\"licence-response\",\"ct\":5,\"purpose\":\"renewal\",\"attempt\":1,\"status\":503,\"reason\":\"licence_unavailable\",\"headers\":\"[REDACTED]\",\"body\":\"[REDACTED]\"}</code></pre>\n\n<h2 id=\"drm-scan-all-encodings\">Scan for every secret in every encoding</h2>\n\n<p>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 <code>LAB-FAKE-</code> prefix finds every token minted during the run without storing any.</p>\n\n<pre><code class=\"language-javascript\">// Searches every artifact, and every entry inside every zip, for each lab\n// secret in each encoding it can take on the wire. Exit 1 on any hit.\n// Usage: node scan.mjs artifacts/hardened\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { execFileSync } from \"node:child_process\";\nimport { join } from \"node:path\";\n\nconst dir = process.argv[2];\nconst hex = (f) =&gt; readFile(f, \"utf8\").then((s) =&gt; s.trim());\nconst forms = (name, bytes) =&gt; [\n  [`${name}/hex`, Buffer.from(bytes.toString(\"hex\"))],\n  [`${name}/HEX`, Buffer.from(bytes.toString(\"hex\").toUpperCase())],\n  [`${name}/base64url`, Buffer.from(bytes.toString(\"base64url\"))],\n  [`${name}/base64`, Buffer.from(bytes.toString(\"base64\"))],\n  [`${name}/raw`, bytes],\n];\nconst signing = await hex(\"signing.hex\");\nconst needles = [\n  ...forms(\"key\", Buffer.from(await hex(\"key.hex\"), \"hex\")),\n  ...forms(\"kid\", Buffer.from(await hex(\"kid.hex\"), \"hex\")),\n  [\"token\", Buffer.from(\"LAB-FAKE-\")],\n  [\"signing-key\", Buffer.from(signing)],\n];\n\nasync function* walk(d) {\n  for (const e of await readdir(d, { withFileTypes: true })) {\n    const p = join(d, e.name);\n    if (e.isDirectory()) yield* walk(p);\n    else if (p.endsWith(\".zip\")) {\n      for (const entry of execFileSync(\"unzip\", [\"-Z1\", p], { encoding: \"utf8\" }).split(\"\\n\").filter(Boolean)) {\n        yield [`${p}!${entry}`, execFileSync(\"unzip\", [\"-p\", p, entry], { maxBuffer: 1 &lt;&lt; 28 })];\n      }\n    } else yield [p, await readFile(p)];\n  }\n}\n\nlet files = 0, hits = 0;\nfor await (const [name, buf] of walk(dir)) {\n  files++;\n  const found = needles.map(([label, n]) =&gt; {\n    let count = 0;\n    for (let i = buf.indexOf(n); i !== -1; i = buf.indexOf(n, i + 1)) count++;\n    return count ? `${label}x${count}` : null;\n  }).filter(Boolean);\n  if (found.length) { hits += found.length; console.log(`LEAK  ${name.slice(dir.length + 1)}  ${found.join(\" \")}`); }\n}\nconsole.log(`${files} files and zip entries scanned, ${needles.length} needles, ${hits ? `${hits} leak finding(s)` : \"0 leaks\"}`);\nprocess.exit(hits ? 1 : 0);</code></pre>\n\n<p>Against the naive artifacts it exits 1. The entitled case's lines, then the run's summary:</p>\n\n<pre><code class=\"language-text\">LEAK  allowed/console.log  key/base64urlx3 kid/base64urlx4 tokenx3\nLEAK  allowed/events.jsonl  key/base64urlx3 kid/base64urlx4 tokenx3\nLEAK  allowed/network.har  key/base64urlx3 kid/base64urlx7 tokenx5\nLEAK  allowed/server.log  tokenx3\nLEAK  allowed/trace.zip!trace.trace  key/base64urlx12 kid/base64urlx16 tokenx12\nLEAK  allowed/trace.zip!trace.network  tokenx3\nLEAK  allowed/trace.zip!resources/93bac8a010467dd15e386c3d1e6f0bfa57a57583.json  kid/base64urlx1 tokenx1\nLEAK  allowed/trace.zip!resources/969e21a56fa069fcbb0b5866c5ab478dc55a3331.mp4  kid/rawx1\nLEAK  allowed/trace.zip!resources/901f98224826dcb6b29ec99b99ffc4d2ee44ad7e.json  kid/base64urlx1\nLEAK  allowed/trace.zip!resources/6d17ff6ffcf5d37314f52a26851c72b9f6c03d2b.json  key/base64urlx1 kid/base64urlx1\n64 files and zip entries scanned, 12 needles, 94 leak finding(s)</code></pre>\n\n<p>Every key hit is base64url. A hex-only grep would have passed:</p>\n\n<pre><code class=\"language-bash\">KEY_HEX=$(cat key.hex)\nKEY_B64URL=$(xxd -r -p key.hex | base64 | tr '+/' '-_' | tr -d '=')\necho \"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 ' ')\"</code></pre>\n\n<pre><code class=\"language-text\">files with hex key: 0  files with base64url key: 12</code></pre>\n\n<p>Neither grep reaches the trace, where most hits are. The <code>kid/raw</code> hit in the <code>.mp4</code> resource is the media itself, captured by the trace.</p>\n\n<p>Hardened mode records the HAR with <code>content: \"omit\"</code> and a media-only <code>urlFilter</code>, and the trace with <code>snapshots: false</code>, which Playwright documents as also turning off network recording; that trade-off is covered in <a href=\"/blog/automation-tutorials/retain-ci-artifacts-explain-failures\">retaining CI artifacts that explain failures</a>. The first hardened run still failed:</p>\n\n<pre><code class=\"language-text\">LEAK  allowed/trace.zip!trace.trace  kid/base64urlx1 tokenx1\nLEAK  denied/trace.zip!trace.trace  kid/base64urlx1 tokenx1\nLEAK  expired/trace.zip!trace.trace  kid/base64urlx1 tokenx1\nLEAK  expired-ignored/trace.zip!trace.trace  kid/base64urlx1 tokenx1\nLEAK  outage/trace.zip!trace.trace  kid/base64urlx1 tokenx1\n36 files and zip entries scanned, 12 needles, 10 leak finding(s)</code></pre>\n\n<p>The token reached the trace through the test itself: that runner passed it to the page as an argument, and the trace records each <code>evaluateExpression</code> call with its arguments. The fix delivers it the way a real app gets it, from its backend:</p>\n\n<pre><code class=\"language-javascript\">// Before: the token is an argument, and the trace records every argument.\nawait page.evaluate((a) =&gt; window.start(a), { token, kid, naive, honourExpiry: c.honourExpiry ?? true });\n\n// After: the lab server hands the page its session, as the app's backend would.\nstate.session = { token, kid };\nawait page.evaluate((a) =&gt; window.start(a), { naive, honourExpiry: c.honourExpiry ?? true });</code></pre>\n\n<p>The hardened scan then exited 0:</p>\n\n<pre><code class=\"language-text\">36 files and zip entries scanned, 12 needles, 0 leaks</code></pre>\n\n<p>It proves absence only for the values it was given. Run it before the upload step and fail the job on exit 1.</p>\n\n<h2 id=\"drm-clearkey-limits\">Where ClearKey stops standing in for a real CDM</h2>\n\n<p>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.</p>\n\n<ul>\n<li><strong>Robustness.</strong> Only the empty string, defined as accepting any ability to decrypt and decode. A test cannot request, or be refused, a hardware-backed level.</li>\n<li><strong>Output protection.</strong> <code>getStatusForPolicy()</code> should always resolve <code>usable</code>, whatever <code>minHdcpVersion</code> is asked for. <code>output-restricted</code> did not appear in any run; HDCP needs the real device and display.</li>\n<li><strong>Expiry.</strong> <code>expiration</code> is always <code>NaN</code>, so duration rules are only as strong as the page.</li>\n<li><strong>Device identity.</strong> <code>distinctiveIdentifier: \"required\"</code> is unsupported. EME requires distinctive identifiers in key system messages to be encrypted with a timestamp or nonce, so real messages always differ.</li>\n<li><strong>Licence format.</strong> 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.</li>\n</ul>\n\n<p>Nor did the lab produce the <code>hardware-context-reset</code> 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.</p>\n\n<h2 id=\"drm-faq\">Questions about testing the licence path</h2>\n\n<h3 id=\"drm-faq-kid-secret\">Is a key ID a secret?</h3>\n<p>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.</p>\n\n<h3 id=\"drm-faq-401-vs-403\">Should a 401 from the licence server be retried?</h3>\n<p>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.</p>\n\n<h3 id=\"drm-faq-shaka-dashjs\">Does this change with Shaka Player or dash.js in place of raw EME?</h3>\n<p>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.</p>\n\n<h2 id=\"drm-references\">Specifications behind the licence tests</h2>\n<ul>\n<li><a href=\"https://www.w3.org/TR/encrypted-media-2/#clear-key\">W3C Encrypted Media Extensions, Clear Key</a>. Robustness, distinctive identifier, <code>getStatusForPolicy()</code> and <code>expiration</code> rules, and the licence request and licence formats.</li>\n<li><a href=\"https://www.w3.org/TR/encrypted-media-2/#dom-mediakeystatus\">EME, MediaKeyStatus</a>. <code>expired</code> requiring an expiration earlier than the current time; <code>output-restricted</code> and <code>output-downscaled</code>.</li>\n<li><a href=\"https://www.w3.org/TR/encrypted-media-2/#dom-mediakeysessionclosedreason\">EME, MediaKeySessionClosedReason</a>. <code>closed-by-application</code> for an explicit <code>close()</code>, and <code>hardware-context-reset</code>.</li>\n<li><a href=\"https://www.w3.org/TR/encrypted-media-2/#dom-mediakeys-getstatusforpolicy\">EME, getStatusForPolicy()</a>. The HDCP policy expressed as <code>minHdcpVersion</code>.</li>\n<li><a href=\"https://www.w3.org/TR/encrypted-media-2/#wait-for-key\">EME, Wait for Key</a>. The <code>waitingforkey</code> event and <code>readyState</code> at or below <code>HAVE_CURRENT_DATA</code> while playback is blocked on a key.</li>\n<li><a href=\"https://www.w3.org/TR/encrypted-media-2/#encrypt-identifiers\">EME, encrypt distinctive identifiers</a>. Distinctive identifiers in key system messages encrypted with a timestamp or nonce.</li>\n<li><a href=\"https://www.w3.org/TR/eme-initdata-keyids/\">W3C \"keyids\" Initialization Data Format</a>. The <code>kids</code> array of base64url key IDs used as initialisation data.</li>\n<li><a href=\"https://www.rfc-editor.org/rfc/rfc4648#section-5\">RFC 4648, section 5</a>. The URL-safe base64 alphabet and omitting padding when the length is known.</li>\n<li><a href=\"https://ffmpeg.org/ffmpeg-formats.html#MOV_002fMPEG_002d4_002fISOMBFF-muxers\">FFmpeg formats, mov/mp4 muxer</a>. <code>encryption_scheme</code> with <code>cenc-aes-ctr</code>, and <code>encryption_key</code> and <code>encryption_kid</code> in hex.</li>\n<li><a href=\"https://ffmpeg.org/ffmpeg-formats.html#mov_002fmp4_002f3gp\">FFmpeg formats, mov/mp4 demuxer</a>. <code>decryption_key</code> for decrypting CENC files, used to prove the lab media is encrypted.</li>\n<li><a href=\"https://playwright.dev/docs/api/class-browser\">Playwright Browser API, newContext</a>. <code>recordHar</code> with <code>content: \"omit\"</code> and <code>urlFilter</code>.</li>\n<li><a href=\"https://playwright.dev/docs/api/class-tracing\">Playwright Tracing API</a>. <code>snapshots.dom</code> capturing DOM snapshots and network activity.</li>\n</ul>\n\n<h2 id=\"drm-apply-today\">Add one leak gate and one refusal test today</h2>\n\n<ul>\n<li>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.</li>\n<li>Write the 403 case first: one licence request, no retry, and an error carrying a code, a message and an action.</li>\n<li>If your test hands a token to the browser through a <code>page.evaluate()</code> argument, move it behind a backend call and re-scan.</li>\n<li>Keep the outage case's redacted event log with each run; the <a href=\"/tools/diff-checker\">diff checker</a> compares two runs' renewal attempts line by line.</li>\n<li>Mark every rule that relies on CDM enforcement (duration, HDCP, robustness) as device-only in part 1's contract table.</li>\n</ul>\n"}