Skip to content

Commit

Permalink
feat: enable Request and Response in pre-request scripting [INS-3379] (
Browse files Browse the repository at this point in the history
…Kong#7128)

* feat: enable ProxyConfig in pre-request scripting

* feat: enable RequestAuth for pre-request scripting

* feat: enable Cookie in pre-request scripting

* feat: enable Certificate in pre-request script

* feat: enable Request and Response in pre-request scripting
  • Loading branch information
ihexxa authored and jackkav committed Mar 13, 2024
1 parent c1a8aff commit 01c0cf6
Show file tree
Hide file tree
Showing 16 changed files with 2,065 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ test.describe('pre-request UI tests', async () => {
},
},
{
name: 'require / require classes from insomnia-collection module',
name: 'require / require classes from insomnia-collection module and init them',
preReqScript: `
const { Property, Header, Variable, QueryParam, Url } = require('insomnia-collection');
const { Property, Header, Variable, QueryParam, Url, RequestAuth, ProxyConfig, Cookie, Certificate, RequestBody, Request, Response } = require('insomnia-collection');
const prop = new Property('pid', 'pname');
const header = new Header({ key: 'headerKey', value: 'headerValue' });
const variable = new Variable({ key: 'headerKey', value: 'headerValue' });
Expand All @@ -82,6 +82,79 @@ test.describe('pre-request UI tests', async () => {
path: ['path1', 'path2'],
protocol: 'https',
});
const proxyConfig = new ProxyConfig({
match: 'http+https://*.example.com:80/*',
host: 'proxy.com',
port: 8080,
tunnel: true,
disabled: false,
authenticate: true,
username: 'proxy_username',
password: 'proxy_password',
});
const reqAuth = new RequestAuth({
type: 'basic',
basic: [
{ key: 'username', value: 'user1' },
{ key: 'password', value: 'pwd1' },
],
});
const cookie = new Cookie({ key: 'queryKey', value: 'queryValue' });
const cert = new Certificate({
name: 'Certificate for example.com',
matches: ['https://example.com'],
key: { src: '/User/path/to/certificate/key' },
cert: { src: '/User/path/to/certificate' },
passphrase: 'iampassphrase',
});
const reqBody = new RequestBody({
mode: 'urlencoded',
urlencoded: [
{ key: 'urlencodedKey', value: 'urlencodedValue' },
],
options: {},
});
const req = new Request({
url: 'https://hostname.com/path',
method: 'GET',
header: [
{ key: 'header1', value: 'val1' },
{ key: 'header2', value: 'val2' },
],
body: {
mode: 'raw',
raw: 'body content',
},
auth: {
type: 'basic',
basic: [
{ key: 'username', value: 'myname' },
{ key: 'password', value: 'mypwd' },
],
},
proxy: undefined,
certificate: undefined,
});
const resp = new Response({
code: 200,
reason: 'OK',
header: [
{ key: 'header1', value: 'val1' },
{ key: 'header2', value: 'val2' },
{ key: 'Content-Length', value: '100' },
{ key: 'Content-Disposition', value: 'attachment; filename="filename.txt"' },
{ key: 'Content-Type', value: 'text/plain; charset=utf-8' },
],
cookie: [
{ key: 'header1', value: 'val1' },
{ key: 'header2', value: 'val2' },
],
body: '{"key": 888}',
stream: undefined,
responseTime: 100,
status: 'OK',
originalRequest: req,
});
// set part of values
insomnia.environment.set('propJson', JSON.stringify(prop.toJSON()));
insomnia.environment.set('headerJson', JSON.stringify(header.toJSON()));
Expand Down
63 changes: 63 additions & 0 deletions packages/insomnia/src/sdk/objects/__tests__/auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { describe, expect, it } from '@jest/globals';

import { RequestAuth } from '../auth';
import { Variable, VariableList } from '../variables';

const varListToObject = (obj: VariableList<Variable> | undefined) => {
if (!obj) {
return undefined;
}

return obj.map(
(optVar: Variable) => ({
// type: 'any', // TODO: fix type
key: optVar.key,
value: optVar.value,
}),
{}
);
};

describe('test sdk objects', () => {
it('test RequestAuth methods', () => {
expect(RequestAuth.isValidType('noauth')).toBeTruthy();

const basicAuthOptions = {
type: 'basic',
basic: [
{ key: 'username', value: 'user1' },
{ key: 'password', value: 'pwd1' },
],
};

const authObj = new RequestAuth(basicAuthOptions);

const basicAuthOptsFromAuth = varListToObject(authObj.parameters());
expect(basicAuthOptsFromAuth).toEqual(basicAuthOptions.basic);

const basicAuthOptions2 = {
type: 'basic',
basic: [
{ key: 'username', value: 'user2' },
{ key: 'password', value: 'pwd2' },
],
};
const bearerAuthOptions = {
type: 'bearer',
bearer: [
{ key: 'token', value: 'mytoken' },
],
};

authObj.update(basicAuthOptions2);
const basicAuthOpt2FromAuth = varListToObject(authObj.parameters());
expect(basicAuthOpt2FromAuth).toEqual(basicAuthOptions2.basic);

authObj.use('bearer', bearerAuthOptions);
const beareerAuthOptFromAuth = varListToObject(authObj.parameters());
expect(beareerAuthOptFromAuth).toEqual(bearerAuthOptions.bearer);

authObj.clear('bearer');
expect(authObj.parameters()).toBeUndefined();
});
});
41 changes: 41 additions & 0 deletions packages/insomnia/src/sdk/objects/__tests__/certificates.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import url from 'node:url';

import { describe, expect, it } from '@jest/globals';

import { Certificate } from '../certificates';
import { setUrlParser } from '../urls';

describe('test Certificate object', () => {
it('test methods', () => {
// make URL work in Node.js
setUrlParser(url.URL);

const cert = new Certificate({
name: 'Certificate for example.com',
matches: ['https://example.com'],
key: { src: '/User/path/to/certificate/key' },
cert: { src: '/User/path/to/certificate' },
passphrase: 'iampassphrase',
});

[
'https://example.com',
'https://example.com/subdomain',
].forEach(testCase => {
expect(cert.canApplyTo(testCase)).toBeTruthy();
});

cert.update({
name: 'Certificate for api.com',
matches: ['https://api.com'],
key: { src: '/User/path/to/certificate/key' },
cert: { src: '/User/path/to/certificate' },
passphrase: 'iampassphrase',
});

expect(cert.name).toEqual('Certificate for api.com');
expect(cert.key).toEqual({ src: '/User/path/to/certificate/key' });
expect(cert.cert).toEqual({ src: '/User/path/to/certificate' });
expect(cert.passphrase).toEqual('iampassphrase');
});
});
68 changes: 68 additions & 0 deletions packages/insomnia/src/sdk/objects/__tests__/cookies.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { describe, expect, it } from '@jest/globals';

import { Cookie } from '../cookies';

describe('test Cookie object', () => {
it('test basic operations', () => {
const cookieStr1 = 'key=value; Domain=inso.com; Path=/; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Max-Age=0;Secure;HttpOnly;HostOnly;Session';

expect(
Cookie.parse(cookieStr1)
).toEqual({
key: 'key',
value: 'value',
domain: 'inso.com',
expires: new Date('2015-10-21T07:28:00.000Z'),
maxAge: '0',
path: '/',
secure: true,
httpOnly: true,
hostOnly: true,
session: true,
extensions: [],
});

const cookie1Opt = {
key: 'myCookie',
value: 'myCookie',
expires: '01 Jan 1970 00:00:01 GMT',
maxAge: '7',
domain: 'domain.com',
path: '/',
secure: true,
httpOnly: true,
hostOnly: true,
session: true,
extensions: [{ key: 'Ext', value: 'ExtValue' }],
};
const cookie1 = new Cookie(cookie1Opt);

const expectedCookieString = 'myCookie=myCookie; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Max-Age=7; Path=/; Secure; HttpOnly; HostOnly; Ext=ExtValue';

expect(cookie1.toString()).toEqual(expectedCookieString);
expect(Cookie.stringify(cookie1)).toEqual(expectedCookieString);

const cookie2 = new Cookie(expectedCookieString);
expect(cookie2.toString()).toEqual(expectedCookieString);
expect(Cookie.stringify(cookie2)).toEqual(expectedCookieString);

const c1 = new Cookie({
key: 'c1',
value: 'c1',
maxAge: '1',
});
const c2 = new Cookie({
key: 'c2',
value: 'c2',
maxAge: '2',
});
const CookieListStr = Cookie.unparse([c1, c2]);
expect(CookieListStr).toEqual(
'c1=c1; Max-Age=1; c2=c2; Max-Age=2'
);

expect(
Cookie.unparseSingle(cookie1Opt)
).toEqual(expectedCookieString);
});
});
57 changes: 57 additions & 0 deletions packages/insomnia/src/sdk/objects/__tests__/proxy-configs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { describe, expect, it } from '@jest/globals';

import { ProxyConfig, ProxyConfigList } from '../proxy-configs';
import { Url } from '../urls';

describe('test ProxyConfig object', () => {
it('test basic operations', () => {

const proxyConfig = new ProxyConfig({
match: 'http+https://*.example.com:80/*',
host: 'proxy.com',
port: 8080,
tunnel: true,
disabled: false,
authenticate: true,
username: 'proxy_username',
password: 'proxy_password',
});

expect(
proxyConfig.getProtocols()
).toEqual(
['http', 'https']
);

proxyConfig.updateProtocols(['http']);
expect(
proxyConfig.getProtocols()
).toEqual(
['http']
);

expect(proxyConfig.getProxyUrl()).toEqual(
'http://proxy_username:proxy_password@proxy.com:8080'
);

expect(
proxyConfig.test('http://a.example.com:80/a')
).toBeTruthy();

const configList = new ProxyConfigList<ProxyConfig>(undefined, []);
configList.add(proxyConfig);
configList.add(new ProxyConfig({
match: 'https://*.example.com:80/*',
host: 'proxy.com',
port: 8080,
tunnel: true,
disabled: false,
authenticate: true,
username: 'proxy_username',
password: 'proxy_password',
}));

const matchedProxyConfigDef = configList.resolve(new Url('http://sub.example.com:80/path'));
expect(matchedProxyConfigDef?.host).toEqual('proxy.com');
});
});
Loading

0 comments on commit 01c0cf6

Please sign in to comment.