Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions .github/tests/cloud-readers.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');

const workflow = fs.readFileSync(path.join(__dirname, '../workflows/keeper-cloud-readers.yml'), 'utf8');
const scriptMatch = workflow.match(/ script: \|\n([\s\S]*)$/);
assert.ok(scriptMatch, 'test the actual installed inline script');
const script = scriptMatch[1].split('\n').map(line => line.startsWith(' ') ? line.slice(12) : line).join('\n');
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const execute = new AsyncFunction('fetch', 'core', 'process', script);
const settingsToken = 'github_pat_' + 's'.repeat(30);
const privateToken = 'github_pat_' + 'p'.repeat(30);
const settingsUrl = 'https://api.github.com/repos/KeeperCommunity/bitcoin-keeper/actions/variables?per_page=1';
const privateUrl = 'https://api.github.com/repos/KeeperCommunity/bitcoin-keeper-private/actions/runs?per_page=1';

function fixture(options = {}) {
const calls = [], messages = [], masked = [];
const process = { env: { SETTINGS_READER: settingsToken, PRIVATE_TEST_READER: privateToken, ...(options.env || {}) } };
const summary = {
addHeading(text) { messages.push(text); return this; },
addRaw(text) { messages.push(text); return this; },
async write() { messages.push('summary written'); },
};
const core = { setSecret(value) { masked.push(value); }, info(value) { messages.push(value); }, summary };
const fetch = async (url, request) => {
assert.equal(process.env.SETTINGS_READER, undefined);
assert.equal(process.env.PRIVATE_TEST_READER, undefined);
assert.equal(request.method, 'GET');
assert.equal(request.redirect, 'error');
assert.ok(request.signal instanceof AbortSignal);
assert.ok([settingsUrl, privateUrl].includes(url));
const token = request.headers.Authorization.slice('Bearer '.length);
calls.push({ url, token });
if (options.transportError) throw new Error(settingsToken + ' private transport detail');
const allowed = (token === settingsToken && url === settingsUrl) || (token === privateToken && url === privateUrl);
const status = allowed ? (options.allowedStatus || 200) : (options.deniedStatus || 404);
return { status, async json() {
if (options.invalidJson) throw new Error(privateToken + ' response detail');
if (options.invalidShape) return { unexpected: true };
return url === settingsUrl ? { variables: [{ name: 'PRIVATE', value: 'private configuration value' }] }
: { workflow_runs: [{ name: 'private job details', id: 123 }] };
} };
};
return { calls, messages, masked, run: () => execute(fetch, core, process), process };
}

test('both independent readers use only their allowed API and do not expose returned data', async () => {
const f = fixture(); await f.run();
assert.deepEqual(f.calls, [
{ url: settingsUrl, token: settingsToken }, { url: privateUrl, token: settingsToken },
{ url: privateUrl, token: privateToken }, { url: settingsUrl, token: privateToken },
]);
assert.deepEqual(f.masked, [settingsToken, privateToken]);
const output = f.messages.join('\n');
for (const forbidden of [settingsToken, privateToken, 'private configuration value', 'private job details']) {
assert.equal(output.includes(forbidden), false);
}
assert.ok(output.includes('does not establish native acceptance or release readiness'));
});

for (const missing of ['SETTINGS_READER', 'PRIVATE_TEST_READER']) {
test('missing ' + missing + ' prevents every network call', async () => {
const f = fixture({ env: { [missing]: '' } });
await assert.rejects(f.run(), /Both approved fine-grained readers are required/);
assert.equal(f.calls.length, 0);
});
}
for (const status of [401, 403, 404, 429, 500]) {
test('denied or unavailable intended capability fails closed: ' + status, async () => {
const f = fixture({ allowedStatus: status });
await assert.rejects(f.run(), /read failed/);
assert.equal(f.messages.length, 0);
});
}
for (const status of [200, 302, 429, 500]) {
test('an unproven negative capability does not pass: ' + status, async () => {
const f = fixture({ deniedStatus: status });
await assert.rejects(f.run(), /outside its approved capability/);
});
}
test('403 also proves the other capability is denied', async () => {
await fixture({ deniedStatus: 403 }).run();
});
for (const option of ['invalidJson', 'invalidShape', 'transportError']) {
test(option + ' never leaks a token or response details through an error', async () => {
const f = fixture({ [option]: true });
await assert.rejects(f.run(), error => !error.message.includes(settingsToken) && !error.message.includes(privateToken) && !error.message.includes('private transport detail'));
});
}
test('manual protected-source route has no checkout, build, or repository-token permissions', () => {
assert.match(workflow, /on:\n workflow_dispatch:\n/);
assert.match(workflow, /permissions: \{\}/);
assert.match(workflow, /github\.ref == 'refs\/heads\/sprint'/);
assert.equal(workflow.includes('actions/checkout'), false);
assert.equal(workflow.includes('run:'), false);
});
11 changes: 8 additions & 3 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,17 @@ jobs:

