File: e2e_test.go

package info (click to toggle)
rekor 1.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,684 kB
  • sloc: sh: 1,649; makefile: 147; sql: 80
file content (1272 lines) | stat: -rw-r--r-- 43,693 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
//
// Copyright 2021 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build e2e

package e2e

import (
	"bytes"
	"context"
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"crypto/tls"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/hex"
	"encoding/json"
	"encoding/pem"
	"errors"
	"fmt"
	"io/ioutil"
	"math/big"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
	"time"

	"golang.org/x/sync/errgroup"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"

	"cloud.google.com/go/pubsub"
	"github.com/cyberphone/json-canonicalization/go/src/webpki.org/jsoncanonicalizer"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag/conv"
	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	"github.com/sigstore/rekor/pkg/api"
	"github.com/sigstore/rekor/pkg/client"
	generatedClient "github.com/sigstore/rekor/pkg/generated/client"
	"github.com/sigstore/rekor/pkg/generated/client/entries"
	"github.com/sigstore/rekor/pkg/generated/client/pubkey"
	"github.com/sigstore/rekor/pkg/generated/models"
	e2ex509 "github.com/sigstore/rekor/pkg/pki/x509/e2ex509"
	"github.com/sigstore/rekor/pkg/sharding"
	"github.com/sigstore/rekor/pkg/signer"
	"github.com/sigstore/rekor/pkg/trillianclient"
	_ "github.com/sigstore/rekor/pkg/types/intoto/v0.0.1"
	rekord "github.com/sigstore/rekor/pkg/types/rekord/v0.0.1"
	"github.com/sigstore/sigstore/pkg/cryptoutils"
	"github.com/sigstore/sigstore/pkg/signature"
	"github.com/sigstore/sigstore/pkg/signature/options"
	"github.com/spf13/viper"
	"github.com/stretchr/testify/require"
)

var (
	testTreeID     int64 = 12345
	testSignerKey        = "testdata/signer.key"
	testSignerCert       = "testdata/signer.pem"
	testSignerPass       = "testpassword"
	testCAPath           = "testdata/ca.pem"
	testCAKeyPath        = "testdata/ca.key"
	testServerAddr       = "localhost:8090"
)

func getUUIDFromUploadOutput(t *testing.T, out string) string {
	t.Helper()
	// Output looks like "Artifact timestamped at ...\m Wrote response \n Created entry at index X, available at $URL/UUID", so grab the UUID:
	urlTokens := strings.Split(strings.TrimSpace(out), " ")
	url := urlTokens[len(urlTokens)-1]
	splitUrl := strings.Split(url, "/")
	return splitUrl[len(splitUrl)-1]
}

func getLogIndexFromUploadOutput(t *testing.T, out string) int {
	t.Helper()
	t.Log(out)
	// Output looks like "Created entry at index X, available at $URL/UUID", so grab the index X:
	split := strings.Split(strings.TrimSpace(out), ",")
	ss := strings.Split(split[0], " ")
	i, err := strconv.Atoi(ss[len(ss)-1])
	if err != nil {
		t.Fatal(err)
	}
	return i
}

func TestEnvVariableValidation(t *testing.T) {
	os.Setenv("REKOR_FORMAT", "bogus")
	defer os.Unsetenv("REKOR_FORMAT")

	runCliErr(t, "loginfo")
}

func TestDuplicates(t *testing.T) {
	artifactPath := filepath.Join(t.TempDir(), "artifact")
	sigPath := filepath.Join(t.TempDir(), "signature.asc")

	createdPGPSignedArtifact(t, artifactPath, sigPath)

	// Write the public key to a file
	pubPath := filepath.Join(t.TempDir(), "pubKey.asc")
	if err := ioutil.WriteFile(pubPath, []byte(publicKey), 0644); err != nil {
		t.Fatal(err)
	}

	// Now upload to rekor!
	out := runCli(t, "upload", "--artifact", artifactPath, "--signature", sigPath, "--public-key", pubPath)
	outputContains(t, out, "Created entry at")

	// Now upload the same one again, we should get a dupe entry.
	out = runCli(t, "upload", "--artifact", artifactPath, "--signature", sigPath, "--public-key", pubPath)
	outputContains(t, out, "Entry already exists")

	// Now do a new one, we should get a new entry
	createdPGPSignedArtifact(t, artifactPath, sigPath)
	out = runCli(t, "upload", "--artifact", artifactPath, "--signature", sigPath, "--public-key", pubPath)
	outputContains(t, out, "Created entry at")
}

type getOut struct {
	Attestation     string
	AttestationType string
	Body            interface{}
	LogIndex        int
	IntegratedTime  int64
}

