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
4 changes: 4 additions & 0 deletions app/cloud-account.js
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,10 @@ class CloudAccount {
rejectCode = reject;
timer = setTimeout(() => reject(new Error(`${this.label} sign-in timed out. Try again.`)), SIGN_IN_TIMEOUT_MS);
this.onCallback = (req, res) => {
// A redirect is answered once, so the socket is closed with the reply.
// Keeping it alive leaves the browser holding an idle connection to a
// server that is about to shut down.
res.setHeader('Connection', 'close');
const url = new URL(req.url, 'http://localhost');
if (req.method !== 'GET' || url.pathname !== '/' || url.searchParams.get('state') !== state) {
res.writeHead(400).end(t('Invalid sign-in callback.'));
Expand Down
52 changes: 32 additions & 20 deletions tests/e2e/lib/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
// fine; performing an action by calling DOM click() or app functions is not.

const fs = require('node:fs');
const net = require('node:net');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { CdpClient, withTimeout } = require('./cdp');
Expand Down Expand Up @@ -49,16 +48,19 @@ function dialogStubSource(answers) {
})()`;
}

function freePort() {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on('error', reject);
server.listen(0, '127.0.0.1', () => {
const { port } = server.address();
server.close(() => resolve(port));
});
});
/** Reads the DevTools port Chromium wrote after binding, so no port is reserved up front. */
function readDevToolsPort(userDataDir) {
const file = path.join(userDataDir, 'DevToolsActivePort');
const text = fs.readFileSync(file, 'utf8');
const port = Number(text.split('\n')[0].trim());
if (!Number.isInteger(port) || port <= 0) throw new Error(`DevToolsActivePort holds no port: ${text.trim()}`);
return port;
}

/** Reads the inspector port out of the "Debugger listening on ws://host:port/..." line Node prints. */
function readInspectPort(log) {
const match = /Debugger listening on ws:\/\/[^:]+:(\d+)\//.exec(log);
return match ? Number(match[1]) : null;
}

async function poll(fn, { timeout = DEFAULT_TIMEOUT_MS, interval = 50, label = 'condition' } = {}) {
Expand Down Expand Up @@ -306,15 +308,17 @@ function keyInfo(name) {
* env extra environment variables for the app
*/
async function launchApp({ dataDir, userDataDir, artifactDir, env = {}, withInspector = true }) {
const cdpPort = await freePort();
const inspectPort = withInspector ? await freePort() : null;
// Ports are chosen by the operating system at bind time, not reserved here
// first: a port that looks free can be taken by another process before
// Electron binds it, which used to make a launch fail with "Address already
// in use". The real ports are read back after the app has bound them.
const args = [
'--disable-dev-shm-usage',
`--user-data-dir=${userDataDir}`,
`--remote-debugging-port=${cdpPort}`,
'--remote-debugging-port=0',
];
if (process.env.STEPFORGE_ALLOW_NO_SANDBOX === '1') args.unshift('--no-sandbox');
if (inspectPort) args.push(`--inspect=${inspectPort}`);
if (withInspector) args.push('--inspect=0');
args.push(REPO_ROOT);

const childEnv = { ...process.env, ...env, STEPFORGE_DATA_DIR: dataDir };
Expand All @@ -330,8 +334,8 @@ async function launchApp({ dataDir, userDataDir, artifactDir, env = {}, withInsp

const app = {
child,
cdpPort,
inspectPort,
cdpPort: null,
inspectPort: null,
log: () => Buffer.concat(logChunks).toString('utf8'),
page: null,
main: null,
Expand All @@ -349,9 +353,13 @@ async function launchApp({ dataDir, userDataDir, artifactDir, env = {}, withInsp
app.close = cleanup;

try {
app.cdpPort = await poll(() => {
if (exited) throw launchError || new Error(`StepForge exited: ${app.log().slice(-2000)}`);
return readDevToolsPort(userDataDir);
}, { timeout: 30000, label: 'StepForge DevTools port' });
const target = await poll(async () => {
if (exited) throw launchError || new Error(`StepForge exited: ${app.log().slice(-2000)}`);
const list = await (await fetch(`http://127.0.0.1:${cdpPort}/json/list`)).json();
const list = await (await fetch(`http://127.0.0.1:${app.cdpPort}/json/list`)).json();
return list.find((t) => t.type === 'page' && t.url.includes('renderer/index.html'));
}, { timeout: 30000, label: 'StepForge window' });
const cdp = new CdpClient(target.webSocketDebuggerUrl);
Expand All @@ -368,7 +376,11 @@ async function launchApp({ dataDir, userDataDir, artifactDir, env = {}, withInsp
label: 'renderer to finish loading',
});
if (withInspector) {
app.main = await connectMainProcess(inspectPort);
app.inspectPort = await poll(() => readInspectPort(app.log()), {
timeout: 15000,
label: 'main process inspector port',
});
app.main = await connectMainProcess(app.inspectPort);
await app.main.evaluate(SHELL_STUB);
await app.main.stubDialogs({});
}
Expand Down Expand Up @@ -431,4 +443,4 @@ async function connectMainProcess(inspectPort) {
};
}