steps:
- name: Checkout code
uses: actions/checkout@v7
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false

- name: Initialize CodeQL
uses: github/codeql-action/init@v4
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4
with:
languages: javascript-typescript

- name: Analyze
uses: github/codeql-action/analyze@v4
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4
with:
category: keeper-javascript-typescript/
wait-for-processing: true
30 changes: 30 additions & 0 deletions .github/workflows/keeper-cloud-reader-contracts.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Cloud reader contracts

on:
pull_request:
paths:
- '.github/workflows/keeper-cloud-readers.yml'
- '.github/workflows/keeper-cloud-reader-contracts.yml'
- '.github/tests/cloud-readers.test.cjs'
push:
branches: [sprint]
paths:
- '.github/workflows/keeper-cloud-readers.yml'
- '.github/workflows/keeper-cloud-reader-contracts.yml'
- '.github/tests/cloud-readers.test.cjs'

permissions:
contents: read

jobs:
contracts:
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
with:
node-version: '24'
- run: node --test .github/tests/cloud-readers.test.cjs
58 changes: 58 additions & 0 deletions .github/workflows/keeper-cloud-readers.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
name: Verify cloud reader access

on:
workflow_dispatch:

permissions: {}

jobs:
verify:
if: github.repository == 'KeeperCommunity/bitcoin-keeper' && github.ref == 'refs/heads/sprint'
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- name: Verify only the approved read capabilities
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
env:
SETTINGS_READER: ${{ secrets.KEEPER_CANONICAL_PIN_READ_TOKEN }}
PRIVATE_TEST_READER: ${{ secrets.KEEPER_CANONICAL_PRIVATE_ACTIONS_READ_TOKEN }}
with:
script: |
const settings = process.env.SETTINGS_READER;
const privateTests = process.env.PRIVATE_TEST_READER;
delete process.env.SETTINGS_READER;
delete process.env.PRIVATE_TEST_READER;
if (![settings, privateTests].every(value => typeof value === 'string' && /^github_pat_[A-Za-z0-9_]{20,250}$/.test(value))) {
throw new Error('Both approved fine-grained readers are required');
}
core.setSecret(settings);
core.setSecret(privateTests);
const routes = Object.freeze({
settings: 'https://api.github.com/repos/KeeperCommunity/bitcoin-keeper/actions/variables?per_page=1',
privateTests: 'https://api.github.com/repos/KeeperCommunity/bitcoin-keeper-private/actions/runs?per_page=1',
});
async function read(token, url) {
try {
return await fetch(url, {
method: 'GET', redirect: 'error', signal: AbortSignal.timeout(20000),
headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' },
});
} catch {
throw new Error('Approved GitHub read could not be completed');
}
}
async function verify(token, allowed, denied, field, label) {
const response = await read(token, allowed);
if (response.status !== 200) throw new Error(`${label} read failed (HTTP ${response.status})`);
let body;
try { body = await response.json(); } catch { throw new Error(`${label} response format was invalid`); }
if (!body || !Array.isArray(body[field])) throw new Error(`${label} response format was invalid`);
const other = await read(token, denied);
if (![403, 404].includes(other.status)) throw new Error(`${label} has access outside its approved capability`);
core.info(`${label}: approved read verified; other capability denied`);
}
await verify(settings, routes.settings, routes.privateTests, 'variables', 'Settings reader');
await verify(privateTests, routes.privateTests, routes.settings, 'workflow_runs', 'Private test reader');
await core.summary.addHeading('Cloud reader access verified')
.addRaw('Both limited readers passed their API checks. No private results or configuration values are included. This check does not establish native acceptance or release readiness.')
.write();
Loading