// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package libkb

import (
	"strings"
	"testing"

	"github.com/keybase/go-crypto/openpgp"
)

// See Issue #40: https://github.com/keybase/client/issues/40
func TestPGPGetPrimaryUID(t *testing.T) {

	armored := `
-----BEGIN PGP PUBLIC KEY BLOCK-----
Comment: GPGTools - https://gpgtools.org

mI0EVUubbgEEAKvIPrcQksiZW/dIX3sfZCSxfZqS8nojN/307rZ7323oAPTG6W7Y
EHfdgpKxUfMrdiNiWtujbybT8XUFhZwuPZF06BMIVmXESBr7rHLZ1Up41HmjvTtR
n1ejyy/tMl9zjydTIxjXsML9mPe3k3KVlrfgrbvadeM6PdYw+oE8tLZRABEBAAG0
IVByaW1hcnkgUHJpbWFyeSA8cHJpbWFyeUB1aWQuY29tPoi8BBMBCgAmAhsDBwsJ
CAcDAgEGFQgCCQoLBBYCAwECHgECF4AFAlVLm6YCGQEACgkQ5+9u0rO5NRk/4wP/
WBY3/C1keVxQMdma/F6l+yeP8SQvzqTLWZKRu1tPyi2DWYu8HnVw5/Upazj/UC8u
4Q7OzBsU0dn+5TUrwSfuTATY7OOSgWo/Nf++rqTU2z4h8kmV/qelGTrBKvshAEMk
/9ejJhPcErXocHHkAGCB+V4lSC70lBsAYoriEg2jmvW0J1NlY29uZGFyeSBTZWNv
bmRhcnkgPHNlY29uZGFyeUB1aWQuY29tPoi5BBMBCgAjBQJVS5uBAhsDBwsJCAcD
AgEGFQgCCQoLBBYCAwECHgECF4AACgkQ5+9u0rO5NRmZzwP/UnO2OBcaT3doVDbz
o246Ur3M/USz9XVhBMabCpd4iANXswi/9iJyFW0rMn3DXAUO3Qj8yh/077FfMqUj
srcmbC4qtscd3X1V7hQ4rOsiEghUu2ZG8XsFxBh01NpDYxrTXQfmJeegUMAirgrA
r8WBLqMoZo8TarCDCw/6ygTxV6y0JFRlcnRpYXJ5IFRlcnRpYXJ5IDx0ZXJ0aWFy
eUB1aWQuY29tPoi5BBMBCgAjBQJVS5uVAhsDBwsJCAcDAgEGFQgCCQoLBBYCAwEC
HgECF4AACgkQ5+9u0rO5NRlZegP8Dl2IGu3WwF4w2Qxj/WzhTeiaLQoTzEsF0IPy
+f+IBO/uC/5bw/b3uNAhGK1wK3hy77II+py2x7/EvJAz2w1Ua9IMD6YuZBQaSzwV
tRhoHOnptdxLNDZPvZVuPl8G6p4yKLqelGymtdtpkObz9w8f+KTcieEUVeM7HbI8
/dwF7da4jQRVS5tuAQQAy0uPwJBoQeXz/uv5ifdXJG39cYFTaONQxa6U3/Wtx3oV
ibdqyygmFliHJJJyx0wjMohVbDT2sl8bHr0gpZxnkDF7+Gmcwcn/ohfKf0h7hrmL
W4nGNdiQiD6QZZz7ebEBuqzUmkAYg33lsYZ8MLI6wLK3sMmzA468di06YUa9eksA
EQEAAYifBBgBCgAJBQJVS5tuAhsMAAoJEOfvbtKzuTUZMFMD/28lUOflsdcLvJyL
L22yGWeoUlKMQmdbreSUo3Ibcdkpsy9ZHDHxWRBN5s/cxHtX6nna5IeHSNIdDruX
HKfiyXs8709e067vsE5FCTMvZCq4vt/lkEJ59xn58QBfEILMwQDNLqVGyA54MPwh
+NwHX7807fKQwvqyVixJoZ3yS6Js
=RH/W
-----END PGP PUBLIC KEY BLOCK-----
`
	expected := "Primary Primary <primary@uid.com>"
	for i := 0; i < 100; i++ {
		key, _, err := ReadOneKeyFromString(armored)
		if err != nil {
			t.Error(err)
		}
		primary := key.GetPrimaryUID()
		if primary != expected {
			t.Errorf("Expected '%s' as a primary UID; got '%s'", expected, primary)
		}
	}
	return
}

func TestOpenPGPMultipleArmored(t *testing.T) {
	// openpgp.ReadArmoredKeyRing only returns the first key block, despite what its
	// comment says.  Here's a test for that:
	r := strings.NewReader(issue454Keys)
	el, err := openpgp.ReadArmoredKeyRing(r)
	if err != nil {
		t.Fatal(err)
	}
	// len(el) should be 2, but it's 1:
	/*
		if len(el) != 2 {
			t.Errorf("number of entities: %d, expected 2", len(el))
		}
	*/

	// we'll make sure that this bug still exists in openpgp, so if it ever
	// gets fixed we can take appropriate action:
	if len(el) != 1 {
		if len(el) == 2 {
			t.Errorf("openpgp.ReadArmoredKeyRing multiple keys bug fixed!")
		} else {
			t.Errorf("openpgp.ReadArmoredKeyRing bug changed...number entities: %d, expected 1.", len(el))
		}
	}
}

