SignPathDocker.psm1

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
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
#Requires -PSEdition Core
#Requires -Modules SignPath

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

################################################################################
# Initialize-DockerSigning
################################################################################

function Initialize-DockerSigning (
  # The name of the Docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # Delegation name
  [Parameter()]
  [ValidateNotNullOrEmpty()]
  [string] $DelegationName = "signpath",

  # If a certificate is given, Add-DelegationCertificate will also be executed.
  [ValidateNotNullOrEmpty()]
  [string] $DelegationCertificatePath,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword,

  # Provide this to always overwrite the resulting root certificate file for the repository, if it already exists
  [Parameter()]
  [switch] $ForceOverwriteRootCertificate = $false,

  # If the flag is set and the repository already exists at the Notary Service, the repository is re-initialized (i.e., deleted and recreated).
  [Parameter()]
  [switch] $ForceReinitializeRepository = $false
) {
<#
  .SYNOPSIS
    Initializes a new Notary repository.
  .DESCRIPTION
    Initializes a Notary repository with the given repository name. If an existing Notary root key is found locally it is reused.
    If you provide -DelegationCertificatePath, the behavior of the command Add-DelegationCertificate will be executed after a successfull initialization.
    You can delete and reinitialize an existing Notary repository by specifying -ForceReinitializeRepository. Mind that existing signatures are dropped when doing so.
    After the repository was created successfully, the root certificate is extracted (see the Get-RootCertificate command for details).
  .EXAMPLE
  Initialize-DockerSigning `
      -Repository "docker.io/namespace/imagename" `
      -NotaryUsername "username" `
      -NotaryPassword (ConvertTo-SecureString -string "password" -AsPlainText)
  .OUTPUTS
    After a successfull creation of the Notary repository its root certificate will be extracted and saved to a file.
  .NOTES
    Author: SignPath GmbH
  #>


  $repositoryInfo = ParseRepository $Repository
  $notaryUrl = GetNotaryUrl $NotaryUrl
  $notaryBasicAuthCredentials = PrepareNotaryCredentials $NotaryUsername $NotaryPassword
  $trustDir = GetTrustDir

  Write-Verbose "Notary URL: $notaryUrl"

  $rootCertificateFilePath = GetRootCertificateFilePath $repositoryInfo
  if((Test-Path $rootCertificateFilePath -PathType Leaf) -and -not $ForceOverwriteRootCertificate) {
    throw "$rootCertificateFilePath already exists. Provide -ForceOverwriteRootCertificate if you want to replace it"
  }

  try {
    PrepareNotaryAuthentication $notaryBasicAuthCredentials

    $repositoryExists = CheckIfRepositoryExists $notaryUrl $trustDir $repositoryInfo

    if ($repositoryExists -and -not $ForceReinitializeRepository) {
      throw "Repository '$($repositoryInfo.FullName)' already exists. Recreating it would remove the existing keys. Use -ForceReinitializeRepository to init anyways."
    }

    if ($repositoryExists -and $ForceReinitializeRepository) {
      Write-Host "Repository '$($repositoryInfo.FullName)' will be reinitialized"
      dockernotary $notaryUrl $trustDir @{} "delete" $repositoryInfo.FullName "--remote"
      $pathToLocalRepository = Join-Path $trustDir "tuf" $repositoryInfo.Registry $repositoryInfo.Namespace $repositoryInfo.Name
    }

    dockernotary $notaryUrl $trustDir @{} "init" $repositoryInfo.FullName

    Write-Host "`nRotate snapshot key responsibility to the notary server"
    dockernotary $notaryUrl $trustDir @{ 1 = "Could not rotate the snapshot key. Does the repository exist?" } "key" "rotate" $repositoryInfo.FullName "snapshot" "-r"

    Write-Host "`nPublish the newly created repository to the notary"
    dockernotary $notaryUrl $trustDir @{} "publish" $repositoryInfo.FullName

    ExtractRootCertificate $trustDir $repositoryInfo $ForceOverwriteRootCertificate
  } finally {
    CleanupNotaryAuthentication
  }

  if(-not [string]::IsNullOrEmpty($DelegationCertificatePath)) {
    Add-DelegationCertificate `
      -Repository $Repository `
      -DelegationName $DelegationName `
      -NotaryUsername $NotaryUsername `
      -NotaryPassword $NotaryPassword `
      -DelegationCertificatePath $DelegationCertificatePath `
      -NotaryUrl $NotaryUrl
  }
}

################################################################################
# Add-DelegationCertificate
################################################################################

function Add-DelegationCertificate (
  # The name of the Docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # Delegation name
  [Parameter()]
  [ValidateNotNullOrEmpty()]
  [string] $DelegationName = "signpath",

  # The given certificate will be registered as the delegation key for the roles 'targets/<DelegationName>' and 'targets/releases' in the given repository.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $DelegationCertificatePath,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword
) {
<#
  .SYNOPSIS
    Adds a delegation certificate to an existing notary repository, so the referenced private key can be used for signing docker images.
  .DESCRIPTION
    Adds the certificate provided with -DelegationCertificatePath to the given Notary repository as a delegation, if the repository exists.
    Based on how docker expects delegations to be set up, there will be two delegations: the delegation will be added to the 'targets/releases' role
    and the 'targets/<DelegationName>' role.
    The provided certificate file can either be in the DER format or the PEM format.
  .EXAMPLE
    Add-DelegationCertificate `
      -Repository "docker.io/namespace/imagename" `
      -NotaryUsername "username" `
      -NotaryPassword (ConvertTo-SecureString -string "password" -AsPlainText) `
      -DelegationCertificatePath "path/to/certificatefile"
  .OUTPUTS
    If the command succeeded, the two delegations are listed.
  .NOTES
    Author: SignPath GmbH
  #>


  $repositoryInfo = ParseRepository $Repository
  $notaryUrl = GetNotaryUrl $NotaryUrl
  $notaryBasicAuthCredentials = PrepareNotaryCredentials $NotaryUsername $NotaryPassword
  $trustDir = GetTrustDir

  $validDelegationCertificatePath = PrepareDelegationCertificate $DelegationCertificatePath

  try {

    PrepareNotaryAuthentication $notaryBasicAuthCredentials

    dockernotary $notaryUrl $trustDir @{} -SuppressOutput "delegation" "add" $repositoryInfo.FullName "targets/releases" $validDelegationCertificatePath "--all-paths"
    dockernotary $notaryUrl $trustDir @{} -SuppressOutput "delegation" "add" $repositoryInfo.FullName "targets/$DelegationName" $validDelegationCertificatePath "--all-paths"

    Write-Host "$([Environment]::NewLine)Publish the newly created two delegation keys to the notary"
    dockernotary $notaryUrl $trustDir @{} "publish" $repositoryInfo.FullName
    dockernotary $notaryUrl $trustDir @{} -SuppressOutput "delegation" "list" $repositoryInfo.FullName
  } finally {
    CleanupNotaryAuthentication
  }
}

