Skip to content

Commit b303dec

Browse files
committed
Add local test for token generate and identity map separately
1 parent 6806068 commit b303dec

File tree

2 files changed

+364
-132
lines changed

2 files changed

+364
-132
lines changed
Lines changed: 351 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,351 @@
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+
// export function handleSummary(data) {
99+
// return {
100+
// 'summary.json': JSON.stringify(data),
101+
// }
102+
// }
103+
104+
// Scenarios
105+
export async function tokenGenerate(data) {
106+
const endpoint = '/v2/token/generate';
107+
if (data.tokenGenerate == null) {
108+
var newData = await generateTokenGenerateRequestWithTime();
109+
data.tokenGenerate = newData;
110+
} else if (data.tokenGenerate.time < (Date.now() - 45000)) {
111+
data.tokenGenerate = await generateTokenGenerateRequestWithTime();
112+
}
113+
114+
var requestBody = data.tokenGenerate.requestBody;
115+
var tokenGenerateData = {
116+
endpoint: endpoint,
117+
requestBody: requestBody,
118+
}
119+
120+
execute(tokenGenerateData, true);
121+
}
122+
123+
export async function identityMap(data) {
124+
const endpoint = '/v2/identity/map';
125+
if ((data.identityMap == null) || (data.identityMap.time < (Date.now() - 45000))) {
126+
data.identityMap = await generateIdentityMapRequestWithTime(2);;
127+
}
128+
129+
var requestBody = data.identityMap.requestBody;
130+
var identityData = {
131+
endpoint: endpoint,
132+
requestBody: requestBody,
133+
}
134+
execute(identityData, true);
135+
}
136+
137+
export async function identityMapLargeBatch(data) {
138+
const endpoint = '/v2/identity/map';
139+
if ((data.identityMap == null) || (data.identityMap.time < (Date.now() - 45000))) {
140+
data.identityMap = await generateIdentityMapRequestWithTime(5000);;
141+
}
142+
143+
var requestBody = data.identityMap.requestBody;
144+
var identityData = {
145+
endpoint: endpoint,
146+
requestBody: requestBody,
147+
}
148+
execute(identityData, true);
149+
}
150+
151+
// Helpers
152+
async function createReqWithTimestamp(timestampArr, obj) {
153+
var envelope = getEnvelopeWithTimestamp(timestampArr, obj);
154+
return encoding.b64encode((await encryptEnvelope(envelope, clientSecret)).buffer);
155+
}
156+
157+
function generateIdentityMapRequest(emailCount) {
158+
var data = {
159+
'optout_check': 1,
160+
"email": []
161+
};
162+
163+
for (var i = 0; i < emailCount; ++i) {
164+
data.email.push(`test${i}@example.com`);
165+
}
166+
167+
return data;
168+
}
169+
170+
function send(data, auth) {
171+
var options = {};
172+
if (auth) {
173+
options.headers = {
174+
'Authorization': `Bearer ${clientKey}`
175+
};
176+
}
177+
178+
return http.post(`${baseUrl}${data.endpoint}`, data.requestBody, options);
179+
}
180+
181+
function execute(data, auth) {
182+
var response = send(data, auth);
183+
184+
check(response, {
185+
'status is 200': r => r.status === 200,
186+
});
187+
}
188+
189+
async function encryptEnvelope(envelope, clientSecret) {
190+
const rawKey = encoding.b64decode(clientSecret);
191+
const key = await crypto.subtle.importKey("raw", rawKey, "AES-GCM", true, [
192+
"encrypt",
193+
"decrypt",
194+
]);
195+
196+
const iv = crypto.getRandomValues(new Uint8Array(12));
197+
198+
const ciphertext = new Uint8Array(await crypto.subtle.encrypt(
199+
{
200+
name: "AES-GCM",
201+
iv: iv,
202+
},
203+
key,
204+
envelope
205+
));
206+
207+
const result = new Uint8Array(+(1 + iv.length + ciphertext.length));
208+
209+
// The version of the envelope format.
210+
result[0] = 1;
211+
212+
result.set(iv, 1);
213+
214+
// The tag is at the end of ciphertext.
215+
result.set(ciphertext, 1 + iv.length);
216+
217+
return result;
218+
}
219+
220+
async function decryptEnvelope(envelope, clientSecret) {
221+
const rawKey = encoding.b64decode(clientSecret);
222+
const rawData = encoding.b64decode(envelope);
223+
const key = await crypto.subtle.importKey("raw", rawKey, "AES-GCM", true, [
224+
"encrypt",
225+
"decrypt",
226+
]);
227+
const length = rawData.byteLength;
228+
const iv = rawData.slice(0, 12);
229+
230+
const decrypted = await crypto.subtle.decrypt(
231+
{
232+
name: "AES-GCM",
233+
iv: iv,
234+
tagLength: 128
235+
},
236+
key,
237+
rawData.slice(12)
238+
);
239+
240+
241+
const decryptedResponse = String.fromCharCode.apply(String, new Uint8Array(decrypted.slice(16)));
242+
const response = JSON.parse(decryptedResponse);
243+
244+
return response;
245+
}
246+
247+
function getEnvelopeWithTimestamp(timestampArray, obj) {
248+
var randomBytes = new Uint8Array(8);
249+
crypto.getRandomValues(randomBytes);
250+
251+
var payload = stringToUint8Array(JSON.stringify(obj));
252+
253+
var envelope = new Uint8Array(timestampArray.length + randomBytes.length + payload.length);
254+
envelope.set(timestampArray);
255+
envelope.set(randomBytes, timestampArray.length);
256+
envelope.set(payload, timestampArray.length + randomBytes.length);
257+
258+
return envelope;
259+
260+
}
261+
function getEnvelope(obj) {
262+
var timestampArr = new Uint8Array(getTimestamp());
263+
return getEnvelopeWithTimestamp(timestampArr, obj);
264+
}
265+
266+
function getTimestamp() {
267+
const now = Date.now();
268+
return getTimestampFromTime(now);
269+
}
270+
271+
function getTimestampFromTime(time) {
272+
const res = new ArrayBuffer(8);
273+
const { hi, lo } = Get32BitPartsBE(time);
274+
const view = new DataView(res);
275+
view.setUint32(0, hi, false);
276+
view.setUint32(4, lo, false);
277+
return res;
278+
}
279+
280+
// http://anuchandy.blogspot.com/2015/03/javascript-how-to-extract-lower-32-bit.html
281+
function Get32BitPartsBE(bigNumber) {
282+
if (bigNumber > 9007199254740991) {
283+
// Max int that JavaScript can represent is 2^53.
284+
throw new Error('The 64-bit value is too big to be represented in JS :' + bigNumber);
285+
}
286+
287+
var bigNumberAsBinaryStr = bigNumber.toString(2);
288+
// Convert the above binary str to 64 bit (actually 52 bit will work) by padding zeros in the left
289+
var bigNumberAsBinaryStr2 = '';
290+
for (var i = 0; i < 64 - bigNumberAsBinaryStr.length; i++) {
291+
bigNumberAsBinaryStr2 += '0';
292+
};
293+
294+
bigNumberAsBinaryStr2 += bigNumberAsBinaryStr;
295+
296+
return {
297+
hi: parseInt(bigNumberAsBinaryStr2.substring(0, 32), 2),
298+
lo: parseInt(bigNumberAsBinaryStr2.substring(32), 2),
299+
};
300+
}
301+
302+
function stringToUint8Array(str) {
303+
const buffer = new ArrayBuffer(str.length);
304+
const view = new Uint8Array(buffer);
305+
for (var i = 0; i < str.length; i++) {
306+
view[i] = str.charCodeAt(i);
307+
}
308+
return view;
309+
}
310+
311+
async function createReq(obj) {
312+
var envelope = getEnvelope(obj);
313+
return encoding.b64encode((await encryptEnvelope(envelope, clientSecret)).buffer);
314+
};
315+
316+
async function generateRequestWithTime(obj) {
317+
var time = Date.now();
318+
var timestampArr = new Uint8Array(getTimestampFromTime(time));
319+
var requestBody = await createReqWithTimestamp(timestampArr, obj);
320+
var element = {
321+
time: time,
322+
requestBody: requestBody
323+
};
324+
325+
return element;
326+
}
327+
328+
329+
async function generateTokenGenerateRequestWithTime() {
330+
let requestData = { 'optout_check': 1, 'email': '[email protected]' };
331+
return await generateRequestWithTime(requestData);
332+
}
333+
334+
async function generateIdentityMapRequestWithTime(emailCount) {
335+
let emails = generateIdentityMapRequest(emailCount);
336+
return await generateRequestWithTime(emails);
337+
}
338+
339+
async function generateKeySharingRequestWithTime() {
340+
let requestData = { };
341+
return await generateRequestWithTime(requestData);
342+
}
343+
344+
const generateSinceTimestampStr = () => {
345+
var date = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000 /* 2 days ago */);
346+
var year = date.getFullYear();
347+
var month = (date.getMonth() + 1).toString().padStart(2, '0');
348+
var day = date.getDate().toString().padStart(2, '0');
349+
350+
return `${year}-${month}-${day}T00:00:00`;
351+
};

0 commit comments

Comments
 (0)