func TestGetCLI(t *testing.T) {
	// Create something and add it to the log
	artifactPath := filepath.Join(t.TempDir(), "artifact")
	sigPath := filepath.Join(t.TempDir(), "signature.asc")

	createdPGPSignedArtifact(t, artifactPath, sigPath)

	// Write the public key to a file
	pubPath := filepath.Join(t.TempDir(), "pubKey.asc")
	if err := ioutil.WriteFile(pubPath, []byte(publicKey), 0644); err != nil {
		t.Fatal(err)
	}
	out := runCli(t, "upload", "--artifact", artifactPath, "--signature", sigPath, "--public-key", pubPath)
	outputContains(t, out, "Created entry at")

	uuid, err := sharding.GetUUIDFromIDString(getUUIDFromUploadOutput(t, out))
	if err != nil {
		t.Error(err)
	}

	// since we at least have 1 valid entry, check the log at index 0
	runCli(t, "get", "--log-index", "0")

	out = runCli(t, "get", "--format=json", "--uuid", uuid)

	// The output here should be in JSON with this structure:
	g := getOut{}
	if err := json.Unmarshal([]byte(out), &g); err != nil {
		t.Error(err)
	}

	if g.IntegratedTime == 0 {
		t.Errorf("Expected IntegratedTime to be set. Got %s", out)
	}
	// Get it with the logindex as well
	runCli(t, "get", "--format=json", "--log-index", strconv.Itoa(g.LogIndex))

	// check index via the file and public key to ensure that the index has updated correctly
	out = runCli(t, "search", "--artifact", artifactPath)
	outputContains(t, out, uuid)

	out = runCli(t, "search", "--public-key", pubPath)
	outputContains(t, out, uuid)

	artifactBytes, err := ioutil.ReadFile(artifactPath)
	if err != nil {
		t.Error(err)
	}
	sha := sha256.Sum256(artifactBytes)

	out = runCli(t, "search", "--sha", fmt.Sprintf("sha256:%s", hex.EncodeToString(sha[:])))
	outputContains(t, out, uuid)

	// Exercise GET with the new EntryID (TreeID + UUID)
	tid := getTreeID(t)
	entryID, err := sharding.CreateEntryIDFromParts(fmt.Sprintf("%x", tid), uuid)
	if err != nil {
		t.Error(err)
	}
	runCli(t, "get", "--format=json", "--uuid", entryID.ReturnEntryIDString())
}

func publicKeyFromRekorClient(ctx context.Context, c *generatedClient.Rekor) (*ecdsa.PublicKey, error) {
	resp, err := c.Pubkey.GetPublicKey(&pubkey.GetPublicKeyParams{Context: ctx})
	if err != nil {
		return nil, err
	}

	// marshal the pubkey
	pubKey, err := cryptoutils.UnmarshalPEMToPublicKey([]byte(resp.GetPayload()))
	if err != nil {
		return nil, err
	}
	ed, ok := pubKey.(*ecdsa.PublicKey)
	if !ok {
		return nil, errors.New("public key retrieved from Rekor is not an ECDSA key")
	}
	return ed, nil
}

func TestSignedEntryTimestamp(t *testing.T) {
	// Create a random payload and sign it
	ctx := context.Background()
	payload := []byte("payload")
	s, err := signer.NewMemory()
	if err != nil {
		t.Fatal(err)
	}
	sig, err := s.SignMessage(bytes.NewReader(payload), options.WithContext(ctx))
	if err != nil {
		t.Fatal(err)
	}
	pubkey, err := s.PublicKey(options.WithContext(ctx))
	if err != nil {
		t.Fatal(err)
	}
	pemBytes, err := cryptoutils.MarshalPublicKeyToPEM(pubkey)
	if err != nil {
		t.Fatal(err)
	}

	// submit our newly signed payload to rekor
	rekorClient, err := client.GetRekorClient(rekorServer())
	if err != nil {
		t.Fatal(err)
	}

	re := rekord.V001Entry{
		RekordObj: models.RekordV001Schema{
			Data: &models.RekordV001SchemaData{
				Content: strfmt.Base64(payload),
			},
			Signature: &models.RekordV001SchemaSignature{
				Content: (*strfmt.Base64)(&sig),
				Format:  conv.Pointer(models.RekordV001SchemaSignatureFormatX509),
				PublicKey: &models.RekordV001SchemaSignaturePublicKey{
					Content: (*strfmt.Base64)(&pemBytes),
				},
			},
		},
	}

	returnVal := models.Rekord{
		APIVersion: conv.Pointer(re.APIVersion()),
		Spec:       re.RekordObj,
	}
	params := entries.NewCreateLogEntryParams()
	params.SetProposedEntry(&returnVal)
	resp, err := rekorClient.Entries.CreateLogEntry(params)
	if err != nil {
		t.Fatal(err)
	}
	logEntry := extractLogEntry(t, resp.GetPayload())

	// verify the signature against the log entry (without the signature)
	timestampSig := logEntry.Verification.SignedEntryTimestamp
	logEntry.Verification = nil
	payload, err = logEntry.MarshalBinary()
	if err != nil {
		t.Fatal(err)
	}
	canonicalized, err := jsoncanonicalizer.Transform(payload)
	if err != nil {
		t.Fatal(err)
	}
	// get rekor's public key
	rekorPubKey, err := publicKeyFromRekorClient(ctx, rekorClient)
	if err != nil {
		t.Fatal(err)
	}

	verifier, err := signature.LoadVerifier(rekorPubKey, crypto.SHA256)
	if err != nil {
		t.Fatal(err)
	}
	if err := verifier.VerifySignature(bytes.NewReader(timestampSig), bytes.NewReader(canonicalized), options.WithContext(ctx)); err != nil {
		t.Fatal("unable to verify")
	}
}

func TestNewAPIWithTLS(t *testing.T) {
	tempDir := t.TempDir()
	testCAPath = filepath.Join(tempDir, "ca.pem")
	testCAKeyPath = filepath.Join(tempDir, "ca.key")
	testSignerKey = filepath.Join(tempDir, "signer.key")
	testSignerCert = filepath.Join(tempDir, "signer.pem")
	t.Logf("Generating CA certificate: %s", testCAPath)
	if err := generateTestCA(testCAPath, testCAKeyPath); err != nil {
		t.Fatalf("Failed to generate CA certificate: %v", err)
	}

	t.Logf("Generating signer key: %s", testSignerKey)
	if err := generateTestSigner(testSignerKey, testSignerCert); err != nil {
		t.Fatalf("Failed to generate signer key: %v", err)
	}

	viper.Set("rekor_server.signer", testSignerKey)
	viper.Set("rekor_server.signer-passwd", testSignerPass)
	viper.Set("trillian_log_server.tls", true)
	viper.Set("trillian_log_server.tls_ca_cert", testCAPath)

	apiInstance, err := api.NewAPI(testTreeID)
	if err != nil {
		t.Fatalf("Failed to create API instance with TLS: %v", err)
	}
	t.Logf("API initialized with TLS: %+v", apiInstance)
}

