{"name":"rotate-shared-secret","title":"Rotate a shared secret","description":"Rotate a secret that services share without downtime: the receiver accepts the current key or a next key, with an empty value never matching; the next key is generated into a 0600 file and never printed; every sender moves to a secret store and is verified delivering; the old key is retired only after the receiver's handled requests in a fixed window match the senders' own delivery records exactly and a search finds no other caller; then the receiver is redeployed, the live domain is confirmed to serve the new build, and probes show the new key passing and the old key, a wrong key and no key refused. Symptoms: rotate the webhook secret, the shared key may have leaked, the key is a literal in a trigger or config file, change the token without breaking anything, who else calls with this key, retire the old secret. Placing a single credential is secure-credential-setup's; a change crossing code, schema and jobs is land-complex-change's.","compatibility":"A receiver you can redeploy and whose live domain can be traced to a deployment; senders that can read a secret store; request logs on the receiver and delivery records on each sender covering one window. A bash shell with openssl and curl. Output is the new key in place on every side, the old key refused, a reconciliation record and a probe record. No key value or hash appears in any output.","allowedTools":"Read Write Edit Grep Glob Bash","license":"MIT","kind":"requestOnly","useWhen":"rotating a key that services share, or retiring one that may have leaked or sits where it should not","group":"workflow","lifecycle":"release","version":"1.0.1","author":"crissmoldovan","install":["npx skills add crissmoldovan/agent-skills --skill rotate-shared-secret"],"asks":["Rotate the shared key between the scheduler and the web app without downtime. Make the app accept\nthe current key or a next one first, never print the new key, and before you retire the old one,\nshow me that every request the app handled in a fixed window matches a delivery the senders\nrecorded.","The webhook key is written as a literal in a database trigger definition. Move it into the\ndatabase's secret store as part of a rotation, and tell me who else could be calling the endpoint\nwith the old key.","You redeployed the receiver. Before you probe anything, show me that the live domain is serving the\nnew deployment and not the previous one."],"commands":["# Tracing off; refuse unless SCRATCH is your own directory, mode 700 (unset, a path is /next.key).\n# Then drop an earlier attempt's key, generate with no newline and check the length: a fresh key\n# and status 0, or no key file and a failure. Later writes and deletes spell it ${SCRATCH:?}.\numask 077\nset +x -o pipefail\nif [ -z \"$(find \"${SCRATCH:?}\" -maxdepth 0 -type d -user \"$(id -u)\" -perm 700 2>/dev/null)\" ]; then\n  echo \"REFUSED: SCRATCH is not a private directory of yours (mode 700); nothing was touched\"; false\nelif rm -f \"$SCRATCH/next.key\" \"$SCRATCH/next.key.tmp\" \\\n  && openssl rand -hex 32 | tr -d '\\n' > \"$SCRATCH/next.key.tmp\" \\\n  && [ \"$(wc -c < \"$SCRATCH/next.key.tmp\" | tr -d ' ')\" -eq 64 ] \\\n  && mv \"$SCRATCH/next.key.tmp\" \"$SCRATCH/next.key\"; then\n  ls -l \"$SCRATCH/next.key\"\nelse\n  rm -f \"$SCRATCH/next.key.tmp\"; echo \"GENERATION FAILED: no key was written\"; false\nfi\n\n# Compare two copies byte for byte: same, DIFFERENT or READ ERROR, never a hash or a key.\ncmp -s \"$SCRATCH/next.key\" \"$SCRATCH/next.copy\"\ncase $? in 0) echo same ;; 1) echo DIFFERENT; false ;; *) echo \"READ ERROR\"; false ;; esac\n\n# Step 4, before any sender drops the old key: a store that cannot be read back leaves the senders'\n# copies as the only readable ones. A new shell has lost step 2's umask, so set it again. Save the\n# old key raw, never printed: a new 0600 copy, or a failure that keeps any copy saved earlier. An\n# old.key that is a directory or a link is refused first: mv would put the copy inside it.\numask 077\nrm -f \"${SCRATCH:?}/old.key.tmp\"\nif [ -d \"$SCRATCH/old.key\" ] || [ -L \"$SCRATCH/old.key\" ]; then\n  echo \"OLD KEY NOT SAVED: old.key is a directory or a link; nothing was read\"; false\nelif <platform-cli> secrets get SHARED_KEY > \"${SCRATCH:?}/old.key.tmp\" && [ -s \"$SCRATCH/old.key.tmp\" ] \\\n  && mv \"${SCRATCH:?}/old.key.tmp\" \"$SCRATCH/old.key\"; then\n  ls -l \"$SCRATCH/old.key\"\nelse\n  rm -f \"${SCRATCH:?}/old.key.tmp\"; echo \"OLD KEY NOT SAVED: no new copy was written\"; false\nfi\n\n# The probes: define them again in every new shell. KIND is bearer or signing, with no default. A\n# bearer key travels in a header file; a signing key never travels, and only its signature is sent,\n# in the receiver's own header and scheme. Every probe gets a fresh body, a new timestamp and nonce\n# (adapt body to your receiver, keeping both wherever its scheme signs them), so a receiver that\n# refuses replays refuses a key, never a repeat. A probe sends nothing when its key file is missing,\n# empty or not a regular file, or its request cannot be built: a nonce, a timestamp or a signature\n# that failed. Every write starts from no file.\numask 077\nrm -f \"${SCRATCH:?}/wrong.key\"; printf '%064d' 0 > \"${SCRATCH:?}/wrong.key\"   # a wrong key of the right length\nsign() { node -e 'const c=require(\"crypto\"),f=require(\"fs\");process.stdout.write(c.createHmac(\"sha256\",f.readFileSync(process.argv[1])).update(f.readFileSync(process.argv[2])).digest(\"hex\"))' \"$1\" \"$2\"; }\nbody() { local n t; rm -f \"${SCRATCH:?}/probe.json\"; n=$(openssl rand -hex 16) && [ \"${#n}\" -eq 32 ] && t=$(date +%s) && [ \"$t\" -gt 0 ] 2>/dev/null && printf '{\"probe\":true,\"timestamp\":%s,\"nonce\":\"%s\"}' \"$t\" \"$n\" > \"${SCRATCH:?}/probe.json\"; }\nprobe() {  # probe <label> <key file, or none>\n  rm -f \"${SCRATCH:?}/probe.hdr\" \"$SCRATCH/probe.json\"\n  if [ \"$2\" != none ] && ! { [ -f \"$2\" ] && [ ! -L \"$2\" ] && [ -s \"$2\" ]; }; then\n    echo \"$1: NOTHING SENT: the key file is missing, empty or not a regular file\"; return 1\n  fi\n  case \"$KIND:$2\" in\n    bearer:none | signing:none) body && : > \"${SCRATCH:?}/probe.hdr\" ;;\n    bearer:*) body && { printf 'x-shared-key: '; cat \"$2\" && echo; } > \"${SCRATCH:?}/probe.hdr\" ;;\n    signing:*) body && { printf '<signature-header>: sha256='; sign \"$2\" \"$SCRATCH/probe.json\" && echo; } > \"${SCRATCH:?}/probe.hdr\" ;;\n    *) false ;;\n  esac || { echo \"$1: NOTHING SENT: KIND is unset, or the body, the key or the signature failed\"; return 1; }\n  curl -s -o /dev/null -w \"$1: %{http_code}\\n\" -H @\"$SCRATCH/probe.hdr\" --data-binary @\"$SCRATCH/probe.json\" \"https://<receiver>/<probe-path>\"\n}\n\n# Step 4, the old key still CURRENT and step 5's window not yet open: prove the copy. It must pass;\n# refused, the copy is not the key, and step 8's old-key probe is UNVERIFIED.\nprobe 'old key, before the senders move (must pass)' \"$SCRATCH/old.key\"\n\n# Step 8, the live domain on the promoted build: the new key passes; the old key, a wrong key and\n# no key are refused.\nprobe 'new key' \"$SCRATCH/next.key\"\nprobe 'old key' \"$SCRATCH/old.key\"\nprobe 'wrong key' \"$SCRATCH/wrong.key\"\nprobe 'no key' none\n\n# Remove every local copy, and check that none is left.\nrm -f \"${SCRATCH:?}/next.key\" \"$SCRATCH/next.copy\" \"$SCRATCH/old.key\" \"$SCRATCH/wrong.key\" \"$SCRATCH/probe.hdr\" \"$SCRATCH/probe.json\"\nls -A \"$SCRATCH\""],"documents":[{"path":"references/deploy-and-probe.md","slug":"deploy-and-probe","title":"Deploy and probe","body":"# Deploy and probe\n\nHow the key moves into each store without being seen, how to know the live domain is serving what\nwas deployed, how to probe it, and how to leave nothing behind.\n\n## Moving the value: standard input or a file, never an argument\n\nEvery store the key enters gets it from the key file, on standard input or as a file the tool reads\nitself:\n\n```bash\n<platform-cli> secrets set SHARED_KEY_NEXT < \"$SCRATCH/next.key\"\n```\n\nThree channels leak, and none of them announces it:\n\n- **A command-line argument** is visible in the process list to other users of the machine, and is\n  saved in shell history.\n- **A tool-call parameter** — handing the value to an agent tool that runs a query or sets a\n  setting — is saved in the session transcript.\n- **The value sent through SQL** reaches whatever on that connection records statements or\n  parameters, and the client's history keeps it too. That includes every way of sending it: typing\n  it into the statement, string formatting, a template literal, client-side variables such as\n  `psql`'s `:'name'`, and a bound parameter. A client-side variable is not a separate channel. The\n  client expands it into the statement before sending it, so the server receives the literal value\n  exactly as if it had been typed.\n\nWhere a store cannot take a value except as an argument, place it by hand through the store's own\ninterface, as `secure-credential-setup` describes, and record that it was done that way.\n\n## When the store is inside a database\n\nA database's own secret store is usually written with SQL, and SQL is where a value most easily\nends up in a log. A bound parameter keeps it out of the statement text but not out of every record:\nthe server's statement and parameter logging, an audit or plan-logging extension, a pooler or proxy\nin between, a driver's debug log or an APM agent's query capture in the client. Each has its own\nswitch, or none, and showing that every one is off is rarely possible. So **the key does not go in\nthrough SQL at all** — not in the statement text, not through a client-side variable, not as a\nbound parameter.\n\nIt goes in through the store's own interface: a command-line tool or API that takes the value as\ndata, from standard input or a file, and builds no SQL from it on your side. Where the store has no\nsuch interface, place it by hand through the store's console, as `secure-credential-setup`\ndescribes, and record that it was done that way.\n\n## The newline trap\n\n`openssl rand -hex 32 > file` writes a trailing newline. One store keeps it and another trims it,\nand the sender and the receiver now hold different keys. Every delivery fails, and both sides look\ncorrectly configured. Generate without it, under `pipefail`, into a temporary file whose exact length\nis checked before it is renamed into place — the example in the skill does this — and when two\ncopies must agree, compare them byte for byte with `cmp -s` inside the shell, tracing off, and\nprint only the verdict: same, different, or a read error that is never taken for either.\n\n## Confirming that the live domain moved\n\nA deploy that succeeded is not a live domain serving it. On some platforms a production redeploy\ncreates a new deployment while the custom domain stays on the previous one until it is promoted, and\nthe deploy command still reports success. Until the domain moves, the old code — and the old key —\nare what callers reach.\n\nAfter every redeploy:\n\n1. Note the deployment id the redeploy produced.\n2. Ask the platform which deployment the live domain's alias points to now.\n3. If the two differ, promote the new deployment to the domain, and ask again.\n\nA check that does not depend on the platform: have each build serve its own commit id on a harmless\npath, and read it through the live domain.\n\n```bash\ncurl -s \"https://<receiver>/<version-path>\"   # must print the commit that was just deployed\n```\n\nProbe only after the live domain is confirmed to be on the new deployment. A probe against the\nprevious build proves something about the previous build.\n\nThe same holds instance by instance. When `NEXT` is first set (step 3), every backend must accept\nboth keys before any sender moves, not only the backend that answered: a sender moved while one\nbackend still lacks `NEXT` fails on every request routed to it. When `CURRENT` is promoted (step\n6), `NEXT` stays set until every backend logs the new key as `current`: a backend the promotion\nmissed still accepts it as `next`, but only while `NEXT` is there. The evidence is the same as for\nthe retirement below — each backend probed on its own, the platform's list of instances with each\none's version, or answers that identify the backend.\n\n## The probes\n\nUse the harmless probe request from the prerequisites: one that authenticates and changes nothing.\n\nA bearer probe sends the key itself, in a header, through every layer a delivery passes: the\nsender's instrumentation, a proxy, WAF or CDN, an APM agent, the receiver's access log. Any of them\nthat records request headers keeps the key before the receiver's slot-only log applies. So before\nthe first probe, each layer on the path is shown not to record that header, or to redact it. If\nthat cannot be shown, the rotation stops there. A signing key, which never travels, does not need\nthis.\n\nA bearer key is read from a header file, so that it is not on the command line. For a **signing\nkey**, nothing travels: the key never leaves its file. Each probe signs its body with the key file\ninside a program, and only the signature is sent, in the receiver's own header and scheme.\n\nEvery probe gets a fresh body: a new timestamp and a new nonce, in the body or wherever the\nreceiver's scheme signs them. A receiver that refuses replays refuses a body it has already seen,\nwhatever key signed it. Never send the old key's probe after the promotion with the body that was\naccepted before it: the receiver refuses it as a replay even while the old key is still valid, and\nthat refusal reads as a retirement that took. Each probe, the old key's after the promotion\nincluded, gets its own timestamp and nonce. For the same reason a probe sends nothing when its key\nfile is missing, empty or not a regular file, or its body or signature failed: an empty signature,\na signature made with an empty key, or a header with no key in it is refused for the wrong reason\ntoo. The body's nonce and timestamp are each checked before the body is written, so a clock that\nfailed sends nothing, never a body with no timestamp in it.\n\nThe skill's example defines `probe`, which does all of this for either kind of key, chosen by\n`KIND` (`bearer` or `signing`, with no default). Define it again in every new shell: a new shell\nhas lost it, and with it the `umask 077` that creates each header file 0600. In order — the first\nbefore any sender drops the old key (step 4), the rest after the promotion (step 8):\n\n```bash\nprobe 'old key, before the senders move (must pass)' \"$SCRATCH/old.key\"\nprobe 'new key' \"$SCRATCH/next.key\"\nprobe 'old key' \"$SCRATCH/old.key\"\nprobe 'wrong key' \"$SCRATCH/wrong.key\"\nprobe 'no key' none\n```\n\nExpected: the new key gets the probe's success code; the old key, the wrong key and no key get the\nreceiver's refusal code. The old-key probe is the only direct evidence that the retirement took:\nthe settings can say the old key is gone while a stale replica, a region the redeploy has not\nreached, or a promotion that landed on part of the fleet still accepts it. So it is mandatory\nwherever it can be done safely. It uses the old key's private copy, saved and proven before any\nsender dropped it; probe every replica or region that can be addressed on its own.\n\nA refusal means something only if a probe built the same way — the same copy of the key, the same\nheader or signature scheme, over a fresh body — was accepted before. A secret command that adds a\nnewline or prints metadata around the value writes a different key into the copy; the signature\nmade from it, or the header built from it, is refused whether the old key was retired or not, and\nthe refusal reads as a retirement that took. So export the raw value where the store has a mode\nfor it, and prove the copy before any sender drops the old key (step 4): while the old key is still\n`CURRENT` and before the reconciliation window opens, probe with it as you will afterwards — the\nsame header or signature scheme, over a fresh body — and see it accepted. Save it then, not at the promotion: a store that cannot be read back — many\nplatforms keep secrets write-only — leaves the senders' copies as the only readable ones, and\nmoving the senders removes them. Save it under a `umask 077` set in the same shell, since a new\nshell has lost step 2's, and refuse an `old.key` that is a directory or a link: `mv` would put the\ncopy inside it, and the cleanup would leave it there. A copy that was not accepted then cannot show anything now.\n\nWhere the backends sit behind a load balancer and cannot be addressed one by one, a probe through\nthe live domain reaches whichever backend answered, and nothing more. One probe proves nothing about\nthe rest. The retirement is verified only by deployment evidence that every backend runs the new\nconfiguration — the platform's own list of instances, each with its deployment or configuration\nversion — or by probes shown to have reached every backend, through answers that identify the\nbackend that gave them. Without either, it is **UNVERIFIED**.\n\nWhen it cannot be done safely — no copy of the old key could be saved and accepted before the\nsenders dropped it, or there is no probe without side effects — the retirement is **UNVERIFIED**.\nRecord exactly that, with the reason. Never write \"the old key is refused\" on the strength of the\nsettings alone.\n\nRecord the status codes, not the response bodies, which may echo request headers.\n\n## Cleaning up\n\n```bash\nrm -f \"${SCRATCH:?}/next.key\" \"$SCRATCH/next.copy\" \"$SCRATCH/old.key\" \"$SCRATCH/wrong.key\" \"$SCRATCH/probe.hdr\" \"$SCRATCH/probe.json\"\nls -A \"$SCRATCH\"\n```\n\nThe listing must show none of them. Because no command ever carried the key as an argument, shell\nhistory holds nothing to remove; if one did, the rotation is not finished until that history is\ncleared and the key is rotated again. The record of the rotation holds dates, the window, the\ncounts, the search, the deployment ids and the probe codes — never the key and never its hash.\n","bodyHtml":"<h2 id=\"deploy-and-probe\">Deploy and probe</h2>\n<p>How the key moves into each store without being seen, how to know the live domain is serving what\nwas deployed, how to probe it, and how to leave nothing behind.</p>\n<h3 id=\"moving-the-value-standard-input-or-a-file-never-an-argument\">Moving the value: standard input or a file, never an argument</h3>\n<p>Every store the key enters gets it from the key file, on standard input or as a file the tool reads\nitself:</p>\n<pre><code class=\"language-bash\">&lt;platform-cli&gt; secrets set SHARED_KEY_NEXT &lt; &quot;$SCRATCH/next.key&quot;\n</code></pre>\n<p>Three channels leak, and none of them announces it:</p>\n<ul>\n<li><strong>A command-line argument</strong> is visible in the process list to other users of the machine, and is\nsaved in shell history.</li>\n<li><strong>A tool-call parameter</strong> — handing the value to an agent tool that runs a query or sets a\nsetting — is saved in the session transcript.</li>\n<li><strong>The value sent through SQL</strong> reaches whatever on that connection records statements or\nparameters, and the client&#39;s history keeps it too. That includes every way of sending it: typing\nit into the statement, string formatting, a template literal, client-side variables such as\n<code>psql</code>&#39;s <code>:&#39;name&#39;</code>, and a bound parameter. A client-side variable is not a separate channel. The\nclient expands it into the statement before sending it, so the server receives the literal value\nexactly as if it had been typed.</li>\n</ul>\n<p>Where a store cannot take a value except as an argument, place it by hand through the store&#39;s own\ninterface, as <code>secure-credential-setup</code> describes, and record that it was done that way.</p>\n<h3 id=\"when-the-store-is-inside-a-database\">When the store is inside a database</h3>\n<p>A database&#39;s own secret store is usually written with SQL, and SQL is where a value most easily\nends up in a log. A bound parameter keeps it out of the statement text but not out of every record:\nthe server&#39;s statement and parameter logging, an audit or plan-logging extension, a pooler or proxy\nin between, a driver&#39;s debug log or an APM agent&#39;s query capture in the client. Each has its own\nswitch, or none, and showing that every one is off is rarely possible. So <strong>the key does not go in\nthrough SQL at all</strong> — not in the statement text, not through a client-side variable, not as a\nbound parameter.</p>\n<p>It goes in through the store&#39;s own interface: a command-line tool or API that takes the value as\ndata, from standard input or a file, and builds no SQL from it on your side. Where the store has no\nsuch interface, place it by hand through the store&#39;s console, as <code>secure-credential-setup</code>\ndescribes, and record that it was done that way.</p>\n<h3 id=\"the-newline-trap\">The newline trap</h3>\n<p><code>openssl rand -hex 32 &gt; file</code> writes a trailing newline. One store keeps it and another trims it,\nand the sender and the receiver now hold different keys. Every delivery fails, and both sides look\ncorrectly configured. Generate without it, under <code>pipefail</code>, into a temporary file whose exact length\nis checked before it is renamed into place — the example in the skill does this — and when two\ncopies must agree, compare them byte for byte with <code>cmp -s</code> inside the shell, tracing off, and\nprint only the verdict: same, different, or a read error that is never taken for either.</p>\n<h3 id=\"confirming-that-the-live-domain-moved\">Confirming that the live domain moved</h3>\n<p>A deploy that succeeded is not a live domain serving it. On some platforms a production redeploy\ncreates a new deployment while the custom domain stays on the previous one until it is promoted, and\nthe deploy command still reports success. Until the domain moves, the old code — and the old key —\nare what callers reach.</p>\n<p>After every redeploy:</p>\n<ol>\n<li>Note the deployment id the redeploy produced.</li>\n<li>Ask the platform which deployment the live domain&#39;s alias points to now.</li>\n<li>If the two differ, promote the new deployment to the domain, and ask again.</li>\n</ol>\n<p>A check that does not depend on the platform: have each build serve its own commit id on a harmless\npath, and read it through the live domain.</p>\n<pre><code class=\"language-bash\">curl -s &quot;https://&lt;receiver&gt;/&lt;version-path&gt;&quot;   # must print the commit that was just deployed\n</code></pre>\n<p>Probe only after the live domain is confirmed to be on the new deployment. A probe against the\nprevious build proves something about the previous build.</p>\n<p>The same holds instance by instance. When <code>NEXT</code> is first set (step 3), every backend must accept\nboth keys before any sender moves, not only the backend that answered: a sender moved while one\nbackend still lacks <code>NEXT</code> fails on every request routed to it. When <code>CURRENT</code> is promoted (step\n6), <code>NEXT</code> stays set until every backend logs the new key as <code>current</code>: a backend the promotion\nmissed still accepts it as <code>next</code>, but only while <code>NEXT</code> is there. The evidence is the same as for\nthe retirement below — each backend probed on its own, the platform&#39;s list of instances with each\none&#39;s version, or answers that identify the backend.</p>\n<h3 id=\"the-probes\">The probes</h3>\n<p>Use the harmless probe request from the prerequisites: one that authenticates and changes nothing.</p>\n<p>A bearer probe sends the key itself, in a header, through every layer a delivery passes: the\nsender&#39;s instrumentation, a proxy, WAF or CDN, an APM agent, the receiver&#39;s access log. Any of them\nthat records request headers keeps the key before the receiver&#39;s slot-only log applies. So before\nthe first probe, each layer on the path is shown not to record that header, or to redact it. If\nthat cannot be shown, the rotation stops there. A signing key, which never travels, does not need\nthis.</p>\n<p>A bearer key is read from a header file, so that it is not on the command line. For a <strong>signing\nkey</strong>, nothing travels: the key never leaves its file. Each probe signs its body with the key file\ninside a program, and only the signature is sent, in the receiver&#39;s own header and scheme.</p>\n<p>Every probe gets a fresh body: a new timestamp and a new nonce, in the body or wherever the\nreceiver&#39;s scheme signs them. A receiver that refuses replays refuses a body it has already seen,\nwhatever key signed it. Never send the old key&#39;s probe after the promotion with the body that was\naccepted before it: the receiver refuses it as a replay even while the old key is still valid, and\nthat refusal reads as a retirement that took. Each probe, the old key&#39;s after the promotion\nincluded, gets its own timestamp and nonce. For the same reason a probe sends nothing when its key\nfile is missing, empty or not a regular file, or its body or signature failed: an empty signature,\na signature made with an empty key, or a header with no key in it is refused for the wrong reason\ntoo. The body&#39;s nonce and timestamp are each checked before the body is written, so a clock that\nfailed sends nothing, never a body with no timestamp in it.</p>\n<p>The skill&#39;s example defines <code>probe</code>, which does all of this for either kind of key, chosen by\n<code>KIND</code> (<code>bearer</code> or <code>signing</code>, with no default). Define it again in every new shell: a new shell\nhas lost it, and with it the <code>umask 077</code> that creates each header file 0600. In order — the first\nbefore any sender drops the old key (step 4), the rest after the promotion (step 8):</p>\n<pre><code class=\"language-bash\">probe &#39;old key, before the senders move (must pass)&#39; &quot;$SCRATCH/old.key&quot;\nprobe &#39;new key&#39; &quot;$SCRATCH/next.key&quot;\nprobe &#39;old key&#39; &quot;$SCRATCH/old.key&quot;\nprobe &#39;wrong key&#39; &quot;$SCRATCH/wrong.key&quot;\nprobe &#39;no key&#39; none\n</code></pre>\n<p>Expected: the new key gets the probe&#39;s success code; the old key, the wrong key and no key get the\nreceiver&#39;s refusal code. The old-key probe is the only direct evidence that the retirement took:\nthe settings can say the old key is gone while a stale replica, a region the redeploy has not\nreached, or a promotion that landed on part of the fleet still accepts it. So it is mandatory\nwherever it can be done safely. It uses the old key&#39;s private copy, saved and proven before any\nsender dropped it; probe every replica or region that can be addressed on its own.</p>\n<p>A refusal means something only if a probe built the same way — the same copy of the key, the same\nheader or signature scheme, over a fresh body — was accepted before. A secret command that adds a\nnewline or prints metadata around the value writes a different key into the copy; the signature\nmade from it, or the header built from it, is refused whether the old key was retired or not, and\nthe refusal reads as a retirement that took. So export the raw value where the store has a mode\nfor it, and prove the copy before any sender drops the old key (step 4): while the old key is still\n<code>CURRENT</code> and before the reconciliation window opens, probe with it as you will afterwards — the\nsame header or signature scheme, over a fresh body — and see it accepted. Save it then, not at the promotion: a store that cannot be read back — many\nplatforms keep secrets write-only — leaves the senders&#39; copies as the only readable ones, and\nmoving the senders removes them. Save it under a <code>umask 077</code> set in the same shell, since a new\nshell has lost step 2&#39;s, and refuse an <code>old.key</code> that is a directory or a link: <code>mv</code> would put the\ncopy inside it, and the cleanup would leave it there. A copy that was not accepted then cannot show anything now.</p>\n<p>Where the backends sit behind a load balancer and cannot be addressed one by one, a probe through\nthe live domain reaches whichever backend answered, and nothing more. One probe proves nothing about\nthe rest. The retirement is verified only by deployment evidence that every backend runs the new\nconfiguration — the platform&#39;s own list of instances, each with its deployment or configuration\nversion — or by probes shown to have reached every backend, through answers that identify the\nbackend that gave them. Without either, it is <strong>UNVERIFIED</strong>.</p>\n<p>When it cannot be done safely — no copy of the old key could be saved and accepted before the\nsenders dropped it, or there is no probe without side effects — the retirement is <strong>UNVERIFIED</strong>.\nRecord exactly that, with the reason. Never write &quot;the old key is refused&quot; on the strength of the\nsettings alone.</p>\n<p>Record the status codes, not the response bodies, which may echo request headers.</p>\n<h3 id=\"cleaning-up\">Cleaning up</h3>\n<pre><code class=\"language-bash\">rm -f &quot;${SCRATCH:?}/next.key&quot; &quot;$SCRATCH/next.copy&quot; &quot;$SCRATCH/old.key&quot; &quot;$SCRATCH/wrong.key&quot; &quot;$SCRATCH/probe.hdr&quot; &quot;$SCRATCH/probe.json&quot;\nls -A &quot;$SCRATCH&quot;\n</code></pre>\n<p>The listing must show none of them. Because no command ever carried the key as an argument, shell\nhistory holds nothing to remove; if one did, the rotation is not finished until that history is\ncleared and the key is rotated again. The record of the rotation holds dates, the window, the\ncounts, the search, the deployment ids and the probe codes — never the key and never its hash.</p>\n","words":1832},{"path":"references/dual-key-receiver.md","slug":"dual-key-receiver","title":"The dual-key receiver","body":"# The dual-key receiver\n\nThe overlap that makes a rotation free of downtime lives in the receiver: for as long as the senders\nare moving, it accepts either key. The code is short. The rule that makes it safe is one line, and\nit is the line most often left out.\n\n## The comparison\n\n```ts\nimport { createHash, timingSafeEqual } from 'node:crypto';\n\nexport type Slot = 'current' | 'next';\n\n// An empty value never matches anything — not an empty header, not a missing one.\nfunction sameKey(presented: string, expected: string): boolean {\n  if (presented === '' || expected === '') return false;\n  // Hash both sides so the buffers have equal length and the comparison takes constant time.\n  const a = createHash('sha256').update(presented).digest();\n  const b = createHash('sha256').update(expected).digest();\n  return timingSafeEqual(a, b);\n}\n\nexport function matchSlot(\n  presented: string | undefined,\n  current: string | undefined,\n  next: string | undefined,\n): Slot | null {\n  // No current key configured: refuse everything, a next key included. Fail closed.\n  if ((current ?? '') === '') return null;\n  const key = presented ?? '';\n  if (sameKey(key, current ?? '')) return 'current';\n  if (sameKey(key, next ?? '')) return 'next';\n  return null;\n}\n```\n\nIn the handler:\n\n```ts\nconst slot = matchSlot(\n  request.headers.get('x-shared-key') ?? undefined,\n  process.env.SHARED_KEY,\n  process.env.SHARED_KEY_NEXT,\n);\nif (slot === null) return new Response('unauthorized', { status: 401 });\n// The slot and the sender's delivery id, never the key.\nlog.info({ event: 'shared-key-auth', slot, delivery: request.headers.get('x-delivery-id') ?? null });\n```\n\nThe same shape works for a signed webhook: verify the signature with `CURRENT`, then with `NEXT`\nwhen it is non-empty, and record which one verified.\n\n### Why the empty-value rule is the one that matters\n\nWithout the guard, an unset `NEXT` reads as the empty string, a request with no key reads as the\nempty string, and the two are equal. The receiver then accepts every unauthenticated request for\nexactly as long as no rotation is in progress — which is most of the time. Nothing fails, and\nnothing in normal traffic shows it.\n\nThe same rule covers `CURRENT` itself: with no current key configured, the receiver refuses\neverything — a request carrying the next key included. A receiver left half-configured, with\n`NEXT` set and `CURRENT` missing, must fail closed rather than run on the next key alone.\n\n### Log the slot, and the delivery id\n\nLogging which slot matched is what turns the reconciliation from a count into a check. Once every\nsender has moved, every handled request should say `next`. One that says `current` is a caller still\non the old key, found before the old key is retired rather than after. The slot also shows the\npromotion landing: with `NEXT` still set to the new key, an instance that has the new `CURRENT`\nlogs it as `current`, and one the change has not reached logs it as `next`.\n\nThe slot cannot see an unknown caller that already holds the next key. The delivery id can: where\neach sender puts a unique id on every request and records it, the ids the receiver logs are matched\none to one against the senders' records, and an id no sender issued is a caller nobody mapped. A\nmatch by count alone is aggregate evidence, because a lost delivery and an unknown request can\ncancel.\n\n### Configuration with whitespace\n\nA configured key with leading or trailing whitespace — usually a newline from the file it was\ngenerated into — is a configuration error. Report it loudly at start-up, without the value. Do not\ntrim it silently: trimming hides the mismatch on this side while a sender may still send the other\nform.\n\n## The tests\n\n| Case | `CURRENT` | `NEXT` | Presented | Expected |\n|---|---|---|---|---|\n| Current key | k1 | unset | k1 | `current` |\n| Next key | k1 | k2 | k2 | `next` |\n| Current key during overlap | k1 | k2 | k1 | `current` |\n| Wrong key | k1 | k2 | x | refused |\n| Missing header, `NEXT` unset | k1 | unset | none | refused |\n| Empty header, `NEXT` unset | k1 | unset | empty | refused |\n| Empty header, `NEXT` set to empty | k1 | empty | empty | refused |\n| Nothing configured | unset | unset | empty | refused |\n| Nothing configured, any key | unset | unset | k1 | refused |\n| `CURRENT` unset, `NEXT` set | unset | k2 | k2 | refused |\n| `CURRENT` empty, `NEXT` set | empty | k2 | k2 | refused |\n| A prefix of the key | k1 | unset | k1 without its last character | refused |\n| New key while the promotion lands | k2 | k2 | k2 | `current` |\n| Old key after promotion | k2 | unset | k1 | refused |\n\nUse made-up values in tests, never a real key.\n\n## Arming them\n\nBreak the empty-value rule — delete the `=== ''` guard — and run the tests. The two \"empty header\"\ncases and the \"missing header\" case must fail. Then delete the current-key guard: the two \"`CURRENT`\nunset or empty, `NEXT` set\" cases must fail. Restore the file from a byte copy and confirm the\nguard is back by searching for it before running the tests again. A suite that stays green with the\nguard deleted is not testing the guard.\n","bodyHtml":"<h2 id=\"the-dual-key-receiver\">The dual-key receiver</h2>\n<p>The overlap that makes a rotation free of downtime lives in the receiver: for as long as the senders\nare moving, it accepts either key. The code is short. The rule that makes it safe is one line, and\nit is the line most often left out.</p>\n<h3 id=\"the-comparison\">The comparison</h3>\n<pre><code class=\"language-ts\">import { createHash, timingSafeEqual } from &#39;node:crypto&#39;;\n\nexport type Slot = &#39;current&#39; | &#39;next&#39;;\n\n// An empty value never matches anything — not an empty header, not a missing one.\nfunction sameKey(presented: string, expected: string): boolean {\n  if (presented === &#39;&#39; || expected === &#39;&#39;) return false;\n  // Hash both sides so the buffers have equal length and the comparison takes constant time.\n  const a = createHash(&#39;sha256&#39;).update(presented).digest();\n  const b = createHash(&#39;sha256&#39;).update(expected).digest();\n  return timingSafeEqual(a, b);\n}\n\nexport function matchSlot(\n  presented: string | undefined,\n  current: string | undefined,\n  next: string | undefined,\n): Slot | null {\n  // No current key configured: refuse everything, a next key included. Fail closed.\n  if ((current ?? &#39;&#39;) === &#39;&#39;) return null;\n  const key = presented ?? &#39;&#39;;\n  if (sameKey(key, current ?? &#39;&#39;)) return &#39;current&#39;;\n  if (sameKey(key, next ?? &#39;&#39;)) return &#39;next&#39;;\n  return null;\n}\n</code></pre>\n<p>In the handler:</p>\n<pre><code class=\"language-ts\">const slot = matchSlot(\n  request.headers.get(&#39;x-shared-key&#39;) ?? undefined,\n  process.env.SHARED_KEY,\n  process.env.SHARED_KEY_NEXT,\n);\nif (slot === null) return new Response(&#39;unauthorized&#39;, { status: 401 });\n// The slot and the sender&#39;s delivery id, never the key.\nlog.info({ event: &#39;shared-key-auth&#39;, slot, delivery: request.headers.get(&#39;x-delivery-id&#39;) ?? null });\n</code></pre>\n<p>The same shape works for a signed webhook: verify the signature with <code>CURRENT</code>, then with <code>NEXT</code>\nwhen it is non-empty, and record which one verified.</p>\n<h4 id=\"why-the-empty-value-rule-is-the-one-that-matters\">Why the empty-value rule is the one that matters</h4>\n<p>Without the guard, an unset <code>NEXT</code> reads as the empty string, a request with no key reads as the\nempty string, and the two are equal. The receiver then accepts every unauthenticated request for\nexactly as long as no rotation is in progress — which is most of the time. Nothing fails, and\nnothing in normal traffic shows it.</p>\n<p>The same rule covers <code>CURRENT</code> itself: with no current key configured, the receiver refuses\neverything — a request carrying the next key included. A receiver left half-configured, with\n<code>NEXT</code> set and <code>CURRENT</code> missing, must fail closed rather than run on the next key alone.</p>\n<h4 id=\"log-the-slot-and-the-delivery-id\">Log the slot, and the delivery id</h4>\n<p>Logging which slot matched is what turns the reconciliation from a count into a check. Once every\nsender has moved, every handled request should say <code>next</code>. One that says <code>current</code> is a caller still\non the old key, found before the old key is retired rather than after. The slot also shows the\npromotion landing: with <code>NEXT</code> still set to the new key, an instance that has the new <code>CURRENT</code>\nlogs it as <code>current</code>, and one the change has not reached logs it as <code>next</code>.</p>\n<p>The slot cannot see an unknown caller that already holds the next key. The delivery id can: where\neach sender puts a unique id on every request and records it, the ids the receiver logs are matched\none to one against the senders&#39; records, and an id no sender issued is a caller nobody mapped. A\nmatch by count alone is aggregate evidence, because a lost delivery and an unknown request can\ncancel.</p>\n<h4 id=\"configuration-with-whitespace\">Configuration with whitespace</h4>\n<p>A configured key with leading or trailing whitespace — usually a newline from the file it was\ngenerated into — is a configuration error. Report it loudly at start-up, without the value. Do not\ntrim it silently: trimming hides the mismatch on this side while a sender may still send the other\nform.</p>\n<h3 id=\"the-tests\">The tests</h3>\n<table>\n<thead>\n<tr>\n<th>Case</th>\n<th><code>CURRENT</code></th>\n<th><code>NEXT</code></th>\n<th>Presented</th>\n<th>Expected</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>Current key</td>\n<td>k1</td>\n<td>unset</td>\n<td>k1</td>\n<td><code>current</code></td>\n</tr>\n<tr>\n<td>Next key</td>\n<td>k1</td>\n<td>k2</td>\n<td>k2</td>\n<td><code>next</code></td>\n</tr>\n<tr>\n<td>Current key during overlap</td>\n<td>k1</td>\n<td>k2</td>\n<td>k1</td>\n<td><code>current</code></td>\n</tr>\n<tr>\n<td>Wrong key</td>\n<td>k1</td>\n<td>k2</td>\n<td>x</td>\n<td>refused</td>\n</tr>\n<tr>\n<td>Missing header, <code>NEXT</code> unset</td>\n<td>k1</td>\n<td>unset</td>\n<td>none</td>\n<td>refused</td>\n</tr>\n<tr>\n<td>Empty header, <code>NEXT</code> unset</td>\n<td>k1</td>\n<td>unset</td>\n<td>empty</td>\n<td>refused</td>\n</tr>\n<tr>\n<td>Empty header, <code>NEXT</code> set to empty</td>\n<td>k1</td>\n<td>empty</td>\n<td>empty</td>\n<td>refused</td>\n</tr>\n<tr>\n<td>Nothing configured</td>\n<td>unset</td>\n<td>unset</td>\n<td>empty</td>\n<td>refused</td>\n</tr>\n<tr>\n<td>Nothing configured, any key</td>\n<td>unset</td>\n<td>unset</td>\n<td>k1</td>\n<td>refused</td>\n</tr>\n<tr>\n<td><code>CURRENT</code> unset, <code>NEXT</code> set</td>\n<td>unset</td>\n<td>k2</td>\n<td>k2</td>\n<td>refused</td>\n</tr>\n<tr>\n<td><code>CURRENT</code> empty, <code>NEXT</code> set</td>\n<td>empty</td>\n<td>k2</td>\n<td>k2</td>\n<td>refused</td>\n</tr>\n<tr>\n<td>A prefix of the key</td>\n<td>k1</td>\n<td>unset</td>\n<td>k1 without its last character</td>\n<td>refused</td>\n</tr>\n<tr>\n<td>New key while the promotion lands</td>\n<td>k2</td>\n<td>k2</td>\n<td>k2</td>\n<td><code>current</code></td>\n</tr>\n<tr>\n<td>Old key after promotion</td>\n<td>k2</td>\n<td>unset</td>\n<td>k1</td>\n<td>refused</td>\n</tr>\n</tbody></table>\n<p>Use made-up values in tests, never a real key.</p>\n<h3 id=\"arming-them\">Arming them</h3>\n<p>Break the empty-value rule — delete the <code>=== &#39;&#39;</code> guard — and run the tests. The two &quot;empty header&quot;\ncases and the &quot;missing header&quot; case must fail. Then delete the current-key guard: the two &quot;<code>CURRENT</code>\nunset or empty, <code>NEXT</code> set&quot; cases must fail. Restore the file from a byte copy and confirm the\nguard is back by searching for it before running the tests again. A suite that stays green with the\nguard deleted is not testing the guard.</p>\n","words":905},{"path":"references/proving-no-other-caller.md","slug":"proving-no-other-caller","title":"Proving no other caller","body":"# Proving no other caller\n\nRetiring the old key refuses every caller still using it. The senders on the map have moved; the\nquestion is whether the map was complete. Memory says it was. This page turns that into a\nmeasurement, and says what the measurement cannot see.\n\n## The reconciliation\n\nThere are two kinds of match, and the record says which one it has.\n\n- **One to one, by a per-request id: proof.** Each sender puts a unique delivery id on every request\n  — a header — and records it; the receiver logs it beside the slot. The ids are then compared\n  with their counts, not as sets: each id appears as many times at the receiver as in the senders'\n  records — normally exactly once on each side. An id the senders never issued is another caller;\n  an id that never arrived is a lost delivery; an id the receiver logged more often than it was\n  sent is a replay, or another caller reusing it. A set comparison collapses that last one into its\n  original, so it is not one to one. Add the id in step 4 of the rotation, while each sender is\n  being changed anyway.\n\n  Extract each side's ids into a file with a checked command — under `pipefail`, its status read —\n  and confirm every sender on the map contributed some. Then compare, failing closed: an empty or\n  unreadable file, or a count that failed, is no evidence, never a match. So is any row that is not\n  an id — blank, holding whitespace, or a placeholder such as `null`, `-` or `\\N` that an\n  extraction prints for a missing header. Two extractions that failed the same way agree with each\n  other, and that agreement is not a match.\n\n  ```bash\n  # One id per line on each side. Only \"ids match one to one\" is a match. Add your log tool's own\n  # placeholder for a missing value to the list; grep exits 1 only when it read both files and found\n  # no blank, whitespace or placeholder row.\n  set -o pipefail\n  if ! { grep -q . receiver-ids.txt && grep -q . sender-ids.txt; }; then\n    echo \"NO EVIDENCE: an id file is missing or empty\"; false\n  elif grep -Eiq -- '^$|[[:space:]]|^(null|nil|none|undefined|nan|-|\\\\N|\\(null\\)|\"\")$' \\\n         receiver-ids.txt sender-ids.txt; [ $? -ne 1 ]; then\n    echo \"NO EVIDENCE: a row is blank, holds whitespace or is a placeholder such as null\"; false\n  elif ! { sort receiver-ids.txt | uniq -c > receiver.counts \\\n           && sort sender-ids.txt | uniq -c > sender.counts; }; then\n    echo \"NO EVIDENCE: counting the ids failed\"; false\n  elif diff receiver.counts sender.counts; then\n    echo \"ids match one to one\"\n  else\n    echo \"MISMATCH: the lines above differ, a repeat included\"; false\n  fi\n  ```\n\n- **By count and endpoints: aggregate evidence, not proof.** Without an id, the steps below compare\n  totals and the first and last second. A delivery lost in the middle of the window and an unknown\n  request in the middle of the window cancel exactly: the totals agree and the endpoints do not\n  move. Comparing counts per short interval — per minute, per hour — narrows it, because a\n  cancellation must then fall inside one interval, but it is still aggregate. Say so in the record.\n\nWhichever kind it is, the slot rule holds on its own: every caller that was never moved still\nholds the old key, so any request matching `current` is one, whatever the counts say. What the slot\ncannot catch is an unknown caller that already holds the next key, such as a service reading the\nsame store; only the ids, or the counts, can show that one.\n\n1. **Fix the window.** It starts after the last sender on the map moved to the next key, and it is\n   longer than the slowest sender's cycle: a job that runs weekly needs more than a week. Write the\n   start and end down in UTC before counting anything.\n2. **Count the receiver's side.** The requests it authenticated and handled in the window, with the\n   first and the last timestamp, to the second. If it logs the slot, count by slot.\n3. **Count the senders' side.** Each sender's own record of what it delivered in the same window —\n   its delivery log, its job history, its outbound request table — with the first and last\n   timestamp of each. Use the senders' records, not the receiver's: the point is two independent\n   accounts of the same traffic.\n4. **Match exactly, and name the kind of match.** With ids: every id with the same count on both\n   sides. Without: the receiver's count equals the senders' total, and the receiver's first and\n   last second equal the earliest and latest of the senders' — recorded as aggregate evidence, with\n   per-interval counts where the logs allow. With slots logged, every handled request matched\n   `next`.\n\nWhat each mismatch means:\n\n| Observation | Meaning |\n|---|---|\n| Receiver count above the senders' total | Something else is calling. Find it before retiring anything. |\n| Receiver count below the senders' total | Deliveries were lost, or a log has a gap. Explain it before trusting the match. |\n| Counts equal, first or last second differs | Possibly a lost delivery and an unknown caller cancelling out. Match request by request. |\n| Counts and endpoints equal, no ids | Aggregate evidence only. A cancellation in the middle of the window is not ruled out; the record says so. |\n| An id at the receiver that no sender issued | Another caller, holding a key that works. Find it before retiring anything. |\n| An id logged at the receiver more often than the senders recorded it | A replay, or another caller reusing the id. Find it before retiring anything. |\n| A blank row, or a placeholder such as `null` or `-`, among the ids | A request that carried no id, or an extraction that missed it. No evidence until it is explained. |\n| Any request matching `current` | A caller on the old key, whatever the counts say. |\n\nWhere clock skew or latency puts one request on either side of a second boundary, match that request\nindividually and record the explanation. Do not relax the rule to \"within a few seconds\" in general:\nthat is exactly the tolerance in which a stray caller hides.\n\n## Where else senders hide\n\nCode search finds the senders someone wrote down in a repository. Search there, and then in the\nplaces it cannot see:\n\n- every repository that could hold a client — not only the receiver's and the known senders';\n- CI and deployment secrets that hold the old value under any name;\n- schedulers and cron configurations, including ones defined in a hosted dashboard;\n- database functions, triggers and scheduled jobs whose definitions can hold a literal;\n- third-party services configured with the receiver's URL — webhook dashboards, monitoring probes,\n  automation tools;\n- runbooks, wikis and READMEs with example requests that someone may have turned into a script;\n- secret stores, searched by setting name for every place the old value was copied to.\n\nRecord the search terms — the header name, the setting names, the receiver's path and host — and\nevery place searched, with what was found. A search reported without its terms cannot be repeated.\n\n## What the evidence cannot see\n\nState each of these beside the result. They are not reasons to skip the reconciliation; they are\nwhat a reader needs in order to know how far to trust it.\n\n- **Retention.** A log kept for seven days cannot show a caller that runs monthly. The window can be\n  no longer than the shorter of the two sides' retention.\n- **Per-call caps.** Some log tools return at most a fixed number of entries per call and need\n  paging. A count exactly equal to the cap is a page, not a total.\n- **Sampling.** A log that samples requests cannot be reconciled one for one. Find an unsampled\n  source, or say that the match is approximate.\n- **No caller identity.** Many request logs carry no caller identity, so a match is by count and\n  time, not by name. Two callers can still be told apart by the slot they matched, which is why the\n  receiver logs it.\n- **Time zones.** Normalise both sides to UTC before comparing seconds.\n\n## After the retirement\n\nFor one full sender cycle after the old key is retired, watch the receiver's refusals. A burst of\nauthentication failures from one source is a caller the reconciliation missed. Seeing it within the\nhour costs a quick fix; seeing it when its owner reports a broken integration costs an incident.\n","bodyHtml":"<h2 id=\"proving-no-other-caller\">Proving no other caller</h2>\n<p>Retiring the old key refuses every caller still using it. The senders on the map have moved; the\nquestion is whether the map was complete. Memory says it was. This page turns that into a\nmeasurement, and says what the measurement cannot see.</p>\n<h3 id=\"the-reconciliation\">The reconciliation</h3>\n<p>There are two kinds of match, and the record says which one it has.</p>\n<ul>\n<li><p><strong>One to one, by a per-request id: proof.</strong> Each sender puts a unique delivery id on every request\n— a header — and records it; the receiver logs it beside the slot. The ids are then compared\nwith their counts, not as sets: each id appears as many times at the receiver as in the senders&#39;\nrecords — normally exactly once on each side. An id the senders never issued is another caller;\nan id that never arrived is a lost delivery; an id the receiver logged more often than it was\nsent is a replay, or another caller reusing it. A set comparison collapses that last one into its\noriginal, so it is not one to one. Add the id in step 4 of the rotation, while each sender is\nbeing changed anyway.</p>\n<p>Extract each side&#39;s ids into a file with a checked command — under <code>pipefail</code>, its status read —\nand confirm every sender on the map contributed some. Then compare, failing closed: an empty or\nunreadable file, or a count that failed, is no evidence, never a match. So is any row that is not\nan id — blank, holding whitespace, or a placeholder such as <code>null</code>, <code>-</code> or <code>\\N</code> that an\nextraction prints for a missing header. Two extractions that failed the same way agree with each\nother, and that agreement is not a match.</p>\n<pre><code class=\"language-bash\"># One id per line on each side. Only &quot;ids match one to one&quot; is a match. Add your log tool&#39;s own\n# placeholder for a missing value to the list; grep exits 1 only when it read both files and found\n# no blank, whitespace or placeholder row.\nset -o pipefail\nif ! { grep -q . receiver-ids.txt &amp;&amp; grep -q . sender-ids.txt; }; then\n  echo &quot;NO EVIDENCE: an id file is missing or empty&quot;; false\nelif grep -Eiq -- &#39;^$|[[:space:]]|^(null|nil|none|undefined|nan|-|\\\\N|\\(null\\)|&quot;&quot;)$&#39; \\\n       receiver-ids.txt sender-ids.txt; [ $? -ne 1 ]; then\n  echo &quot;NO EVIDENCE: a row is blank, holds whitespace or is a placeholder such as null&quot;; false\nelif ! { sort receiver-ids.txt | uniq -c &gt; receiver.counts \\\n         &amp;&amp; sort sender-ids.txt | uniq -c &gt; sender.counts; }; then\n  echo &quot;NO EVIDENCE: counting the ids failed&quot;; false\nelif diff receiver.counts sender.counts; then\n  echo &quot;ids match one to one&quot;\nelse\n  echo &quot;MISMATCH: the lines above differ, a repeat included&quot;; false\nfi\n</code></pre>\n</li>\n<li><p><strong>By count and endpoints: aggregate evidence, not proof.</strong> Without an id, the steps below compare\ntotals and the first and last second. A delivery lost in the middle of the window and an unknown\nrequest in the middle of the window cancel exactly: the totals agree and the endpoints do not\nmove. Comparing counts per short interval — per minute, per hour — narrows it, because a\ncancellation must then fall inside one interval, but it is still aggregate. Say so in the record.</p>\n</li>\n</ul>\n<p>Whichever kind it is, the slot rule holds on its own: every caller that was never moved still\nholds the old key, so any request matching <code>current</code> is one, whatever the counts say. What the slot\ncannot catch is an unknown caller that already holds the next key, such as a service reading the\nsame store; only the ids, or the counts, can show that one.</p>\n<ol>\n<li><strong>Fix the window.</strong> It starts after the last sender on the map moved to the next key, and it is\nlonger than the slowest sender&#39;s cycle: a job that runs weekly needs more than a week. Write the\nstart and end down in UTC before counting anything.</li>\n<li><strong>Count the receiver&#39;s side.</strong> The requests it authenticated and handled in the window, with the\nfirst and the last timestamp, to the second. If it logs the slot, count by slot.</li>\n<li><strong>Count the senders&#39; side.</strong> Each sender&#39;s own record of what it delivered in the same window —\nits delivery log, its job history, its outbound request table — with the first and last\ntimestamp of each. Use the senders&#39; records, not the receiver&#39;s: the point is two independent\naccounts of the same traffic.</li>\n<li><strong>Match exactly, and name the kind of match.</strong> With ids: every id with the same count on both\nsides. Without: the receiver&#39;s count equals the senders&#39; total, and the receiver&#39;s first and\nlast second equal the earliest and latest of the senders&#39; — recorded as aggregate evidence, with\nper-interval counts where the logs allow. With slots logged, every handled request matched\n<code>next</code>.</li>\n</ol>\n<p>What each mismatch means:</p>\n<table>\n<thead>\n<tr>\n<th>Observation</th>\n<th>Meaning</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>Receiver count above the senders&#39; total</td>\n<td>Something else is calling. Find it before retiring anything.</td>\n</tr>\n<tr>\n<td>Receiver count below the senders&#39; total</td>\n<td>Deliveries were lost, or a log has a gap. Explain it before trusting the match.</td>\n</tr>\n<tr>\n<td>Counts equal, first or last second differs</td>\n<td>Possibly a lost delivery and an unknown caller cancelling out. Match request by request.</td>\n</tr>\n<tr>\n<td>Counts and endpoints equal, no ids</td>\n<td>Aggregate evidence only. A cancellation in the middle of the window is not ruled out; the record says so.</td>\n</tr>\n<tr>\n<td>An id at the receiver that no sender issued</td>\n<td>Another caller, holding a key that works. Find it before retiring anything.</td>\n</tr>\n<tr>\n<td>An id logged at the receiver more often than the senders recorded it</td>\n<td>A replay, or another caller reusing the id. Find it before retiring anything.</td>\n</tr>\n<tr>\n<td>A blank row, or a placeholder such as <code>null</code> or <code>-</code>, among the ids</td>\n<td>A request that carried no id, or an extraction that missed it. No evidence until it is explained.</td>\n</tr>\n<tr>\n<td>Any request matching <code>current</code></td>\n<td>A caller on the old key, whatever the counts say.</td>\n</tr>\n</tbody></table>\n<p>Where clock skew or latency puts one request on either side of a second boundary, match that request\nindividually and record the explanation. Do not relax the rule to &quot;within a few seconds&quot; in general:\nthat is exactly the tolerance in which a stray caller hides.</p>\n<h3 id=\"where-else-senders-hide\">Where else senders hide</h3>\n<p>Code search finds the senders someone wrote down in a repository. Search there, and then in the\nplaces it cannot see:</p>\n<ul>\n<li>every repository that could hold a client — not only the receiver&#39;s and the known senders&#39;;</li>\n<li>CI and deployment secrets that hold the old value under any name;</li>\n<li>schedulers and cron configurations, including ones defined in a hosted dashboard;</li>\n<li>database functions, triggers and scheduled jobs whose definitions can hold a literal;</li>\n<li>third-party services configured with the receiver&#39;s URL — webhook dashboards, monitoring probes,\nautomation tools;</li>\n<li>runbooks, wikis and READMEs with example requests that someone may have turned into a script;</li>\n<li>secret stores, searched by setting name for every place the old value was copied to.</li>\n</ul>\n<p>Record the search terms — the header name, the setting names, the receiver&#39;s path and host — and\nevery place searched, with what was found. A search reported without its terms cannot be repeated.</p>\n<h3 id=\"what-the-evidence-cannot-see\">What the evidence cannot see</h3>\n<p>State each of these beside the result. They are not reasons to skip the reconciliation; they are\nwhat a reader needs in order to know how far to trust it.</p>\n<ul>\n<li><strong>Retention.</strong> A log kept for seven days cannot show a caller that runs monthly. The window can be\nno longer than the shorter of the two sides&#39; retention.</li>\n<li><strong>Per-call caps.</strong> Some log tools return at most a fixed number of entries per call and need\npaging. A count exactly equal to the cap is a page, not a total.</li>\n<li><strong>Sampling.</strong> A log that samples requests cannot be reconciled one for one. Find an unsampled\nsource, or say that the match is approximate.</li>\n<li><strong>No caller identity.</strong> Many request logs carry no caller identity, so a match is by count and\ntime, not by name. Two callers can still be told apart by the slot they matched, which is why the\nreceiver logs it.</li>\n<li><strong>Time zones.</strong> Normalise both sides to UTC before comparing seconds.</li>\n</ul>\n<h3 id=\"after-the-retirement\">After the retirement</h3>\n<p>For one full sender cycle after the old key is retired, watch the receiver&#39;s refusals. A burst of\nauthentication failures from one source is a caller the reconciliation missed. Seeing it within the\nhour costs a quick fix; seeing it when its owner reports a broken integration costs an incident.</p>\n","words":1449}],"body":"# Rotate a shared secret\n\nA shared secret is easy to change and hard to change safely. The receiver and every sender have to\nagree at every moment, or deliveries fail. The new value has to travel to each of them without\npassing through a terminal, a transcript or a log. And the old value can be retired only once\nnothing is still using it — which nobody actually knows, because the list of senders is a memory,\nnot a measurement.\n\nEach of those goes wrong quietly. With the next key unset, \"the current key or the next key\"\naccepts an empty header too. A redeploy reports success while the domain serves the previous build.\nA code search finds two senders, and a third, a job configured in a dashboard years ago, stops\nworking the morning after.\n\nThis skill rotates with an overlap, so nothing fails while the senders move, and it retires the old\nkey on evidence: the receiver's handled requests matched one for one against the senders' own\ndelivery records, plus a search, with the limits of both stated.\n\n### What this skill does not own\n\n| The job | Whose it is | What this skill does with it |\n|---|---|---|\n| Placing one credential in a secret store without the value entering the transcript | `secure-credential-setup` | Follows its placement rule for every store the key enters. |\n| Finding every reader of a key in the code | `investigate-codebase` | Asks it for the search, then adds the places code search cannot see. |\n| What a change to the receiver would affect | `blast-area` | Consults it when the receiver's auth code is shared by other routes. |\n| A change crossing code, schema and scheduled jobs | `land-complex-change` | Runs inside its budget when the rotation is part of a larger change. |\n| Writing in a repository other than this one | `work-in-external-repo` | Hands over when a sender lives in another repository. |\n| Telling the reader where the rotation stands | `report-progress` | Supplies the step, the window, the counts and the probe results. |\n\nInstall the companions with `npx skills add crissmoldovan/agent-skills`.\n\n## When to Use\n\n- A key shared between services you control — a webhook signing key, a service-to-service bearer\n  key, an internal API key — has to change: a suspected leak, someone leaving, a scheduled\n  rotation, or the key found somewhere it should not be.\n- A key is held as a literal — in a configuration file, in a database trigger's definition, in a\n  job's arguments — and has to move to a secret store. Moving it is a rotation: the old value has\n  been readable wherever it sat.\n- Nobody can say with evidence who else calls the receiver with the key.\n\nNot for a credential you hold against someone else's service: rotate that in the provider's\nconsole and place it with `secure-credential-setup`. Not for asymmetric signing keys that carry a\nkey id: publishing the new public key beside the old one is already the overlap this skill builds by\nhand. And where a short outage is acceptable and the only sender deploys with the receiver, a plain\nswap is simpler.\n\n## Prerequisites\n\n1. **The secret's map.** Every receiver, every known sender, and where each holds the key today:\n   an environment variable, a secret store, a configuration file, a literal in a trigger or job\n   definition, a CI secret, a third-party dashboard.\n   **Complete when:** each holder is listed with its location, and the list says where it came\n   from.\n2. **A secret store every sender can read.** The receiver's platform secrets, a database's own\n   secret store, a vault — one per side is fine.\n   **Complete when:** each sender has a store it can read at run time, named.\n3. **A receiver you can redeploy and trace.** A deploy path, and a way to ask which deployment the\n   live domain serves right now.\n   **Complete when:** you have read the live domain's current deployment id once.\n4. **Logs on both sides, with their limits known.** The receiver's handled-request log with\n   timestamps, and each sender's own record of what it delivered. Their retention, any per-call\n   entry cap in the tools that read them, and whether they identify the caller.\n   **Complete when:** each log is named with its retention and its tooling limits.\n5. **A harmless probe.** A request that authenticates and changes nothing, or changes something\n   idempotent.\n   **Complete when:** the probe request is written down and its expected success code known.\n6. **A private scratch directory.** Outside any repository, created under `umask 077`.\n   **Complete when:** it exists, is yours with mode 700, and `SCRATCH` names it in your shell.\n7. **A request path that keeps no copy of a bearer key.** Any layer that records request headers —\n   the sender's instrumentation, a proxy, WAF or CDN, an APM agent, an access log — keeps the key.\n   **Complete when:** before the first probe, every layer on the path is shown not to record that\n   header, or to redact it; if that cannot be shown, the rotation stops. A signing key never\n   travels.\n\n## Procedure\n\n**The every-instance rule.** The receiver and each sender can run as several instances — replicas,\nregions, a rollout part-way through — and evidence from one instance says nothing about the others.\nSo every claim below about what the receiver accepts, or what a sender sends, covers every instance,\non one of three kinds of evidence: each instance addressed and checked on its own; the platform's\nown list of instances, each with its deployment or configuration version; or answers — probe\nresponses, delivery records — that identify the instance that gave them and, between them, name\nevery one. Short of that, a step that needs it waits, and a retirement already done is recorded as\n**UNVERIFIED**.\n\n1. **Make the receiver accept the current key or a next key, and test it.** Two settings, `CURRENT`\n   and `NEXT`. A request passes when its key equals `CURRENT`, or when `NEXT` is non-empty and its\n   key equals `NEXT`. An empty value never matches anything: an unset `NEXT` must not let an empty\n   or missing header through, and an unset `CURRENT` refuses everything. Compare in constant time,\n   and log which slot matched — `current` or `next` — never the key. Test every case, arm the tests\n   by breaking the empty-value rule, then deploy with `NEXT` unset\n   ([the dual-key receiver](references/dual-key-receiver.md)).\n   **Complete when:** the tests pass and were watched failing with the empty-value rule broken, and\n   the live domain serves the build that contains them.\n\n2. **Generate the next key into a 0600 file, and never print it.** `umask 077`, then write the\n   output of a cryptographic random source to a temporary file, with no trailing newline, check its\n   exact length, and only then rename it into place: a generator that failed must leave no key file\n   at all, never an empty one that a store would accept. Never echo it, open it in a viewer, pass\n   it as a command-line argument, or hand it to a tool call as a parameter: each of those puts it in\n   a terminal, a process list or a transcript. When two copies must be the same, compare them byte\n   for byte with tracing off, printing only same, different or read error — never a hash.\n   **Complete when:** the key file exists with mode 0600 and its exact expected length, and no output\n   of any command so far contains the key, its hash or its length.\n\n3. **Set it on the receiver as `NEXT`, redeploy, and confirm the live domain moved.** Feed the file\n   to the platform's secret command on standard input. Redeploy, then read the deployment id the\n   live domain serves and compare it with the one the redeploy produced; promote it if they differ\n   ([deploy and probe](references/deploy-and-probe.md)). Probe with the next key. A sender moved\n   while one backend still lacks `NEXT` fails on every request routed there, so no sender moves\n   until the overlap holds on every receiver instance, by the every-instance rule.\n   **Complete when:** the live domain serves the new deployment, and both the current key and the\n   next key are accepted on every receiver instance, not only on the one that answered a probe.\n\n4. **Move every sender to read the key from a secret store, then verify its delivery.** First, keep\n   a private copy of the old key for step 8, before any sender drops it: a receiver store that\n   cannot be read back leaves the senders' copies as the only readable ones, and this step removes\n   them. Save it into a 0600 file from a copy that can still be read, never printed, in the store's\n   raw form where it has one, under a `umask 077` set again, since a new shell has lost step 2's. A\n   command that adds a newline or wraps the value in metadata writes a different key, and a probe\n   with it is refused for the wrong reason. So prove the copy: while the old key is still `CURRENT`,\n   before step 5's window opens, probe with it as step 8 will — the same header or signature\n   scheme, over a fresh body — and see it accepted. Then, one sender at a time: put the next key into its store from the file,\n   change the sender to read it from the store instead of wherever it held the old one, deploy, and\n   watch a real delivery arrive and log the `next` slot at the receiver. That delivery shows one\n   instance moved; a quiet instance still on the old value fails only once the old key is retired,\n   so every instance of the sender is shown reading the store, by the every-instance rule. A key\n   written as a literal in a definition — a trigger, a job, a configuration file — is readable by\n   anyone who can read that definition, and changing it means redefining code; reading it from a\n   store fixes both. Remove the literal and any fallback to it. While the sender is being changed\n   anyway, have it send a unique delivery id on every request and record it, so that step 5 can\n   match requests one to one. A store written with SQL takes the key through its own interface or\n   by hand, never through SQL ([deploy and probe](references/deploy-and-probe.md)).\n   **Complete when:** the old key is in a 0600 file that the receiver accepted before any sender\n   dropped it, or the record says why no such copy could be had; every sender on the map has\n   delivered at least one request that the receiver logged as matching `next`; every instance of\n   every sender is shown reading the store, and no sender still holds the old value anywhere.\n\n5. **Prove no other caller exists before retiring the old key.** Pick a fixed window that starts\n   after the last sender moved and is longer than the slowest sender's cycle. Count the receiver's\n   handled requests in the window and the senders' own delivery records for the same window. They\n   must match exactly: the same count, and the same first and last second. Where the senders send a\n   delivery id and the receiver logs it, match the ids one to one instead: that is proof, provided\n   each id is counted — as many times on one side as on the other, normally once — so that a\n   repeated request cannot hide behind its original, and every row is an id: a blank row or a\n   placeholder such as `null` is no evidence. Without ids, the count and endpoints are aggregate\n   evidence, not proof — a lost delivery and an unknown request in the middle of the window cancel\n   exactly — and the record says so. If the receiver logs the slot, every request in the window\n   must have matched `next`. Then search code and configuration for any other sender —\n   repositories, CI, schedulers, database definitions, provider dashboards, runbooks with example\n   requests. State what the evidence cannot see: the log retention, any paging the tools needed,\n   and whether the logs identify the caller at all\n   ([proving no other caller](references/proving-no-other-caller.md)).\n   **Complete when:** the ids match one to one, or the counts and the first and last seconds match\n   exactly and the record calls that aggregate evidence; the search terms and places are recorded\n   with what they found; and the caveats are written beside the result.\n\n6. **Promote `NEXT` to `CURRENT`, and remove `NEXT` only once the new `CURRENT` holds everywhere.**\n   With the old key's copy kept from step 4, set `CURRENT` from the next key's file, on standard\n   input, leaving `NEXT` in place, and redeploy as in step 7. An instance the change reached logs\n   the new key as `current`; one it missed still accepts it as `next`, so no sender fails\n   meanwhile. Delete `NEXT` only when every receiver instance logs the new key as `current`, by the\n   every-instance rule.\n   **Complete when:** every receiver instance matched the new key as `current` while `NEXT` was\n   still set, `NEXT` was deleted after that, and the old key's copy from step 4 is still in its\n   0600 file, or the record says why there is none.\n\n7. **Redeploy, and verify that the live domain moved.** A production redeploy can leave a custom\n   domain pointing at the previous build, and until it moves, the old key still works there. Read\n   the deployment id behind the live domain, and promote the new deployment if they differ.\n   **Complete when:** the live domain's deployment id is the new deployment's, read after the\n   redeploy.\n\n8. **Probe the live domain: the new key passes; the old key, a wrong key and no key are refused.**\n   Send the harmless probe four times. How a key is presented depends on the receiver:\n   - **A bearer key** travels in a header, read from a header file rather than written on the\n     command line.\n   - **A signing key never travels.** Sign a fresh probe body with each key file — the new key,\n     the old key, a wrong key — reading the key inside the program, and send only the signature,\n     in the receiver's own header and scheme. Fresh means a new timestamp and nonce every time: a\n     receiver that refuses replays refuses a body it has seen whatever key signed it, and that\n     refusal reads as a retirement that took. The fourth probe sends no signature. The\n     `x-shared-key` header in the examples is for bearer keys only.\n\n   The example's `probe` sends either kind, by `KIND`, and sends nothing when it cannot build the\n   request — a key file that is missing, empty or not a regular file included: an empty key makes a\n   blank header or a signature with no key, refused for the wrong reason. Define it again in a new\n   shell, which also sets `umask 077` again.\n\n   The old-key probe is not optional. A stale replica, a region or instance the redeploy has not\n   reached, or a promotion that landed on part of the fleet still accepts the old key, and nothing\n   else shows it. The probes cover every receiver instance, by the every-instance rule. Where\n   replicas or regions can be addressed one by one, probe each of them. Where they sit behind a load\n   balancer and cannot, a probe through the live domain reaches one backend and says nothing of the\n   rest: the retirement stays **UNVERIFIED** unless every backend is covered, by the platform's list\n   of instances or by answers that identify each backend. Where the old key cannot be probed safely\n   at all — no copy of it was accepted before the promotion, or no probe is free of side effects —\n   the retirement is **UNVERIFIED** too, with the reason. The record never says the old key is\n   refused on less than that.\n   **Complete when:** the record shows the new key accepted and the old key, the wrong key and the\n   missing key refused, each with its status code, for every backend — each probed directly, or all\n   covered by the every-instance rule's other evidence — or the retirement recorded as UNVERIFIED\n   with the reason.\n\n9. **Delete every local copy, and record what happened.** Remove the next, old and wrong key files,\n   the probe's header and body files and any copy made for comparison, and confirm they are gone.\n   Write the record: the dates, the window, the counts, the search, the deployment ids, the probes\n   and the caveats. No key value and no hash.\n   **Complete when:** no copy of the key exists outside the secret stores, and the record is\n   written.\n\n## Usage Examples\n\n```text\nRotate the shared key between the scheduler and the web app without downtime. Make the app accept\nthe current key or a next one first, never print the new key, and before you retire the old one,\nshow me that every request the app handled in a fixed window matches a delivery the senders\nrecorded.\n```\n\n```text\nThe webhook key is written as a literal in a database trigger definition. Move it into the\ndatabase's secret store as part of a rotation, and tell me who else could be calling the endpoint\nwith the old key.\n```\n\n```text\nYou redeployed the receiver. Before you probe anything, show me that the live domain is serving the\nnew deployment and not the previous one.\n```\n\n```bash\n# Tracing off; refuse unless SCRATCH is your own directory, mode 700 (unset, a path is /next.key).\n# Then drop an earlier attempt's key, generate with no newline and check the length: a fresh key\n# and status 0, or no key file and a failure. Later writes and deletes spell it ${SCRATCH:?}.\numask 077\nset +x -o pipefail\nif [ -z \"$(find \"${SCRATCH:?}\" -maxdepth 0 -type d -user \"$(id -u)\" -perm 700 2>/dev/null)\" ]; then\n  echo \"REFUSED: SCRATCH is not a private directory of yours (mode 700); nothing was touched\"; false\nelif rm -f \"$SCRATCH/next.key\" \"$SCRATCH/next.key.tmp\" \\\n  && openssl rand -hex 32 | tr -d '\\n' > \"$SCRATCH/next.key.tmp\" \\\n  && [ \"$(wc -c < \"$SCRATCH/next.key.tmp\" | tr -d ' ')\" -eq 64 ] \\\n  && mv \"$SCRATCH/next.key.tmp\" \"$SCRATCH/next.key\"; then\n  ls -l \"$SCRATCH/next.key\"\nelse\n  rm -f \"$SCRATCH/next.key.tmp\"; echo \"GENERATION FAILED: no key was written\"; false\nfi\n\n# Compare two copies byte for byte: same, DIFFERENT or READ ERROR, never a hash or a key.\ncmp -s \"$SCRATCH/next.key\" \"$SCRATCH/next.copy\"\ncase $? in 0) echo same ;; 1) echo DIFFERENT; false ;; *) echo \"READ ERROR\"; false ;; esac\n\n# Step 4, before any sender drops the old key: a store that cannot be read back leaves the senders'\n# copies as the only readable ones. A new shell has lost step 2's umask, so set it again. Save the\n# old key raw, never printed: a new 0600 copy, or a failure that keeps any copy saved earlier. An\n# old.key that is a directory or a link is refused first: mv would put the copy inside it.\numask 077\nrm -f \"${SCRATCH:?}/old.key.tmp\"\nif [ -d \"$SCRATCH/old.key\" ] || [ -L \"$SCRATCH/old.key\" ]; then\n  echo \"OLD KEY NOT SAVED: old.key is a directory or a link; nothing was read\"; false\nelif <platform-cli> secrets get SHARED_KEY > \"${SCRATCH:?}/old.key.tmp\" && [ -s \"$SCRATCH/old.key.tmp\" ] \\\n  && mv \"${SCRATCH:?}/old.key.tmp\" \"$SCRATCH/old.key\"; then\n  ls -l \"$SCRATCH/old.key\"\nelse\n  rm -f \"${SCRATCH:?}/old.key.tmp\"; echo \"OLD KEY NOT SAVED: no new copy was written\"; false\nfi\n\n# The probes: define them again in every new shell. KIND is bearer or signing, with no default. A\n# bearer key travels in a header file; a signing key never travels, and only its signature is sent,\n# in the receiver's own header and scheme. Every probe gets a fresh body, a new timestamp and nonce\n# (adapt body to your receiver, keeping both wherever its scheme signs them), so a receiver that\n# refuses replays refuses a key, never a repeat. A probe sends nothing when its key file is missing,\n# empty or not a regular file, or its request cannot be built: a nonce, a timestamp or a signature\n# that failed. Every write starts from no file.\numask 077\nrm -f \"${SCRATCH:?}/wrong.key\"; printf '%064d' 0 > \"${SCRATCH:?}/wrong.key\"   # a wrong key of the right length\nsign() { node -e 'const c=require(\"crypto\"),f=require(\"fs\");process.stdout.write(c.createHmac(\"sha256\",f.readFileSync(process.argv[1])).update(f.readFileSync(process.argv[2])).digest(\"hex\"))' \"$1\" \"$2\"; }\nbody() { local n t; rm -f \"${SCRATCH:?}/probe.json\"; n=$(openssl rand -hex 16) && [ \"${#n}\" -eq 32 ] && t=$(date +%s) && [ \"$t\" -gt 0 ] 2>/dev/null && printf '{\"probe\":true,\"timestamp\":%s,\"nonce\":\"%s\"}' \"$t\" \"$n\" > \"${SCRATCH:?}/probe.json\"; }\nprobe() {  # probe <label> <key file, or none>\n  rm -f \"${SCRATCH:?}/probe.hdr\" \"$SCRATCH/probe.json\"\n  if [ \"$2\" != none ] && ! { [ -f \"$2\" ] && [ ! -L \"$2\" ] && [ -s \"$2\" ]; }; then\n    echo \"$1: NOTHING SENT: the key file is missing, empty or not a regular file\"; return 1\n  fi\n  case \"$KIND:$2\" in\n    bearer:none | signing:none) body && : > \"${SCRATCH:?}/probe.hdr\" ;;\n    bearer:*) body && { printf 'x-shared-key: '; cat \"$2\" && echo; } > \"${SCRATCH:?}/probe.hdr\" ;;\n    signing:*) body && { printf '<signature-header>: sha256='; sign \"$2\" \"$SCRATCH/probe.json\" && echo; } > \"${SCRATCH:?}/probe.hdr\" ;;\n    *) false ;;\n  esac || { echo \"$1: NOTHING SENT: KIND is unset, or the body, the key or the signature failed\"; return 1; }\n  curl -s -o /dev/null -w \"$1: %{http_code}\\n\" -H @\"$SCRATCH/probe.hdr\" --data-binary @\"$SCRATCH/probe.json\" \"https://<receiver>/<probe-path>\"\n}\n\n# Step 4, the old key still CURRENT and step 5's window not yet open: prove the copy. It must pass;\n# refused, the copy is not the key, and step 8's old-key probe is UNVERIFIED.\nprobe 'old key, before the senders move (must pass)' \"$SCRATCH/old.key\"\n\n# Step 8, the live domain on the promoted build: the new key passes; the old key, a wrong key and\n# no key are refused.\nprobe 'new key' \"$SCRATCH/next.key\"\nprobe 'old key' \"$SCRATCH/old.key\"\nprobe 'wrong key' \"$SCRATCH/wrong.key\"\nprobe 'no key' none\n\n# Remove every local copy, and check that none is left.\nrm -f \"${SCRATCH:?}/next.key\" \"$SCRATCH/next.copy\" \"$SCRATCH/old.key\" \"$SCRATCH/wrong.key\" \"$SCRATCH/probe.hdr\" \"$SCRATCH/probe.json\"\nls -A \"$SCRATCH\"\n```\n\n## What it looks like\n\nA specimen, not a prompt.\n\n### The reconciliation that retires the old key\n\n```text\nRotation of <secret name> — receiver <service>; senders <sender A>, <sender B>\nWindow: <date> 00:00:00 to 23:59:59 UTC; the last sender moved at <time> the day before\n\nReceiver, authenticated requests handled:  <n>   first 00:00:07   last 23:59:41\n  slot matched: next <n>, current 0\nSender A, delivery records:                <a>   first 00:00:07   last 23:59:41\nSender B, delivery records:                <b>   first 02:15:00   last 23:45:00\nSenders together: <a> + <b> = <n> — an exact match, with the same first and last second\nDelivery ids: <n> logged at the receiver, <n> recorded by the senders, matched one to one;\n  none unknown, none missing, none repeated\n\nSearch for other senders: \"<header name>\", \"<setting name>\", \"<receiver path>\" across the\n  repositories, CI secrets, the scheduler, database function and trigger definitions, and the\n  provider's webhook dashboard. Found: sender A and sender B, nothing else.\nCaveats: receiver logs are kept for 7 days, so a caller rarer than weekly would not appear. The log\n  command returns at most 1,000 entries per call; the count was paged. The logs carry no caller\n  identity beyond the delivery id, so the match is by id and time, not by name.\nDecision: retire the old key.\n```\n\nThe decision rests on a match a reader can redo, not on a belief about who the senders are, and\nthe record says what the match cannot rule out.\n\n## Pitfalls\n\n- **An empty next key that matches an empty header.** With `NEXT` unset, \"the key equals `NEXT`\"\n  is true for a request with no key at all. Every dual-key check needs the non-empty guard, and a\n  test that fails without it.\n- **The key printed \"just to check\".** Terminal scrollback, shell history, a transcript and a log\n  aggregator each keep their own copy, and none of them is a secret store.\n- **The key as an argument.** A command-line argument is visible in the process list and saved in\n  shell history. A tool-call parameter is saved in the transcript. Values travel on standard input\n  or in files.\n- **The key sent through SQL.** Statement text, a client-side variable such as `psql`'s `:'name'`,\n  and a bound parameter each reach some log: the server's, an extension's, a proxy's, the\n  client's. The key goes in through the store's own interface, or by hand.\n- **A hash printed for comparison.** A hash is a stable fingerprint of the key in every place the\n  output lands. Compare byte for byte inside the shell and print only the verdict.\n- **A trailing newline on one side.** A key file written with a newline, fed to one store that\n  keeps it and another that trims it, gives the sender and the receiver different keys. Every\n  delivery fails, and both sides look correctly configured. The same newline on the exported old\n  key makes the old-key probe fail for the wrong reason, which reads as a retirement that took.\n- **A key file written in a new shell.** `umask 077` lasts as long as the shell that set it, and a\n  redirect into an existing file keeps that file's mode. A step run days later in a new terminal\n  writes the old key's copy and the header files 0644. Every block that writes a key sets the\n  umask itself and starts from no file, and a directory where the file belongs is refused, since\n  `mv` would put the key inside it.\n- **The old key's last readable copy removed.** With a store that cannot be read back, the\n  senders' copies are the only readable ones, and moving the senders removes them. Save and prove\n  the old key before the first sender moves, or the old-key probe has nothing to send.\n- **A signed probe sent twice.** A receiver that refuses replays refuses a body it has seen,\n  whatever key signed it. Every signed probe gets a new timestamp and nonce.\n- **A redeploy that did not move the domain.** The deploy succeeds, the probes pass, and they pass\n  against the previous build, which still accepts the old key. Read the deployment behind the live\n  domain every time.\n- **Retiring on a code search alone.** Senders live in schedulers, dashboards, database definitions\n  and scripts on someone's machine. A search finds what was written down in the places searched.\n- **Equal counts, different requests.** A lost delivery and an unknown caller in the middle of the\n  window cancel out in a count, and the first and last seconds do not move. A per-request id matched\n  one to one tells them apart. Without one, the match is aggregate evidence, and the record says\n  so. The `current` slot catches any caller still on the old key either way.\n- **A window shorter than the slowest sender.** A weekly job is invisible in a daily window.\n- **Counting one page.** A log tool that returns a capped number of entries per call returns exactly\n  the cap when there are more. A count equal to the cap is a reason to page, not a result.\n- **A fallback to the old literal.** A sender that reads \"the store, or else the old value\" still\n  holds the old value, and recovers to it when the store read fails.\n- **One instance standing for all.** A probe one backend answered, a delivery one replica sent:\n  each shows that instance only. Senders moved while one receiver backend lacks `NEXT` fail there; a\n  quiet sender replica on the old literal fails after the retirement; a replica the redeploy missed\n  still accepts the old key, and only the old-key probe shows it — without that, UNVERIFIED.\n- **`NEXT` removed too early, or never.** Removed before every instance has the new `CURRENT`, it\n  takes the overlap from the instances the promotion missed, and moved senders fail there. Left\n  set after the promotion, it keeps two keys accepted indefinitely.\n\n## Verification\n\n- [ ] Every receiver and known sender is listed with where it held the key.\n- [ ] The receiver accepts `CURRENT` or a non-empty `NEXT`; an empty value never matches; the\n      comparison is constant-time; the slot is logged and the key is not.\n- [ ] The receiver's tests cover current, next, wrong, missing and empty keys, and were watched\n      failing with the empty-value rule broken.\n- [ ] For a bearer key, every layer on the request path was shown, before the first probe, not to\n      record its header.\n- [ ] The next key was generated into a 0600 file in a private `SCRATCH`, with no trailing newline,\n      and no output contained the key or its hash; every file holding a key was created 0600, under\n      a `umask 077` set in the same shell.\n- [ ] Every value reached every store on standard input or from a file, through the store's own\n      interface or by hand: never as an argument, a tool parameter or through SQL.\n- [ ] After each redeploy, the live domain's deployment id was read and matched the new deployment.\n- [ ] Before any sender moved, every receiver instance accepted both the current and the next key.\n- [ ] Every sender reads the key from a secret store, with no literal and no fallback left; each\n      delivered a request the receiver logged as matching `next`, and every instance of each was\n      shown reading the store.\n- [ ] The reconciliation window started after the last sender moved and was longer than the slowest\n      sender's cycle.\n- [ ] Receiver requests and sender delivery records matched exactly: one to one by delivery id,\n      each id as many times on each side, or else in count and in first and last second, recorded\n      as aggregate evidence — with paging where the tools capped entries.\n- [ ] The search for other senders is recorded with its terms, its places and its result.\n- [ ] Log retention and the lack of caller identity, where it applies, are stated as caveats.\n- [ ] The old key's copy was saved and accepted before any sender dropped the old key; every\n      receiver instance matched the new key as `current` while `NEXT` was still set, and only then\n      was `NEXT` removed.\n- [ ] For every backend — each probed directly, or all covered by deployment evidence or by probes\n      shown to reach each one — the new key was accepted, and the old key, a wrong key and no key\n      were refused; a signing key was probed by signature and never sent, each probe with a fresh\n      body; otherwise the retirement is recorded as UNVERIFIED, with the reason.\n- [ ] Every local copy of the key was deleted, and the record holds no key value and no hash.\n\n## Deeper reading\n\n- [The dual-key receiver](references/dual-key-receiver.md): the comparison, the empty-value rule,\n  slot logging, the test cases and how to arm them.\n- [Proving no other caller](references/proving-no-other-caller.md): the window, the exact match,\n  where else senders hide, and what log tooling limits do to the evidence.\n- [Deploy and probe](references/deploy-and-probe.md): moving values, never through SQL; the newline\n  trap; confirming the live domain moved; the probes and what they need; cleaning up.\n","bodyHtml":"<h2 id=\"rotate-a-shared-secret\">Rotate a shared secret</h2>\n<p>A shared secret is easy to change and hard to change safely. The receiver and every sender have to\nagree at every moment, or deliveries fail. The new value has to travel to each of them without\npassing through a terminal, a transcript or a log. And the old value can be retired only once\nnothing is still using it — which nobody actually knows, because the list of senders is a memory,\nnot a measurement.</p>\n<p>Each of those goes wrong quietly. With the next key unset, &quot;the current key or the next key&quot;\naccepts an empty header too. A redeploy reports success while the domain serves the previous build.\nA code search finds two senders, and a third, a job configured in a dashboard years ago, stops\nworking the morning after.</p>\n<p>This skill rotates with an overlap, so nothing fails while the senders move, and it retires the old\nkey on evidence: the receiver&#39;s handled requests matched one for one against the senders&#39; own\ndelivery records, plus a search, with the limits of both stated.</p>\n<h4 id=\"what-this-skill-does-not-own\">What this skill does not own</h4>\n<table>\n<thead>\n<tr>\n<th>The job</th>\n<th>Whose it is</th>\n<th>What this skill does with it</th>\n</tr>\n</thead>\n<tbody><tr>\n<td>Placing one credential in a secret store without the value entering the transcript</td>\n<td><code>secure-credential-setup</code></td>\n<td>Follows its placement rule for every store the key enters.</td>\n</tr>\n<tr>\n<td>Finding every reader of a key in the code</td>\n<td><code>investigate-codebase</code></td>\n<td>Asks it for the search, then adds the places code search cannot see.</td>\n</tr>\n<tr>\n<td>What a change to the receiver would affect</td>\n<td><code>blast-area</code></td>\n<td>Consults it when the receiver&#39;s auth code is shared by other routes.</td>\n</tr>\n<tr>\n<td>A change crossing code, schema and scheduled jobs</td>\n<td><code>land-complex-change</code></td>\n<td>Runs inside its budget when the rotation is part of a larger change.</td>\n</tr>\n<tr>\n<td>Writing in a repository other than this one</td>\n<td><code>work-in-external-repo</code></td>\n<td>Hands over when a sender lives in another repository.</td>\n</tr>\n<tr>\n<td>Telling the reader where the rotation stands</td>\n<td><code>report-progress</code></td>\n<td>Supplies the step, the window, the counts and the probe results.</td>\n</tr>\n</tbody></table>\n<p>Install the companions with <code>npx skills add crissmoldovan/agent-skills</code>.</p>\n<h3 id=\"when-to-use\">When to Use</h3>\n<ul>\n<li>A key shared between services you control — a webhook signing key, a service-to-service bearer\nkey, an internal API key — has to change: a suspected leak, someone leaving, a scheduled\nrotation, or the key found somewhere it should not be.</li>\n<li>A key is held as a literal — in a configuration file, in a database trigger&#39;s definition, in a\njob&#39;s arguments — and has to move to a secret store. Moving it is a rotation: the old value has\nbeen readable wherever it sat.</li>\n<li>Nobody can say with evidence who else calls the receiver with the key.</li>\n</ul>\n<p>Not for a credential you hold against someone else&#39;s service: rotate that in the provider&#39;s\nconsole and place it with <code>secure-credential-setup</code>. Not for asymmetric signing keys that carry a\nkey id: publishing the new public key beside the old one is already the overlap this skill builds by\nhand. And where a short outage is acceptable and the only sender deploys with the receiver, a plain\nswap is simpler.</p>\n<h3 id=\"prerequisites\">Prerequisites</h3>\n<ol>\n<li><strong>The secret&#39;s map.</strong> Every receiver, every known sender, and where each holds the key today:\nan environment variable, a secret store, a configuration file, a literal in a trigger or job\ndefinition, a CI secret, a third-party dashboard.\n<strong>Complete when:</strong> each holder is listed with its location, and the list says where it came\nfrom.</li>\n<li><strong>A secret store every sender can read.</strong> The receiver&#39;s platform secrets, a database&#39;s own\nsecret store, a vault — one per side is fine.\n<strong>Complete when:</strong> each sender has a store it can read at run time, named.</li>\n<li><strong>A receiver you can redeploy and trace.</strong> A deploy path, and a way to ask which deployment the\nlive domain serves right now.\n<strong>Complete when:</strong> you have read the live domain&#39;s current deployment id once.</li>\n<li><strong>Logs on both sides, with their limits known.</strong> The receiver&#39;s handled-request log with\ntimestamps, and each sender&#39;s own record of what it delivered. Their retention, any per-call\nentry cap in the tools that read them, and whether they identify the caller.\n<strong>Complete when:</strong> each log is named with its retention and its tooling limits.</li>\n<li><strong>A harmless probe.</strong> A request that authenticates and changes nothing, or changes something\nidempotent.\n<strong>Complete when:</strong> the probe request is written down and its expected success code known.</li>\n<li><strong>A private scratch directory.</strong> Outside any repository, created under <code>umask 077</code>.\n<strong>Complete when:</strong> it exists, is yours with mode 700, and <code>SCRATCH</code> names it in your shell.</li>\n<li><strong>A request path that keeps no copy of a bearer key.</strong> Any layer that records request headers —\nthe sender&#39;s instrumentation, a proxy, WAF or CDN, an APM agent, an access log — keeps the key.\n<strong>Complete when:</strong> before the first probe, every layer on the path is shown not to record that\nheader, or to redact it; if that cannot be shown, the rotation stops. A signing key never\ntravels.</li>\n</ol>\n<h3 id=\"procedure\">Procedure</h3>\n<p><strong>The every-instance rule.</strong> The receiver and each sender can run as several instances — replicas,\nregions, a rollout part-way through — and evidence from one instance says nothing about the others.\nSo every claim below about what the receiver accepts, or what a sender sends, covers every instance,\non one of three kinds of evidence: each instance addressed and checked on its own; the platform&#39;s\nown list of instances, each with its deployment or configuration version; or answers — probe\nresponses, delivery records — that identify the instance that gave them and, between them, name\nevery one. Short of that, a step that needs it waits, and a retirement already done is recorded as\n<strong>UNVERIFIED</strong>.</p>\n<ol>\n<li><p><strong>Make the receiver accept the current key or a next key, and test it.</strong> Two settings, <code>CURRENT</code>\nand <code>NEXT</code>. A request passes when its key equals <code>CURRENT</code>, or when <code>NEXT</code> is non-empty and its\nkey equals <code>NEXT</code>. An empty value never matches anything: an unset <code>NEXT</code> must not let an empty\nor missing header through, and an unset <code>CURRENT</code> refuses everything. Compare in constant time,\nand log which slot matched — <code>current</code> or <code>next</code> — never the key. Test every case, arm the tests\nby breaking the empty-value rule, then deploy with <code>NEXT</code> unset\n(<a href=\"references/dual-key-receiver.md\">the dual-key receiver</a>).\n<strong>Complete when:</strong> the tests pass and were watched failing with the empty-value rule broken, and\nthe live domain serves the build that contains them.</p>\n</li>\n<li><p><strong>Generate the next key into a 0600 file, and never print it.</strong> <code>umask 077</code>, then write the\noutput of a cryptographic random source to a temporary file, with no trailing newline, check its\nexact length, and only then rename it into place: a generator that failed must leave no key file\nat all, never an empty one that a store would accept. Never echo it, open it in a viewer, pass\nit as a command-line argument, or hand it to a tool call as a parameter: each of those puts it in\na terminal, a process list or a transcript. When two copies must be the same, compare them byte\nfor byte with tracing off, printing only same, different or read error — never a hash.\n<strong>Complete when:</strong> the key file exists with mode 0600 and its exact expected length, and no output\nof any command so far contains the key, its hash or its length.</p>\n</li>\n<li><p><strong>Set it on the receiver as <code>NEXT</code>, redeploy, and confirm the live domain moved.</strong> Feed the file\nto the platform&#39;s secret command on standard input. Redeploy, then read the deployment id the\nlive domain serves and compare it with the one the redeploy produced; promote it if they differ\n(<a href=\"references/deploy-and-probe.md\">deploy and probe</a>). Probe with the next key. A sender moved\nwhile one backend still lacks <code>NEXT</code> fails on every request routed there, so no sender moves\nuntil the overlap holds on every receiver instance, by the every-instance rule.\n<strong>Complete when:</strong> the live domain serves the new deployment, and both the current key and the\nnext key are accepted on every receiver instance, not only on the one that answered a probe.</p>\n</li>\n<li><p><strong>Move every sender to read the key from a secret store, then verify its delivery.</strong> First, keep\na private copy of the old key for step 8, before any sender drops it: a receiver store that\ncannot be read back leaves the senders&#39; copies as the only readable ones, and this step removes\nthem. Save it into a 0600 file from a copy that can still be read, never printed, in the store&#39;s\nraw form where it has one, under a <code>umask 077</code> set again, since a new shell has lost step 2&#39;s. A\ncommand that adds a newline or wraps the value in metadata writes a different key, and a probe\nwith it is refused for the wrong reason. So prove the copy: while the old key is still <code>CURRENT</code>,\nbefore step 5&#39;s window opens, probe with it as step 8 will — the same header or signature\nscheme, over a fresh body — and see it accepted. Then, one sender at a time: put the next key into its store from the file,\nchange the sender to read it from the store instead of wherever it held the old one, deploy, and\nwatch a real delivery arrive and log the <code>next</code> slot at the receiver. That delivery shows one\ninstance moved; a quiet instance still on the old value fails only once the old key is retired,\nso every instance of the sender is shown reading the store, by the every-instance rule. A key\nwritten as a literal in a definition — a trigger, a job, a configuration file — is readable by\nanyone who can read that definition, and changing it means redefining code; reading it from a\nstore fixes both. Remove the literal and any fallback to it. While the sender is being changed\nanyway, have it send a unique delivery id on every request and record it, so that step 5 can\nmatch requests one to one. A store written with SQL takes the key through its own interface or\nby hand, never through SQL (<a href=\"references/deploy-and-probe.md\">deploy and probe</a>).\n<strong>Complete when:</strong> the old key is in a 0600 file that the receiver accepted before any sender\ndropped it, or the record says why no such copy could be had; every sender on the map has\ndelivered at least one request that the receiver logged as matching <code>next</code>; every instance of\nevery sender is shown reading the store, and no sender still holds the old value anywhere.</p>\n</li>\n<li><p><strong>Prove no other caller exists before retiring the old key.</strong> Pick a fixed window that starts\nafter the last sender moved and is longer than the slowest sender&#39;s cycle. Count the receiver&#39;s\nhandled requests in the window and the senders&#39; own delivery records for the same window. They\nmust match exactly: the same count, and the same first and last second. Where the senders send a\ndelivery id and the receiver logs it, match the ids one to one instead: that is proof, provided\neach id is counted — as many times on one side as on the other, normally once — so that a\nrepeated request cannot hide behind its original, and every row is an id: a blank row or a\nplaceholder such as <code>null</code> is no evidence. Without ids, the count and endpoints are aggregate\nevidence, not proof — a lost delivery and an unknown request in the middle of the window cancel\nexactly — and the record says so. If the receiver logs the slot, every request in the window\nmust have matched <code>next</code>. Then search code and configuration for any other sender —\nrepositories, CI, schedulers, database definitions, provider dashboards, runbooks with example\nrequests. State what the evidence cannot see: the log retention, any paging the tools needed,\nand whether the logs identify the caller at all\n(<a href=\"references/proving-no-other-caller.md\">proving no other caller</a>).\n<strong>Complete when:</strong> the ids match one to one, or the counts and the first and last seconds match\nexactly and the record calls that aggregate evidence; the search terms and places are recorded\nwith what they found; and the caveats are written beside the result.</p>\n</li>\n<li><p><strong>Promote <code>NEXT</code> to <code>CURRENT</code>, and remove <code>NEXT</code> only once the new <code>CURRENT</code> holds everywhere.</strong>\nWith the old key&#39;s copy kept from step 4, set <code>CURRENT</code> from the next key&#39;s file, on standard\ninput, leaving <code>NEXT</code> in place, and redeploy as in step 7. An instance the change reached logs\nthe new key as <code>current</code>; one it missed still accepts it as <code>next</code>, so no sender fails\nmeanwhile. Delete <code>NEXT</code> only when every receiver instance logs the new key as <code>current</code>, by the\nevery-instance rule.\n<strong>Complete when:</strong> every receiver instance matched the new key as <code>current</code> while <code>NEXT</code> was\nstill set, <code>NEXT</code> was deleted after that, and the old key&#39;s copy from step 4 is still in its\n0600 file, or the record says why there is none.</p>\n</li>\n<li><p><strong>Redeploy, and verify that the live domain moved.</strong> A production redeploy can leave a custom\ndomain pointing at the previous build, and until it moves, the old key still works there. Read\nthe deployment id behind the live domain, and promote the new deployment if they differ.\n<strong>Complete when:</strong> the live domain&#39;s deployment id is the new deployment&#39;s, read after the\nredeploy.</p>\n</li>\n<li><p><strong>Probe the live domain: the new key passes; the old key, a wrong key and no key are refused.</strong>\nSend the harmless probe four times. How a key is presented depends on the receiver:</p>\n<ul>\n<li><strong>A bearer key</strong> travels in a header, read from a header file rather than written on the\ncommand line.</li>\n<li><strong>A signing key never travels.</strong> Sign a fresh probe body with each key file — the new key,\nthe old key, a wrong key — reading the key inside the program, and send only the signature,\nin the receiver&#39;s own header and scheme. Fresh means a new timestamp and nonce every time: a\nreceiver that refuses replays refuses a body it has seen whatever key signed it, and that\nrefusal reads as a retirement that took. The fourth probe sends no signature. The\n<code>x-shared-key</code> header in the examples is for bearer keys only.</li>\n</ul>\n<p>The example&#39;s <code>probe</code> sends either kind, by <code>KIND</code>, and sends nothing when it cannot build the\nrequest — a key file that is missing, empty or not a regular file included: an empty key makes a\nblank header or a signature with no key, refused for the wrong reason. Define it again in a new\nshell, which also sets <code>umask 077</code> again.</p>\n<p>The old-key probe is not optional. A stale replica, a region or instance the redeploy has not\nreached, or a promotion that landed on part of the fleet still accepts the old key, and nothing\nelse shows it. The probes cover every receiver instance, by the every-instance rule. Where\nreplicas or regions can be addressed one by one, probe each of them. Where they sit behind a load\nbalancer and cannot, a probe through the live domain reaches one backend and says nothing of the\nrest: the retirement stays <strong>UNVERIFIED</strong> unless every backend is covered, by the platform&#39;s list\nof instances or by answers that identify each backend. Where the old key cannot be probed safely\nat all — no copy of it was accepted before the promotion, or no probe is free of side effects —\nthe retirement is <strong>UNVERIFIED</strong> too, with the reason. The record never says the old key is\nrefused on less than that.\n<strong>Complete when:</strong> the record shows the new key accepted and the old key, the wrong key and the\nmissing key refused, each with its status code, for every backend — each probed directly, or all\ncovered by the every-instance rule&#39;s other evidence — or the retirement recorded as UNVERIFIED\nwith the reason.</p>\n</li>\n<li><p><strong>Delete every local copy, and record what happened.</strong> Remove the next, old and wrong key files,\nthe probe&#39;s header and body files and any copy made for comparison, and confirm they are gone.\nWrite the record: the dates, the window, the counts, the search, the deployment ids, the probes\nand the caveats. No key value and no hash.\n<strong>Complete when:</strong> no copy of the key exists outside the secret stores, and the record is\nwritten.</p>\n</li>\n</ol>\n<h3 id=\"usage-examples\">Usage Examples</h3>\n<pre><code class=\"language-text\">Rotate the shared key between the scheduler and the web app without downtime. Make the app accept\nthe current key or a next one first, never print the new key, and before you retire the old one,\nshow me that every request the app handled in a fixed window matches a delivery the senders\nrecorded.\n</code></pre>\n<pre><code class=\"language-text\">The webhook key is written as a literal in a database trigger definition. Move it into the\ndatabase&#39;s secret store as part of a rotation, and tell me who else could be calling the endpoint\nwith the old key.\n</code></pre>\n<pre><code class=\"language-text\">You redeployed the receiver. Before you probe anything, show me that the live domain is serving the\nnew deployment and not the previous one.\n</code></pre>\n<pre><code class=\"language-bash\"># Tracing off; refuse unless SCRATCH is your own directory, mode 700 (unset, a path is /next.key).\n# Then drop an earlier attempt&#39;s key, generate with no newline and check the length: a fresh key\n# and status 0, or no key file and a failure. Later writes and deletes spell it ${SCRATCH:?}.\numask 077\nset +x -o pipefail\nif [ -z &quot;$(find &quot;${SCRATCH:?}&quot; -maxdepth 0 -type d -user &quot;$(id -u)&quot; -perm 700 2&gt;/dev/null)&quot; ]; then\n  echo &quot;REFUSED: SCRATCH is not a private directory of yours (mode 700); nothing was touched&quot;; false\nelif rm -f &quot;$SCRATCH/next.key&quot; &quot;$SCRATCH/next.key.tmp&quot; \\\n  &amp;&amp; openssl rand -hex 32 | tr -d &#39;\\n&#39; &gt; &quot;$SCRATCH/next.key.tmp&quot; \\\n  &amp;&amp; [ &quot;$(wc -c &lt; &quot;$SCRATCH/next.key.tmp&quot; | tr -d &#39; &#39;)&quot; -eq 64 ] \\\n  &amp;&amp; mv &quot;$SCRATCH/next.key.tmp&quot; &quot;$SCRATCH/next.key&quot;; then\n  ls -l &quot;$SCRATCH/next.key&quot;\nelse\n  rm -f &quot;$SCRATCH/next.key.tmp&quot;; echo &quot;GENERATION FAILED: no key was written&quot;; false\nfi\n\n# Compare two copies byte for byte: same, DIFFERENT or READ ERROR, never a hash or a key.\ncmp -s &quot;$SCRATCH/next.key&quot; &quot;$SCRATCH/next.copy&quot;\ncase $? in 0) echo same ;; 1) echo DIFFERENT; false ;; *) echo &quot;READ ERROR&quot;; false ;; esac\n\n# Step 4, before any sender drops the old key: a store that cannot be read back leaves the senders&#39;\n# copies as the only readable ones. A new shell has lost step 2&#39;s umask, so set it again. Save the\n# old key raw, never printed: a new 0600 copy, or a failure that keeps any copy saved earlier. An\n# old.key that is a directory or a link is refused first: mv would put the copy inside it.\numask 077\nrm -f &quot;${SCRATCH:?}/old.key.tmp&quot;\nif [ -d &quot;$SCRATCH/old.key&quot; ] || [ -L &quot;$SCRATCH/old.key&quot; ]; then\n  echo &quot;OLD KEY NOT SAVED: old.key is a directory or a link; nothing was read&quot;; false\nelif &lt;platform-cli&gt; secrets get SHARED_KEY &gt; &quot;${SCRATCH:?}/old.key.tmp&quot; &amp;&amp; [ -s &quot;$SCRATCH/old.key.tmp&quot; ] \\\n  &amp;&amp; mv &quot;${SCRATCH:?}/old.key.tmp&quot; &quot;$SCRATCH/old.key&quot;; then\n  ls -l &quot;$SCRATCH/old.key&quot;\nelse\n  rm -f &quot;${SCRATCH:?}/old.key.tmp&quot;; echo &quot;OLD KEY NOT SAVED: no new copy was written&quot;; false\nfi\n\n# The probes: define them again in every new shell. KIND is bearer or signing, with no default. A\n# bearer key travels in a header file; a signing key never travels, and only its signature is sent,\n# in the receiver&#39;s own header and scheme. Every probe gets a fresh body, a new timestamp and nonce\n# (adapt body to your receiver, keeping both wherever its scheme signs them), so a receiver that\n# refuses replays refuses a key, never a repeat. A probe sends nothing when its key file is missing,\n# empty or not a regular file, or its request cannot be built: a nonce, a timestamp or a signature\n# that failed. Every write starts from no file.\numask 077\nrm -f &quot;${SCRATCH:?}/wrong.key&quot;; printf &#39;%064d&#39; 0 &gt; &quot;${SCRATCH:?}/wrong.key&quot;   # a wrong key of the right length\nsign() { node -e &#39;const c=require(&quot;crypto&quot;),f=require(&quot;fs&quot;);process.stdout.write(c.createHmac(&quot;sha256&quot;,f.readFileSync(process.argv[1])).update(f.readFileSync(process.argv[2])).digest(&quot;hex&quot;))&#39; &quot;$1&quot; &quot;$2&quot;; }\nbody() { local n t; rm -f &quot;${SCRATCH:?}/probe.json&quot;; n=$(openssl rand -hex 16) &amp;&amp; [ &quot;${#n}&quot; -eq 32 ] &amp;&amp; t=$(date +%s) &amp;&amp; [ &quot;$t&quot; -gt 0 ] 2&gt;/dev/null &amp;&amp; printf &#39;{&quot;probe&quot;:true,&quot;timestamp&quot;:%s,&quot;nonce&quot;:&quot;%s&quot;}&#39; &quot;$t&quot; &quot;$n&quot; &gt; &quot;${SCRATCH:?}/probe.json&quot;; }\nprobe() {  # probe &lt;label&gt; &lt;key file, or none&gt;\n  rm -f &quot;${SCRATCH:?}/probe.hdr&quot; &quot;$SCRATCH/probe.json&quot;\n  if [ &quot;$2&quot; != none ] &amp;&amp; ! { [ -f &quot;$2&quot; ] &amp;&amp; [ ! -L &quot;$2&quot; ] &amp;&amp; [ -s &quot;$2&quot; ]; }; then\n    echo &quot;$1: NOTHING SENT: the key file is missing, empty or not a regular file&quot;; return 1\n  fi\n  case &quot;$KIND:$2&quot; in\n    bearer:none | signing:none) body &amp;&amp; : &gt; &quot;${SCRATCH:?}/probe.hdr&quot; ;;\n    bearer:*) body &amp;&amp; { printf &#39;x-shared-key: &#39;; cat &quot;$2&quot; &amp;&amp; echo; } &gt; &quot;${SCRATCH:?}/probe.hdr&quot; ;;\n    signing:*) body &amp;&amp; { printf &#39;&lt;signature-header&gt;: sha256=&#39;; sign &quot;$2&quot; &quot;$SCRATCH/probe.json&quot; &amp;&amp; echo; } &gt; &quot;${SCRATCH:?}/probe.hdr&quot; ;;\n    *) false ;;\n  esac || { echo &quot;$1: NOTHING SENT: KIND is unset, or the body, the key or the signature failed&quot;; return 1; }\n  curl -s -o /dev/null -w &quot;$1: %{http_code}\\n&quot; -H @&quot;$SCRATCH/probe.hdr&quot; --data-binary @&quot;$SCRATCH/probe.json&quot; &quot;https://&lt;receiver&gt;/&lt;probe-path&gt;&quot;\n}\n\n# Step 4, the old key still CURRENT and step 5&#39;s window not yet open: prove the copy. It must pass;\n# refused, the copy is not the key, and step 8&#39;s old-key probe is UNVERIFIED.\nprobe &#39;old key, before the senders move (must pass)&#39; &quot;$SCRATCH/old.key&quot;\n\n# Step 8, the live domain on the promoted build: the new key passes; the old key, a wrong key and\n# no key are refused.\nprobe &#39;new key&#39; &quot;$SCRATCH/next.key&quot;\nprobe &#39;old key&#39; &quot;$SCRATCH/old.key&quot;\nprobe &#39;wrong key&#39; &quot;$SCRATCH/wrong.key&quot;\nprobe &#39;no key&#39; none\n\n# Remove every local copy, and check that none is left.\nrm -f &quot;${SCRATCH:?}/next.key&quot; &quot;$SCRATCH/next.copy&quot; &quot;$SCRATCH/old.key&quot; &quot;$SCRATCH/wrong.key&quot; &quot;$SCRATCH/probe.hdr&quot; &quot;$SCRATCH/probe.json&quot;\nls -A &quot;$SCRATCH&quot;\n</code></pre>\n<h3 id=\"what-it-looks-like\">What it looks like</h3>\n<p>A specimen, not a prompt.</p>\n<h4 id=\"the-reconciliation-that-retires-the-old-key\">The reconciliation that retires the old key</h4>\n<pre><code class=\"language-text\">Rotation of &lt;secret name&gt; — receiver &lt;service&gt;; senders &lt;sender A&gt;, &lt;sender B&gt;\nWindow: &lt;date&gt; 00:00:00 to 23:59:59 UTC; the last sender moved at &lt;time&gt; the day before\n\nReceiver, authenticated requests handled:  &lt;n&gt;   first 00:00:07   last 23:59:41\n  slot matched: next &lt;n&gt;, current 0\nSender A, delivery records:                &lt;a&gt;   first 00:00:07   last 23:59:41\nSender B, delivery records:                &lt;b&gt;   first 02:15:00   last 23:45:00\nSenders together: &lt;a&gt; + &lt;b&gt; = &lt;n&gt; — an exact match, with the same first and last second\nDelivery ids: &lt;n&gt; logged at the receiver, &lt;n&gt; recorded by the senders, matched one to one;\n  none unknown, none missing, none repeated\n\nSearch for other senders: &quot;&lt;header name&gt;&quot;, &quot;&lt;setting name&gt;&quot;, &quot;&lt;receiver path&gt;&quot; across the\n  repositories, CI secrets, the scheduler, database function and trigger definitions, and the\n  provider&#39;s webhook dashboard. Found: sender A and sender B, nothing else.\nCaveats: receiver logs are kept for 7 days, so a caller rarer than weekly would not appear. The log\n  command returns at most 1,000 entries per call; the count was paged. The logs carry no caller\n  identity beyond the delivery id, so the match is by id and time, not by name.\nDecision: retire the old key.\n</code></pre>\n<p>The decision rests on a match a reader can redo, not on a belief about who the senders are, and\nthe record says what the match cannot rule out.</p>\n<h3 id=\"pitfalls\">Pitfalls</h3>\n<ul>\n<li><strong>An empty next key that matches an empty header.</strong> With <code>NEXT</code> unset, &quot;the key equals <code>NEXT</code>&quot;\nis true for a request with no key at all. Every dual-key check needs the non-empty guard, and a\ntest that fails without it.</li>\n<li><strong>The key printed &quot;just to check&quot;.</strong> Terminal scrollback, shell history, a transcript and a log\naggregator each keep their own copy, and none of them is a secret store.</li>\n<li><strong>The key as an argument.</strong> A command-line argument is visible in the process list and saved in\nshell history. A tool-call parameter is saved in the transcript. Values travel on standard input\nor in files.</li>\n<li><strong>The key sent through SQL.</strong> Statement text, a client-side variable such as <code>psql</code>&#39;s <code>:&#39;name&#39;</code>,\nand a bound parameter each reach some log: the server&#39;s, an extension&#39;s, a proxy&#39;s, the\nclient&#39;s. The key goes in through the store&#39;s own interface, or by hand.</li>\n<li><strong>A hash printed for comparison.</strong> A hash is a stable fingerprint of the key in every place the\noutput lands. Compare byte for byte inside the shell and print only the verdict.</li>\n<li><strong>A trailing newline on one side.</strong> A key file written with a newline, fed to one store that\nkeeps it and another that trims it, gives the sender and the receiver different keys. Every\ndelivery fails, and both sides look correctly configured. The same newline on the exported old\nkey makes the old-key probe fail for the wrong reason, which reads as a retirement that took.</li>\n<li><strong>A key file written in a new shell.</strong> <code>umask 077</code> lasts as long as the shell that set it, and a\nredirect into an existing file keeps that file&#39;s mode. A step run days later in a new terminal\nwrites the old key&#39;s copy and the header files 0644. Every block that writes a key sets the\numask itself and starts from no file, and a directory where the file belongs is refused, since\n<code>mv</code> would put the key inside it.</li>\n<li><strong>The old key&#39;s last readable copy removed.</strong> With a store that cannot be read back, the\nsenders&#39; copies are the only readable ones, and moving the senders removes them. Save and prove\nthe old key before the first sender moves, or the old-key probe has nothing to send.</li>\n<li><strong>A signed probe sent twice.</strong> A receiver that refuses replays refuses a body it has seen,\nwhatever key signed it. Every signed probe gets a new timestamp and nonce.</li>\n<li><strong>A redeploy that did not move the domain.</strong> The deploy succeeds, the probes pass, and they pass\nagainst the previous build, which still accepts the old key. Read the deployment behind the live\ndomain every time.</li>\n<li><strong>Retiring on a code search alone.</strong> Senders live in schedulers, dashboards, database definitions\nand scripts on someone&#39;s machine. A search finds what was written down in the places searched.</li>\n<li><strong>Equal counts, different requests.</strong> A lost delivery and an unknown caller in the middle of the\nwindow cancel out in a count, and the first and last seconds do not move. A per-request id matched\none to one tells them apart. Without one, the match is aggregate evidence, and the record says\nso. The <code>current</code> slot catches any caller still on the old key either way.</li>\n<li><strong>A window shorter than the slowest sender.</strong> A weekly job is invisible in a daily window.</li>\n<li><strong>Counting one page.</strong> A log tool that returns a capped number of entries per call returns exactly\nthe cap when there are more. A count equal to the cap is a reason to page, not a result.</li>\n<li><strong>A fallback to the old literal.</strong> A sender that reads &quot;the store, or else the old value&quot; still\nholds the old value, and recovers to it when the store read fails.</li>\n<li><strong>One instance standing for all.</strong> A probe one backend answered, a delivery one replica sent:\neach shows that instance only. Senders moved while one receiver backend lacks <code>NEXT</code> fail there; a\nquiet sender replica on the old literal fails after the retirement; a replica the redeploy missed\nstill accepts the old key, and only the old-key probe shows it — without that, UNVERIFIED.</li>\n<li><strong><code>NEXT</code> removed too early, or never.</strong> Removed before every instance has the new <code>CURRENT</code>, it\ntakes the overlap from the instances the promotion missed, and moved senders fail there. Left\nset after the promotion, it keeps two keys accepted indefinitely.</li>\n</ul>\n<h3 id=\"verification\">Verification</h3>\n<ul>\n<li><input disabled=\"\" type=\"checkbox\"> Every receiver and known sender is listed with where it held the key.</li>\n<li><input disabled=\"\" type=\"checkbox\"> The receiver accepts <code>CURRENT</code> or a non-empty <code>NEXT</code>; an empty value never matches; the\ncomparison is constant-time; the slot is logged and the key is not.</li>\n<li><input disabled=\"\" type=\"checkbox\"> The receiver&#39;s tests cover current, next, wrong, missing and empty keys, and were watched\nfailing with the empty-value rule broken.</li>\n<li><input disabled=\"\" type=\"checkbox\"> For a bearer key, every layer on the request path was shown, before the first probe, not to\nrecord its header.</li>\n<li><input disabled=\"\" type=\"checkbox\"> The next key was generated into a 0600 file in a private <code>SCRATCH</code>, with no trailing newline,\nand no output contained the key or its hash; every file holding a key was created 0600, under\na <code>umask 077</code> set in the same shell.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Every value reached every store on standard input or from a file, through the store&#39;s own\ninterface or by hand: never as an argument, a tool parameter or through SQL.</li>\n<li><input disabled=\"\" type=\"checkbox\"> After each redeploy, the live domain&#39;s deployment id was read and matched the new deployment.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Before any sender moved, every receiver instance accepted both the current and the next key.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Every sender reads the key from a secret store, with no literal and no fallback left; each\ndelivered a request the receiver logged as matching <code>next</code>, and every instance of each was\nshown reading the store.</li>\n<li><input disabled=\"\" type=\"checkbox\"> The reconciliation window started after the last sender moved and was longer than the slowest\nsender&#39;s cycle.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Receiver requests and sender delivery records matched exactly: one to one by delivery id,\neach id as many times on each side, or else in count and in first and last second, recorded\nas aggregate evidence — with paging where the tools capped entries.</li>\n<li><input disabled=\"\" type=\"checkbox\"> The search for other senders is recorded with its terms, its places and its result.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Log retention and the lack of caller identity, where it applies, are stated as caveats.</li>\n<li><input disabled=\"\" type=\"checkbox\"> The old key&#39;s copy was saved and accepted before any sender dropped the old key; every\nreceiver instance matched the new key as <code>current</code> while <code>NEXT</code> was still set, and only then\nwas <code>NEXT</code> removed.</li>\n<li><input disabled=\"\" type=\"checkbox\"> For every backend — each probed directly, or all covered by deployment evidence or by probes\nshown to reach each one — the new key was accepted, and the old key, a wrong key and no key\nwere refused; a signing key was probed by signature and never sent, each probe with a fresh\nbody; otherwise the retirement is recorded as UNVERIFIED, with the reason.</li>\n<li><input disabled=\"\" type=\"checkbox\"> Every local copy of the key was deleted, and the record holds no key value and no hash.</li>\n</ul>\n<h3 id=\"deeper-reading\">Deeper reading</h3>\n<ul>\n<li><a href=\"references/dual-key-receiver.md\">The dual-key receiver</a>: the comparison, the empty-value rule,\nslot logging, the test cases and how to arm them.</li>\n<li><a href=\"references/proving-no-other-caller.md\">Proving no other caller</a>: the window, the exact match,\nwhere else senders hide, and what log tooling limits do to the evidence.</li>\n<li><a href=\"references/deploy-and-probe.md\">Deploy and probe</a>: moving values, never through SQL; the newline\ntrap; confirming the live domain moved; the probes and what they need; cleaning up.</li>\n</ul>\n","outline":["When to Use","Prerequisites","Procedure","Usage Examples","What it looks like","Pitfalls","Verification","Deeper reading"],"words":5169}