################################################################################
# Get-RootCertificate
################################################################################

function Get-RootCertificate (
  # The name of the Docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword,

  # Provide this to always overwrite the root certificate of the repository, if it already exists.
  [Parameter()]
  [switch] $ForceOverwriteRootCertificate = $false
) {
<#
  .SYNOPSIS
    Extracts the root certificate as a PEM-formatted file from an existing notary repository.
  .DESCRIPTION
    You can use this command to retrieve the repository's root certificate.
    It downloads the current state of the Notary repository and extracts the certificate in the PEM format into the current directory.
    If you want to overwrite a file with the same name, provide the switch -ForceOverwriteRootCertificate.
  .EXAMPLE
  Get-RootCertificate `
      -Repository "docker.io/namespace/imagename" `
      -NotaryUsername "username" `
      -NotaryPassword (ConvertTo-SecureString -string "password" -AsPlainText)
  .OUTPUTS
    A file with the name <registry>_<namespace>_<name>.RootCertificate.pem, which contains the Notary repository root certificate encoded as PEM.
  .NOTES
    Author: SignPath GmbH
  #>


  $repositoryInfo = ParseRepository $Repository
  $notaryUrl = GetNotaryUrl $NotaryUrl
  $notaryBasicAuthCredentials = PrepareNotaryCredentials $NotaryUsername $NotaryPassword
  $trustDir = GetTrustDir

  $rootCertificateFilePath = GetRootCertificateFilePath $repositoryInfo
  if((Test-Path $rootCertificateFilePath -PathType Leaf) -and -not $ForceOverwriteRootCertificate) {
    throw "$rootCertificateFilePath already exists. Provide -ForceOverwriteRootCertificate if you want to replace it"
  }

  try {
    PrepareNotaryAuthentication $notaryBasicAuthCredentials

    $repositoryExists = CheckIfRepositoryExists $notaryUrl $trustDir $repositoryInfo

    if (-not $repositoryExists) {
      throw "Repository '$($repositoryInfo.FullName)' does not exist."
    }

    Write-Host "Loading repository $($repositoryInfo.FullName)"
    dockernotary $notaryUrl $trustDir @{} "list" $repositoryInfo.FullName

    ExtractRootCertificate $trustDir $repositoryInfo $ForceOverwriteRootCertificate
  } finally {
    CleanupNotaryAuthentication
  }
}

################################################################################
# Invoke-DockerSigning
################################################################################

function Invoke-DockerSigning (
  # The name of the Docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # All Docker image tags that you want to sign, at least 1 (all of them must point to the same image)
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string[]] $Tags,

  # The URL to the SignPath API, e.g. 'https://app.signpath.io/api/'.
  [Parameter()]
  [ValidateNotNullOrEmpty()]
  [string] $ApiUrl = "https://app.signpath.io/api/",

  # The URL to the Docker Registry. If empty it is extracted from the $Repository parameter. If the repository
  # states "docker.io" as registry, we hardcode the URL to 'https://registry-1.docker.io'.
  [Parameter()]
  [string] $RegistryUrl,

  # A username authorized to read metadata of the given Docker repository. If not set, the REGISTRY_AUTH
  # environment variable is used as a fallback.
  [Parameter()]
  [string] $RegistryUsername,

  # The password for the given RegistryUsername. If not set, the REGISTRY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $RegistryPassword,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword,

  # The SignPath CI user's API token.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $CIUserToken,

  # The ID of your SignPath organization.
  # Go to "Project > Signing policy" in the web client and copy the first ID from the url to retrieve this value
  # (e.g. https://app.signpath.io/<OrganizationId>/SigningPolicies/<SigningPolicyId>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $OrganizationId,

  # The slug of your SignPath project.
  [Parameter(Mandatory)]
  [string] $ProjectSlug,

  # Allows you to override the default artifact configuration of the project.
  [Parameter()]
  [string] $ArtifactConfigurationSlug,

  # The slug of your SignPath signing policy.
  [Parameter(Mandatory)]
  [string] $SigningPolicySlug,

  # An optional description of the signing operation that could be helpful for the approver.
  [Parameter()]
  [string] $Description,

  # The total time in seconds that the cmdlet will wait for a single SignService API service call to succeed
  # (across several retries). Defaults to 600 seconds.
  [Parameter()]
  [int] $ServiceUnavailableTimeoutInSeconds = 600,

  # The HTTP timeout used for the upload and download SignPath HTTP requests. Defaults to 300 seconds.
  [Parameter()]
  [int] $UploadAndDownloadRequestTimeoutInSeconds = 300,

  # The maximum time in seconds that the cmdlet will wait for the signing request to complete (upload and download
  # have no specific timeouts). Defaults to 600 seconds.
  [Parameter()]
  [int] $WaitForCompletionTimeoutInSeconds = 600
) {
  <#
  .SYNOPSIS
    Creates signed Docker TUF metadata via the SignPath REST API and pushes it to the given Notary Service.
  .DESCRIPTION
    The Invoke-DockerSigning cmdlet
     - creates a SignPath Docker signing data file
     - submits a SignPath signing request with the created SignPath Docker signing data file (via the SignPath REST
       API)
     - downloads the resulting signed artifact
     - extracts the signed Docker TUF metadata and pushes it to the Notary Service
    The New-DockerSigningData, Submit-SigningRequest and Push-SignedDockerSigningData can also be used individually
    for more detailed control over the process.
 
    To tweak HTTP related timing issues with the SignPath REST API use the parameters
    ServiceUnavailableNumberOfRetries and ServiceUnavailableRetryTimeoutInSeconds.
  .EXAMPLE
  Invoke-DockerSigning `
      -Repository "docker.io/library/alpine" `
      -Tags "latest" `
      -CIUserToken "aJoe3s2m7hkhVyoba4H4weqj9UxIk6nKRXGhGbH7nv4x2" `
      -OrganizationId "1c0ab26c-12f3-4c6e-a043-2568e133d2de" `
      -ProjectSlug "MyDockerProject" `
      -SigningPolicySlug "TestSigning"
  .OUTPUTS
    You can verify the results by setting DOCKER_CONTENT_TRUST=1 and performing a docker pull of the specified
    repository and tag. The latest signed image as stated by the Notary Service should be pulled, the image ID
    should match the image's ID you just signed.
  .NOTES
    Author: SignPath GmbH
  #>

  $ErrorActionPreference = "Stop"

  $tempDirectory = NewTemporaryDirectory
  try {
    $unsignedPackagePath = Join-Path $tempDirectory "docker-signing-data-file.zip"
    $signedPackagePath = Join-Path $tempDirectory "signed.zip"

    New-DockerSigningData -Repository $Repository `
                          -OutputArtifactPath $unsignedPackagePath `
                          -Tags $Tags `
                          -RegistryUrl $RegistryUrl `
                          -RegistryUsername $RegistryUsername `
                          -RegistryPassword $RegistryPassword `
                          -NotaryUrl $NotaryUrl `
                          -NotaryUsername $NotaryUsername `
                          -NotaryPassword $NotaryPassword

    Submit-SigningRequest -ApiUrl $ApiUrl `
                          -CiUserToken $CIUserToken `
                          -OrganizationId $OrganizationId `
                          -ProjectSlug $ProjectSlug `
                          -ArtifactConfigurationSlug $ArtifactConfigurationSlug `
                          -SigningPolicySlug $SigningPolicySlug `
                          -InputArtifactPath $unsignedPackagePath `
                          -OutputArtifactPath $signedPackagePath `
                          -Description $Description `
                          -ServiceUnavailableTimeoutInSeconds $ServiceUnavailableTimeoutInSeconds `
                          -UploadAndDownloadRequestTimeoutInSeconds $UploadAndDownloadRequestTimeoutInSeconds `
                          -WaitForCompletionTimeoutInSeconds $WaitForCompletionTimeoutInSeconds `
                          -WaitForCompletion

    Push-SignedDockerSigningData -Repository $Repository `
                                 -InputArtifactPath $signedPackagePath `
                                 -NotaryUrl $NotaryUrl `
                                 -NotaryUsername $NotaryUsername `
                                 -NotaryPassword $NotaryPassword
  }
  finally {
    Remove-Item $tempDirectory -Recurse -Force
  }
}

################################################################################
# New-DockerSigningData
################################################################################

function New-DockerSigningData (
  # The name of the docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # Specifies the path of the resulting SignPath Docker signing data file.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $OutputArtifactPath,

  # All Docker image tags that you want to sign, at least 1 (all of them must point to the same image)
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string[]] $Tags,

  # The URL to the Docker Registry. If empty it is extracted from the $Repository parameter. If the repository
  # states "docker.io" as registry, we hardcode the URL to 'https://registry-1.docker.io'.
  [Parameter()]
  [string] $RegistryUrl,

  # A username authorized to read metadata of the given Docker repository. If not set, the REGISTRY_AUTH
  # environment variable is used as a fallback.
  [Parameter()]
  [string] $RegistryUsername,

  # The password for the given RegistryUsername. If not set, the REGISTRY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $RegistryPassword,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword
) {
  <#
  .SYNOPSIS
    Creates a SignPath Docker signing data file.
  .DESCRIPTION
    The New-DockerSigningData cmdlet creates a SignPath Docker signing data file ready for signing with SignPath.
  .EXAMPLE
  New-DockerSigningData
    -Repository "docker.io/library/alpine" `
    -OutputArtifactPath "MyDockerSigningData.zip"
    -Tags "latest"
  .OUTPUTS
    A SignPath Docker signing data file at the given OutputArtifactPath that is ready for signing with SignPath.
  .NOTES
    Author: SignPath GmbH
  #>

  $ErrorActionPreference = "Stop"

  $repositoryInfo = ParseRepository $Repository
  $outputArtifactPath = PrepareOutputArtifactPath $OutputArtifactPath
  $registryBasicAuthCredentails = PrepareRegistryCredentials $RegistryUsername $RegistryPassword $NotaryUsername $NotaryPassword
  $notaryBasicAuthCredentials = PrepareNotaryCredentials $NotaryUsername $NotaryPassword
  EnsureIsZipFile $outputArtifactPath

  UpdateLocalDockerTrustData $repositoryInfo $NotaryUrl $notaryBasicAuthCredentials

  $metadataFiles = [System.Collections.Generic.List[string]](CollectExistingMetadataFiles $Repository)

  $temporaryDockerSigningDataDirectory = NewTemporaryDirectory
  try {
    CopyMetadataFilesToDirectory $metadataFiles $temporaryDockerSigningDataDirectory

    $signingMetadataJson = Join-Path $temporaryDockerSigningDataDirectory "signingmetadata.json"
    $registryUrl = GetRegistryUrl $repositoryInfo $RegistryUrl
    Write-Verbose "Registry URL: $registryUrl"

    GenerateSigningMetadata $signingMetadataJson $Tags $repositoryInfo $registryUrl $registryBasicAuthCredentails

    Write-Verbose "Creating SignPath Docker signing data file from collected files..."
    $temporaryDockerSigningDataDirectoryWithoutRoot = Join-Path $temporaryDockerSigningDataDirectory "*"
    Compress-Archive -Path $temporaryDockerSigningDataDirectoryWithoutRoot -DestinationPath $outputArtifactPath
  }
  finally {
    # Note: this code path is uncovered, as we cannot know in a test which directory is created by the script
    Remove-Item $temporaryDockerSigningDataDirectory -Recurse -Force
  }

  Write-Host "Successfully created SignPath Docker signing data file '$outputArtifactPath'."
}