func TestDialE2E(t *testing.T) {
	tempDir := t.TempDir()

	serverKeyPath := filepath.Join(tempDir, "server.key")
	serverCertPath := filepath.Join(tempDir, "server.pem")
	require.NoError(t, generateTestCA(serverKeyPath, serverCertPath))

	serverCert, err := tls.LoadX509KeyPair(serverCertPath, serverKeyPath)
	require.NoError(t, err)

	serverTLSConfig := &tls.Config{
		Certificates: []tls.Certificate{serverCert},
	}

	listener, err := net.Listen("tcp", "localhost:0")
	require.NoError(t, err)
	defer listener.Close()

	server := grpc.NewServer(grpc.Creds(credentials.NewTLS(serverTLSConfig)))
	healthServer := health.NewServer()
	healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)
	grpc_health_v1.RegisterHealthServer(server, healthServer)

	go func() {
		if err := server.Serve(listener); err != nil && err != grpc.ErrServerStopped {
			t.Logf("Server error: %v", err)
		}
	}()
	defer server.Stop()

	tests := []struct {
		name          string
		tlsCACert     string
		useSystemTLS  bool
		expectedError bool
	}{
		{
			name:          "Connection with custom CA cert",
			tlsCACert:     serverCertPath,
			useSystemTLS:  false,
			expectedError: false,
		},
		{
			name:          "Connection with system TLS",
			tlsCACert:     "",
			useSystemTLS:  true,
			expectedError: true,
		},
		{
			name:          "Insecure connection attempt",
			tlsCACert:     "",
			useSystemTLS:  false,
			expectedError: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			viper.Reset()
			viper.Set("trillian_log_server.tls_ca_cert", tt.tlsCACert)
			viper.Set("trillian_log_server.tls", tt.useSystemTLS)

			conn, _ := trillianclient.TestDial("localhost", uint16(listener.Addr().(*net.TCPAddr).Port), tt.tlsCACert, tt.useSystemTLS)
			require.NotNil(t, conn)

			ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
			defer cancel()

			healthClient := grpc_health_v1.NewHealthClient(conn)
			resp, err := healthClient.Check(ctx, &grpc_health_v1.HealthCheckRequest{})

			if tt.expectedError {
				require.Error(t, err)
			} else {
				require.NoError(t, err)
				require.Equal(t, grpc_health_v1.HealthCheckResponse_SERVING, resp.Status)
			}
			conn.Close()
		})
	}
}

func generateTestSigner(keyPath, certPath string) error {
	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return err
	}

	template := x509.Certificate{
		SerialNumber: bigSerial(),
		Subject:      pkix.Name{CommonName: "Test Signer"},
		NotBefore:    time.Now(),
		NotAfter:     time.Now().Add(365 * 24 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageCodeSigning},
	}

	certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		return err
	}

	keyFile, err := os.Create(keyPath)
	if err != nil {
		return err
	}
	defer keyFile.Close()
	privBytes, _ := x509.MarshalECPrivateKey(priv)
	pem.Encode(keyFile, &pem.Block{Type: "EC PRIVATE KEY", Bytes: privBytes})

	certFile, err := os.Create(certPath)
	if err != nil {
		return err
	}
	defer certFile.Close()
	pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certDER})

	return nil
}

func generateTestCA(keyPath, certPath string) error {
	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		return err
	}

	template := x509.Certificate{
		SerialNumber: bigSerial(),
		Subject:      pkix.Name{CommonName: "Test Signer"},
		NotBefore:    time.Now(),
		NotAfter:     time.Now().Add(365 * 24 * time.Hour),
		KeyUsage:     x509.KeyUsageDigitalSignature,
		//:Necessary  as cannot validate certificate for 127.0.0.1 because it doesn't contain any IP SANs
		ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
		DNSNames:    []string{"localhost"},
	}

	certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
	if err != nil {
		return err
	}

	keyFile, err := os.Create(keyPath)
	if err != nil {
		return err
	}
	defer keyFile.Close()
	privBytes, err := x509.MarshalECPrivateKey(priv)
	if err != nil {
		return err
	}
	pem.Encode(keyFile, &pem.Block{Type: "EC PRIVATE KEY", Bytes: privBytes})

	certFile, err := os.Create(certPath)
	if err != nil {
		return err
	}
	defer certFile.Close()
	pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certDER})

	return nil
}

func bigSerial() *big.Int {
	serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
	return serial
}