module.exports = { launchApp, poll, freePort, REPO_ROOT, DEFAULT_TIMEOUT_MS };
module.exports = { launchApp, poll, REPO_ROOT, DEFAULT_TIMEOUT_MS };
45 changes: 45 additions & 0 deletions tests/unit/cloud-accounts.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const test = require('node:test');
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const fs = require('node:fs');
const net = require('node:net');
const path = require('node:path');
const { OneDrive, SCOPE } = require('../../app/onedrive');
const { Dropbox, REDIRECT_PORTS } = require('../../app/dropbox');
Expand Down Expand Up @@ -200,6 +201,50 @@ test('OneDrive sign-in keeps waiting when the browser could not be opened, and s
assert.equal((await connected).connected, true);
});

test('the loopback sign-in page closes its connection, leaving no socket to the stopped server', async (t) => {
let link;
const { account } = setup(t, OneDrive, {
clientId: ONEDRIVE_ID,
openExternal: async (url) => { link = url; },
fetchImpl: async (url) => {
if (url.endsWith('/oauth2/v2.0/token')) return json({ access_token: 'access', refresh_token: 'refresh', expires_in: 3600 });
if (url.startsWith('https://graph.microsoft.com/v1.0/me/drive?')) return json({ id: 'drive-123' });
return json({});
},
});
const connected = account.connect();
while (!link) await new Promise((resolve) => setTimeout(resolve, 5));
const authorization = new URL(link);
const redirect = new URL(authorization.searchParams.get('redirect_uri'));

// Both answers the browser can get: the refusal and the success page.
redirect.searchParams.set('code', 'the-code');
redirect.searchParams.set('state', 'wrong');
const refused = await fetch(redirect);
assert.equal(refused.status, 400);
assert.equal(refused.headers.get('connection'), 'close', 'a refused callback closes the connection');
await refused.text();

redirect.searchParams.set('state', authorization.searchParams.get('state'));
const accepted = await fetch(redirect);
assert.equal(accepted.status, 200);
assert.equal(accepted.headers.get('connection'), 'close', 'the success page closes the connection');
await accepted.text();

assert.equal((await connected).connected, true);

// Nothing may still be connected to the loopback port once sign-in is over,
// or the dead socket raises an error after the test that owns it has ended.
const port = Number(redirect.port);
await new Promise((resolve) => setTimeout(resolve, 50));
const reusable = await new Promise((resolve) => {
const probe = net.createServer();
probe.once('error', () => resolve(false));
probe.listen(port, '127.0.0.1', () => probe.close(() => resolve(true)));
});
assert.equal(reusable, true, `port ${port} is free for another listener after sign-in`);
});

// ---- Dropbox --------------------------------------------------------------

test('Dropbox signs in with PKCE on a registered port and asks for offline access', async (t) => {
Expand Down
Loading