################################################################################
# Push-SignedDockerSigningData
################################################################################

function Push-SignedDockerSigningData (
  # The name of the Docker repository (<registry>/<namespace>/<name>).
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $Repository,

  # Specifies the path of the signed SignPath Docker signing data file.
  [Parameter(Mandatory)]
  [ValidateNotNullOrEmpty()]
  [string] $InputArtifactPath,

  # The URL to the Notary Service. If empty, the environment variable DOCKER_CONTENT_TRUST_SERVER is used as a
  # fallback, if also empty, the Docker Notary Service URL 'https://notary.docker.io' is used.
  [Parameter()]
  [string] $NotaryUrl,

  # A username authorized to push to the given Docker repository. If not set, the NOTARY_AUTH environment variable
  # is used as a fallback.
  [Parameter()]
  [string] $NotaryUsername,

  # The password for the given NotaryUsername. If not set, the NOTARY_AUTH environment variable is used as a
  # fallback.
  [Parameter()]
  [SecureString] $NotaryPassword
) {
  <#
  .SYNOPSIS
    Extracts signed Docker TUF metadata out of a signed SignPath Docker signing data file and pushes it to a Notary
    Service.
  .DESCRIPTION
    The Push-SignedDockerSigningData cmdlet pushes signed Docker TUF metadata to the Notary Service and thereby
    updates the up-to-date image versions for clients that have DOCKER_CONTENT_TRUST set to 1.
  .EXAMPLE
  Push-SignedDockerSigningData `
      -Repository $repository `
      -InputArtifactPath "signed.zip"
  .OUTPUTS
    You can verify the results by setting DOCKER_CONTENT_TRUST=1 and performing a docker pull of the specified
    repository and tag. The latest signed image as stated by the Notary Service should be pulled, the image ID
    should match the image's ID you just signed.
  .NOTES
    Author: SignPath GmbH
  #>

  $ErrorActionPreference = "Stop"

  $repositoryInfo = ParseRepository $Repository
  $inputArtifactPath = PrepareInputArtifactPath $InputArtifactPath
  $notaryUrl = GetNotaryUrl $NotaryUrl
  $notaryBasicAuthCredentials = PrepareNotaryCredentials $NotaryUsername $NotaryPassword
  Write-Verbose "Notary URL: $notaryUrl"

  $tempDirectory = NewTemporaryDirectory
  try {
    Write-Verbose "Extracting signed SignPath Docker signing data file..."
    Expand-Archive $inputArtifactPath -DestinationPath $tempDirectory

    $targetsDirectory = Join-Path $tempDirectory "targets"

    if (-not (Test-Path $targetsDirectory)) {
      throw "Could not find targets files in signed package"
    }

    $delegationFiles = @()
    foreach ($file in (Get-ChildItem $targetsDirectory)) {
      $delegationName = $file.Name -replace ".json", ""
      $delegationFile = @{
        Path = $file.FullName
        Name = "targets/$delegationName"
      }
      $delegationFiles += $delegationFile
    }

    Write-Verbose "Pushing signed metadata files to Notary service..."
    PushFiles $notaryUrl $repositoryInfo $delegationFiles $notaryBasicAuthCredentials
  }
  finally {
    Remove-Item $tempDirectory -Recurse -Force
  }

  Write-Host "Successfully pushed signed metadata to Notary service."
}