func TestEntryUpload(t *testing.T) {
	artifactPath := filepath.Join(t.TempDir(), "artifact")
	sigPath := filepath.Join(t.TempDir(), "signature.asc")

	// Create the entry file
	createdPGPSignedArtifact(t, artifactPath, sigPath)
	payload, err := ioutil.ReadFile(artifactPath)
	if err != nil {
		t.Fatal(err)
	}
	sig, err := ioutil.ReadFile(sigPath)
	if err != nil {
		t.Fatal(err)
	}

	entryPath := filepath.Join(t.TempDir(), "entry.json")
	pubKeyBytes := []byte(publicKey)

	re := rekord.V001Entry{
		RekordObj: models.RekordV001Schema{
			Data: &models.RekordV001SchemaData{
				Content: strfmt.Base64(payload),
			},
			Signature: &models.RekordV001SchemaSignature{
				Content: (*strfmt.Base64)(&sig),
				Format:  conv.Pointer(models.RekordV001SchemaSignatureFormatPgp),
				PublicKey: &models.RekordV001SchemaSignaturePublicKey{
					Content: (*strfmt.Base64)(&pubKeyBytes),
				},
			},
		},
	}

	returnVal := models.Rekord{
		APIVersion: conv.Pointer(re.APIVersion()),
		Spec:       re.RekordObj,
	}
	entryBytes, err := json.Marshal(returnVal)
	if err != nil {
		t.Fatal(err)
	}
	if err := ioutil.WriteFile(entryPath, entryBytes, 0644); err != nil {
		t.Fatal(err)
	}

	// Start pubsub client to capture notifications. Values match those in
	// docker-compose.test.yml.
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	psc, err := pubsub.NewClient(ctx, "test-project")
	if err != nil {
		t.Fatalf("Create pubsub client: %v", err)
	}
	topic, err := psc.CreateTopic(ctx, "new-entry")
	if err != nil {
		// Assume error is AlreadyExists if one occurrs unless it is context timeout.
		// If the error was not AlreadyExists, it will be caught in later error
		// checks in this test.
		if errors.Is(err, os.ErrDeadlineExceeded) {
			t.Fatalf("Create pubsub topic: %v", err)
		}
		topic = psc.Topic("new-entry")
	}
	filters := []string{
		`attributes:rekor_entry_kind`,                          // Ignore any messages that do not have this attribute
		`attributes.rekor_signing_subjects = "test@rekor.dev"`, // This is the email in the hard-coded PGP test key
		`attributes.datacontenttype = "application/json"`,      // Only fetch the JSON formatted events
	}
	cfg := pubsub.SubscriptionConfig{
		Topic:  topic,
		Filter: strings.Join(filters, " AND "),
	}
	sub, err := psc.CreateSubscription(ctx, "new-entry-sub", cfg)
	if err != nil {
		if errors.Is(err, os.ErrDeadlineExceeded) {
			t.Fatalf("Create pubsub subscription: %v", err)
		}
		sub = psc.Subscription("new-entry-sub")
	}
	ch := make(chan []byte, 1)
	go func() {
		if err := sub.Receive(ctx, func(_ context.Context, m *pubsub.Message) {
			ch <- m.Data
		}); err != nil {
			t.Errorf("Receive pubusub msg: %v", err)
		}
	}()

	// Now upload to rekor!
	out := runCli(t, "upload", "--entry", entryPath)
	outputContains(t, out, "Created entry at")

	// Await pubsub
	select {
	case msg := <-ch:
		t.Logf("Got pubsub message!\n%s", string(msg))
	case <-ctx.Done():
		t.Errorf("Did not receive pubsub message: %v", ctx.Err())
	}
}

// Regression test for https://github.com/sigstore/rekor/pull/956
// Requesting an inclusion proof concurrently with an entry write triggers
// a race where the inclusion proof returned does not verify because the
// tree head changes.
func TestInclusionProofRace(t *testing.T) {
	// Create a random artifact and sign it.
	artifactPath := filepath.Join(t.TempDir(), "artifact")
	sigPath := filepath.Join(t.TempDir(), "signature.asc")

	e2ex509.CreatedX509SignedArtifact(t, artifactPath, sigPath)
	dataBytes, _ := ioutil.ReadFile(artifactPath)
	h := sha256.Sum256(dataBytes)
	dataSHA := hex.EncodeToString(h[:])

	// Write the public key to a file
	pubPath := filepath.Join(t.TempDir(), "pubKey.asc")
	if err := ioutil.WriteFile(pubPath, []byte(e2ex509.RSACert), 0644); err != nil {
		t.Fatal(err)
	}

	// Upload an entry
	runCli(t, "upload", "--type=hashedrekord", "--pki-format=x509", "--artifact-hash", dataSHA, "--signature", sigPath, "--public-key", pubPath)

	// Constantly uploads new signatures on an entry.
	uploadRoutine := func(pubPath string) error {
		// Create a random artifact and sign it.
		artifactPath := filepath.Join(t.TempDir(), "artifact")
		sigPath := filepath.Join(t.TempDir(), "signature.asc")

		e2ex509.CreatedX509SignedArtifact(t, artifactPath, sigPath)
		dataBytes, _ := ioutil.ReadFile(artifactPath)
		h := sha256.Sum256(dataBytes)
		dataSHA := hex.EncodeToString(h[:])

		// Upload an entry
		out := runCli(t, "upload", "--type=hashedrekord", "--pki-format=x509", "--artifact-hash", dataSHA, "--signature", sigPath, "--public-key", pubPath)
		outputContains(t, out, "Created entry at")

		return nil
	}

	// Attempts to verify the original entry.
	verifyRoutine := func(dataSHA, sigPath, pubPath string) error {
		out := runCli(t, "verify", "--type=hashedrekord", "--pki-format=x509", "--artifact-hash", dataSHA, "--signature", sigPath, "--public-key", pubPath)

		if strings.Contains(out, "calculated root") || strings.Contains(out, "wrong") {
			return errors.New(out)
		}

		return nil
	}

	var g errgroup.Group
	for i := 0; i < 50; i++ {
		g.Go(func() error { return uploadRoutine(pubPath) })
		g.Go(func() error { return verifyRoutine(dataSHA, sigPath, pubPath) })
	}

	if err := g.Wait(); err != nil {
		t.Fatal(err)
	}
}

// TestIssue1308 should be run once before any other tests (against an empty log)
func TestIssue1308(t *testing.T) {
	// we run this to validate issue 1308 which needs to be tested against an empty log
	if getTotalTreeSize(t) == 0 {
		TestSearchQueryNonExistentEntry(t)
	} else {
		t.Skip("skipping because log is not empty")
	}
}

func TestSearchQueryNonExistentEntry(t *testing.T) {
	// Nonexistent but well-formed entry results in 200 with empty array as body
	wd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}
	b, err := ioutil.ReadFile(filepath.Join(wd, "canonical_rekor.json"))
	if err != nil {
		t.Fatal(err)
	}
	body := fmt.Sprintf("{\"entries\":[%s]}", b)
	resp, err := http.Post(fmt.Sprintf("%s/api/v1/log/entries/retrieve", rekorServer()),
		"application/json",
		bytes.NewBuffer([]byte(body)))
	if err != nil {
		t.Fatal(err)
	}
	c, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode != 200 {
		t.Fatalf("expected status 200, got %d instead: %v", resp.StatusCode, string(c))
	}
	if strings.TrimSpace(string(c)) != "[]" {
		t.Fatalf("expected empty JSON array as response, got %s instead", string(c))
	}
}

func getTreeID(t *testing.T) int64 {
	out := runCli(t, "loginfo")
	tidStr := strings.TrimSpace(strings.Split(out, "TreeID: ")[1])
	tid, err := strconv.ParseInt(tidStr, 10, 64)
	if err != nil {
		t.Error(err)
	}
	t.Log("Tree ID:", tid)
	return tid
}

func getTotalTreeSize(t *testing.T) int64 {
	out := runCli(t, "loginfo")
	sizeStr := strings.Fields(strings.Split(out, "Total Tree Size: ")[1])[0]
	size, err := strconv.ParseInt(sizeStr, 10, 64)
	if err != nil {
		t.Error(err)
	}
	t.Log("Total Tree Size:", size)
	return size
}

// This test confirms that we validate tree ID when using the /api/v1/log/entries/retrieve endpoint
// https://github.com/sigstore/rekor/issues/1014
func TestSearchValidateTreeID(t *testing.T) {
	// Create something and add it to the log
	artifactPath := filepath.Join(t.TempDir(), "artifact")
	sigPath := filepath.Join(t.TempDir(), "signature.asc")

	createdPGPSignedArtifact(t, artifactPath, sigPath)

	// Write the public key to a file
	pubPath := filepath.Join(t.TempDir(), "pubKey.asc")
	if err := ioutil.WriteFile(pubPath, []byte(publicKey), 0644); err != nil {
		t.Fatal(err)
	}
	out := runCli(t, "upload", "--artifact", artifactPath, "--signature", sigPath, "--public-key", pubPath)
	outputContains(t, out, "Created entry at")

	uuid, err := sharding.GetUUIDFromIDString(getUUIDFromUploadOutput(t, out))
	if err != nil {
		t.Error(err)
	}
	// Make sure we can get by Entry ID
	tid := getTreeID(t)
	entryID, err := sharding.CreateEntryIDFromParts(fmt.Sprintf("%x", tid), uuid)
	if err != nil {
		t.Fatal(err)
	}
	body := "{\"entryUUIDs\":[\"%s\"]}"
	resp, err := http.Post(fmt.Sprintf("%s/api/v1/log/entries/retrieve", rekorServer()), "application/json", bytes.NewBuffer([]byte(fmt.Sprintf(body, entryID.ReturnEntryIDString()))))
	if err != nil {
		t.Fatal(err)
	}
	if resp.StatusCode != 200 {
		t.Fatalf("expected 200 status code but got %d", resp.StatusCode)
	}

	// Make sure we fail with a random tree ID
	fakeTID := tid + 1
	entryID, err = sharding.CreateEntryIDFromParts(fmt.Sprintf("%x", fakeTID), uuid)
	if err != nil {
		t.Fatal(err)
	}

	resp, err = http.Post(fmt.Sprintf("%s/api/v1/log/entries/retrieve", rekorServer()), "application/json", bytes.NewBuffer([]byte(fmt.Sprintf(body, entryID.ReturnEntryIDString()))))
	if err != nil {
		t.Fatal(err)
	}
	// Not Found because currently we don't detect that an unused random tree ID is invalid.
	c, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode != 200 {
		t.Fatalf("expected status 200, got %d instead", resp.StatusCode)
	}
	if strings.TrimSpace(string(c)) != "[]" {
		t.Fatalf("expected empty JSON array as response, got %s instead", string(c))
	}
}

