Skip to content

pfx option of https.Agent isn't respected #14417

Closed

Description

@mirismaili

What version of Bun is running?

1.1.30+7996d06b8

What platform is your computer?

  • Microsoft Windows NT 10.0.22631.0 x64
  • Linux 5.15.153.1-microsoft-standard-WSL2 x86_64 x86_64 [Ubuntu 24.04 LTS]

What steps can reproduce the bug?

  1. Create a simple self-signed HTTPS server that requires client-cert. You can create it however you want. For example, using Nginx. But we create and run it using Node.js, with the help of instructions at https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener, https://nodejs.org/api/tls.html#tlscreateserveroptions-secureconnectionlistener, etc.:
    import {readFile} from 'node:fs/promises'
    import {createServer} from 'node:https'
    
    createServer(
      {
        // Self-signed HTTPS server:
        key: await readFile('private-key.pem'),
        cert: await readFile('certificate.pem'),
        // Request client to send its certificate:
        requestCert: true,
        ca: [await readFile('certificate.pem')], // In practice, this should be different from server's `cert`. But FOR CONVENIENCE, we use the same cert for both, here!!
      },
      (req, res) => {
        const clientCert = req.socket.getPeerCertificate()
    
        if (req.client.authorized) {
          console.log('Client certificate authorized:', clientCert.subject)
          res.writeHead(200)
          res.end(`Hello, ${clientCert.subject.CN}, your certificate is valid!`)
          return
        }
        if (clientCert && clientCert.subject) {
          console.log('Client certificate presented but not authorized:', clientCert.subject)
          res.writeHead(403)
          res.end('Client certificate is not authorized.')
          return
        }
        console.log('No client cert')
        res.writeHead(401)
        res.end('Client certificate required.')
      },
    ).listen(8000, () => {
      console.log('Server is running on:', 'https://localhost:8000')
    })
    To generate keys, according to the first link, run these commands:
    openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' -keyout private-key.pem -out certificate.pem
    openssl pkcs12 -certpbe AES-256-CBC -export -out test_cert.pfx -inkey private-key.pem -in certificate.pem -passout pass:sample
    Note that the file that is generated in the second command (test_cert.pfx) will be used in our client.js later.
  2. Store it in the same folder you created the keys and name it server.js and run it using Node.js:
    node server.js
    It should log:
    Server is running on: https://localhost:8000
  3. Test it using curl (This step may not work in Windows environment. I ran it in WSL/[Ubuntu 24.04 LTS]):
    3.1. Without the client cert. We expect an error, in this state:
    $ curl -k https://localhost:8000
    curl: (56) OpenSSL SSL_read: OpenSSL/3.0.13: error:0A00045C:SSL routines::tlsv13 alert certificate required, errno 0
    3.2. With the valid client-cert. We expect successful connection, in this state:
    $ curl -k --cert-type p12 --cert test_cert.pfx:sample https://localhost:8000
    Hello, localhost, your certificate is valid!
  4. Create client.js in the same folder:
    import {readFile} from 'node:fs/promises'
    import https from 'node:https'
    
    const req = https.request(
      'https://localhost:8000',
      {
        method: 'GET',
        agent: new https.Agent({
          pfx: await readFile('test_cert.pfx'),
          passphrase: 'sample',
        }),
        ca: await readFile('certificate.pem'),
      },
      (res) => {
        if (res.statusCode === 200) console.log('Successfully connected.')
      },
    )
    req.end()
  5. Run it using Node.js:
$ node client.js
Successfully connected.
  1. Run it using Bun.js:
    $ bun client.js
    ERR_TLS_CERT_ALTNAME_INVALID: ERR_TLS_CERT_ALTNAME_INVALID fetching "https://localhost:8000/". For more information, pass `verbose: true` in the second argument to fetch()
    path: "https://localhost:8000/"

It fails. But I think this is not due to not-supporting pfx option of https.Agent. I think it's for not supporting ca option (that we need it, because the certificate of our HTTPS server is self-signed).

Another way to accept self-singed connections, is disabling NODE_TLS_REJECT_UNAUTHORIZED. In this case, we get this error (w/ or w/o ca option):

$ NODE_TLS_REJECT_UNAUTHORIZED=0 bun client.js
ConnectionClosed: The socket connection was closed unexpectedly. For more information, pass `verbose: true` in the second argument to fetch()
 path: "https://localhost:8000/"

Bun v1.1.30 (Linux x64)

In my real case (that I can't provide its reproduce steps here) with authorized certificate chain (NOT self-signed) I get 302/ Found that (in that special case) is exactly similar to the same behaviour when I don't provide the client-cert at all. So I think pfx option isn't respected.

What is the expected behavior?

Like Node.js:

$ bun client.js
Successfully connected.

BUT NOT!

What do you see instead?

It has been fully explained during reproduce steps.

Additional information

No response

Activity

  1. antingle commented on Oct 14, 2024

    @antingle

    I'm also very interested in Bun finishing Agent support for the https module. We have been building a project with Bun but are currently blocked from safely deploying it because we need the ability to use self signed certificates through the Agent ca option. 🙏

  2. self-assigned this
    on Oct 16, 2024
  3. LucasBonafe commented on Jan 3, 2025

    @LucasBonafe

    Same situation here, any solution?

    Edit: I had to use execFileSync('node', ['src/filePath.js', variables]) and run it through Node in JavaScript, treating the response with JSON.parse(String(response)).

  4. asilvas-godaddy commented on Feb 18, 2025

    @asilvas-godaddy

    Blocker not being able to use client cert requests via https.Agent.

  5. removed their assignment
    on Feb 20, 2025
  6. jrvidotti commented on Apr 28, 2025

    @jrvidotti

    Had trouble trying to make this work whith Bun. With tsx it worker perfectly.

        const pfxFile = fs.readFileSync(this.config.pfxPath);
    
        this.axiosInstance = axios.create({
          baseURL: this.config.baseUrl,
          httpsAgent: new https.Agent({
            pfx: pfxFile,
            passphrase: this.config.pfxPassword,
          }),
        });
    
  7. BrianIto commented on Jul 8, 2025

    @BrianIto

    +1 in the same position here.

  8. enriquecaballero-agx commented on Nov 7, 2025

    @enriquecaballero-agx

    Yeah, total blocker here as well. Would love to hear from Bun the team about this. These issues have been open for a while, which is concerning.

  9. cirospaciari commented on Nov 11, 2025

    @cirospaciari
    Member

    we plan to implement this soon but converting the pfx -> pem is the workaround for now.

  10. robobun commented on Jul 24, 2026

    @robobun
    Collaborator

    Fixed on main.

    Verified on main at df84f8d: https.Agent({ pfx, passphrase }) with a ca option now sends the client certificate and connects successfully, matching Node.js.

    $ bun client.js
    statusCode: 200
    Successfully connected.
    body: Hello, localhost, your certificate is valid!
    

    Fixed by #31587 (node:http client rewrite on net/tls) together with #31155 (tls pfx support).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions