forked from sigstore/sigstore-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_cli.py
More file actions
1305 lines (1134 loc) · 45.2 KB
/
_cli.py
File metadata and controls
1305 lines (1134 loc) · 45.2 KB
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
# Copyright 2022 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.
from __future__ import annotations
import argparse
import base64
import json
import logging
import os
import sys
from concurrent import futures
from dataclasses import dataclass
from pathlib import Path
from typing import Any, NoReturn, Union
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.x509 import load_pem_x509_certificate
from pydantic import ValidationError
from rich.console import Console
from rich.logging import RichHandler
from sigstore_models.bundle.v1 import Bundle as RawBundle
from sigstore_models.common.v1 import HashAlgorithm
from typing_extensions import TypeAlias
from sigstore import __version__, dsse
from sigstore._internal.fulcio.client import ExpiredCertificate
from sigstore._internal.rekor import _hashedrekord_from_parts
from sigstore._internal.rekor.client import RekorClient
from sigstore._utils import sha256_digest
from sigstore.dsse import StatementBuilder, Subject
from sigstore.dsse._predicate import (
PredicateType,
SLSAPredicateV0_2,
SLSAPredicateV1_0,
)
from sigstore.errors import CertValidationError, Error, VerificationError
from sigstore.hashes import Hashed
from sigstore.models import Bundle, ClientTrustConfig, InvalidBundle
from sigstore.oidc import (
ExpiredIdentity,
IdentityToken,
Issuer,
detect_credential,
)
from sigstore.sign import Signer, SigningContext
from sigstore.verify import (
Verifier,
policy,
)
_console = Console(file=sys.stderr)
logging.basicConfig(
format="%(message)s", datefmt="[%X]", handlers=[RichHandler(console=_console)]
)
_logger = logging.getLogger(__name__)
# NOTE: We configure the top package logger, rather than the root logger,
# to avoid overly verbose logging in third-party code by default.
_package_logger = logging.getLogger("sigstore")
_package_logger.setLevel(os.environ.get("SIGSTORE_LOGLEVEL", "INFO").upper())
@dataclass(frozen=True)
class SigningOutputs:
signature: Path | None = None
certificate: Path | None = None
bundle: Path | None = None
@dataclass(frozen=True)
class VerificationUnbundledMaterials:
certificate: Path
signature: Path
@dataclass(frozen=True)
class VerificationBundledMaterials:
bundle: Path
VerificationMaterials: TypeAlias = Union[
VerificationUnbundledMaterials, VerificationBundledMaterials
]
# Map of inputs -> outputs for signing operations
OutputMap: TypeAlias = dict[Path, SigningOutputs]
def _fatal(message: str) -> NoReturn:
"""
Logs a fatal condition and exits.
"""
_logger.fatal(message)
sys.exit(1)
def _invalid_arguments(args: argparse.Namespace, message: str) -> NoReturn:
"""
An `argparse` helper that fixes up the type hints on our use of
`ArgumentParser.error`.
"""
args._parser.error(message)
raise ValueError("unreachable")
def _boolify_env(envvar: str) -> bool:
"""
An `argparse` helper for turning an environment variable into a boolean.
The semantics here closely mirror `distutils.util.strtobool`.
See: <https://docs.python.org/3/distutils/apiref.html#distutils.util.strtobool>
"""
val = os.getenv(envvar)
if val is None:
return False
val = val.lower()
if val in {"y", "yes", "true", "t", "on", "1"}:
return True
elif val in {"n", "no", "false", "f", "off", "0"}:
return False
else:
raise ValueError(f"can't coerce '{val}' to a boolean")
def _add_shared_verify_input_options(group: argparse._ArgumentGroup) -> None:
"""
Common input options, shared between all `sigstore verify` subcommands.
"""
group.add_argument(
"--certificate",
"--cert",
metavar="FILE",
type=Path,
default=os.getenv("SIGSTORE_CERTIFICATE"),
help="The PEM-encoded certificate to verify against; not used with multiple inputs",
)
group.add_argument(
"--signature",
metavar="FILE",
type=Path,
default=os.getenv("SIGSTORE_SIGNATURE"),
help="The signature to verify against; not used with multiple inputs",
)
group.add_argument(
"--bundle",
metavar="FILE",
type=Path,
default=os.getenv("SIGSTORE_BUNDLE"),
help=("The Sigstore bundle to verify with; not used with multiple inputs"),
)
def file_or_digest(arg: str) -> Hashed | Path:
path = Path(arg)
if path.is_file():
return path
elif arg.startswith("sha256"):
digest = bytes.fromhex(arg[len("sha256:") :])
if len(digest) != 32:
raise ValueError
return Hashed(
digest=digest,
algorithm=HashAlgorithm.SHA2_256,
)
else:
raise ValueError
group.add_argument(
"files_or_digest",
metavar="FILE_OR_DIGEST",
type=file_or_digest,
nargs="+",
help="The file path or the digest to verify. The digest should start with the 'sha256:' prefix.",
)
def _add_shared_verification_options(group: argparse._ArgumentGroup) -> None:
group.add_argument(
"--offline",
action="store_true",
default=_boolify_env("SIGSTORE_OFFLINE"),
help="Perform offline verification; requires a Sigstore bundle",
)
def _add_shared_oidc_options(
group: argparse._ArgumentGroup | argparse.ArgumentParser,
) -> None:
"""
Common OIDC options, shared between `sigstore sign` and `sigstore get-identity-token`.
"""
group.add_argument(
"--oidc-client-id",
metavar="ID",
type=str,
default=os.getenv("SIGSTORE_OIDC_CLIENT_ID", "sigstore"),
help="The custom OpenID Connect client ID to use during OAuth2",
)
group.add_argument(
"--oidc-client-secret",
metavar="SECRET",
type=str,
default=os.getenv("SIGSTORE_OIDC_CLIENT_SECRET"),
help="The custom OpenID Connect client secret to use during OAuth2",
)
group.add_argument(
"--oidc-disable-ambient-providers",
action="store_true",
default=_boolify_env("SIGSTORE_OIDC_DISABLE_AMBIENT_PROVIDERS"),
help="Disable ambient OpenID Connect credential detection (e.g. on GitHub Actions)",
)
group.add_argument(
"--oidc-issuer",
metavar="URL",
type=str,
default=os.getenv("SIGSTORE_OIDC_ISSUER", None),
help="The OpenID Connect issuer to use",
)
group.add_argument(
"--oauth-force-oob",
action="store_true",
default=_boolify_env("SIGSTORE_OAUTH_FORCE_OOB"),
help="Force an out-of-band OAuth flow and do not automatically start the default web browser",
)
def _parser() -> argparse.ArgumentParser:
# Arguments in parent_parser can be used for both commands and subcommands
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument(
"-v",
"--verbose",
action="count",
default=0,
help="run with additional debug logging; supply multiple times to increase verbosity",
)
parser = argparse.ArgumentParser(
prog="sigstore",
description="a tool for signing and verifying Python package distributions",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[parent_parser],
)
parser.add_argument(
"-V", "--version", action="version", version=f"sigstore {__version__}"
)
global_instance_options = parser.add_mutually_exclusive_group()
global_instance_options.add_argument(
"--staging",
action="store_true",
default=_boolify_env("SIGSTORE_STAGING"),
help="Use sigstore's staging instances, instead of the default production instances",
)
global_instance_options.add_argument(
"--trust-config",
metavar="FILE",
type=Path,
help="The client trust configuration to use",
)
subcommands = parser.add_subparsers(
required=True,
dest="subcommand",
metavar="COMMAND",
help="the operation to perform",
)
# `sigstore attest`
attest = subcommands.add_parser(
"attest",
help="sign one or more inputs using DSSE",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[parent_parser],
)
attest.add_argument(
"--rekor-version",
type=int,
metavar="VERSION",
default=argparse.SUPPRESS,
help="Force the rekor transparency log version. Valid values are [1, 2]. By default the highest available version is used",
)
attest.add_argument(
"files",
metavar="FILE",
type=Path,
nargs="+",
help="The file to sign",
)
dsse_options = attest.add_argument_group("DSSE options")
dsse_options.add_argument(
"--predicate",
metavar="FILE",
type=Path,
required=True,
help="Path to the predicate file",
)
dsse_options.add_argument(
"--predicate-type",
metavar="TYPE",
choices=list(PredicateType),
type=PredicateType,
required=True,
help=f"Specify a predicate type ({', '.join(list(PredicateType))})",
)
oidc_options = attest.add_argument_group("OpenID Connect options")
oidc_options.add_argument(
"--identity-token",
metavar="TOKEN",
type=str,
default=os.getenv("SIGSTORE_IDENTITY_TOKEN"),
help="the OIDC identity token to use",
)
_add_shared_oidc_options(oidc_options)
output_options = attest.add_argument_group("Output options")
output_options.add_argument(
"--bundle",
metavar="FILE",
type=Path,
default=os.getenv("SIGSTORE_BUNDLE"),
help=(
"Write a single Sigstore bundle to the given file; does not work with multiple input "
"files"
),
)
output_options.add_argument(
"--overwrite",
action="store_true",
default=_boolify_env("SIGSTORE_OVERWRITE"),
help="Overwrite preexisting bundle outputs, if present",
)
# `sigstore sign`
sign = subcommands.add_parser(
"sign",
help="sign one or more inputs",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[parent_parser],
)
sign.add_argument(
"--rekor-version",
type=int,
metavar="VERSION",
default=argparse.SUPPRESS,
help="Force the rekor transparency log version. Valid values are [1, 2]. By default the highest available version is used",
)
oidc_options = sign.add_argument_group("OpenID Connect options")
oidc_options.add_argument(
"--identity-token",
metavar="TOKEN",
type=str,
default=os.getenv("SIGSTORE_IDENTITY_TOKEN"),
help="the OIDC identity token to use",
)
_add_shared_oidc_options(oidc_options)
output_options = sign.add_argument_group("Output options")
output_options.add_argument(
"--no-default-files",
action="store_true",
default=_boolify_env("SIGSTORE_NO_DEFAULT_FILES"),
help="Don't emit the default output files ({input}.sigstore.json)",
)
output_options.add_argument(
"--signature",
"--output-signature",
metavar="FILE",
type=Path,
default=os.getenv("SIGSTORE_OUTPUT_SIGNATURE"),
help=(
"Write a single signature to the given file; does not work with multiple input files"
),
)
output_options.add_argument(
"--certificate",
"--output-certificate",
metavar="FILE",
type=Path,
default=os.getenv("SIGSTORE_OUTPUT_CERTIFICATE"),
help=(
"Write a single certificate to the given file; does not work with multiple input files"
),
)
output_options.add_argument(
"--bundle",
metavar="FILE",
type=Path,
default=os.getenv("SIGSTORE_BUNDLE"),
help=(
"Write a single Sigstore bundle to the given file; does not work with multiple input "
"files"
),
)
output_options.add_argument(
"--output-directory",
metavar="DIR",
type=Path,
default=os.getenv("SIGSTORE_OUTPUT_DIRECTORY"),
help=(
"Write default outputs to the given directory (conflicts with --signature, --certificate"
", --bundle)"
),
)
output_options.add_argument(
"--overwrite",
action="store_true",
default=_boolify_env("SIGSTORE_OVERWRITE"),
help="Overwrite preexisting signature and certificate outputs, if present",
)
sign.add_argument(
"files",
metavar="FILE",
type=Path,
nargs="+",
help="The file to sign",
)
# `sigstore verify`
verify = subcommands.add_parser(
"verify",
help="verify one or more inputs",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[parent_parser],
)
verify_subcommand = verify.add_subparsers(
required=True,
dest="verify_subcommand",
metavar="COMMAND",
help="the kind of verification to perform",
)
# `sigstore verify identity`
verify_identity = verify_subcommand.add_parser(
"identity",
help="verify against a known identity and identity provider",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[parent_parser],
)
input_options = verify_identity.add_argument_group("Verification inputs")
_add_shared_verify_input_options(input_options)
verification_options = verify_identity.add_argument_group("Verification options")
_add_shared_verification_options(verification_options)
verification_options.add_argument(
"--cert-identity",
metavar="IDENTITY",
type=str,
default=os.getenv("SIGSTORE_CERT_IDENTITY"),
help="The identity to check for in the certificate's Subject Alternative Name",
required=True,
)
verification_options.add_argument(
"--cert-oidc-issuer",
metavar="URL",
type=str,
default=os.getenv("SIGSTORE_CERT_OIDC_ISSUER"),
help="The OIDC issuer URL to check for in the certificate's OIDC issuer extension",
required=True,
)
# `sigstore verify github`
verify_github = verify_subcommand.add_parser(
"github",
help="verify against GitHub Actions-specific claims",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[parent_parser],
)
input_options = verify_github.add_argument_group("Verification inputs")
_add_shared_verify_input_options(input_options)
verification_options = verify_github.add_argument_group("Verification options")
_add_shared_verification_options(verification_options)
verification_options.add_argument(
"--cert-identity",
metavar="IDENTITY",
type=str,
default=os.getenv("SIGSTORE_CERT_IDENTITY"),
help="The identity to check for in the certificate's Subject Alternative Name",
)
verification_options.add_argument(
"--trigger",
dest="workflow_trigger",
metavar="EVENT",
type=str,
default=os.getenv("SIGSTORE_VERIFY_GITHUB_WORKFLOW_TRIGGER"),
help="The GitHub Actions event name that triggered the workflow",
)
verification_options.add_argument(
"--sha",
dest="workflow_sha",
metavar="SHA",
type=str,
default=os.getenv("SIGSTORE_VERIFY_GITHUB_WORKFLOW_SHA"),
help="The `git` commit SHA that the workflow run was invoked with",
)
verification_options.add_argument(
"--name",
dest="workflow_name",
metavar="NAME",
type=str,
default=os.getenv("SIGSTORE_VERIFY_GITHUB_WORKFLOW_NAME"),
help="The name of the workflow that was triggered",
)
verification_options.add_argument(
"--repository",
dest="workflow_repository",
metavar="REPO",
type=str,
default=os.getenv("SIGSTORE_VERIFY_GITHUB_WORKFLOW_REPOSITORY"),
help="The repository slug that the workflow was triggered under",
)
verification_options.add_argument(
"--ref",
dest="workflow_ref",
metavar="REF",
type=str,
default=os.getenv("SIGSTORE_VERIFY_GITHUB_WORKFLOW_REF"),
help="The `git` ref that the workflow was invoked with",
)
# `sigstore get-identity-token`
get_identity_token = subcommands.add_parser(
"get-identity-token",
help="retrieve and return a Sigstore-compatible OpenID Connect token",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[parent_parser],
)
_add_shared_oidc_options(get_identity_token)
# `sigstore plumbing`
plumbing = subcommands.add_parser(
"plumbing",
help="developer-only plumbing operations",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[parent_parser],
)
plumbing_subcommands = plumbing.add_subparsers(
required=True,
dest="plumbing_subcommand",
metavar="COMMAND",
help="the operation to perform",
)
# `sigstore plumbing fix-bundle`
fix_bundle = plumbing_subcommands.add_parser(
"fix-bundle",
help="fix (and optionally upgrade) older bundle formats",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[parent_parser],
)
fix_bundle.add_argument(
"--bundle",
metavar="FILE",
type=Path,
required=True,
help=("The bundle to fix and/or upgrade"),
)
fix_bundle.add_argument(
"--upgrade-version",
action="store_true",
help="Upgrade the bundle to the latest bundle spec version",
)
fix_bundle.add_argument(
"--in-place",
action="store_true",
help="Overwrite the input bundle with its fix instead of emitting to stdout",
)
# `sigstore plumbing update-trust-root`
plumbing_subcommands.add_parser(
"update-trust-root",
help="update the local trust root to the latest version via TUF",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[parent_parser],
)
return parser
def main(args: list[str] | None = None) -> None:
if not args:
args = sys.argv[1:]
parser = _parser()
args = parser.parse_args(args)
# Configure logging upfront, so that we don't miss anything.
if args.verbose >= 1:
_package_logger.setLevel("DEBUG")
if args.verbose >= 2:
logging.getLogger().setLevel("DEBUG")
_logger.debug(f"parsed arguments {args}")
# Stuff the parser back into our namespace, so that we can use it for
# error handling later.
args._parser = parser
try:
if args.subcommand == "sign":
_sign(args)
elif args.subcommand == "attest":
_attest(args)
elif args.subcommand == "verify":
if args.verify_subcommand == "identity":
_verify_identity(args)
elif args.verify_subcommand == "github":
_verify_github(args)
elif args.subcommand == "get-identity-token":
_get_identity_token(args)
elif args.subcommand == "plumbing":
if args.plumbing_subcommand == "fix-bundle":
_fix_bundle(args)
elif args.plumbing_subcommand == "update-trust-root":
_update_trust_root(args)
else:
_invalid_arguments(args, f"Unknown subcommand: {args.subcommand}")
except Error as e:
e.log_and_exit(_logger, args.verbose >= 1)
def _get_identity_token(args: argparse.Namespace) -> None:
"""
Output the OIDC authentication token
"""
identity = _get_identity(args, _get_trust_config(args))
if identity:
print(identity)
else:
_invalid_arguments(args, "No identity token supplied or detected!")
def _sign_file_threaded(
signer: Signer,
predicate_type: str | None,
predicate: dict[str, Any] | None,
file: Path,
outputs: SigningOutputs,
) -> None:
"""sign method to be called from signing thread"""
_logger.debug(f"signing for {file.name}")
with file.open(mode="rb") as io:
# The input can be indefinitely large, so we perform a streaming
# digest and sign the prehash rather than buffering it fully.
digest = sha256_digest(io)
try:
if predicate is None:
result = signer.sign_artifact(input_=digest)
else:
subject = Subject(name=file.name, digest={"sha256": digest.digest.hex()})
statement_builder = StatementBuilder(
subjects=[subject],
predicate_type=predicate_type,
predicate=predicate,
)
result = signer.sign_dsse(statement_builder.build())
except ExpiredIdentity as exp_identity:
_logger.error("Signature failed: identity token has expired")
raise exp_identity
except ExpiredCertificate as exp_certificate:
_logger.error("Signature failed: Fulcio signing certificate has expired")
raise exp_certificate
_logger.info(
f"Transparency log entry created at index: {result.log_entry._inner.log_index}"
)
if outputs.signature is not None:
signature = base64.b64encode(result.signature).decode()
with outputs.signature.open(mode="w") as io:
print(signature, file=io)
if outputs.certificate is not None:
cert_pem = signer._signing_cert().public_bytes(Encoding.PEM).decode()
with outputs.certificate.open(mode="w") as io:
print(cert_pem, file=io)
if outputs.bundle is not None:
with outputs.bundle.open(mode="w") as io:
print(result.to_json(), file=io)
def _sign_common(
args: argparse.Namespace, output_map: OutputMap, predicate: dict[str, Any] | None
) -> None:
"""
Signing logic for both `sigstore sign` and `sigstore attest`
Both `sign` and `attest` share the same signing logic, the only change is
whether they sign over a DSSE envelope or a hashedrekord.
This function differentiates between the two using the `predicate` argument. If
present, it will generate an in-toto statement and wrap it in a DSSE envelope. If
not, it will use a hashedrekord.
"""
# Select the signing context to use.
trust_config = _get_trust_config(args)
signing_ctx = SigningContext.from_trust_config(trust_config)
# The order of precedence for identities is as follows:
#
# 1) Explicitly supplied identity token
# 2) Ambient credential detected in the environment, unless disabled
# 3) Interactive OAuth flow
identity: IdentityToken | None
if args.identity_token:
identity = IdentityToken(args.identity_token, args.oidc_client_id)
else:
identity = _get_identity(args, trust_config)
if not identity:
_invalid_arguments(args, "No identity token supplied or detected!")
# Not all commands provide --predicate-type
predicate_type = getattr(args, "predicate_type", None)
with signing_ctx.signer(identity) as signer:
print("Using ephemeral certificate:")
cert_pem = signer._signing_cert().public_bytes(Encoding.PEM).decode()
print(cert_pem)
# sign in threads: this is relevant for especially Rekor v2 as otherwise we wait
# for log inclusion for each signature separately
with futures.ThreadPoolExecutor() as executor:
jobs = [
executor.submit(
_sign_file_threaded,
signer,
predicate_type,
predicate,
file,
outputs,
)
for file, outputs in output_map.items()
]
for job in futures.as_completed(jobs):
job.result()
for file, outputs in output_map.items():
if outputs.signature is not None:
print(f"Signature written to {outputs.signature}")
if outputs.certificate is not None:
print(f"Certificate written to {outputs.certificate}")
if outputs.bundle is not None:
print(f"Sigstore bundle written to {outputs.bundle}")
def _attest(args: argparse.Namespace) -> None:
predicate_path = args.predicate
if not predicate_path.is_file():
_invalid_arguments(args, f"Predicate must be a file: {predicate_path}")
try:
with open(predicate_path, "r") as f:
predicate = json.load(f)
# We do a basic sanity check using our Pydantic models to see if the
# contents of the predicate file match the specified predicate type.
# Since most of the predicate fields are optional, this only checks that
# the fields that are present and correctly spelled have the expected
# type.
if args.predicate_type == PredicateType.SLSA_v0_2:
SLSAPredicateV0_2.model_validate(predicate)
elif args.predicate_type == PredicateType.SLSA_v1_0:
SLSAPredicateV1_0.model_validate(predicate)
else:
_invalid_arguments(
args,
f'Unsupported predicate type "{args.predicate_type}". Predicate type must be one of: {list(PredicateType)}',
)
except (ValidationError, json.JSONDecodeError) as e:
_invalid_arguments(
args, f'Unable to parse predicate of type "{args.predicate_type}": {e}'
)
# Build up the map of inputs -> outputs ahead of any signing operations,
# so that we can fail early if overwriting without `--overwrite`.
output_map: OutputMap = {}
for file in args.files:
if not file.is_file():
_invalid_arguments(args, f"Input must be a file: {file}")
bundle = args.bundle
output_dir = file.parent
if not bundle:
bundle = output_dir / f"{file.name}.sigstore.json"
if bundle and bundle.exists() and not args.overwrite:
_invalid_arguments(
args,
f"Refusing to overwrite outputs without --overwrite: {bundle}",
)
output_map[file] = SigningOutputs(bundle=bundle)
# We sign the contents of the predicate file, rather than signing the Pydantic
# model's JSON dump. This is because doing a JSON -> Model -> JSON roundtrip might
# change the original predicate if it doesn't match exactly our Pydantic model
# (e.g.: if it has extra fields).
_sign_common(args, output_map=output_map, predicate=predicate)
def _sign(args: argparse.Namespace) -> None:
has_sig = bool(args.signature)
has_crt = bool(args.certificate)
has_bundle = bool(args.bundle)
# `--no-default-files` has no effect on `--bundle`, but we forbid it because
# it indicates user confusion.
if args.no_default_files and has_bundle:
_invalid_arguments(
args, "--no-default-files may not be combined with --bundle."
)
# Fail if `--signature` or `--certificate` is specified *and* we have more
# than one input.
if (has_sig or has_crt or has_bundle) and len(args.files) > 1:
_invalid_arguments(
args,
"Error: --signature, --certificate, and --bundle can't be used with "
"explicit outputs for multiple inputs.",
)
if args.output_directory and (has_sig or has_crt or has_bundle):
_invalid_arguments(
args,
"Error: --signature, --certificate, and --bundle can't be used with "
"an explicit output directory.",
)
# Fail if either `--signature` or `--certificate` is specified, but not both.
if has_sig ^ has_crt:
_invalid_arguments(
args, "Error: --signature and --certificate must be used together."
)
# Build up the map of inputs -> outputs ahead of any signing operations,
# so that we can fail early if overwriting without `--overwrite`.
output_map: OutputMap = {}
for file in args.files:
if not file.is_file():
_invalid_arguments(args, f"Input must be a file: {file}")
sig, cert, bundle = (
args.signature,
args.certificate,
args.bundle,
)
output_dir = args.output_directory or file.parent
if output_dir.exists() and not output_dir.is_dir():
_invalid_arguments(
args, f"Output directory exists and is not a directory: {output_dir}"
)
output_dir.mkdir(parents=True, exist_ok=True)
if not bundle and not args.no_default_files:
bundle = output_dir / f"{file.name}.sigstore.json"
if not args.overwrite:
extants = []
if sig and sig.exists():
extants.append(str(sig))
if cert and cert.exists():
extants.append(str(cert))
if bundle and bundle.exists():
extants.append(str(bundle))
if extants:
_invalid_arguments(
args,
"Refusing to overwrite outputs without --overwrite: "
f"{', '.join(extants)}",
)
output_map[file] = SigningOutputs(
signature=sig, certificate=cert, bundle=bundle
)
_sign_common(args, output_map=output_map, predicate=None)
def _collect_verification_state(
args: argparse.Namespace,
) -> tuple[Verifier, list[tuple[Path | Hashed, Hashed, Bundle]]]:
"""
Performs CLI functionality common across all `sigstore verify` subcommands.
Returns a tuple of the active verifier instance and a list of `(path, hashed, bundle)`
tuples, where `path` is the filename for display purposes, `hashed` is the
pre-hashed input to the file being verified and `bundle` is the `Bundle` to verify with.
"""
# Fail if --certificate, --signature, or --bundle is specified, and we
# have more than one input.
if (args.certificate or args.signature or args.bundle) and len(
args.files_or_digest
) > 1:
_invalid_arguments(
args,
"--certificate, --signature, or --bundle can only be used "
"with a single input file or digest",
)
# Fail if `--certificate` or `--signature` is used with `--bundle`.
if args.bundle and (args.certificate or args.signature):
_invalid_arguments(
args, "--bundle cannot be used with --certificate or --signature"
)
# Fail if digest input is not used with `--bundle` or both `--certificate` and `--signature`.
if any(isinstance(x, Hashed) for x in args.files_or_digest):
if not args.bundle and not (args.certificate and args.signature):
_invalid_arguments(
args,
"verifying a digest input (sha256:*) needs either --bundle or both --certificate and --signature",
)
# Fail if `--certificate` or `--signature` is used with `--offline`.
if args.offline and (args.certificate or args.signature):
_invalid_arguments(
args, "--offline cannot be used with --certificate or --signature"
)
# The converse of `sign`: we build up an expected input map and check
# that we have everything so that we can fail early.
input_map: dict[Path | Hashed, VerificationMaterials] = {}
for file in (f for f in args.files_or_digest if isinstance(f, Path)):
if not file.is_file():
_invalid_arguments(args, f"Input must be a file: {file}")
sig, cert, bundle = (
args.signature,
args.certificate,
args.bundle,
)
if sig is None:
sig = file.parent / f"{file.name}.sig"
if cert is None:
cert = file.parent / f"{file.name}.crt"
if bundle is None:
# NOTE(ww): If the user hasn't specified a bundle via `--bundle` and
# `{input}.sigstore.json` doesn't exist, then we try `{input}.sigstore`
# for backwards compatibility.
legacy_default_bundle = file.parent / f"{file.name}.sigstore"
bundle = file.parent / f"{file.name}.sigstore.json"
if not bundle.is_file() and legacy_default_bundle.is_file():
if not cert.is_file() or not sig.is_file():
# NOTE(ww): Only show this warning if bare materials
# are not provided, since bare materials take precedence over
# a .sigstore bundle.
_logger.warning(
f"{file}: {legacy_default_bundle} should be named {bundle}. "
"Support for discovering 'bare' .sigstore inputs will be deprecated in "
"a future release."
)
bundle = legacy_default_bundle
elif bundle.is_file() and legacy_default_bundle.is_file():
# Don't allow the user to implicitly verify `{input}.sigstore.json` if
# `{input}.sigstore` is also present, since this implies user confusion.
_invalid_arguments(
args,
f"Conflicting inputs: {bundle} and {legacy_default_bundle}",
)
missing = []
if args.signature or args.certificate:
if not sig.is_file():
missing.append(str(sig))
if not cert.is_file():
missing.append(str(cert))
input_map[file] = VerificationUnbundledMaterials(
certificate=cert, signature=sig
)
else:
# If a user hasn't explicitly supplied `--signature` or `--certificate`,
# we expect a bundle either supplied via `--bundle` or with the
# default `{input}.sigstore(.json)?` name.
if not bundle.is_file():
missing.append(str(bundle))