-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.test.js
More file actions
287 lines (242 loc) ยท 7.47 KB
/
Copy pathgithub.test.js
File metadata and controls
287 lines (242 loc) ยท 7.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import { describe, it, expect, vi, afterEach } from "vitest";
import {
base64UrlEncode,
createJWT,
importPrivateKey,
sign,
} from "./github.js";
const SIGN_ALGORITHM = "RSASSA-PKCS1-v1_5";
const HASH_ALGORITHM = "SHA-256";
async function generateSigningKeyPair() {
return await crypto.subtle.generateKey(
{
name: SIGN_ALGORITHM,
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: HASH_ALGORITHM,
},
true,
["sign", "verify"]
);
}
function arrayBufferToBase64(buffer) {
let binary = "";
const bytes = new Uint8Array(buffer);
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function formatPem(buffer, label = "PRIVATE KEY") {
const base64 = arrayBufferToBase64(buffer);
const lines = base64.match(/.{1,64}/g) ?? [];
return `-----BEGIN ${label}-----\n${lines.join("\n")}\n-----END ${label}-----`;
}
async function exportPrivateKeyPem(privateKey) {
const pkcs8 = await crypto.subtle.exportKey("pkcs8", privateKey);
return formatPem(pkcs8);
}
function readDerLength(bytes, offset) {
const first = bytes[offset];
if ((first & 0x80) === 0) {
return { length: first, bytesRead: 1 };
}
const size = first & 0x7f;
let length = 0;
for (let i = 0; i < size; i++) {
length = (length << 8) | bytes[offset + 1 + i];
}
return { length, bytesRead: 1 + size };
}
function readDerElement(bytes, offset = 0) {
const tag = bytes[offset];
const { length, bytesRead } = readDerLength(bytes, offset + 1);
const headerLength = 1 + bytesRead;
const start = offset + headerLength;
const end = start + length;
return {
tag,
length,
headerLength,
start,
end,
value: bytes.slice(start, end),
};
}
function encodeDerLength(length) {
if (length < 0x80) {
return Uint8Array.of(length);
}
const octets = [];
let value = length;
while (value > 0) {
octets.unshift(value & 0xff);
value >>= 8;
}
return Uint8Array.of(0x80 | octets.length, ...octets);
}
function encodeDer(tag, value) {
return Uint8Array.of(tag, ...encodeDerLength(value.length), ...value);
}
function concatUint8Arrays(...arrays) {
const totalLength = arrays.reduce((sum, array) => sum + array.length, 0);
const result = new Uint8Array(totalLength);
let offset = 0;
for (const array of arrays) {
result.set(array, offset);
offset += array.length;
}
return result;
}
function wrapPkcs1InPkcs8(pkcs1Der) {
const version = Uint8Array.of(0x02, 0x01, 0x00);
const algorithmIdentifier = Uint8Array.of(
0x30,
0x0d,
0x06,
0x09,
0x2a,
0x86,
0x48,
0x86,
0xf7,
0x0d,
0x01,
0x01,
0x01,
0x05,
0x00
);
const privateKey = encodeDer(0x04, pkcs1Der);
return encodeDer(
0x30,
concatUint8Arrays(version, algorithmIdentifier, privateKey)
);
}
async function exportPkcs1PrivateKey(privateKey) {
const pkcs8 = new Uint8Array(await crypto.subtle.exportKey("pkcs8", privateKey));
const privateKeyInfo = readDerElement(pkcs8);
let offset = privateKeyInfo.start;
const version = readDerElement(pkcs8, offset);
offset = version.end;
const algorithm = readDerElement(pkcs8, offset);
offset = algorithm.end;
const privateKeyOctetString = readDerElement(pkcs8, offset);
return {
der: privateKeyOctetString.value,
pem: formatPem(privateKeyOctetString.value, "RSA PRIVATE KEY"),
};
}
function base64UrlDecode(value) {
const base64 = value.replace(/-/g, "+").replace(/_/g, "/");
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
const binary = atob(padded);
return Uint8Array.from(binary, (char) => char.charCodeAt(0));
}
function decodeJwtPart(value) {
return JSON.parse(new TextDecoder().decode(base64UrlDecode(value)));
}
async function verifySignature(publicKey, data, signature) {
return await crypto.subtle.verify(
SIGN_ALGORITHM,
publicKey,
base64UrlDecode(signature),
new TextEncoder().encode(data)
);
}
afterEach(() => {
vi.restoreAllMocks();
});
describe("base64UrlEncode", () => {
it("๋ฌธ์์ด์ padding ์๋ base64url ๋ก ์ธ์ฝ๋ฉํ๋ค", () => {
expect(base64UrlEncode("Hello")).toBe("SGVsbG8");
});
it("+, /, = ๋ฌธ์๋ฅผ URL-safe ๋ฌธ์๋ก ์นํํ๋ค", () => {
expect(base64UrlEncode(new Uint8Array([251, 255, 238]))).toBe("-__u");
});
});
describe("importPrivateKey", () => {
it("PKCS8 PEM private key ๋ฅผ Web Crypto ์๋ช
ํค๋ก import ํ๋ค", async () => {
const keyPair = await generateSigningKeyPair();
const pem = await exportPrivateKeyPem(keyPair.privateKey);
const importedKey = await importPrivateKey(pem);
const signature = await crypto.subtle.sign(
SIGN_ALGORITHM,
importedKey,
new TextEncoder().encode("payload")
);
const isValid = await crypto.subtle.verify(
SIGN_ALGORITHM,
keyPair.publicKey,
signature,
new TextEncoder().encode("payload")
);
expect(importedKey.type).toBe("private");
expect(importedKey.extractable).toBe(false);
expect(importedKey.usages).toEqual(["sign"]);
expect(isValid).toBe(true);
});
it("PKCS1 PEM RSA private key ๋ Web Crypto ์๋ช
ํค๋ก import ํ๋ค", async () => {
const keyPair = await generateSigningKeyPair();
const { der: pkcs1Der, pem } = await exportPkcs1PrivateKey(keyPair.privateKey);
const expectedPkcs8Bytes = wrapPkcs1InPkcs8(pkcs1Der);
const importKeySpy = vi.spyOn(crypto.subtle, "importKey");
const importedKey = await importPrivateKey(pem);
const signature = await crypto.subtle.sign(
SIGN_ALGORITHM,
importedKey,
new TextEncoder().encode("payload")
);
const isValid = await crypto.subtle.verify(
SIGN_ALGORITHM,
keyPair.publicKey,
signature,
new TextEncoder().encode("payload")
);
expect(importedKey.type).toBe("private");
expect(importedKey.extractable).toBe(false);
expect(importedKey.usages).toEqual(["sign"]);
const importedDer = new Uint8Array(importKeySpy.mock.calls[0][1]);
expect(Array.from(importedDer)).toEqual(Array.from(expectedPkcs8Bytes));
expect(isValid).toBe(true);
});
});
describe("sign", () => {
it("RS256 ์๋ช
์ base64url ๋ฌธ์์ด๋ก ๋ฐํํ๋ค", async () => {
const keyPair = await generateSigningKeyPair();
const pem = await exportPrivateKeyPem(keyPair.privateKey);
const importedKey = await importPrivateKey(pem);
const signature = await sign("header.payload", importedKey);
expect(signature).toMatch(/^[A-Za-z0-9_-]+$/);
expect(signature).not.toContain("=");
expect(await verifySignature(keyPair.publicKey, "header.payload", signature)).toBe(
true
);
});
});
describe("createJWT", () => {
it("GitHub App JWT header/payload ๋ฅผ ๋ง๋ค๊ณ RS256 ์ผ๋ก ์๋ช
ํ๋ค", async () => {
const keyPair = await generateSigningKeyPair();
const pem = await exportPrivateKeyPem(keyPair.privateKey);
vi.spyOn(Date, "now").mockReturnValue(1_700_000_000_000);
const jwt = await createJWT("12345", pem);
const [encodedHeader, encodedPayload, signature] = jwt.split(".");
expect(jwt.split(".")).toHaveLength(3);
expect(decodeJwtPart(encodedHeader)).toEqual({
alg: "RS256",
typ: "JWT",
});
expect(decodeJwtPart(encodedPayload)).toEqual({
iat: 1_699_999_940,
exp: 1_700_000_600,
iss: "12345",
});
expect(
await verifySignature(
keyPair.publicKey,
`${encodedHeader}.${encodedPayload}`,
signature
)
).toBe(true);
});
});