diff --git a/docs/release-signed-run-identity.md b/docs/release-signed-run-identity.md new file mode 100644 index 0000000..a3adbd4 --- /dev/null +++ b/docs/release-signed-run-identity.md @@ -0,0 +1,32 @@ +# Inactive signed run identity inspection + +This isolated reference is not imported into the Worker, release workflow or +publisher. It preserves the current fixed GitHub issuer, repository IDs, main +workflow ref, audience, signature and expiration checks. A regression test binds +its verifier to the active implementation apart from the named identity extension. +No existing verifier semantics are changed by adding this module. + +The reference requires signed run_id and run_attempt as canonical positive decimal +strings of at most20digits and workflow_sha as a40character lowercase hex SHA. +Strings avoid rounding identifiers. The returned immutable record preserves these +claims but separately marks serviceRunVerified, artifactUploadAttemptVerified and +productionActionAllowed false. workflow_sha is the executing workflow revision, +not necessarily the candidate commit, and is never silently substituted for it. + +A valid signature authenticates the issuer's claims. It does not prove a particular +validation run completed, an artifact belongs to that attempt, or a deployment +occurred. Independently fetched exact run/attempt and original artifact provenance +must establish those facts. matchExpectedRun is only a structural field comparison; +it accepts neither service authority nor permission from caller assertions. + +Tests use an ephemeral synthetic RSA key and fixed responses, not real credentials +or live issuer qualification. Wrong issuer/audience/repository/workflow/ref/event, +expired tokens, modified signed run attempts, malformed identifiers and redirects +fail. No route, credential, workflow trigger, activation or public-site change is +included. Existing denied operations remain denied. Next: bounded authenticated +service evidence acquisition and read-only shadow admission before any write path. + +The fetcher and clock options are trusted test/runtime dependencies, never request +input. Synthetic tests intentionally supply a fixture signing-key response. A +future admission route must bind the real fixed issuer fetch and trusted finite +clock internally; exposing these options would defeat identity/time guarantees. diff --git a/tests/publisher-run-identity.test.cjs b/tests/publisher-run-identity.test.cjs new file mode 100644 index 0000000..12fe5a6 --- /dev/null +++ b/tests/publisher-run-identity.test.cjs @@ -0,0 +1,9 @@ +const {test}=require('node:test'),assert=require('node:assert/strict'),crypto=require('node:crypto'),fs=require('node:fs'); +const repo='LeiterConsulting/splunk-version-value-explorer',now=1794777600000; +let signing;const modulePromise=import('../tools/release-coordination/publisher-run-identity.mjs'); +async function fixture(changes={}){signing||=await crypto.webcrypto.subtle.generateKey({name:'RSASSA-PKCS1-v1_5',modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:'SHA-256'},true,['sign','verify']);const seconds=now/1000,claims={iss:'https://token.actions.githubusercontent.com',aud:'https://versioncompass.com',sub:'repo:'+repo+':ref:refs/heads/main',repository:repo,repository_id:'1366223729',repository_owner_id:'152733483',repository_visibility:'public',ref:'refs/heads/main',ref_type:'branch',workflow_ref:repo+'/.github/workflows/publish-content.yml@refs/heads/main',runner_environment:'github-hosted',event_name:'workflow_run',sha:'a'.repeat(40),workflow_sha:'b'.repeat(40),run_id:'43758558524',run_attempt:'2',iat:seconds,nbf:seconds-1,exp:seconds+300,...changes};const b64=x=>Buffer.from(JSON.stringify(x)).toString('base64url'),body=b64({alg:'RS256',typ:'JWT',kid:'fixture'})+'.'+b64(claims),sig=await crypto.webcrypto.subtle.sign('RSASSA-PKCS1-v1_5',signing.privateKey,Buffer.from(body)),jwks={keys:[{...await crypto.webcrypto.subtle.exportKey('jwk',signing.publicKey),kid:'fixture',use:'sig',alg:'RS256'}]};return {token:body+'.'+Buffer.from(sig).toString('base64url'),fetcher:async(url,options)=>{assert.equal(url,'https://token.actions.githubusercontent.com/.well-known/jwks');assert.equal(options.redirect,'manual');return Response.json(jwks)}}} +test('signed identity preserves exact strings but never asserts run or artifact provenance',async()=>{const m=await modulePromise,f=await fixture(),r=await m.inspectPublisherRunIdentity(f.token,{...f,now});assert.equal(r.runId,'43758558524');assert.equal(r.runAttempt,'2');assert.equal(r.workflowSha,'b'.repeat(40));assert.equal(r.claimsSignatureVerified,true);for(const k of ['serviceRunVerified','artifactUploadAttemptVerified','productionActionAllowed'])assert.equal(r[k],false);assert(Object.isFrozen(r));assert.equal(m.matchExpectedRun(r,r).identityFieldsMatch,true);for(const key of ['runId','runAttempt','commit','workflowSha','eventName','workflowRef'])assert.throws(()=>m.matchExpectedRun(r,{...r,[key]:'changed'}),/mismatch/)}); +test('missing, numeric, ambiguous or huge run identifiers fail closed',async()=>{const m=await modulePromise;for(const key of ['run_id','run_attempt'])for(const value of [undefined,null,1,'0','01','1.0','-1',' 1','1e2','9'.repeat(21)]){const f=await fixture({[key]:value});await assert.rejects(m.inspectPublisherRunIdentity(f.token,{...f,now}),/signed run identity/)}for(const value of [undefined,null,1,'x','A'.repeat(40)]){const f=await fixture({workflow_sha:value});await assert.rejects(m.inspectPublisherRunIdentity(f.token,{...f,now}),/signed run identity/)}}); +test('signature and existing issuer, audience, workflow, ref and expiry boundaries remain',async()=>{const m=await modulePromise;for(const changes of [{iss:'https://evil.example'},{aud:'other'},{repository_id:'1'},{ref:'refs/heads/other'},{workflow_ref:repo+'/.github/workflows/other.yml@refs/heads/main'},{event_name:'pull_request'},{exp:now/1000-1}]){const f=await fixture(changes);await assert.rejects(m.inspectPublisherRunIdentity(f.token,{...f,now}),/identity/)}const f=await fixture(),parts=f.token.split('.');const claims=JSON.parse(Buffer.from(parts[1],'base64url'));claims.run_attempt='3';parts[1]=Buffer.from(JSON.stringify(claims)).toString('base64url');await assert.rejects(m.inspectPublisherRunIdentity(parts.join('.'),{...f,now}),/signature/)}); +test('key redirects and unsigned claims fail; structural matching never grants authority',async()=>{const m=await modulePromise,f=await fixture();await assert.rejects(m.inspectPublisherRunIdentity(f.token,{now,fetcher:async()=>new Response('',{status:302})}),/unavailable/);await assert.rejects(m.inspectPublisherRunIdentity('{}',{...f,now}),/token/);const fake={commit:'x',eventName:'x',runId:'x',runAttempt:'x',workflowSha:'x',workflowRef:'x'};const r=m.matchExpectedRun(fake,fake);assert.equal(r.serviceRunVerified,false);assert.equal(r.productionActionAllowed,false)}); +test('inactive reference retains exact existing cryptographic verifier except named extensions',()=>{let reference=fs.readFileSync('tools/release-coordination/publisher-run-identity.mjs','utf8').split('// Structural expected identity')[0];reference=reference.split('\n').slice(2).join('\n').replace('inspectPublisherRunIdentity','verifyPublisherOIDC');reference=reference.replace(/ const decimal=x=>[^\n]*\n if\(!decimal\(claims.run_id\)[^\n]*\n/,'');reference=reference.replace(/return Object.freeze\(\{ type:'github-oidc-signed-run-claims'[^\n]*\);/,"return { type: 'github-oidc', commit: claims.sha, eventName: claims.event_name };");const upstream=fs.readFileSync('worker/publisher.mjs','utf8').split('async function publisherIdentity')[0];assert.equal(reference.trim(),upstream.trim())}); diff --git a/tools/release-coordination/publisher-run-identity.mjs b/tools/release-coordination/publisher-run-identity.mjs new file mode 100644 index 0000000..1d15adf --- /dev/null +++ b/tools/release-coordination/publisher-run-identity.mjs @@ -0,0 +1,68 @@ +// Inactive identity inspection reference; not in the Worker build. +const REPOSITORY='LeiterConsulting/splunk-version-value-explorer'; +/* Separate maintenance boundary. No browser identity, telemetry or public writes. */ +const publisherIssuer = 'https://token.actions.githubusercontent.com'; +const publisherAudience = 'https://versioncompass.com'; +const publisherWorkflow = REPOSITORY + '/.github/workflows/publish-content.yml@refs/heads/main'; + +function publisherBase64(value) { + if (!/^[A-Za-z0-9_-]+$/.test(value)) throw Error('Invalid token'); + return Uint8Array.from(atob(value.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0)); +} +export async function inspectPublisherRunIdentity(token, { fetcher = (...args) => globalThis.fetch(...args), now = Date.now() } = {}) { + if (typeof token !== 'string' || token.length > 16000) throw Error('Invalid token'); + const parts = token.split('.'); if (parts.length !== 3) throw Error('Invalid token'); + const decode = part => JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(publisherBase64(part))); + let header, claims; + try { header = decode(parts[0]); claims = decode(parts[1]); } catch { throw Error('Invalid token'); } + if (header.alg !== 'RS256' || header.typ !== 'JWT' || typeof header.kid !== 'string' || header.jku || header.jwk || header.crit) throw Error('Invalid token'); + const seconds = Math.floor(now / 1000); + if (claims.iss !== publisherIssuer || claims.aud !== publisherAudience || + claims.repository !== REPOSITORY || claims.repository_id !== '1366223729' || claims.repository_owner_id !== '152733483' || + claims.repository_visibility !== 'public' || claims.ref !== 'refs/heads/main' || claims.ref_type !== 'branch' || + claims.workflow_ref !== publisherWorkflow || claims.runner_environment !== 'github-hosted' || + !['repo:' + REPOSITORY + ':ref:refs/heads/main', 'repo:LeiterConsulting@152733483/splunk-version-value-explorer@1366223729:ref:refs/heads/main'].includes(claims.sub) || + !['workflow_run', 'workflow_dispatch'].includes(claims.event_name) || !/^[a-f0-9]{40}$/.test(claims.sha) || + !Number.isSafeInteger(claims.exp) || !Number.isSafeInteger(claims.nbf) || !Number.isSafeInteger(claims.iat) || + claims.exp <= seconds || claims.nbf > seconds + 30 || claims.iat > seconds + 30 || claims.iat < seconds - 600 || claims.exp - claims.iat > 600) throw Error('Invalid publisher identity'); + const decimal=x=>typeof x==='string'&&/^[1-9][0-9]{0,19}$/.test(x); + if(!decimal(claims.run_id)||!decimal(claims.run_attempt)||typeof claims.workflow_sha!=='string'||!/^[a-f0-9]{40}$/.test(claims.workflow_sha))throw Error('Invalid signed run identity'); + let response; + // Workers supports manual redirect handling; reject every non-2xx response + // without following it, preserving the fixed issuer boundary. + try { response = await fetcher(publisherIssuer + '/.well-known/jwks', { redirect: 'manual', signal: AbortSignal.timeout(10000) }); } + catch (error) { + if (/illegal invocation/i.test(error.message)) throw Error('Publisher identity fetch receiver invalid'); + if (/redirect/i.test(error.message)) throw Error('Publisher identity redirect rejected'); + if (/not implemented|not supported|unsupported|not a function/i.test(error.message)) throw Error('Publisher identity fetch option unsupported'); + throw Error('Publisher identity unavailable'); + } + if (!response.ok) throw Error('Publisher identity unavailable (HTTP ' + response.status + ')'); + if (!response.body) throw Error('Publisher identity unavailable'); + const reader = response.body.getReader(), chunks = []; let size = 0; + try { + while (true) { const { value, done } = await reader.read(); if (done) break; size += value.byteLength; if (size > 128 * 1024) throw Error('Publisher identity exceeds limit'); chunks.push(value); } + } finally { await reader.cancel().catch(() => {}); } + const bytes = new Uint8Array(size); let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } + let keys; + try { keys = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)).keys; } + catch { throw Error('Invalid signing key document'); } + const matches = Array.isArray(keys) ? keys.filter(key => key.kid === header.kid && key.kty === 'RSA' && (!key.use || key.use === 'sig') && (!key.alg || key.alg === 'RS256')) : []; + if (matches.length !== 1) throw Error('Unknown signing key'); + let key; + try { key = await crypto.subtle.importKey('jwk', matches[0], { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']); } + catch { throw Error('Signing key import unavailable'); } + let verified; + try { verified = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, publisherBase64(parts[2]), new TextEncoder().encode(parts[0] + '.' + parts[1])); } + catch { throw Error('Signature verification unavailable'); } + if (!verified) throw Error('Invalid signature'); + return Object.freeze({ type:'github-oidc-signed-run-claims', commit:claims.sha, eventName:claims.event_name, runId:claims.run_id, runAttempt:claims.run_attempt, workflowSha:claims.workflow_sha, workflowRef:claims.workflow_ref, claimsSignatureVerified:true, serviceRunVerified:false, artifactUploadAttemptVerified:false, productionActionAllowed:false }); +} + +// Structural expected identity only: does not authenticate an API receipt. +export function matchExpectedRun(identity,expected){ + const keys=['commit','eventName','runId','runAttempt','workflowSha','workflowRef']; + if(!identity||!expected||keys.some(key=>typeof identity[key]!=='string'||typeof expected[key]!=='string'||identity[key]!==expected[key]))throw Error('Expected run identity mismatch'); + return {identityFieldsMatch:true,serviceRunVerified:false,artifactUploadAttemptVerified:false,productionActionAllowed:false}; +}