################################################################################
# HELPER FUNCTIONS
################################################################################

function NewTemporaryDirectory {
  Write-Verbose "Creating temporary directory..."

  $parent = [System.IO.Path]::GetTempPath()
  [string] $name = [System.Guid]::NewGuid()
  $path = Join-Path $parent $name

  Write-Verbose "Temporary directory path: $path"
  return New-Item -ItemType Directory -Path $path
}

function ParseRepository ([string] $repository) {
  Write-Verbose "Parsing repository '$repository'..."

  $repositoryRegexResult = $repository | Select-String -Pattern "(?<registry>.*?)/((?<namespace>.*)/)?(?<name>.*)"
  if(!$repositoryRegexResult -or $repositoryRegexResult.Matches.Count -eq 0) {
    throw "Repository needs to be in format '<registry>/<namespace(s)>/<name>'."
  }

  $registry = $repositoryRegexResult.Matches[0].Groups["registry"].Value
  $namespace = $repositoryRegexResult.Matches[0].Groups["namespace"].Value
  $name = $repositoryRegexResult.Matches[0].Groups["name"].Value

  if([string]::IsNullOrEmpty($namespace)) {
    $namespaceUrlPart = "";
  } else {
    $namespaceUrlPart = "$namespace/"
  }

  Write-Verbose "Parsed registry: $registry"
  Write-Verbose "Parsed namespace: $namespace"
  Write-Verbose "Parsed name: $name"

  return @{
    Registry = $registry
    Namespace = $namespace
    NamespaceUrlPart = $namespaceUrlPart
    Name = $name
    FullName = $repository
  }
}

function PrepareOutputArtifactPath ([string] $outputArtifactPath) {
  $outputArtifactPath = NormalizePath $outputArtifactPath

  if(Test-Path -Path $outputArtifactPath) {
    throw "There is already a file at '$outputArtifactPath'."
  }

  return $outputArtifactPath
}

function PrepareInputArtifactPath ([string] $inputArtifactPath) {
  $inputArtifactPath = NormalizePath $inputArtifactPath

  if(-not (Test-Path -Path $inputArtifactPath)) {
    throw "The input artifact path '$inputArtifactPath' does not exist."
  }

  return $inputArtifactPath
}

