Unverified Commit f20728ac authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

fix Image when used with `--experimental-https` (#55775)

The IPC request to `imageOptimizer` assumed the server was listening on http, so this updates it to pull the protocol from `getRequestMeta` instead. This also adds the option to pass in a path to the CA Root so that the dev server can add it to `NODE_EXTRA_CA_CERTS`


Closes NEXT-1646
Fixes #55706
parent 57cd1d02
...@@ -9,6 +9,7 @@ export const validArgs: arg.Spec = { ...@@ -9,6 +9,7 @@ export const validArgs: arg.Spec = {
'--experimental-https': Boolean, '--experimental-https': Boolean,
'--experimental-https-key': String, '--experimental-https-key': String,
'--experimental-https-cert': String, '--experimental-https-cert': String,
'--experimental-https-ca': String,
'--experimental-test-proxy': Boolean, '--experimental-test-proxy': Boolean,
'--experimental-upload-trace': String, '--experimental-upload-trace': String,
......
...@@ -15,7 +15,10 @@ import loadConfig, { getEnabledExperimentalFeatures } from '../server/config' ...@@ -15,7 +15,10 @@ import loadConfig, { getEnabledExperimentalFeatures } from '../server/config'
import { findPagesDir } from '../lib/find-pages-dir' import { findPagesDir } from '../lib/find-pages-dir'
import { fileExists, FileType } from '../lib/file-exists' import { fileExists, FileType } from '../lib/file-exists'
import { getNpxCommand } from '../lib/helpers/get-npx-command' import { getNpxCommand } from '../lib/helpers/get-npx-command'
import { createSelfSignedCertificate } from '../lib/mkcert' import {
SelfSignedCertificate,
createSelfSignedCertificate,
} from '../lib/mkcert'
import uploadTrace from '../trace/upload-trace' import uploadTrace from '../trace/upload-trace'
import { initialEnv, loadEnvConfig } from '@next/env' import { initialEnv, loadEnvConfig } from '@next/env'
import { trace } from '../trace' import { trace } from '../trace'
...@@ -249,6 +252,7 @@ const nextDev: CliCommand = async (args) => { ...@@ -249,6 +252,7 @@ const nextDev: CliCommand = async (args) => {
...((initialEnv || process.env) as typeof process.env), ...((initialEnv || process.env) as typeof process.env),
TURBOPACK: process.env.TURBOPACK, TURBOPACK: process.env.TURBOPACK,
NEXT_PRIVATE_WORKER: '1', NEXT_PRIVATE_WORKER: '1',
NODE_EXTRA_CA_CERTS: options.selfSignedCertificate?.rootCA,
}, },
}) })
...@@ -282,15 +286,17 @@ const nextDev: CliCommand = async (args) => { ...@@ -282,15 +286,17 @@ const nextDev: CliCommand = async (args) => {
'Self-signed certificates are currently an experimental feature, use at your own risk.' 'Self-signed certificates are currently an experimental feature, use at your own risk.'
) )
let certificate: { key: string; cert: string } | undefined let certificate: SelfSignedCertificate | undefined
if ( const key = args['--experimental-https-key']
args['--experimental-https-key'] && const cert = args['--experimental-https-cert']
args['--experimental-https-cert'] const rootCA = args['--experimental-https-ca']
) {
if (key && cert) {
certificate = { certificate = {
key: path.resolve(args['--experimental-https-key']), key: path.resolve(key),
cert: path.resolve(args['--experimental-https-cert']), cert: path.resolve(cert),
rootCA: rootCA ? path.resolve(rootCA) : undefined,
} }
} else { } else {
certificate = await createSelfSignedCertificate(host) certificate = await createSelfSignedCertificate(host)
......
...@@ -10,6 +10,12 @@ const { fetch } = require('next/dist/compiled/undici') as { ...@@ -10,6 +10,12 @@ const { fetch } = require('next/dist/compiled/undici') as {
const MKCERT_VERSION = 'v1.4.4' const MKCERT_VERSION = 'v1.4.4'
export interface SelfSignedCertificate {
key: string
cert: string
rootCA?: string
}
function getBinaryName() { function getBinaryName() {
const platform = process.platform const platform = process.platform
const arch = process.arch === 'x64' ? 'amd64' : process.arch const arch = process.arch === 'x64' ? 'amd64' : process.arch
...@@ -66,7 +72,7 @@ async function downloadBinary() { ...@@ -66,7 +72,7 @@ async function downloadBinary() {
export async function createSelfSignedCertificate( export async function createSelfSignedCertificate(
host?: string, host?: string,
certDir: string = 'certificates' certDir: string = 'certificates'
) { ): Promise<SelfSignedCertificate | undefined> {
try { try {
const binaryPath = await downloadBinary() const binaryPath = await downloadBinary()
if (!binaryPath) throw new Error('missing mkcert binary') if (!binaryPath) throw new Error('missing mkcert binary')
...@@ -98,7 +104,7 @@ export async function createSelfSignedCertificate( ...@@ -98,7 +104,7 @@ export async function createSelfSignedCertificate(
{ stdio: 'ignore' } { stdio: 'ignore' }
) )
const caLocation = execSync(`${binaryPath} -CAROOT`).toString() const caLocation = execSync(`${binaryPath} -CAROOT`).toString().trim()
if (!fs.existsSync(keyPath) || !fs.existsSync(certPath)) { if (!fs.existsSync(keyPath) || !fs.existsSync(certPath)) {
throw new Error('Certificate files not found') throw new Error('Certificate files not found')
...@@ -121,6 +127,7 @@ export async function createSelfSignedCertificate( ...@@ -121,6 +127,7 @@ export async function createSelfSignedCertificate(
return { return {
key: keyPath, key: keyPath,
cert: certPath, cert: certPath,
rootCA: `${caLocation}/rootCA.pem`,
} }
} catch (err) { } catch (err) {
Log.error( Log.error(
......
...@@ -3,6 +3,7 @@ import '../node-polyfill-fetch' ...@@ -3,6 +3,7 @@ import '../node-polyfill-fetch'
import '../require-hook' import '../require-hook'
import type { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import type { SelfSignedCertificate } from '../../lib/mkcert'
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
...@@ -38,10 +39,7 @@ export interface StartServerOptions { ...@@ -38,10 +39,7 @@ export interface StartServerOptions {
envInfo?: string[] envInfo?: string[]
expFeatureInfo?: string[] expFeatureInfo?: string[]
// this is dev-server only // this is dev-server only
selfSignedCertificate?: { selfSignedCertificate?: SelfSignedCertificate
key: string
cert: string
}
isExperimentalTestProxy?: boolean isExperimentalTestProxy?: boolean
} }
......
...@@ -530,9 +530,9 @@ export default class NextNodeServer extends BaseServer { ...@@ -530,9 +530,9 @@ export default class NextNodeServer extends BaseServer {
if (this.isRenderWorker) { if (this.isRenderWorker) {
const invokeRes = await invokeRequest( const invokeRes = await invokeRequest(
`http://${this.fetchHostname || 'localhost'}:${this.port}${ `${getRequestMeta(req, '_protocol')}://${
newReq.url || '' this.fetchHostname || 'localhost'
}`, }:${this.port}${newReq.url || ''}`,
{ {
method: newReq.method || 'GET', method: newReq.method || 'GET',
headers: newReq.headers, headers: newReq.headers,
......
import { createNextDescribe } from '../../../lib/e2e-utils'
createNextDescribe(
'app dir next-image (with https)',
{
files: __dirname,
skipDeployment: true,
startCommand: `yarn next dev --experimental-https`,
},
({ next }) => {
if (!process.env.CI) {
console.warn('only runs on CI as it requires administrator privileges')
it('only runs on CI as it requires administrator privileges', () => {})
return
}
it('loads images without any errors', async () => {
let failCount = 0
const browser = await next.browser('/', {
beforePageLoad(page) {
page.on('response', (response) => {
const url = response.url()
if (!url.includes('/_next/image')) return
const status = response.status()
console.log(`URL: ${url} Status: ${status}`)
if (!response.ok()) {
console.log(`Request failed: ${url}`)
failCount++
}
})
},
})
const image = browser.elementByCss('#app-page')
const src = await image.getAttribute('src')
expect(src).toContain(
'/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Ftest.3f1a293b.png&w=828&q=90'
)
expect(failCount).toBe(0)
})
}
)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment