package jose

import (
	"crypto"
	"crypto/ed25519"
	"crypto/rand"
	"reflect"
	"testing"
	"time"

	"go.step.sm/crypto/x25519"
)

func Test_x25519Thumbprint(t *testing.T) {
	type args struct {
		key  x25519.PublicKey
		hash crypto.Hash
	}
	tests := []struct {
		name    string
		args    args
		want    []byte
		wantErr bool
	}{
		{"ok", args{[]byte{
			0x0f, 0xf9, 0x2b, 0x4a, 0xa2, 0x9d, 0x86, 0xc5,
			0x27, 0xbf, 0x44, 0x24, 0xbc, 0x5c, 0xae, 0x7d,
			0x48, 0x1d, 0xcb, 0x61, 0x8d, 0xea, 0x2f, 0x9a,
			0x88, 0xe4, 0x3c, 0xf5, 0xc4, 0xc7, 0xdb, 0x11,
		}, crypto.SHA256}, []byte{
			0x24, 0x2d, 0xa5, 0xce, 0xcd, 0x0a, 0x21, 0x5d,
			0x3e, 0xc8, 0x4d, 0x2e, 0xe9, 0x1b, 0x6c, 0x70,
			0xc2, 0xa9, 0xca, 0x2b, 0x45, 0x4b, 0xcd, 0x53,
			0x79, 0xfa, 0xce, 0x2e, 0xde, 0xe6, 0x1c, 0x79,
		}, false},
		{"fail too short", args{[]byte{
			0x0f, 0xf9, 0x2b, 0x4a, 0xa2, 0x9d, 0x86, 0xc5,
			0x27, 0xbf, 0x44, 0x24, 0xbc, 0x5c, 0xae, 0x7d,
			0x48, 0x1d, 0xcb, 0x61, 0x8d, 0xea, 0x2f, 0x9a,
			0x88, 0xe4, 0x3c, 0xf5, 0xc4, 0xc7, 0xdb,
		}, crypto.SHA256}, nil, true},
		{"fail too long", args{[]byte{
			0x0f, 0xf9, 0x2b, 0x4a, 0xa2, 0x9d, 0x86, 0xc5,
			0x27, 0xbf, 0x44, 0x24, 0xbc, 0x5c, 0xae, 0x7d,
			0x48, 0x1d, 0xcb, 0x61, 0x8d, 0xea, 0x2f, 0x9a,
			0x88, 0xe4, 0x3c, 0xf5, 0xc4, 0xc7, 0xdb, 0x11, 0x12,
		}, crypto.SHA256}, nil, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := x25519Thumbprint(tt.args.key, tt.args.hash)
			if (err != nil) != tt.wantErr {
				t.Errorf("x25519Thumbprint() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("x25519Thumbprint() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestX25519Signer_SignVerify(t *testing.T) {
	pub, priv, err := x25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	edPub, edPriv, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	type args struct {
		sig       SigningKey
		opts      *SignerOptions
		payload   []byte
		publicKey crypto.PublicKey
	}
	tests := []struct {
		name    string
		args    args
		want    Claims
		wantErr bool
	}{
		{"ok", args{
			SigningKey{
				Algorithm: XEdDSA,
				Key: x25519.PrivateKey{
					0x4e, 0x6c, 0xd9, 0xe8, 0x40, 0x4d, 0xe1, 0xe0,
					0xc5, 0x22, 0x72, 0x8f, 0x78, 0xde, 0x88, 0x26,
					0x58, 0x4b, 0x44, 0xef, 0xbc, 0xf6, 0xac, 0x10,
					0x97, 0x67, 0x60, 0xcc, 0x41, 0xf1, 0x82, 0x0b,
				},
			},
			new(SignerOptions).WithType("JWT"),
			[]byte(`{"iss":"test-iss","sub":"test-sub","aud":"test-aud","exp":1234,"nbf":1200,"iat":1000,"jti":"test-jti"}`),
			x25519.PublicKey{
				0x51, 0xf3, 0xfe, 0x72, 0xb4, 0x35, 0x66, 0x52,
				0x16, 0x16, 0x38, 0xfb, 0x9b, 0xf7, 0x17, 0x06,
				0x87, 0xb6, 0x35, 0x53, 0xc1, 0x63, 0x9c, 0x73,
				0xa7, 0x79, 0x1e, 0xd2, 0xba, 0xf8, 0xcb, 0x67,
			},
		}, Claims{
			Issuer:    "test-iss",
			Subject:   "test-sub",
			Audience:  []string{"test-aud"},
			Expiry:    NewNumericDate(time.Unix(1234, 0)),
			NotBefore: NewNumericDate(time.Unix(1200, 0)),
			IssuedAt:  NewNumericDate(time.Unix(1000, 0)),
			ID:        "test-jti",
		}, false},
		{"ok empty", args{
			SigningKey{
				Algorithm: XEdDSA,
				Key: x25519.PrivateKey{
					0x4e, 0x6c, 0xd9, 0xe8, 0x40, 0x4d, 0xe1, 0xe0,
					0xc5, 0x22, 0x72, 0x8f, 0x78, 0xde, 0x88, 0x26,
					0x58, 0x4b, 0x44, 0xef, 0xbc, 0xf6, 0xac, 0x10,
					0x97, 0x67, 0x60, 0xcc, 0x41, 0xf1, 0x82, 0x0b,
				},
			},
			new(SignerOptions).WithType("JWT"),
			[]byte(`{}`),
			x25519.PublicKey{
				0x51, 0xf3, 0xfe, 0x72, 0xb4, 0x35, 0x66, 0x52,
				0x16, 0x16, 0x38, 0xfb, 0x9b, 0xf7, 0x17, 0x06,
				0x87, 0xb6, 0x35, 0x53, 0xc1, 0x63, 0x9c, 0x73,
				0xa7, 0x79, 0x1e, 0xd2, 0xba, 0xf8, 0xcb, 0x67,
			},
		}, Claims{}, false},
		{"ok random", args{
			SigningKey{Algorithm: XEdDSA, Key: priv},
			new(SignerOptions).WithType("JWT"),
			[]byte(`{"iss":"test-iss","sub":"test-sub","aud":"test-aud","exp":1234,"nbf":1200,"iat":1000,"jti":"test-jti"}`),
			pub,
		}, Claims{
			Issuer:    "test-iss",
			Subject:   "test-sub",
			Audience:  []string{"test-aud"},
			Expiry:    NewNumericDate(time.Unix(1234, 0)),
			NotBefore: NewNumericDate(time.Unix(1200, 0)),
			IssuedAt:  NewNumericDate(time.Unix(1000, 0)),
			ID:        "test-jti",
		}, false},
		{"ok ed25519", args{
			SigningKey{Algorithm: EdDSA, Key: edPriv},
			new(SignerOptions).WithType("JWT"),
			[]byte(`{"iss":"test-iss","sub":"test-sub","aud":"test-aud","exp":1234,"nbf":1200,"iat":1000,"jti":"test-jti"}`),
			edPub,
		}, Claims{
			Issuer:    "test-iss",
			Subject:   "test-sub",
			Audience:  []string{"test-aud"},
			Expiry:    NewNumericDate(time.Unix(1234, 0)),
			NotBefore: NewNumericDate(time.Unix(1200, 0)),
			IssuedAt:  NewNumericDate(time.Unix(1000, 0)),
			ID:        "test-jti",
		}, false},
		{"fail algorithm", args{
			SigningKey{Algorithm: EdDSA, Key: priv},
			new(SignerOptions).WithType("JWT"),
			[]byte(`{"iss":"test-iss","sub":"test-sub","aud":"test-aud","exp":1234,"nbf":1200,"iat":1000,"jti":"test-jti"}`),
			pub,
		}, Claims{}, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			signer, err := NewSigner(tt.args.sig, tt.args.opts)
			if (err != nil) != tt.wantErr {
				t.Errorf("NewSigner() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !tt.wantErr {
				var got Claims

				sig, err := signer.Sign(tt.args.payload)
				if err != nil {
					t.Errorf("Signer.Sign() error = %v", err)
					return
				}
				jwt, err := ParseSigned(sig.FullSerialize())
				if err != nil {
					t.Errorf("ParseSigned() error = %v", err)
					return
				}
				if err := Verify(jwt, tt.args.publicKey, &got); err != nil {
					t.Errorf("Verify() error = %v", err)
					return
				}
				if !reflect.DeepEqual(got, tt.want) {
					t.Errorf("JSONWebSignature.CompactSerialize() = %v, want %v", got, tt.want)
				}
			}
		})
	}
}

func TestX25519Signer_Public(t *testing.T) {
	pub, priv, err := x25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	tests := []struct {
		name string
		s    X25519Signer
		want *JSONWebKey
	}{
		{"ok", X25519Signer(priv), &JSONWebKey{Key: pub}},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := tt.s.Public(); !reflect.DeepEqual(got, tt.want) {
				t.Errorf("X25519Signer.Public() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestX25519Signer_Algs(t *testing.T) {
	_, priv, err := x25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	tests := []struct {
		name string
		s    X25519Signer
		want []SignatureAlgorithm
	}{
		{"ok", X25519Signer(priv), []SignatureAlgorithm{XEdDSA}},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := tt.s.Algs(); !reflect.DeepEqual(got, tt.want) {
				t.Errorf("X25519Signer.Algs() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestX25519Signer_SignPayload(t *testing.T) {
	buf := mustTeeReader(t)
	rand.Reader = buf

	// Random
	buf.Write([]byte{
		0x4e, 0x6c, 0xd9, 0xe8, 0x40, 0x4d, 0xe1, 0xe0,
		0xc5, 0x22, 0x72, 0x8f, 0x78, 0xde, 0x88, 0x26,
		0x58, 0x4b, 0x44, 0xef, 0xbc, 0xf6, 0xac, 0x10,
		0x97, 0x67, 0x60, 0xcc, 0x41, 0xf1, 0x82, 0xb,
		0xb8, 0x69, 0x6, 0xf3, 0xad, 0xa5, 0x46, 0x6f,
		0xc2, 0xf3, 0x9, 0x78, 0x7b, 0x3c, 0x6f, 0xd6,
		0x39, 0x19, 0xb1, 0x48, 0xd6, 0x6, 0xb7, 0x79,
		0xfb, 0xf7, 0xda, 0x61, 0xee, 0x57, 0x7b, 0xe6,
	})

	signer := X25519Signer{
		0xb0, 0x3d, 0x85, 0x79, 0x6d, 0x92, 0x89, 0x78,
		0x26, 0xaf, 0x9d, 0xb9, 0x13, 0x98, 0xf3, 0xf9,
		0x73, 0x7d, 0x5f, 0x5c, 0xde, 0x76, 0xd1, 0xc4,
		0x4c, 0x3a, 0x3f, 0xa9, 0x6e, 0xe5, 0x19, 0x46,
	}

	type args struct {
		payload []byte
		alg     SignatureAlgorithm
	}
	tests := []struct {
		name    string
		s       X25519Signer
		args    args
		want    []byte
		wantErr bool
	}{
		{"ok", signer, args{[]byte(`{}`), XEdDSA}, []byte{
			0xe5, 0x1a, 0xc0, 0x63, 0xd7, 0xfa, 0xf9, 0x0e,
			0xe1, 0xfd, 0xfa, 0x03, 0xcb, 0x14, 0x1a, 0xc1,
			0x63, 0x15, 0x83, 0x69, 0xf5, 0xf9, 0x3f, 0xa9,
			0x8b, 0xa2, 0xc2, 0x6a, 0xc3, 0x8c, 0x23, 0xec,
			0xa6, 0xa7, 0xea, 0x17, 0x82, 0x80, 0xcf, 0x02,
			0x4a, 0x61, 0x93, 0x99, 0x74, 0x85, 0xa4, 0x20,
			0xe0, 0xa0, 0xe0, 0x26, 0x28, 0x79, 0xbd, 0xf3,
			0x59, 0x6e, 0xbe, 0x40, 0xbe, 0xb0, 0xf8, 0x08,
		}, false},
		{"fail", signer, args{[]byte(`{}`), EdDSA}, nil, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := tt.s.SignPayload(tt.args.payload, tt.args.alg)
			if (err != nil) != tt.wantErr {
				t.Errorf("X25519Signer.SignPayload() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("X25519Signer.SignPayload() = %x, want %v", got, tt.want)
			}
		})
	}
}

func TestX25519Verifier_VerifyPayload(t *testing.T) {
	verifier := X25519Verifier{
		0x47, 0x0e, 0x9b, 0xf6, 0x21, 0x5e, 0xbd, 0x7e,
		0xc9, 0xaa, 0x9f, 0xb7, 0xfa, 0xd1, 0xc7, 0xdd,
		0xaf, 0x6e, 0x12, 0x44, 0x9e, 0xac, 0xd7, 0x43,
		0x53, 0xe4, 0x0e, 0x3f, 0xfa, 0x24, 0x0b, 0x3c,
	}

	type args struct {
		payload   []byte
		signature []byte
		alg       SignatureAlgorithm
	}
	tests := []struct {
		name    string
		v       X25519Verifier
		args    args
		wantErr bool
	}{
		{"ok", verifier, args{[]byte(`{}`), []byte{
			0xe5, 0x1a, 0xc0, 0x63, 0xd7, 0xfa, 0xf9, 0x0e,
			0xe1, 0xfd, 0xfa, 0x03, 0xcb, 0x14, 0x1a, 0xc1,
			0x63, 0x15, 0x83, 0x69, 0xf5, 0xf9, 0x3f, 0xa9,
			0x8b, 0xa2, 0xc2, 0x6a, 0xc3, 0x8c, 0x23, 0xec,
			0xa6, 0xa7, 0xea, 0x17, 0x82, 0x80, 0xcf, 0x02,
			0x4a, 0x61, 0x93, 0x99, 0x74, 0x85, 0xa4, 0x20,
			0xe0, 0xa0, 0xe0, 0x26, 0x28, 0x79, 0xbd, 0xf3,
			0x59, 0x6e, 0xbe, 0x40, 0xbe, 0xb0, 0xf8, 0x08,
		}, XEdDSA}, false},
		{"fail signature", verifier, args{[]byte(`{}`), []byte{
			0x00, 0x1a, 0xc0, 0x63, 0xd7, 0xfa, 0xf9, 0x0e,
			0xe1, 0xfd, 0xfa, 0x03, 0xcb, 0x14, 0x1a, 0xc1,
			0x63, 0x15, 0x83, 0x69, 0xf5, 0xf9, 0x3f, 0xa9,
			0x8b, 0xa2, 0xc2, 0x6a, 0xc3, 0x8c, 0x23, 0xec,
			0xa6, 0xa7, 0xea, 0x17, 0x82, 0x80, 0xcf, 0x02,
			0x4a, 0x61, 0x93, 0x99, 0x74, 0x85, 0xa4, 0x20,
			0xe0, 0xa0, 0xe0, 0x26, 0x28, 0x79, 0xbd, 0xf3,
			0x59, 0x6e, 0xbe, 0x40, 0xbe, 0xb0, 0xf8, 0x08,
		}, XEdDSA}, true},
		{"fail algorithm", verifier, args{[]byte(`{}`), []byte{
			0xe5, 0x1a, 0xc0, 0x63, 0xd7, 0xfa, 0xf9, 0x0e,
			0xe1, 0xfd, 0xfa, 0x03, 0xcb, 0x14, 0x1a, 0xc1,
			0x63, 0x15, 0x83, 0x69, 0xf5, 0xf9, 0x3f, 0xa9,
			0x8b, 0xa2, 0xc2, 0x6a, 0xc3, 0x8c, 0x23, 0xec,
			0xa6, 0xa7, 0xea, 0x17, 0x82, 0x80, 0xcf, 0x02,
			0x4a, 0x61, 0x93, 0x99, 0x74, 0x85, 0xa4, 0x20,
			0xe0, 0xa0, 0xe0, 0x26, 0x28, 0x79, 0xbd, 0xf3,
			0x59, 0x6e, 0xbe, 0x40, 0xbe, 0xb0, 0xf8, 0x08,
		}, EdDSA}, true},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if err := tt.v.VerifyPayload(tt.args.payload, tt.args.signature, tt.args.alg); (err != nil) != tt.wantErr {
				t.Errorf("X25519Verifier.VerifyPayload() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}
