Skip to content

Commit 93db1f7

Browse files
committed
Add local test for token generate and identity map separately
1 parent 3d1617b commit 93db1f7

File tree

2 files changed

+358
-132
lines changed

2 files changed

+358
-132
lines changed
Lines changed: 345 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,345 @@
1+
2+
import { crypto } from "k6/experimental/webcrypto";
3+
import encoding from 'k6/encoding';
4+
import { check } from 'k6';
5+
import http from 'k6/http';
6+
7+
const vus = 300;
8+
// Get Key and Secret from: https://start.1password.com/open/i?a=SWHBRR7FURBBXPZORJWBGP5UBM&v=cknem3yiubq6f2guyizd2ifsnm&i=ywhkqovi4p5wzoi7me4564hod4&h=thetradedesk.1password.com
9+
const baseUrl = "";
10+
const clientSecret = "";
11+
const clientKey = "";
12+
const identityMapVUs = 300;
13+
const identityMapLargeBatchVUs = 10;
14+
15+
const generateVUs = vus;
16+
const testDuration = '5m'
17+
18+
export const options = {
19+
insecureSkipTLSVerify: true,
20+
noConnectionReuse: false,
21+
scenarios: {
22+
// Warmup scenarios
23+
identityMapWarmup: {
24+
executor: 'ramping-vus',
25+
exec: 'identityMap',
26+
stages: [
27+
{ duration: '30s', target: identityMapVUs}
28+
],
29+
gracefulRampDown: '0s',
30+
},
31+
// Actual testing scenarios
32+
// identityMap: {
33+
// executor: 'constant-vus',
34+
// exec: 'identityMap',
35+
// vus: identityMapVUs,
36+
// duration: testDuration,
37+
// gracefulStop: '0s',
38+
// startTime: '40s',
39+
// },
40+
// identityMapLargeBatchSequential: {
41+
// executor: 'constant-vus',
42+
// exec: 'identityMapLargeBatch',
43+
// vus: 1,
44+
// duration: '300s',
45+
// gracefulStop: '0s',
46+
// startTime: '40s',
47+
// },
48+
identityMapLargeBatch: {
49+
executor: 'constant-vus',
50+
exec: 'identityMapLargeBatch',
51+
vus: identityMapLargeBatchVUs,
52+
duration: '300s',
53+
gracefulStop: '0s',
54+
startTime: '40s',
55+
},
56+
},
57+
// So we get count in the summary, to demonstrate different metrics are different
58+
summaryTrendStats: ['avg', 'min', 'med', 'max', 'p(90)', 'p(95)', 'p(99)', 'count'],
59+
thresholds: {
60+
// Intentionally empty. We'll programatically define our bogus
61+
// thresholds (to generate the sub-metrics) below. In your real-world
62+
// load test, you can add any real threshoulds you want here.
63+
}
64+
};
65+
66+
// https://community.k6.io/t/multiple-scenarios-metrics-per-each/1314/3
67+
for (let key in options.scenarios) {
68+
// Each scenario automaticall tags the metrics it generates with its own name
69+
let thresholdName = `http_req_duration{scenario:${key}}`;
70+
// Check to prevent us from overwriting a threshold that already exists
71+
if (!options.thresholds[thresholdName]) {
72+
options.thresholds[thresholdName] = [];
73+
}
74+
// 'max>=0' is a bogus condition that will always be fulfilled
75+
options.thresholds[thresholdName].push('max>=0');
76+
}
77+
78+
export async function setup() {
79+
var token = await generateRefreshRequest();
80+
return {
81+
tokenGenerate: null,
82+
identityMap: null,
83+
refreshToken: token
84+
};
85+
86+
async function generateRefreshRequest() {
87+
let request = await createReq( {'optout_check': 1, 'email': '[email protected]'});
88+
var requestData = {
89+
endpoint: '/v2/token/generate',
90+
requestBody: request,
91+
}
92+
let response = await send(requestData, clientKey);
93+
let decrypt = await decryptEnvelope(response.body, clientSecret)
94+
return decrypt.body.refresh_token;
95+
};
96+
}
97+
98+
// Scenarios
99+
export async function tokenGenerate(data) {
100+
const endpoint = '/v2/token/generate';
101+
if (data.tokenGenerate == null) {
102+
var newData = await generateTokenGenerateRequestWithTime();
103+
data.tokenGenerate = newData;
104+
} else if (data.tokenGenerate.time < (Date.now() - 45000)) {
105+
data.tokenGenerate = await generateTokenGenerateRequestWithTime();
106+
}
107+
108+
var requestBody = data.tokenGenerate.requestBody;
109+
var tokenGenerateData = {
110+
endpoint: endpoint,
111+
requestBody: requestBody,
112+
}
113+
114+
execute(tokenGenerateData, true);
115+
}
116+
117+
export async function identityMap(data) {
118+
const endpoint = '/v2/identity/map';
119+
if ((data.identityMap == null) || (data.identityMap.time < (Date.now() - 45000))) {
120+
data.identityMap = await generateIdentityMapRequestWithTime(2);;
121+
}
122+
123+
var requestBody = data.identityMap.requestBody;
124+
var identityData = {
125+
endpoint: endpoint,
126+
requestBody: requestBody,
127+
}
128+
execute(identityData, true);
129+
}
130+
131+
export async function identityMapLargeBatch(data) {
132+
const endpoint = '/v2/identity/map';
133+
if ((data.identityMap == null) || (data.identityMap.time < (Date.now() - 45000))) {
134+
data.identityMap = await generateIdentityMapRequestWithTime(5000);;
135+
}
136+
137+
var requestBody = data.identityMap.requestBody;
138+
var identityData = {
139+
endpoint: endpoint,
140+
requestBody: requestBody,
141+
}
142+
execute(identityData, true);
143+
}
144+
145+
// Helpers
146+
async function createReqWithTimestamp(timestampArr, obj) {
147+
var envelope = getEnvelopeWithTimestamp(timestampArr, obj);
148+
return encoding.b64encode((await encryptEnvelope(envelope, clientSecret)).buffer);
149+
}
150+
151+
function generateIdentityMapRequest(emailCount) {
152+
var data = {
153+
'optout_check': 1,
154+
"email": []
155+
};
156+
157+
for (var i = 0; i < emailCount; ++i) {
158+
data.email.push(`test${i}@example.com`);
159+
}
160+
161+
return data;
162+
}
163+
164+
function send(data, auth) {
165+
var options = {};
166+
if (auth) {
167+
options.headers = {
168+
'Authorization': `Bearer ${clientKey}`
169+
};
170+
}
171+
172+
return http.post(`${baseUrl}${data.endpoint}`, data.requestBody, options);
173+
}
174+
175+
function execute(data, auth) {
176+
var response = send(data, auth);
177+
178+
check(response, {
179+
'status is 200': r => r.status === 200,
180+
});
181+
}
182+
183+
async function encryptEnvelope(envelope, clientSecret) {
184+
const rawKey = encoding.b64decode(clientSecret);
185+
const key = await crypto.subtle.importKey("raw", rawKey, "AES-GCM", true, [
186+
"encrypt",
187+
"decrypt",
188+
]);
189+
190+
const iv = crypto.getRandomValues(new Uint8Array(12));
191+
192+
const ciphertext = new Uint8Array(await crypto.subtle.encrypt(
193+
{
194+
name: "AES-GCM",
195+
iv: iv,
196+
},
197+
key,
198+
envelope
199+
));
200+
201+
const result = new Uint8Array(+(1 + iv.length + ciphertext.length));
202+
203+
// The version of the envelope format.
204+
result[0] = 1;
205+
206+
result.set(iv, 1);
207+
208+
// The tag is at the end of ciphertext.
209+
result.set(ciphertext, 1 + iv.length);
210+
211+
return result;
212+
}
213+
214+
async function decryptEnvelope(envelope, clientSecret) {
215+
const rawKey = encoding.b64decode(clientSecret);
216+
const rawData = encoding.b64decode(envelope);
217+
const key = await crypto.subtle.importKey("raw", rawKey, "AES-GCM", true, [
218+
"encrypt",
219+
"decrypt",
220+
]);
221+
const length = rawData.byteLength;
222+
const iv = rawData.slice(0, 12);
223+
224+
const decrypted = await crypto.subtle.decrypt(
225+
{
226+
name: "AES-GCM",
227+
iv: iv,
228+
tagLength: 128
229+
},
230+
key,
231+
rawData.slice(12)
232+
);
233+
234+
235+
const decryptedResponse = String.fromCharCode.apply(String, new Uint8Array(decrypted.slice(16)));
236+
const response = JSON.parse(decryptedResponse);
237+
238+
return response;
239+
}
240+
241+
function getEnvelopeWithTimestamp(timestampArray, obj) {
242+
var randomBytes = new Uint8Array(8);
243+
crypto.getRandomValues(randomBytes);
244+
245+
var payload = stringToUint8Array(JSON.stringify(obj));
246+
247+
var envelope = new Uint8Array(timestampArray.length + randomBytes.length + payload.length);
248+
envelope.set(timestampArray);
249+
envelope.set(randomBytes, timestampArray.length);
250+
envelope.set(payload, timestampArray.length + randomBytes.length);
251+
252+
return envelope;
253+
254+
}
255+
function getEnvelope(obj) {
256+
var timestampArr = new Uint8Array(getTimestamp());
257+
return getEnvelopeWithTimestamp(timestampArr, obj);
258+
}
259+
260+
function getTimestamp() {
261+
const now = Date.now();
262+
return getTimestampFromTime(now);
263+
}
264+
265+
function getTimestampFromTime(time) {
266+
const res = new ArrayBuffer(8);
267+
const { hi, lo } = Get32BitPartsBE(time);
268+
const view = new DataView(res);
269+
view.setUint32(0, hi, false);
270+
view.setUint32(4, lo, false);
271+
return res;
272+
}
273+
274+
// http://anuchandy.blogspot.com/2015/03/javascript-how-to-extract-lower-32-bit.html
275+
function Get32BitPartsBE(bigNumber) {
276+
if (bigNumber > 9007199254740991) {
277+
// Max int that JavaScript can represent is 2^53.
278+
throw new Error('The 64-bit value is too big to be represented in JS :' + bigNumber);
279+
}
280+
281+
var bigNumberAsBinaryStr = bigNumber.toString(2);
282+
// Convert the above binary str to 64 bit (actually 52 bit will work) by padding zeros in the left
283+
var bigNumberAsBinaryStr2 = '';
284+
for (var i = 0; i < 64 - bigNumberAsBinaryStr.length; i++) {
285+
bigNumberAsBinaryStr2 += '0';
286+
};
287+
288+
bigNumberAsBinaryStr2 += bigNumberAsBinaryStr;
289+
290+
return {
291+
hi: parseInt(bigNumberAsBinaryStr2.substring(0, 32), 2),
292+
lo: parseInt(bigNumberAsBinaryStr2.substring(32), 2),
293+
};
294+
}
295+
296+
function stringToUint8Array(str) {
297+
const buffer = new ArrayBuffer(str.length);
298+
const view = new Uint8Array(buffer);
299+
for (var i = 0; i < str.length; i++) {
300+
view[i] = str.charCodeAt(i);
301+
}
302+
return view;
303+
}
304+
305+
async function createReq(obj) {
306+
var envelope = getEnvelope(obj);
307+
return encoding.b64encode((await encryptEnvelope(envelope, clientSecret)).buffer);
308+
};
309+
310+
async function generateRequestWithTime(obj) {
311+
var time = Date.now();
312+
var timestampArr = new Uint8Array(getTimestampFromTime(time));
313+
var requestBody = await createReqWithTimestamp(timestampArr, obj);
314+
var element = {
315+
time: time,
316+
requestBody: requestBody
317+
};
318+
319+
return element;
320+
}
321+
322+
323+
async function generateTokenGenerateRequestWithTime() {
324+
let requestData = { 'optout_check': 1, 'email': '[email protected]' };
325+
return await generateRequestWithTime(requestData);
326+
}
327+
328+
async function generateIdentityMapRequestWithTime(emailCount) {
329+
let emails = generateIdentityMapRequest(emailCount);
330+
return await generateRequestWithTime(emails);
331+
}
332+
333+
async function generateKeySharingRequestWithTime() {
334+
let requestData = { };
335+
return await generateRequestWithTime(requestData);
336+
}
337+
338+
const generateSinceTimestampStr = () => {
339+
var date = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000 /* 2 days ago */);
340+
var year = date.getFullYear();
341+
var month = (date.getMonth() + 1).toString().padStart(2, '0');
342+
var day = date.getDate().toString().padStart(2, '0');
343+
344+
return `${year}-${month}-${day}T00:00:00`;
345+
};

0 commit comments

Comments
 (0)