function NormalizePath ([string] $path) {
  if(-not [System.IO.Path]::IsPathRooted($path)) {
    # Note: this code path is uncovered, as we do not want to write to the $PWD directory (= current directory).
    return Join-Path $PWD $path
  }
  return $path
}

function EnsureIsZipFile ([string] $path) {
  if(-not $path.EndsWith(".zip")) {
    throw "The output artifact path must be a ZIP file."
  }
}

function GetRegistryUrl ($repositoryInfo, [string] $registryUrl) {
  if(-not [string]::IsNullOrEmpty($registryUrl)) {
    return $registryUrl
  } elseif ($repositoryInfo.Registry -eq "docker.io") {
    # Note: this code path is uncovered, as we cannot test that the real Registry is contacted by the script.
    return "https://registry-1.docker.io"
  } else {
    return "https://$($repositoryInfo.Registry)"
  }
}

function GetNotaryUrl ([string] $notaryUrl) {
  if(-not [string]::IsNullOrEmpty($notaryUrl)) {
    return $notaryUrl
  } elseif(-not [string]::IsNullOrEmpty($env:DOCKER_CONTENT_TRUST_SERVER)) {
    return $env:DOCKER_CONTENT_TRUST_SERVER
  } else {
    # Note: this code path is uncovered, as we cannot test that the real Notary is contacted by the script.
    return "https://notary.docker.io"
  }
}

function UpdateLocalDockerTrustData ($repositoryInfo, $notaryUrl, $notaryBasicAuthCredentials) {
  $notaryUrl = GetNotaryUrl $notaryUrl
  try {
    SetDockerContentTrustServerEnvironmentVariable $notaryUrl
    PrepareNotaryAuthentication $notaryBasicAuthCredentials

    docker trust inspect $repositoryInfo.FullName | Out-Null
  } finally {
    CleanupNotaryAuthentication
    CleanupDockerContentTrustServerEnvironmentVariable
  }
}

function CollectExistingMetadataFiles ([string] $repository) {
  Write-Verbose "Collecting existing metadata files..."

  $trustDir = GetTrustDir
  $tufDirectory = Join-Path $trustDir "tuf"
  if(-not [string]::IsNullOrEmpty($env:SignPathDockerSigningMetadataDirectory)) {
    $metadataDirectory = $env:SignPathDockerSigningMetadataDirectory
  } else {
    $metadataDirectory = Join-Path $tufDirectory $repository "metadata"
  }

  $metadataFiles = New-Object System.Collections.Generic.List[string]

  $rootJson = Join-Path $metadataDirectory "root.json"
  if(-not (Test-Path -Path $rootJson)) {
    throw "Required root.json file not found at '$rootJson'."
  }
  Write-Verbose "Collected root.json"
  $metadataFiles.Add($rootJson) | Out-Null

  $targetsJson = Join-Path $metadataDirectory "targets.json"
  if(-not (Test-Path -Path $targetsJson)) {
    throw "Required targets.json file not found at '$targetsJson'."
  }
  Write-Verbose "Collected targets.json"
  $metadataFiles.Add($targetsJson) | Out-Null

  $targetsDirectory = Join-Path $metadataDirectory "targets"

  if(Test-Path -Path $targetsDirectory) {
    $files = Get-ChildItem $targetsDirectory
    foreach ($file in $files) {
      $metadataFiles.Add($file.FullName) | Out-Null
      Write-Verbose "Collected $($file.Name)"
    }
  }

  return $metadataFiles
}