// TestSearchLogQuerySingleShard provides coverage testing on the searchLogQuery endpoint within a single shard
func TestSearchLogQuerySingleShard(t *testing.T) {

	// Write the shared public key to a file
	pubPath := filepath.Join(t.TempDir(), "logQuery_pubKey.asc")
	pubKeyBytes := []byte(publicKey)
	if err := ioutil.WriteFile(pubPath, pubKeyBytes, 0644); err != nil {
		t.Fatal(err)
	}

	// Create two valid log entries to use for the test cases
	firstArtifactPath := filepath.Join(t.TempDir(), "artifact1")
	firstSigPath := filepath.Join(t.TempDir(), "signature1.asc")
	createdPGPSignedArtifact(t, firstArtifactPath, firstSigPath)
	firstArtifactBytes, _ := ioutil.ReadFile(firstArtifactPath)
	firstSigBytes, _ := ioutil.ReadFile(firstSigPath)

	firstRekord := rekord.V001Entry{
		RekordObj: models.RekordV001Schema{
			Data: &models.RekordV001SchemaData{
				Content: strfmt.Base64(firstArtifactBytes),
			},
			Signature: &models.RekordV001SchemaSignature{
				Content: (*strfmt.Base64)(&firstSigBytes),
				Format:  conv.Pointer(models.RekordV001SchemaSignatureFormatPgp),
				PublicKey: &models.RekordV001SchemaSignaturePublicKey{
					Content: (*strfmt.Base64)(&pubKeyBytes),
				},
			},
		},
	}
	firstEntry := &models.Rekord{
		APIVersion: conv.Pointer(firstRekord.APIVersion()),
		Spec:       firstRekord.RekordObj,
	}

	secondArtifactPath := filepath.Join(t.TempDir(), "artifact2")
	secondSigPath := filepath.Join(t.TempDir(), "signature2.asc")
	createdPGPSignedArtifact(t, secondArtifactPath, secondSigPath)
	secondArtifactBytes, _ := ioutil.ReadFile(secondArtifactPath)
	secondSigBytes, _ := ioutil.ReadFile(secondSigPath)

	secondRekord := rekord.V001Entry{
		RekordObj: models.RekordV001Schema{
			Data: &models.RekordV001SchemaData{
				Content: strfmt.Base64(secondArtifactBytes),
			},
			Signature: &models.RekordV001SchemaSignature{
				Content: (*strfmt.Base64)(&secondSigBytes),
				Format:  conv.Pointer(models.RekordV001SchemaSignatureFormatPgp),
				PublicKey: &models.RekordV001SchemaSignaturePublicKey{
					Content: (*strfmt.Base64)(&pubKeyBytes),
				},
			},
		},
	}
	secondEntry := &models.Rekord{
		APIVersion: conv.Pointer(secondRekord.APIVersion()),
		Spec:       secondRekord.RekordObj,
	}

	// Now upload them to rekor!
	firstOut := runCli(t, "upload", "--artifact", firstArtifactPath, "--signature", firstSigPath, "--public-key", pubPath)
	secondOut := runCli(t, "upload", "--artifact", secondArtifactPath, "--signature", secondSigPath, "--public-key", pubPath)

	firstEntryID := getUUIDFromUploadOutput(t, firstOut)
	firstUUID, _ := sharding.GetUUIDFromIDString(firstEntryID)
	firstIndex := int64(getLogIndexFromUploadOutput(t, firstOut))
	secondEntryID := getUUIDFromUploadOutput(t, secondOut)
	secondUUID, _ := sharding.GetUUIDFromIDString(secondEntryID)
	secondIndex := int64(getLogIndexFromUploadOutput(t, secondOut))

	// this is invalid because treeID is > int64
	invalidEntryID := "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeeefff"
	invalidIndex := int64(-1)
	invalidEntry := &models.Rekord{
		APIVersion: conv.Pointer(secondRekord.APIVersion()),
	}

	nonexistentArtifactPath := filepath.Join(t.TempDir(), "artifact3")
	nonexistentSigPath := filepath.Join(t.TempDir(), "signature3.asc")
	createdPGPSignedArtifact(t, nonexistentArtifactPath, nonexistentSigPath)
	nonexistentArtifactBytes, _ := ioutil.ReadFile(nonexistentArtifactPath)
	nonexistentSigBytes, _ := ioutil.ReadFile(nonexistentSigPath)

	nonexistentEntryID := "0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeeefff"
	nonexistentUUID := "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeeefff"
	nonexistentIndex := int64(999999999) // assuming we don't put that many entries in the log
	nonexistentRekord := rekord.V001Entry{
		RekordObj: models.RekordV001Schema{
			Data: &models.RekordV001SchemaData{
				Content: strfmt.Base64(nonexistentArtifactBytes),
			},
			Signature: &models.RekordV001SchemaSignature{
				Content: (*strfmt.Base64)(&nonexistentSigBytes),
				Format:  conv.Pointer(models.RekordV001SchemaSignatureFormatPgp),
				PublicKey: &models.RekordV001SchemaSignaturePublicKey{
					Content: (*strfmt.Base64)(&pubKeyBytes),
				},
			},
		},
	}
	nonexistentEntry := &models.Rekord{
		APIVersion: conv.Pointer("0.0.1"),
		Spec:       nonexistentRekord.RekordObj,
	}

	type testCase struct {
		name                      string
		expectSuccess             bool
		expectedErrorResponseCode int64
		expectedEntryIDs          []string
		entryUUIDs                []string
		logIndexes                []*int64
		entries                   []models.ProposedEntry
	}

	testCases := []testCase{
		{
			name:             "empty entryUUIDs",
			expectSuccess:    true,
			expectedEntryIDs: []string{},
			entryUUIDs:       []string{},
		},
		{
			name:             "first in log (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID},
			entryUUIDs:       []string{firstEntryID},
		},
		{
			name:             "first in log (using UUID in entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID},
			entryUUIDs:       []string{firstUUID},
		},
		{
			name:             "second in log (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{secondEntryID},
			entryUUIDs:       []string{secondEntryID},
		},
		{
			name:                      "invalid entryID (using entryUUIDs)",
			expectSuccess:             false,
			expectedErrorResponseCode: http.StatusBadRequest,
			entryUUIDs:                []string{invalidEntryID},
		},
		{
			name:             "valid entryID not in log (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{},
			entryUUIDs:       []string{nonexistentEntryID},
		},
		{
			name:             "valid UUID not in log (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{},
			entryUUIDs:       []string{nonexistentUUID},
		},
		{
			name:             "both valid entries in log (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entryUUIDs:       []string{firstEntryID, secondEntryID},
		},
		{
			name:             "both valid entries in log (one with UUID, other with entryID) (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entryUUIDs:       []string{firstEntryID, secondUUID},
		},
		{
			name:                      "one valid entry in log, one malformed (using entryUUIDs)",
			expectSuccess:             false,
			expectedErrorResponseCode: http.StatusBadRequest,
			entryUUIDs:                []string{firstEntryID, invalidEntryID},
		},
		{
			name:             "one existing, one valid entryID but not in log (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID},
			entryUUIDs:       []string{firstEntryID, nonexistentEntryID},
		},
		{
			name:             "two existing, one valid entryID but not in log (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entryUUIDs:       []string{firstEntryID, secondEntryID, nonexistentEntryID},
		},
		{
			name:             "two existing, one valid entryID but not in log (different ordering 1) (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entryUUIDs:       []string{firstEntryID, nonexistentEntryID, secondEntryID},
		},
		{
			name:             "two existing, one valid entryID but not in log (different ordering 2) (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entryUUIDs:       []string{nonexistentEntryID, firstEntryID, secondEntryID},
		},
		{
			name:             "two existing, one valid entryID but not in log (different ordering 3) (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entryUUIDs:       []string{nonexistentUUID, firstEntryID, secondEntryID},
		},
		{
			name:             "two existing, one valid entryID but not in log (different ordering 4) (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entryUUIDs:       []string{nonexistentEntryID, firstUUID, secondEntryID},
		},
		{
			name:             "two existing, one valid entryID but not in log (different ordering 5) (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entryUUIDs:       []string{nonexistentEntryID, firstEntryID, secondUUID},
		},
		{
			name:             "two existing, one valid entryID but not in log (different ordering 6) (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entryUUIDs:       []string{nonexistentUUID, firstEntryID, secondUUID},
		},
		{
			name:             "two existing, one valid entryID but not in log (different ordering 7) (using entryUUIDs)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entryUUIDs:       []string{nonexistentEntryID, firstUUID, secondUUID},
		},
		{
			name:                      "request more than 10 entries (using entryUUIDs)",
			expectSuccess:             false,
			expectedErrorResponseCode: http.StatusUnprocessableEntity,
			entryUUIDs:                []string{firstEntryID, firstEntryID, firstEntryID, firstEntryID, firstEntryID, firstEntryID, firstEntryID, firstEntryID, firstEntryID, firstEntryID, firstEntryID},
		},
		{
			name:             "empty logIndexes",
			expectSuccess:    true,
			expectedEntryIDs: []string{},
			logIndexes:       []*int64{},
		},
		{
			name:             "first in log (using logIndexes)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID},
			logIndexes:       []*int64{&firstIndex},
		},
		{
			name:             "second in log (using logIndexes)",
			expectSuccess:    true,
			expectedEntryIDs: []string{secondEntryID},
			logIndexes:       []*int64{&secondIndex},
		},
		{
			name:                      "invalid logIndex (using logIndexes)",
			expectSuccess:             false,
			expectedErrorResponseCode: http.StatusUnprocessableEntity,
			logIndexes:                []*int64{&invalidIndex},
		},
		{
			name:             "valid index not in log (using logIndexes)",
			expectSuccess:    true,
			expectedEntryIDs: []string{},
			logIndexes:       []*int64{&nonexistentIndex},
		},
		{
			name:             "both valid entries in log (using logIndexes)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			logIndexes:       []*int64{&firstIndex, &secondIndex},
		},
		{
			name:                      "one valid entry in log, one malformed (using logIndexes)",
			expectSuccess:             false,
			expectedErrorResponseCode: http.StatusUnprocessableEntity,
			logIndexes:                []*int64{&firstIndex, &invalidIndex},
		},
		{
			name:             "one existing, one valid Index but not in log (using logIndexes)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID},
			logIndexes:       []*int64{&firstIndex, &nonexistentIndex},
		},
		{
			name:             "two existing, one valid Index but not in log (using logIndexes)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			logIndexes:       []*int64{&firstIndex, &secondIndex, &nonexistentIndex},
		},
		{
			name:             "two existing, one valid Index but not in log (different ordering 1) (using logIndexes)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			logIndexes:       []*int64{&firstIndex, &nonexistentIndex, &secondIndex},
		},
		{
			name:             "two existing, one valid Index but not in log (different ordering 2) (using logIndexes)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			logIndexes:       []*int64{&nonexistentIndex, &firstIndex, &secondIndex},
		},
		{
			name:                      "request more than 10 entries (using logIndexes)",
			expectSuccess:             false,
			expectedErrorResponseCode: http.StatusUnprocessableEntity,
			logIndexes:                []*int64{&firstIndex, &firstIndex, &firstIndex, &firstIndex, &firstIndex, &firstIndex, &firstIndex, &firstIndex, &firstIndex, &firstIndex, &firstIndex},
		},
		{
			name:             "empty entries",
			expectSuccess:    true,
			expectedEntryIDs: []string{},
			entries:          []models.ProposedEntry{},
		},
		{
			name:             "first in log (using entries)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID},
			entries:          []models.ProposedEntry{firstEntry},
		},
		{
			name:             "second in log (using entries)",
			expectSuccess:    true,
			expectedEntryIDs: []string{secondEntryID},
			entries:          []models.ProposedEntry{secondEntry},
		},
		{
			name:                      "invalid entry (using entries)",
			expectSuccess:             false,
			expectedErrorResponseCode: http.StatusUnprocessableEntity,
			entries:                   []models.ProposedEntry{invalidEntry},
		},
		{
			name:             "valid entry not in log (using entries)",
			expectSuccess:    true,
			expectedEntryIDs: []string{},
			entries:          []models.ProposedEntry{nonexistentEntry},
		},
		{
			name:             "both valid entries in log (using entries)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entries:          []models.ProposedEntry{firstEntry, secondEntry},
		},
		{
			name:                      "one valid entry in log, one malformed (using entries)",
			expectSuccess:             false,
			expectedErrorResponseCode: http.StatusUnprocessableEntity,
			entries:                   []models.ProposedEntry{firstEntry, invalidEntry},
		},
		{
			name:             "one existing, one valid Index but not in log (using entries)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID},
			entries:          []models.ProposedEntry{firstEntry, nonexistentEntry},
		},
		{
			name:             "two existing, one valid Index but not in log (using entries)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entries:          []models.ProposedEntry{firstEntry, secondEntry, nonexistentEntry},
		},
		{
			name:             "two existing, one valid Index but not in log (different ordering 1) (using entries)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entries:          []models.ProposedEntry{firstEntry, nonexistentEntry, secondEntry},
		},
		{
			name:             "two existing, one valid Index but not in log (different ordering 2) (using entries)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID},
			entries:          []models.ProposedEntry{nonexistentEntry, firstEntry, secondEntry},
		},
		{
			name:                      "request more than 10 entries (using entries)",
			expectSuccess:             false,
			expectedErrorResponseCode: http.StatusUnprocessableEntity,
			entries:                   []models.ProposedEntry{firstEntry, firstEntry, firstEntry, firstEntry, firstEntry, firstEntry, firstEntry, firstEntry, firstEntry, firstEntry, firstEntry},
		},
		{
			name:                      "request more than 10 entries (using mixture)",
			expectSuccess:             false,
			expectedErrorResponseCode: http.StatusUnprocessableEntity,
			entryUUIDs:                []string{firstEntryID, firstEntryID, firstEntryID, firstEntryID},
			logIndexes:                []*int64{&firstIndex, &firstIndex, &firstIndex},
			entries:                   []models.ProposedEntry{firstEntry, firstEntry, firstEntry, firstEntry},
		},
		{
			name:                      "request valid and invalid (using mixture)",
			expectSuccess:             false,
			expectedErrorResponseCode: http.StatusUnprocessableEntity,
			entryUUIDs:                []string{firstEntryID, firstEntryID, firstEntryID, firstEntryID},
			logIndexes:                []*int64{&invalidIndex, &invalidIndex, &invalidIndex},
			entries:                   []models.ProposedEntry{firstEntry, firstEntry, firstEntry},
		},
		{
			name:             "request valid and nonexistent (using mixture)",
			expectSuccess:    true,
			expectedEntryIDs: []string{firstEntryID, secondEntryID, firstEntryID, secondEntryID, firstEntryID, secondEntryID},
			entryUUIDs:       []string{firstEntryID, secondEntryID, nonexistentEntryID},
			logIndexes:       []*int64{&firstIndex, &secondIndex, &nonexistentIndex},
			entries:          []models.ProposedEntry{firstEntry, secondEntry, nonexistentEntry},
		},
	}

	for _, test := range testCases {
		rekorClient, err := client.GetRekorClient(rekorServer(), client.WithRetryCount(0))
		if err != nil {
			t.Fatal(err)
		}
		t.Run(test.name, func(t *testing.T) {
			params := entries.NewSearchLogQueryParams()
			entry := &models.SearchLogQuery{}
			if len(test.entryUUIDs) > 0 {
				t.Log("trying with entryUUIDs: ", test.entryUUIDs)
				entry.EntryUUIDs = test.entryUUIDs
			}
			if len(test.logIndexes) > 0 {
				entry.LogIndexes = test.logIndexes
			}
			if len(test.entries) > 0 {
				entry.SetEntries(test.entries)
			}
			params.SetEntry(entry)

			resp, err := rekorClient.Entries.SearchLogQuery(params)
			if err != nil {
				if !test.expectSuccess {
					if _, ok := err.(*entries.SearchLogQueryBadRequest); ok {
						if test.expectedErrorResponseCode != http.StatusBadRequest {
							t.Fatalf("unexpected error code received: expected %d, got %d: %v", test.expectedErrorResponseCode, http.StatusBadRequest, err)
						}
					} else if _, ok := err.(*entries.SearchLogQueryUnprocessableEntity); ok {
						if test.expectedErrorResponseCode != http.StatusUnprocessableEntity {
							t.Fatalf("unexpected error code received: expected %d, got %d: %v", test.expectedErrorResponseCode, http.StatusUnprocessableEntity, err)
						}
					} else if e, ok := err.(*entries.SearchLogQueryDefault); ok {
						t.Fatalf("unexpected error: %v", e)
					}
				} else {
					t.Fatalf("unexpected error: %v", err)
				}
			} else {
				if len(resp.Payload) != len(test.expectedEntryIDs) {
					t.Fatalf("unexpected number of responses received: expected %d, got %d", len(test.expectedEntryIDs), len(resp.Payload))
				}
				// walk responses, build up list of returned entry IDs
				returnedEntryIDs := []string{}
				for _, entry := range resp.Payload {
					// do this for dynamic keyed entries
					for entryID := range entry {
						t.Log("received entry: ", entryID)
						returnedEntryIDs = append(returnedEntryIDs, entryID)
					}
				}
				// we have the expected number of responses, let's ensure they're the ones we expected
				if out := cmp.Diff(returnedEntryIDs, test.expectedEntryIDs, cmpopts.SortSlices(func(a, b string) bool { return a < b })); out != "" {
					t.Fatalf("unexpected responses: %v", out)
				}
			}
		})
	}
}

func TestGetLogProofInvalidShard(t *testing.T) {
	// Test case for GetLogProofHandler where a valid int64 is given for logIndex,
	// but it doesn't match a known shard. This should result in a 400 Bad Request, not a 500 error.
	treeID := "999999999999999999" // A large int64 value
	firstSize := "1"
	lastSize := "2"

	url := fmt.Sprintf("%s/api/v1/log/proof?treeID=%s&firstSize=%s&lastSize=%s", rekorServer(), treeID, firstSize, lastSize)
	resp, err := http.Get(url)
	if err != nil {
		t.Fatalf("unexpected error getting log proof: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusBadRequest {
		bodyBytes, _ := ioutil.ReadAll(resp.Body)
		t.Fatalf("expected status code %d, got %d: %s", http.StatusBadRequest, resp.StatusCode, string(bodyBytes))
	}
}