func TestMultipleArmored(t *testing.T) {

	// ReadOneKeyFromString will return the public key for issue454Keys
	b1, _, err := ReadOneKeyFromString(issue454Keys)
	if err != nil {
		t.Fatal(err)
	}
	if b1.HasSecretKey() {
		t.Errorf("ReadOneKeyFromString returned a private key for issue454Keys.  Expected just the public key (the first one).")
	}

	// ReadPrivateKeyFromString should skip the first public key in issue454Keys
	// and use the private key that follows it.
	b2, _, err := ReadPrivateKeyFromString(issue454Keys)
	if err != nil {
		t.Fatal(err)
	}
	if !b2.HasSecretKey() {
		t.Errorf("ReadPrivateKeyFromString returned only a public key for issue454Keys.  Expected a private key.")
	}
}

const issue454Keys = `-----BEGIN PGP PUBLIC KEY BLOCK-----
Comment: GPGTools - http://gpgtools.org

mQINBFVo5d8BEADByJSWkOrCQsjZcPurVIPIDSz6Fz3C7Pu+0/ZDbCDSAtZKINkN
OEh+YeFXENa5wrKWjXB3A3r9+X73wGztocnHRSJ688Sf6J03jCDneh2CutUELFRV
MXf3r63Fr3RoemF+D+AN+m5hgj7pVfw614ncBYITMQLLbOLjI2N90BLn6V2Txqg8
cInL2IIAoT8neySO+/0D86+89tq4OiIIbcBZwvUJS6i8ArZuw2aJC36u9/oAnPNS
H6K9AF7RJBMOLKExeBOiHSJBhnitlzqYYp24a85stpMX1XEi38pueVufs9lqzOgM
k6e4cfyNRLLElay2BPZ6IVeK59buj98N9F606EI6bS7nHpeYkW14F27/SuBWQ4gb
s4eEWdCX2/U401tK/3mma2t7Ybp37vn5x4ER+5g16DmXdhW+GSYCh69CnyJwXJGX
ZJRLS3mryhGHhZslUEpsJ+T/CY/wOa31T0+g4/9kEbXbYkmBP5eB+If5lvmkYmDR
I7JMG8OfPj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Uc8hcUgwN6iefcAFhj2iOzMmVQ1bVot3ue
43rK7kZeXpuHGjz2+PxfbrOIOCGBwRRQPz0h72/kfHXtkcxrhL0StmYAAooSpq2y
NVRPRJ2tsXKK06ovtdgJRL9MFrND88bjLMsbxXA7ejqLyhhGTnPydDtFrzsGkw3Q
z5r1K2p88A2mGkix3/H0CnkcSSTxI/ID2OQndQOZ0+fFJjM8GzlFJYkW61yqV4kF
BNmRPFd1/mM6ofRbJ/ec6LUQkV6of9mRtSHtNTzZLpRtxqDTDVA6H/R+dqEhg/ni
2jAapEr4VzIbew==
=pyUo
-----END PGP PUBLIC KEY BLOCK-----
-----BEGIN PGP PRIVATE KEY BLOCK-----
Comment: GPGTools - http://gpgtools.org

[encoded data, 6565 characters]
LpRtxqDTDVA6H/R+dqEhg/ni2jAapEr4VzIbew==
=bXrj
-----END PGP PRIVATE KEY BLOCK-----`

func TestReadOneKeyFromBytes(t *testing.T) {

	t.Log("If this test panics for you, then you need to update github.com/keybase/go-crypto/openpgp")
	// found by go-fuzz:
	// (errors are ok, panics are not...these all caused panics with an older version of
	// openpgp)
	_, _, err := ReadOneKeyFromBytes([]byte("\x9900\x03000000\x01\x00\x00\x00\x030"))
	if err != nil {
		t.Log(err)
	}
	_, _, err = ReadOneKeyFromBytes([]byte("\xd1\x1b\x0000000000000000000" + "000000000"))
	if err != nil {
		t.Log(err)
	}
	_, _, err = ReadOneKeyFromBytes([]byte("0\xd1\x03\x0000"))
	if err != nil {
		t.Log(err)
	}
}

func TestPGPSubkeyWarning(t *testing.T) {

	const missingCrossSignatureKey = `-----BEGIN PGP PUBLIC KEY BLOCK-----
Charset: UTF-8

mQENBFMYynYBCACVOZ3/e8Bm2b9KH9QyIlHGo/i1bnkpqsgXj8tpJ2MIUOnXMMAY
ztW7kKFLCmgVdLIC0vSoLA4yhaLcMojznh/2CcUglZeb6Ao8Gtelr//Rd5DRfPpG
zqcfUo+m+eO1co2Orabw0tZDfGpg5p3AYl0hmxhUyYSc/xUq93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JrakiqDmUZv9xtplY7zsHSQjpd6xGflbU2n+iX99Q+nav0ETQZifNUEd4N
1ljDGQejcTyKD6Pkg6wBL3x9/RJye7Zszazm4+toJXZ8xJ3800+BtaPoI39akYJm
+ijzbskvN0v/j5GOFJwQO0pPRAFtdHqRs9Kf4YanxhedB4dIUblzlIJuKsxFit6N
lgGRblagG3Vv2eBszbxzPbJjHCgVLR3RmrVezKOsZjr/2i7X+xLWIR0uD3IN1qOW
CXQxLBizEEmSNVNxsp7KPGTLnqO3bPtqFirxS9PJLIMPTPLNBY7ZYuPNTMqVIUWF
4artDmrG
=7FfJ
-----END PGP PUBLIC KEY BLOCK-----`

	_, w, err := ReadOneKeyFromString(missingCrossSignatureKey)
	if err != nil {
		t.Error(err)
	}

	if w.IsEmpty() {
		t.Errorf("Expected a bad subkey warning")
	}
}