function CopyMetadataFilesToDirectory ($metadataFiles, $targetDirectory){
  $tempTargetsDir = Join-Path $targetDirectory "targets"

  foreach ($filePath in $metadataFiles) {
    if ((Get-Item $filePath) -is [System.IO.DirectoryInfo]) { continue }

    if ($filePath.Contains("targets\")) {
      if(-not (Test-Path $tempTargetsDir)) {
        New-Item -Path $tempTargetsDir -Type Directory | Out-Null
      }
      $tempTargetsFilePath = Join-Path $tempTargetsDir ([System.IO.Path]::GetFileName($filePath))
      Copy-Item $filePath $tempTargetsFilePath | Out-Null
    } else {
      Copy-Item $filePath $targetDirectory | Out-Null
    }
  }
}

function GenerateSigningMetadata ([string] $signingMetadataJson, $tags, $repositoryInfo, [string] $registryUrl, [string] $registryBasicAuthCredentials) {
  Write-Verbose "Generating JSON for signingmetadata.json..."

  $tagObjects = $tags | %{
    $manifest = GetManifest $registryUrl $repositoryInfo $_ $registryBasicAuthCredentials
    $hash = ParseDockerContentDigestHeader $manifest.Headers["Docker-Content-Digest"]
    $length = $manifest.Headers["Content-Length"]

    return "{ ""Name"": ""$_"", ""Hash"": ""$hash"", ""Length"": $length }"
  }
  $tagString = ($tagObjects -join ',' + [System.Environment]::NewLine + ' ')

  $expiresDate = (Get-Date).AddYears(3)
  $expiresDateString = Get-Date $expiresDate -format o

  $signingMetadataContent = @"
{
  "Tags": [
    $tagString
  ],
  "Expires": "$expiresDateString",
  "Repository": "$($repositoryInfo.FullName)",
  "SchemaVersion": "1.0"
}
"@


  Write-Verbose "Writing JSON to signingmetadata.json..."
  Write-Verbose $signingMetadataContent
  Set-Content $signingMetadataJson $signingMetadataContent
}

function GetManifest ([string] $registryUrl, $repositoryInfo, [string] $tag, [string] $registryAuth) {
  $authorization = ""

  Write-Verbose "Trying to obtain manifest (list.v2 format) without authentication..."
  $listContentType = "application/vnd.docker.distribution.manifest.list.v2+json"
  $listManifestInfo = GetManifestWithContentType $registryUrl $repositoryInfo $tag $listContentType $authorization
  if($listManifestInfo.StatusCode -eq 401) {
    Write-Verbose "Challenged received"
    $repositoryForScope = "$($repositoryInfo.NamespaceUrlPart)$($repositoryInfo.Name)"
    $authorization = DockerAuth $listManifestInfo $repositoryForScope $registryAuth
    Write-Verbose "Trying to obtain manifest (list.v2 format) with authentication..."
    $listManifestInfo = GetManifestWithContentType $registryUrl $repositoryInfo $tag $listContentType $authorization
  }

  if($listManifestInfo.Headers["Content-Type"] -eq $listContentType) {
    Write-Verbose "Succeeded."
    return $listManifestInfo
  }

  Write-Verbose "Failed."

  Write-Verbose "Trying to obtain manifest (v2 format) instead..."
  $contentTypeV2 = "application/vnd.docker.distribution.manifest.v2+json"
  $manifestInfo = GetManifestWithContentType  $registryUrl $repositoryInfo $tag $contentTypeV2 $authorization
  if($manifestInfo.Headers["Content-Type"] -eq $contentTypeV2) {
    Write-Verbose "Succeeded."
    return $manifestInfo
  }

  Write-Verbose "Failed."

  throw "The manifest format '$($manifestInfo.Headers["Content-Type"])' is not supported."
}

function GetManifestWithContentType ([string] $registryUrl, $repositoryInfo, $tag, [string] $contentType , [string] $authorization) {
  $headers = @{}
  $headers["Accept"] = $contentType

  $allowUnauthorized = $True
  if(-not [string]::IsNullOrEmpty($authorization)) {
    $headers["Authorization"] = "$authorization"
    $allowUnauthorized = $False
  }

  $manifestUrl = "$registryUrl/v2/$($repositoryInfo.NamespaceUrlPart)$($repositoryInfo.Name)/manifests/$($tag)"
  Write-Verbose "URL: $manifestUrl"
  $response = Invoke-WebRequest -Headers $headers $manifestUrl -SkipHttpErrorCheck
  EnsureSuccessStatusCode $manifestUrl $response $allowUnauthorized
  return $response
}

function DockerAuth ($challenge, $repositoryForScope, [string] $basicAuthCredentials) {
  Write-Verbose "Trying to authenticate... (repository for scope: $repositoryForScope)"

  if(!$challenge.Headers["WWW-Authenticate"]) {
    throw "WWW-Authenticate header in authorization challenge expected but it's missing.";
  }

  $wwwAuthenticateHeader = $challenge.Headers["WWW-Authenticate"][0]
  Write-Verbose "WWW-Authenticate header received: $wwwAuthenticateHeader"

  if($wwwAuthenticateHeader -like "Basic*") {
    return "Basic $basicAuthCredentials"
  }

  if($wwwAuthenticateHeader -like "Bearer*") {
    Write-Verbose "Parsing Bearer WWW-Authenticate header..."
    $realmRegexResult =   $wwwAuthenticateHeader | Select-String -Pattern "realm=""(?<realm>.*?)"""
    $serviceRegexResult = $wwwAuthenticateHeader | Select-String -Pattern "service=""(?<service>.*?)"""
    $realm = $realmRegexResult.Matches[0].Groups["realm"].Value
    $service = $serviceRegexResult.Matches[0].Groups["service"].Value
    $scope = "repository:$($repositoryForScope):push,pull" # do not parse from realm, not useful for self-hosted registries
    Write-Verbose "Realm: $realm"
    Write-Verbose "Service: $service"
    Write-Verbose "Scope: $scope"

    $authEndpointUrl = "$($realm)?scope=$scope&service=$service"
    $headers = @{}
    if (-not([string]::IsNullOrEmpty($basicAuthCredentials))) {
      $headers["Authorization"] = "Basic $basicAuthCredentials"
    }

    Write-Verbose "Authenticating against $authEndpointUrl"
    $authResponse = Invoke-RestMethod -Headers $headers $authEndpointUrl
    Write-Verbose "Authentication succeeded."

    return "Bearer $($authResponse.token)"
  }

  throw "WWW-Authenticate header '$wwwAuthenticateHeader' not supported."
}

function ParseDockerContentDigestHeader ([string] $dockerContentDigestHeader) {
  try {
    $hexString = $dockerContentDigestHeader -replace "sha256:", ""
    $bytes = [byte[]]::new($hexString.Length / 2)

    for($i = 0; $i -lt $hexString.Length; $i += 2) {
      $bytes[$i/2] = [convert]::ToByte($hexString.Substring($i, 2), 16)
    }

    return [Convert]::ToBase64String($bytes)
  }
  catch {
    throw "Could not parse Docker-Content-Digest header '$dockerContentDigestHeader'.";
  }
}

function PushFiles ([string] $notaryUrl, $repositoryInfo, $files, $notaryBasicAuthCredentials) {
  $initialResponse = PushFilesInternal $notaryUrl $repositoryInfo -Files $files
  if($initialResponse.StatusCode -eq 401) {
    Write-Verbose "Received challenge result, we need to authenticate"
    $authorization = DockerAuth $initialResponse $repositoryInfo.FullName $notaryBasicAuthCredentials
    PushFilesInternal $notaryUrl $repositoryInfo -Files $files -Authorization $authorization | Out-Null
  }
}

function PushFilesInternal ([string] $notaryUrl, $repositoryInfo, $files, $authorization) {
  $normalizedNotaryUrl = $notaryUrl.Trim("/")
  $pushUrl = "$normalizedNotaryUrl/v2/$($repositoryInfo.FullName)/_trust/tuf/"
  $headers = @{}
  $allowUnauthorized = $True
  if(-not [string]::IsNullOrEmpty($authorization)) {
    $headers["Authorization"] = "$authorization"
    $allowUnauthorized = $False
    Write-Verbose "Pushing metadata files to Notary service (with authorization)..."
  } else {
    Write-Verbose "Pushing metadata files to Notary service (without authorization)..."
  }

  $multipartContent = BuildMultipartContent $files
  try {
    Write-Verbose "URL: $pushUrl"
    $response = Invoke-WebRequest -Method Post -Headers $headers -ContentType "multipart/form-data" -Body $multipartContent.Content $pushUrl -SkipHttpErrorCheck
    EnsureSuccessStatusCode $pushUrl $response $allowUnauthorized
    return $response
  }
  finally {
    $multipartContent.Content.Dispose()
  }
}

function BuildMultipartContent ($files) {
  Write-Verbose "Building multipart content..."
  $multipartContent = [System.Net.Http.MultipartFormDataContent]::new()

  foreach($file in $files) {
    Write-Verbose "Building multipart content for file '$($file.Name)'..."
    $fileStream = [System.IO.FileStream]::new($file.Path, [System.IO.FileMode]::Open)

    $fileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data")
    $fileHeader.Name = "files"
    $fileHeader.FileName = $file.Name

    $fileContent = [System.Net.Http.StreamContent]::new($fileStream)
    $fileContent.Headers.ContentDisposition = $fileHeader
    $fileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("text/octet-stream")

    $multipartContent.Add($fileContent)
  }

  return @{ Content = $multipartContent }
}

function EnsureSuccessStatusCode([string] $requestUrl, $response, [boolean] $allowUnauthorized) {
  $statusCode = $response.StatusCode
  Write-Verbose "Status code: $statusCode"
  if($statusCode -lt 200 -or $statusCode -ge 300) {
    if($allowUnauthorized -and $statusCode -eq 401) {
      return;
    }
    $content = $response.Content
    throw "Response status code $statusCode indicates failure. Request '$requestUrl'. Response: '$content'.";
  }
}

function CheckIfRepositoryExists($notaryUrl, $trustDir, $repositoryInfo) {
  # it is not possible to call the notary cli to check if a repo does exist, because you can't known if $LASTEXITCODE == 1 means its not there or
  # the http request within the cli failed. So use Invoke-WebRequest.

  $response = TryGetNotaryRepositoryRootJson $notaryUrl $repositoryInfo $env:NOTARY_AUTH

  $statusCode = $response.StatusCode

  if ($statusCode -eq 200) {
    return $True
  }

  if ($statusCode -eq 404) {
    return $False
  }

  throw "Could not determin if repository '$($repositoryInfo.FullName)' already exists. Is there a connection issue to $notaryUrl ? StatusCode: $statusCode"
}

function TryGetNotaryRepositoryRootJson ([string] $notaryUrl, $repositoryInfo, [string] $notaryAuth) {
  $headers = @{}
  $headers["Authorization"] = "Basic $notaryAuth"

  $normalizedNotaryUrl = $notaryUrl.Trim("/")
  $requestUrl = "$normalizedNotaryUrl/v2/$($repositoryInfo.FullName)/_trust/tuf/root.json"

  Write-Verbose "challenge URL: $requestUrl"
  $response = Invoke-WebRequest -Headers $headers $requestUrl -SkipHttpErrorCheck
  Write-Verbose "Challenge response: $response"
  if($response.StatusCode -eq 401) {

    $repositoryForScope = $repositoryInfo.FullName
    $authorization = DockerAuth $response $repositoryForScope $notaryAuth

    $headers["Authorization"] = "$authorization"
    Write-Verbose "Check repo exists URL: $requestUrl"
    $response = Invoke-WebRequest -Headers $headers $requestUrl -SkipHttpErrorCheck
  }
  Write-Verbose $response
  return $response
}

function dockernotary (
  [Parameter(Mandatory)]
  [string] $notaryUrl,

  [Parameter(Mandatory)]
  [string] $trustDir,

  [Parameter(Mandatory)]
  [Hashtable] $errorMessages,

  [Parameter()]
  [Switch] $SuppressOutput,

  [Parameter(ValueFromRemainingArguments = $true)]
  [string[]] $passthrough
  )
{
  if($SuppressOutput.IsPresent) {
    notary @passthrough --server $notaryUrl --trustDir $trustDir | Out-Null
  } else {
    notary @passthrough --server $notaryUrl --trustDir $trustDir
  }

  #This notary cli call can't be wrapped into another caller, as the notary then has issues with its user input

  if ($LASTEXITCODE -ne 0) {
    if($errorMessages.ContainsKey($LASTEXITCODE)) {
      throw $errorMessages[$LASTEXITCODE]
    } else {
      throw "notary command failed with error code $LASTEXITCODE. Aborting."
    }
  }
}

function PrepareRegistryCredentials ([string] $registryUsername, [SecureString] $registryPassword, [string] $notaryUsername, [SecureString] $notaryPassword) {
  Write-Verbose "Preparing Registry credentials..."
  if(-not [string]::IsNullOrEmpty($registryUsername) -and -not [string]::IsNullOrEmpty((ConvertTo-PlainText $registryPassword))) {
    Write-Verbose "Using RegistryUsername/RegistryPassword combination."
    return BuildBasicAuthCredentialsFromUsernameAndPassword $registryUsername $registryPassword
  } elseif (-not [string]::IsNullOrEmpty($env:REGISTRY_AUTH)) {
    Write-Verbose "Using REGISTRY_AUTH environment variable."
    return $env:REGISTRY_AUTH
  } else {
    Write-Verbose "Neither RegistryUsername/RegistryPassword nor REGISTRY_AUTH set, going for Notary credentials instead..."
    return PrepareNotaryCredentials $notaryUsername $notaryPassword
  }
}

function PrepareNotaryCredentials ([string] $notaryUsername, [SecureString] $notaryPassword) {
  Write-Verbose "Preparing Notary credentials..."
  if([string]::IsNullOrEmpty($notaryUsername) -or [string]::IsNullOrEmpty((ConvertTo-PlainText $notaryPassword))) {
    Write-Verbose "Using NOTARY_AUTH environment variable."

    if([string]::IsNullOrEmpty($env:NOTARY_AUTH)) {
      Write-Verbose "No credentials found => executing unauthenticated."
    }

    return $env:NOTARY_AUTH
  }

  Write-Verbose "Using NotaryUsername/NotaryPassword combination."
  return BuildBasicAuthCredentialsFromUsernameAndPassword $notaryUsername $notaryPassword
}

function BuildBasicAuthCredentialsFromUsernameAndPassword ([string] $username, [SecureString] $password) {
  $plainTextPassword = ConvertTo-PlainText $password
  $basicAuthUnencoded = "${username}:${plainTextPassword}"
  $bytes = [System.Text.Encoding]::UTF8.GetBytes($basicAuthUnencoded)
  return [System.Convert]::ToBase64String($bytes)
}

function ConvertTo-PlainText([SecureString] $secureString) {
  return [System.Net.NetworkCredential]::new("", $secureString).Password
}

function SetDockerContentTrustServerEnvironmentVariable ($notaryUrl) {
  $originalDockerContentTrustServerValue = $env:DOCKER_CONTENT_TRUST_SERVER
  [Environment]::SetEnvironmentVariable("DOCKER_CONTENT_TRUST_SERVER_BAK", $originalDockerContentTrustServerValue, "Process")

  [Environment]::SetEnvironmentVariable("DOCKER_CONTENT_TRUST_SERVER", $notaryUrl, "Process")
}

function CleanupDockerContentTrustServerEnvironmentVariable {
  $originalDockerContentTrustServerValue = $env:DOCKER_CONTENT_TRUST_SERVER_BAK
  [Environment]::SetEnvironmentVariable("DOCKER_CONTENT_TRUST_SERVER", $originalDockerContentTrustServerValue, "Process")

  Remove-Item -ErrorAction SilentlyContinue Env:\DOCKER_CONTENT_TRUST_SERVER_BAK
}

function PrepareNotaryAuthentication ($notaryBasicAuthCredentials) {
  $originalNotaryAuthValue = $env:NOTARY_AUTH
  [Environment]::SetEnvironmentVariable("NOTARY_AUTH_BAK", $originalNotaryAuthValue, "Process")

  [Environment]::SetEnvironmentVariable("NOTARY_AUTH", $notaryBasicAuthCredentials, "Process")
}

function CleanupNotaryAuthentication {
  $originalNotaryAuthValue = $env:NOTARY_AUTH_BAK
  [Environment]::SetEnvironmentVariable("NOTARY_AUTH", $originalNotaryAuthValue, "Process")

  Remove-Item -ErrorAction SilentlyContinue Env:\NOTARY_AUTH_BAK
}

function GetTrustDir {
  if([string]::IsNullOrEmpty($env:DOCKER_CONFIG)) {
    return Join-Path "$HOME" ".docker" "trust"
  } else {
    return Join-Path $env:DOCKER_CONFIG "trust"
  }
}

function ExtractRootCertificate ($trustDir, $repositoryInfo, $forceOverwriteRootCertificate) {
  $rootJsonPath = Join-Path $trustDir "tuf" $repositoryInfo.FullName "metadata" "root.json"

  if(-not (Test-Path $rootJsonPath -PathType Leaf)) {
    throw "Could not find root.json to extract root certificate at $rootJsonPath"
  }

  $rootJsonObject = Get-Content $rootJsonPath | ConvertFrom-Json

  $keyCount = $rootJsonObject.signed.roles.root.keyids.Length
  if ($keyCount -ne 1) {
    throw "Assertion: There is more than one root key. We didn't expect that."
  }

  $rootKeyId = $rootJsonObject.signed.roles.root.keyids[0]
  $rootCertEncoded = $rootJsonObject.signed.keys.$rootKeyId.keyval.public

  $decodedBytes = [System.Convert]::FromBase64String($rootCertEncoded);
  $rootCertPemString = [System.Text.Encoding]::ASCII.GetString($decodedBytes);

  $outputFilePath = GetRootCertificateFilePath $repositoryInfo

  [System.IO.File]::WriteAllText($outputFilePath, $rootCertPemString)
  Write-Host "Created file $outputFilePath"
}

function GetRootCertificateFilePath ($repositoryInfo) {
  return NormalizePath "$($repositoryInfo.Registry)_$($repositoryInfo.Namespace)_$($repositoryInfo.Name).RootCertificate.pem"
}

function PrepareDelegationCertificate ($delegationCertificatePath) {
  $normalizedPath = NormalizePath $delegationCertificatePath

  if(-not (Test-Path $normalizedPath -PathType Leaf)) {
    throw "Could not find a delegation certificate at $normalizedPath"
  }

  if (-not ((Get-Content -Raw $normalizedPath).Contains("--BEGIN CERTIFICATE"))) {
    $normalizedPath = ConvertToNewPemFile $normalizedPath
  }

  return $normalizedPath
}

function ConvertToNewPemFile ($path) {
  try {
    $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::New($path)

    $pem = [System.Convert]::ToBase64String($cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert), [System.Base64FormattingOptions]::InsertLineBreaks)

    $sb = [System.Text.StringBuilder]::New()

    $sb.AppendLine("-----BEGIN CERTIFICATE-----") | Out-Null
    $sb.AppendLine($pem) | Out-Null
    $sb.AppendLine("-----END CERTIFICATE-----") | Out-Null

    $tempFileName = "$([Guid]::NewGuid()).pem"
    $tempDir = [System.IO.Path]::GetTempPath()
    $resultingFilePath = Join-Path $tempDir $tempFileName

    [System.IO.File]::WriteAllText($resultingFilePath, $sb.ToString())

    return $resultingFilePath
  } finally {
    $cert.Dispose()
  }
}

Export-ModuleMember Initialize-DockerSigning
Export-ModuleMember Add-DelegationCertificate
Export-ModuleMember Get-RootCertificate
Export-ModuleMember Invoke-DockerSigning
Export-ModuleMember New-DockerSigningData
Export-ModuleMember Push-SignedDockerSigningData

# SIG # Begin signature block
# MIIj3gYJKoZIhvcNAQcCoIIjzzCCI8sCAQExDzANBglghkgBZQMEAgEFAD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