package hpkp

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"reflect"
	"testing"
)

var certs = []string{
	`-----BEGIN CERTIFICATE-----
MIIHeTCCBmGgAwIBAgIQC/20CQrXteZAwwsWyVKaJzANBgkqhkiG9w0BAQsFADB1
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMTQwMgYDVQQDEytEaWdpQ2VydCBTSEEyIEV4dGVuZGVk
IFZhbGlkYXRpb24gU2VydmVyIENBMB4XDTE2MDMxMDAwMDAwMFoXDTE4MDUxNzEy
MDAwMFowgf0xHTAbBgNVBA8MFFByaXZhdGUgT3JnYW5pemF0aW9uMRMwEQYLKwYB
BAGCNzwCAQMTAlVTMRkwFwYLKwYBBAGCNzwCAQITCERlbGF3YXJlMRAwDgYDVQQF
Ewc1MTU3NTUwMSQwIgYDVQQJExs4OCBDb2xpbiBQIEtlbGx5LCBKciBTdHJlZXQx
DjAMBgNVBBETBTk0MTA3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5p
YTEWMBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEVMBMGA1UEChMMR2l0SHViLCBJbmMu
MRMwEQYDVQQDEwpnaXRodWIuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
CgKCAQEA54hc8pZclxgcupjiA/F/OZGRwm/ZlucoQGTNTKmBEgNsrn/mxhngWmPw
bAvUaLP//T79Jc+1WXMpxMiz9PK6yZRRFuIo0d2bx423NA6hOL2RTtbnfs+y0PFS
/YTpQSelTuq+Fuwts5v6aAweNyMcYD0HBybkkdosFoDccBNzJ92Ac8I5EVDUc3Or
/4jSyZwzxu9kdmBlBzeHMvsqdH8SX9mNahXtXxRpwZnBiUjw36PgN+s9GLWGrafd
02T0ux9Yzd5ezkMxukqEAQ7AKIIijvaWPAJbK/52XLhIy2vpGNylyni/DQD18bBP
T+ZG1uv0QQ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GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec
nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z
eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF
hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2
Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe
vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep
+OkuE6N36B9K
-----END CERTIFICATE-----
`,
}

func peerCerts(c []string) []*x509.Certificate {
	out := []*x509.Certificate{}
	for i := range c {
		block, _ := pem.Decode([]byte(certs[i]))
		if block == nil {
			panic("failed to parse certificate PEM")
		}
		cert, err := x509.ParseCertificate(block.Bytes)
		if err != nil {
			panic("failed to parse certificate: " + err.Error())
		}
		out = append(out, cert)
	}
	return out
}

func TestNewPinFailure(t *testing.T) {
	tests := []struct {
		name           string
		host           string
		port           int
		header         *Header
		connState      tls.ConnectionState
		expectedReport *PinFailure
		expectedURI    string
	}{
		{
			name: "nil test",
		},
		{
			name: "basic",
			host: "github.com",
			port: 443,
			header: &Header{
				Permanent:         true,
				IncludeSubDomains: false,
				Sha256Pins: []string{
					"LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A=",
				},
			},
			connState: tls.ConnectionState{
				ServerName:       "github.com",
				PeerCertificates: peerCerts(certs[:1]),
				VerifiedChains:   [][]*x509.Certificate{peerCerts(certs)},
			},
			expectedReport: &PinFailure{
				Hostname:          "github.com",
				Port:              443,
				IncludeSubdomains: false,
				NotedHostname:     "github.com",
				KnownPins: []string{
					"LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A=",
				},
				EffectiveExpirationDate:   "1970-01-01T00:00:00Z",
				ServedCertificateChain:    certs[:1],
				ValidatedCertificateChain: certs,
			},
			expectedURI: "",
		},
	}

	for _, test := range tests {
		pf, uri := NewPinFailure(test.host, test.port, test.header, test.connState)

		if uri != test.expectedURI {
			t.Logf("want:%v", test.expectedURI)
			t.Logf("got:%v", uri)
			t.Fatalf("test case failed: %s", test.name)
		}

		if !equalFailures(pf, test.expectedReport) {
			t.Logf("want:%v", test.expectedReport)
			t.Logf("got:%v", pf)
			t.Fatalf("test case failed: %s", test.name)
		}
	}
}

func equalFailures(a, b *PinFailure) bool {
	if a == nil && b == nil {
		return true
	}

	if a == nil || b == nil {
		return false
	}

	if a.Port != b.Port {
		return false
	}

	if a.Hostname != b.Hostname {
		return false
	}

	if !reflect.DeepEqual(a.KnownPins, b.KnownPins) {
		return false
	}

	if a.NotedHostname != b.NotedHostname {
		return false
	}

	if a.IncludeSubdomains != b.IncludeSubdomains {
		return false
	}

	if !reflect.DeepEqual(a.ServedCertificateChain, b.ServedCertificateChain) {
		return false
	}

	if a.EffectiveExpirationDate != b.EffectiveExpirationDate {
		return false
	}

	if !reflect.DeepEqual(a.ValidatedCertificateChain, b.ValidatedCertificateChain) {
		return false
	}

	return true
}
