summaryrefslogtreecommitdiffstats
path: root/test/http2-alpn.js
blob: 04b8cb6abd8c9b22e278c958742a11fce4f82629 (plain)
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
'use strict'

const https = require('node:https')
const { once } = require('node:events')
const { createSecureServer } = require('node:http2')
const { readFileSync } = require('node:fs')
const { join } = require('node:path')
const { test } = require('tap')

const { Client } = require('..')

// get the crypto fixtures
const key = readFileSync(join(__dirname, 'fixtures', 'key.pem'), 'utf8')
const cert = readFileSync(join(__dirname, 'fixtures', 'cert.pem'), 'utf8')
const ca = readFileSync(join(__dirname, 'fixtures', 'ca.pem'), 'utf8')

test('Should upgrade to HTTP/2 when HTTPS/1 is available for GET', async (t) => {
  t.plan(10)

  const body = []
  const httpsBody = []

  // create the server and server stream handler
  const server = createSecureServer(
    {
      key,
      cert,
      allowHTTP1: true
    },
    (req, res) => {
      const { socket: { alpnProtocol } } = req.httpVersion === '2.0' ? req.stream.session : req

      // handle http/1 requests
      res.writeHead(200, {
        'content-type': 'application/json; charset=utf-8',
        'x-custom-request-header': req.headers['x-custom-request-header'] || '',
        'x-custom-response-header': `using ${req.httpVersion}`
      })
      res.end(JSON.stringify({
        alpnProtocol,
        httpVersion: req.httpVersion
      }))
    }
  )

  server.listen(0)
  await once(server, 'listening')

  // close the server on teardown
  t.teardown(server.close.bind(server))

  // set the port
  const port = server.address().port

  // test undici against http/2
  const client = new Client(`https://localhost:${port}`, {
    connect: {
      ca,
      servername: 'agent1'
    },
    allowH2: true
  })

  // close the client on teardown
  t.teardown(client.close.bind(client))

  // make an undici request using where it wants http/2
  const response = await client.request({
    path: '/',
    method: 'GET',
    headers: {
      'x-custom-request-header': 'want 2.0'
    }
  })

  response.body.on('data', chunk => {
    body.push(chunk)
  })

  await once(response.body, 'end')

  t.equal(response.statusCode, 200)
  t.equal(response.headers['content-type'], 'application/json; charset=utf-8')
  t.equal(response.headers['x-custom-request-header'], 'want 2.0')
  t.equal(response.headers['x-custom-response-header'], 'using 2.0')
  t.equal(Buffer.concat(body).toString('utf8'), JSON.stringify({
    alpnProtocol: 'h2',
    httpVersion: '2.0'
  }))

  // make an https request for http/1 to confirm undici is using http/2
  const httpsOptions = {
    ca,
    servername: 'agent1',
    headers: {
      'x-custom-request-header': 'want 1.1'
    }
  }

  const httpsResponse = await new Promise((resolve, reject) => {
    const httpsRequest = https.get(`https://localhost:${port}/`, httpsOptions, (res) => {
      res.on('data', (chunk) => {
        httpsBody.push(chunk)
      })

      res.on('end', () => {
        resolve(res)
      })
    }).on('error', (err) => {
      reject(err)
    })

    t.teardown(httpsRequest.destroy.bind(httpsRequest))
  })

  t.equal(httpsResponse.statusCode, 200)
  t.equal(httpsResponse.headers['content-type'], 'application/json; charset=utf-8')
  t.equal(httpsResponse.headers['x-custom-request-header'], 'want 1.1')
  t.equal(httpsResponse.headers['x-custom-response-header'], 'using 1.1')
  t.equal(Buffer.concat(httpsBody).toString('utf8'), JSON.stringify({
    alpnProtocol: false,
    httpVersion: '1.1'
  }))
})

