import test from 'ava'

import { importX509 } from '../../src/index.js'

const cert = `-----BEGIN CERTIFICATE-----
MIID5jCCAs6gAwIBAgIBAjANBgkqhkiG9w0BAQsFADB7MQswCQYDVQQGEwJVUzEL
MAkGA1UECBMCVE4xEDAOBgNVBAoTB01TSUdOSUExDDAKBgNVBAsTA1JORDEXMBUG
A1UEAxMOTVNJR05JQSBSTkQgQ0ExJjAkBgkqhkiG9w0BCQEWF3BhdmxvLmx5c292
QG1zaWduaWEuY29tMB4XDTE5MTExMzA4MjAwMFoXDTI4MTExMzA4MjAwMFowgYAx
CzAJBgNVBAYTAlVTMQswCQYDVQQIEwJUTjEQMA4GA1UEChMHTVNJR05JQTEUMBIG
A1UECxMLTVNJR05JQSBSTkQxFDASBgNVBAMTC01TSUdOSUEgUk5EMSYwJAYJKoZI
hvcNAQkBFhdwYXZsby5seXNvdkBtc2lnbmlhLmNvbTCCASIwDQYJKoZIhvcNAQEB
BQADggEPADCCAQoCggEBAKRoo30zttpiFlBKnOAmlOcT07xPms7Z6/ZdN9KnE/Po
NQx7g6+Ap6b+trA2WDG80jEtwAy5XJcm81rBvJJvjwWQhiPjhXHvEibl+5zTYEXQ
tvl3qKNdikXuXPBLI/rwmZTNZd2aa5biVoLEY+cQVLOjdAZS9ZIkeuLYeLEZfNky
7rLa4XyRO4W4XEUWgafOp+ZSXATOz48XCb+fmaek4d8epsVJ/X3Qww9I9mqg8QA7
/EH9ASOYvbMzOjSuDjYBCRq4SJw/YBJDnBcBJSESzLJDDCJQyP4BOD2+P5UZ/OWS
NyzEDCLfLsiCVjdt0mNXrn/tGpdLoy1rVfC2SOAoZEUCAwEAAaNvMG0wDAYDVR0T
AQH/BAIwADAdBgNVHQ4EFgQUU/luo/bbBOlrQ7wrC3+ggkITcSYwCwYDVR0PBAQD
AgSwMBEGCWCGSAGG+EIBAQQEAwIFoDAeBglghkgBhvhCAQ0EERYPeGNhIGNlcnRp
ZmljYXRlMA0GCSqGSIb3DQEBCwUAA4IBAQAXroFZ9FeP10gtQguptDo6U0SIAB9n
qjN1IktyqatfUuVtThuxXAb3QQ7kYmGCZEaOIKoFdVc8i9aR5ZrYC1VIN4+cGLv7
P36Zl2q4i2G/X0QzniPPvsPyOUXeTVs3k6Sxe07uWdxsglq9LcVW++PvGYzotZP+
ZtmTzYAQtgadhPNo7+QmTO1FDju9p9hTFK7WhmXAO48bF9jrFiTkbwmo6PdlQiqi
PQYlbfO0XV727QUZ1YyG8rR/3VVRsBOmwZBKCj0dkh9eiRcNpJloqe1uZ83EBG/W
Cic5wE9P+Ol/pFNJFpfjXMsmT8lkCK954aYf2xoH1bHkONYAEEk0iQu/
-----END CERTIFICATE-----`

test('https://github.com/panva/jose/issues/459', (t) => {
  return t.notThrowsAsync(() => importX509(cert, 'RS256'))
})

test('X.509 import rejects a truncated certificate', async (t) => {
  const der = Buffer.from(cert.replace(/-----[^-]+-----|\s/g, ''), 'base64')
  const truncated = `-----BEGIN CERTIFICATE-----\n${der.subarray(0, -1).toString('base64')}\n-----END CERTIFICATE-----`

  await t.throwsAsync(importX509(truncated, 'RS256'))
})

test('X.509 import tolerates data after the PEM footer', async (t) => {
  await t.notThrowsAsync(importX509(`${cert}AAAA`, 'RS256'))
})

test('X.509 import rejects symmetric algorithms', async (t) => {
  await t.throwsAsync(importX509(cert, 'HS256'), {
    code: 'ERR_JOSE_NOT_SUPPORTED',
    message: 'Invalid or unsupported "alg" (Algorithm) value',
  })
})
