Skip to content

Commit

Permalink
chore: simplify ca cert handling for app and inso (#4738)
Browse files Browse the repository at this point in the history
* move file write to main

* fix tests

* fix path import

* generate root certs at app start

* remove unused scripts

* consistently use os.tmpdir for cacerts

* clean up gitignore

* setup ca cert once

* use cainfo_blob

* fix lint

* fix curl mock

* fix formatting
  • Loading branch information
jackkav authored May 11, 2022
1 parent 4e47da1 commit bddf13a
Show file tree
Hide file tree
Showing 8 changed files with 19 additions and 49 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,4 @@ packages/insomnia-smoke-test/screenshots
*.tsbuildinfo
dist
.history
packages/insomnia/src/network/ca_certs.ts
packages/insomnia/src/main.min.js.map
5 changes: 2 additions & 3 deletions packages/insomnia/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,13 @@
"scripts": {
"bootstrap": "npm run build:sr",
"prebuild": "npm run clean",
"build": "npm run generate:ca-certs && npm run build:sr && npm run build:app",
"build": "npm run build:sr && npm run build:app",
"build:app": "esr --cache ./scripts/build.ts --noErrorTruncation",
"build:main.min.js": "cross-env NODE_ENV=development esr esbuild.main.ts",
"build:sr": "npm run generate:ca-certs && esr esbuild.sr.ts",
"build:sr": " esr esbuild.sr.ts",
"bump-version": "esr scripts/bumpVersion.ts",
"clean": "tsc --build tsconfig.build.json --clean",
"postclean": "rimraf build dist src/main.min.js",
"generate:ca-certs": "esr scripts/generateCACerts.ts",
"lint": "eslint . --ext .js,.ts,.tsx --cache",
"lint:fix": "npm run lint -- --fix",
"package": "cross-env USE_HARD_LINKS=false electron-builder build --config electron-builder.config.js",
Expand Down
10 changes: 0 additions & 10 deletions packages/insomnia/scripts/generateCACerts.ts

This file was deleted.

3 changes: 2 additions & 1 deletion packages/insomnia/src/__mocks__/@getinsomnia/node-libcurl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class Curl extends EventEmitter {
static option = {
ACCEPT_ENCODING: 'ACCEPT_ENCODING',
CAINFO: 'CAINFO',
CAINFO_BLOB: 'CAINFO_BLOB',
COOKIEFILE: 'COOKIEFILE',
COOKIELIST: 'COOKIELIST',
CUSTOMREQUEST: 'CUSTOMREQUEST',
Expand Down Expand Up @@ -77,7 +78,7 @@ class Curl extends EventEmitter {
throw new Error(`Invalid option ${name} ${value}`);
}

if (name === Curl.option.CAINFO) {
if (name === Curl.option.CAINFO_BLOB) {
// Just ignore this because it's platform-specific
return;
}
Expand Down
20 changes: 9 additions & 11 deletions packages/insomnia/src/main.development.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as electron from 'electron';
import contextMenu from 'electron-context-menu';
import installExtension, { REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS } from 'electron-devtools-installer';
import { writeFile } from 'fs';
import { writeFile } from 'fs/promises';
import path from 'path';

import appConfig from '../config/config.json';
Expand Down Expand Up @@ -226,7 +226,7 @@ async function _trackStats() {
return { filePath, canceled };
});

ipcMain.handle('installPlugin', async (_, options) => {
ipcMain.handle('installPlugin', (_, options) => {
return installPlugin(options);
});

Expand Down Expand Up @@ -263,15 +263,13 @@ async function _trackStats() {
return authorizeUserInWindow({ url, urlSuccessRegex, urlFailureRegex, sessionId });
});

ipcMain.handle('writeFile', (_, options) => {
return new Promise<string>((resolve, reject) => {
writeFile(options.path, options.content, err => {
if (err != null) {
return reject(err);
}
resolve(options.path);
});
});
ipcMain.handle('writeFile', async (_, options) => {
try {
await writeFile(options.path, options.content);
return options.path;
} catch (err) {
throw new Error(err);
}
});

ipcMain.handle('curlRequest', (_, options) => {
Expand Down
6 changes: 3 additions & 3 deletions packages/insomnia/src/network/libcurl-promise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import fs from 'fs';
import mkdirp from 'mkdirp';
import path from 'path';
import { Readable, Writable } from 'stream';
import tls from 'tls';
import { ValueOf } from 'type-fest';
import { parse as urlParse } from 'url';
import { v4 as uuidv4 } from 'uuid';
Expand All @@ -29,7 +30,6 @@ interface CurlRequestOptions {
finalUrl: string;
settings: SettingsUsedHere;
certificates: ClientCertificate[];
fullCAPath: string;
socketPath?: string;
authHeader?: { name: string; value: string };
}
Expand Down Expand Up @@ -82,7 +82,7 @@ export const curlRequest = (options: CurlRequestOptions) => new Promise<CurlRequ
const responseBodyPath = path.join(responsesDir, uuidv4() + '.response');
const debugTimeline: ResponseTimelineEntry[] = [];

const { requestId, req, finalUrl, settings, certificates, fullCAPath, socketPath, authHeader } = options;
const { requestId, req, finalUrl, settings, certificates, socketPath, authHeader } = options;
const curl = new Curl();

curl.setOpt(Curl.option.URL, finalUrl);
Expand All @@ -92,7 +92,7 @@ export const curlRequest = (options: CurlRequestOptions) => new Promise<CurlRequ
curl.setOpt(Curl.option.NOPROGRESS, true); // True so debug function works
curl.setOpt(Curl.option.ACCEPT_ENCODING, ''); // True so curl doesn't print progress

curl.setOpt(Curl.option.CAINFO, fullCAPath);
curl.setOpt(Curl.option.CAINFO_BLOB, tls.rootCertificates.join('\n'));

certificates.forEach(validCert => {
const { passphrase, cert, key, pfx } = validCert;
Expand Down
4 changes: 2 additions & 2 deletions packages/insomnia/src/network/multipart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ if (process.type === 'renderer') {
throw new Error('multipart.ts unavailable in renderer');
}

import electron from 'electron';
import fs from 'fs';
import { lookup } from 'mime-types';
import os from 'os';
import path from 'path';

import type { RequestBodyParameter } from '../models/request';
Expand All @@ -19,7 +19,7 @@ interface Multipart {

export async function buildMultipart(params: RequestBodyParameter[]) {
return new Promise<Multipart>(async (resolve, reject) => {
const filePath = path.join(electron.app.getPath('temp'), Math.random() + '.body');
const filePath = path.join(os.tmpdir(), Math.random() + '.body');
const writeStream = fs.createWriteStream(filePath);
const lineBreak = '\r\n';
let totalSize = 0;
Expand Down
19 changes: 1 addition & 18 deletions packages/insomnia/src/network/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
STATUS_CODE_PLUGIN_ERROR,
} from '../common/constants';
import { database as db } from '../common/database';
import { getDataDirectory, getTempDir } from '../common/electron-helpers';
import { getDataDirectory } from '../common/electron-helpers';
import {
delay,
getContentTypeHeader,
Expand All @@ -38,7 +38,6 @@ import { isWorkspace } from '../models/workspace';
import * as pluginContexts from '../plugins/context/index';
import * as plugins from '../plugins/index';
import { getAuthHeader } from './authentication';
import caCerts from './ca_certs';
import { urlMatchesCertHost } from './url-matches-cert-host';

export interface ResponsePatch {
Expand Down Expand Up @@ -127,21 +126,6 @@ export async function _actuallySend(
timeline.push({ value: `Current time is ${new Date().toISOString()}`, name: 'TEXT', timestamp: Date.now() });
timeline.push({ value: `${renderedRequest.settingEncodeUrl ? 'Enable' : 'Disable'} automatic URL encoding`, name: 'TEXT', timestamp: Date.now() });

// Setup CA Root Certificates
const baseCAPath = getTempDir();
const fullCAPath = pathJoin(baseCAPath, 'ca-certs.pem');

try {
fs.statSync(fullCAPath);
} catch (err) {
// Doesn't exist yet, so write it
mkdirp.sync(baseCAPath);
// TODO: Should mock cacerts module for testing.
// This is literally coercing a function to string in tests due to lack of val-loader.
fs.writeFileSync(fullCAPath, String(caCerts));
console.log('[net] Set CA to', fullCAPath);
}

if (!renderedRequest.settingSendCookies) {
timeline.push({ value: 'Disable cookie sending due to user setting', name: 'TEXT', timestamp: Date.now() });
}
Expand All @@ -162,7 +146,6 @@ export async function _actuallySend(
socketPath,
settings,
certificates,
fullCAPath,
authHeader,
};
const { patch, debugTimeline, headerResults, responseBodyPath } = await nodejsCurlRequest(requestOptions);
Expand Down

0 comments on commit bddf13a

Please sign in to comment.