test('Should upgrade to HTTP/2 when HTTPS/1 is available for POST', async (t) => {
  t.plan(15)

  const requestChunks = []
  const responseBody = []

  const httpsRequestChunks = []
  const httpsResponseBody = []

  const expectedBody = 'hello'
  const buf = Buffer.from(expectedBody)
  const body = new ArrayBuffer(buf.byteLength)

  buf.copy(new Uint8Array(body))

  // create the server and server stream handler
  const server = createSecureServer(
    {
      key,
      cert,
      allowHTTP1: true
    },
    (req, res) => {
      // use the stream handler for http2
      if (req.httpVersion === '2.0') {
        return
      }

      const { socket: { alpnProtocol } } = req

      req.on('data', (chunk) => {
        httpsRequestChunks.push(chunk)
      })

      req.on('end', () => {
        // handle http/1 requests
        res.writeHead(201, {
          'content-type': 'text/plain; charset=utf-8',
          'x-custom-request-header': req.headers['x-custom-request-header'] || '',
          'x-custom-alpn-protocol': alpnProtocol
        })
        res.end('hello http/1!')
      })
    }
  )

  server.on('stream', (stream, headers) => {
    t.equal(headers[':method'], 'POST')
    t.equal(headers[':path'], '/')
    t.equal(headers[':scheme'], 'https')

    const { socket: { alpnProtocol } } = stream.session

    stream.on('data', (chunk) => {
      requestChunks.push(chunk)
    })

    stream.respond({
      ':status': 201,
      'content-type': 'text/plain; charset=utf-8',
      'x-custom-request-header': headers['x-custom-request-header'] || '',
      'x-custom-alpn-protocol': alpnProtocol
    })

    stream.end('hello h2!')
  })

  server.listen(0)
  await once(server, 'listening')

  // close the server on teardown
  t.teardown(server.close.bind(server))

  // set the port
  const port = server.address().port

  // test undici against http/2
  const client = new Client(`https://localhost:${port}`, {
    connect: {
      ca,
      servername: 'agent1'
    },
    allowH2: true
  })

  // close the client on teardown
  t.teardown(client.close.bind(client))

  // make an undici request using where it wants http/2
  const response = await client.request({
    path: '/',
    method: 'POST',
    headers: {
      'x-custom-request-header': 'want 2.0'
    },
    body
  })

  response.body.on('data', (chunk) => {
    responseBody.push(chunk)
  })

  await once(response.body, 'end')

  t.equal(response.statusCode, 201)
  t.equal(response.headers['content-type'], 'text/plain; charset=utf-8')
  t.equal(response.headers['x-custom-request-header'], 'want 2.0')
  t.equal(response.headers['x-custom-alpn-protocol'], 'h2')
  t.equal(Buffer.concat(responseBody).toString('utf-8'), 'hello h2!')
  t.equal(Buffer.concat(requestChunks).toString('utf-8'), expectedBody)

  // make an https request for http/1 to confirm undici is using http/2
  const httpsOptions = {
    ca,
    servername: 'agent1',
    method: 'POST',
    headers: {
      'content-type': 'text/plain; charset=utf-8',
      'content-length': Buffer.byteLength(body),
      'x-custom-request-header': 'want 1.1'
    }
  }

  const httpsResponse = await new Promise((resolve, reject) => {
    const httpsRequest = https.request(`https://localhost:${port}/`, httpsOptions, (res) => {
      res.on('data', (chunk) => {
        httpsResponseBody.push(chunk)
      })

      res.on('end', () => {
        resolve(res)
      })
    }).on('error', (err) => {
      reject(err)
    })

    httpsRequest.on('error', (err) => {
      reject(err)
    })

    httpsRequest.write(Buffer.from(body))

    t.teardown(httpsRequest.destroy.bind(httpsRequest))
  })

  t.equal(httpsResponse.statusCode, 201)
  t.equal(httpsResponse.headers['content-type'], 'text/plain; charset=utf-8')
  t.equal(httpsResponse.headers['x-custom-request-header'], 'want 1.1')
  t.equal(httpsResponse.headers['x-custom-alpn-protocol'], 'false')
  t.equal(Buffer.concat(httpsResponseBody).toString('utf-8'), 'hello http/1!')
  t.equal(Buffer.concat(httpsRequestChunks).toString('utf-8'), expectedBody)
})