Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
915 lines (829 loc) · 25.5 KB
/
Copy pathmain.go
File metadata and controls
915 lines (829 loc) · 25.5 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
// Chainloop is an open source project that allows you to collect, attest, and distribute pieces of evidence from your Software Supply Chain.
package main
import (
"context"
"encoding/json"
"fmt"
"main/internal/dagger"
"time"
)
const (
chainloopVersion = "v1.122.2"
platformVersion = "v1.127.2"
// gitlabCADir holds the custom CA of the Gitlab server. The CLI image is scratch-based,
// so SSL_CERT_DIR points Go at it, on top of the default ca-certificates.crt bundle
gitlabCADir = "/etc/ssl/gitlab"
)
var execOpts = dagger.ContainerWithExecOpts{
UseEntrypoint: true,
}
type Chainloop struct {
// +private
Instance InstanceInfo
// +private
Enterprise bool
}
// New creates a new Chainloop module client.
func New(
// Use the enterprise CLI image (ghcr.io/chainloop-dev/platform/cli)
// +optional
enterprise bool,
) *Chainloop {
return &Chainloop{
Enterprise: enterprise,
}
}
// A Chainloop attestation
// https://docs.chainloop.dev/concepts/attestations
type Attestation struct {
AttestationID string
OrgName string
repository *dagger.Directory
// +private
Token *dagger.Secret
// +private
RegistryAuth RegistryAuth
Client *Chainloop
// +private
parentCIContext *ParentCIContext
// +private
githubEventFile *dagger.File
}
// Configuration for a container registry client
type RegistryAuth struct {
// Address of the registry
Address string
// Username to use when authenticating to the registry
Username string
// Password to use when authenticating to the registry
Password *dagger.Secret
}
// Configuration for a Chainloop instance
type InstanceInfo struct {
// hostname for the Control Plane API i.e mycontrolplane:443
ControlplaneAPI string
// path to a custom CA for the Control Plane API
ControlplaneCAPath *dagger.File
// hostname for the cas API i.e myCAS:443
CASAPI string
// path to a custom CA for the CAS API
CASCAPath *dagger.File
// hostname for the Platform API i.e api.app.chainloop.dev:443
PlatformAPI string
// path to a custom CA for the Platform API
PlatformCAPath *dagger.File
// Password to use when authenticating to the registry
Insecure bool
}
// ParentCIContext holds environment variables from a parent CI system (Github Actions, Gitlab CI)
// to enable PR/MR auto-detection and commit verification when running Chainloop via Dagger inside those CI systems
type ParentCIContext struct {
// Github Actions PR context
// Repository name (owner/repo)
GithubRepository string
// Run ID for the workflow run
GithubRunID string
// Event name (e.g., "pull_request", "pull_request_target")
GithubEventName string
// Source branch name
GithubHeadRef string
// Target branch name
GithubBaseRef string
// Github token for API access and commit verification
GithubToken *dagger.Secret
// Gitlab CI MR context
// CI indicator (always "true" in Gitlab CI)
GitlabCI string
// Server URL (e.g., "https://gitlab.com")
GitlabServerURL string
// Project path (e.g., "group/project")
GitlabProjectPath string
// Job URL
GitlabJobURL string
// Pipeline source (should be "merge_request_event" for MRs)
GitlabPipelineSource string
// Merge request internal ID
GitlabMRIID string
// Merge request title
GitlabMRTitle string
// Merge request description
GitlabMRDescription string
// Source branch name
GitlabMRSourceBranch string
// Target branch name
GitlabMRTargetBranch string
// Project URL
GitlabMRProjectURL string
// User login
GitlabUserLogin string
// Gitlab job token for API access, for example to read merge request details
GitlabJobToken *dagger.Secret
// Gitlab token with the read_api scope for commit verification
GitlabToken *dagger.Secret
// Custom CA certificate of the Gitlab server
GitlabCA *dagger.File
}
// Initialize a new attestation
//
// Cached only for the session: a new attestation must be initialized on every run,
// reusing a cached attestation ID from a previous run fails once that attestation is gone
//
// +cache="session"
func (m *Chainloop) Init(
ctx context.Context,
// Chainloop API token
token *dagger.Secret,
// Workflow Contract revision, default is the latest
// +optional
contractRevision string,
// Path to the source repository to be attested
// +optional
repository *dagger.Directory,
// Workflow name to be used for the attestation
workflowName string,
// Project name to be used for the attestation
projectName string,
// name of an existing contract to attach it to the auto-created workflow
// +optional
contractName string,
// Version of the project to be used for the attestation
// +optional
projectVersion string,
// mark the version as release
// +optional
release bool,
// Control whether this project version is promoted to "latest".
// ON_CREATE (default): new versions become latest, existing ones are untouched.
// TRUE: force-promote a pre-release version. FALSE: skip promotion entirely.
// +optional
// +default="ON_CREATE"
markLatest MarkLatest,
// Github event file for PR detection (when running in Github Actions)
// +optional
githubEventFile *dagger.File,
// Github repository name (owner/repo)
// +optional
githubRepository string,
// Github run ID for the workflow run
// +optional
githubRunID string,
// Github event name (e.g., "pull_request", "pull_request_target")
// +optional
githubEventName string,
// Github source branch name
// +optional
githubHeadRef string,
// Github target branch name
// +optional
githubBaseRef string,
// Github token for API access and commit verification (when running in Github Actions)
// +optional
githubToken *dagger.Secret,
// Gitlab CI indicator (should be "true" when running in Gitlab CI)
// +optional
gitlabCI string,
// Gitlab server URL (e.g., "https://gitlab.com")
// +optional
gitlabServerURL string,
// Gitlab project path (e.g., "group/project")
// +optional
gitlabProjectPath string,
// Gitlab job URL
// +optional
gitlabJobURL string,
// Gitlab pipeline source (should be "merge_request_event" for MRs)
// +optional
gitlabPipelineSource string,
// Gitlab merge request internal ID
// +optional
gitlabMRIID string,
// Gitlab merge request title
// +optional
gitlabMRTitle string,
// Gitlab merge request description
// +optional
gitlabMRDescription string,
// Gitlab source branch name
// +optional
gitlabMRSourceBranch string,
// Gitlab target branch name
// +optional
gitlabMRTargetBranch string,
// Gitlab project URL
// +optional
gitlabMRProjectURL string,
// Gitlab user login
// +optional
gitlabUserLogin string,
// Gitlab job token for API access, for example to read merge request details (when running in Gitlab CI)
// +optional
gitlabJobToken *dagger.Secret,
// Gitlab personal, project or group access token with the read_api scope to verify the commit signature.
// Required for private and internal projects: the commit signature API does not accept job tokens
// +optional
gitlabToken *dagger.Secret,
// Custom CA certificate (PEM) of a self-managed Gitlab server that uses a private CA
// +optional
gitlabCA *dagger.File,
) (*Attestation, error) {
// Construct ParentCIContext from individual parameters
var parentCIContext *ParentCIContext
if githubRepository != "" || githubRunID != "" || githubEventName != "" || githubHeadRef != "" || githubBaseRef != "" ||
gitlabCI != "" || gitlabServerURL != "" || gitlabProjectPath != "" || gitlabJobURL != "" ||
gitlabPipelineSource != "" || gitlabMRIID != "" || gitlabMRTitle != "" ||
gitlabMRDescription != "" || gitlabMRSourceBranch != "" || gitlabMRTargetBranch != "" ||
gitlabMRProjectURL != "" || gitlabUserLogin != "" {
parentCIContext = &ParentCIContext{
GithubRepository: githubRepository,
GithubRunID: githubRunID,
GithubEventName: githubEventName,
GithubHeadRef: githubHeadRef,
GithubBaseRef: githubBaseRef,
GithubToken: githubToken,
GitlabCI: gitlabCI,
GitlabServerURL: gitlabServerURL,
GitlabProjectPath: gitlabProjectPath,
GitlabJobURL: gitlabJobURL,
GitlabPipelineSource: gitlabPipelineSource,
GitlabMRIID: gitlabMRIID,
GitlabMRTitle: gitlabMRTitle,
GitlabMRDescription: gitlabMRDescription,
GitlabMRSourceBranch: gitlabMRSourceBranch,
GitlabMRTargetBranch: gitlabMRTargetBranch,
GitlabMRProjectURL: gitlabMRProjectURL,
GitlabUserLogin: gitlabUserLogin,
GitlabJobToken: gitlabJobToken,
GitlabToken: gitlabToken,
GitlabCA: gitlabCA,
}
}
att := &Attestation{
Token: token,
repository: repository,
Client: m,
parentCIContext: parentCIContext,
githubEventFile: githubEventFile,
}
// Append the contract revision to the args if provided
args := []string{
"attestation", "init", "--remote-state", "-o", "json", "--workflow", workflowName, "--project", projectName,
}
if contractRevision != "" {
args = append(args,
"--contract-revision", contractRevision,
)
}
if contractName != "" {
args = append(args,
"--contract", contractName,
)
}
if projectVersion != "" {
args = append(args,
"--version", projectVersion,
)
}
if release {
args = append(args,
"--release",
)
}
// Map the tri-state enum onto the CLI's --mark-latest flag. ON_CREATE omits
// the flag so the server applies its default behavior. An enum (non-empty
// string) is used instead of *bool because Dagger v0.19.11 collapses *bool
// to bool in the generated SDK and drops the false value (see PFM-6269).
switch markLatest {
case MarkLatestTrue:
args = append(args, "--mark-latest=true")
case MarkLatestFalse:
args = append(args, "--mark-latest=false")
case MarkLatestOnCreate:
// omit the flag → CLI sends no value → server applies its default
}
info, err := att.
Container(0).
WithExec(args, execOpts).
Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("attestation init: %w", err)
}
var resp struct {
AttestationID string
WorkflowMeta struct {
Organization string
}
}
if err := json.Unmarshal([]byte(info), &resp); err != nil {
return nil, fmt.Errorf("unmarshal attestation init response: %w", err)
}
att.AttestationID = resp.AttestationID
att.OrgName = resp.WorkflowMeta.Organization
return att, nil
}
// Resume an attestation from its identifier
func (m *Chainloop) Resume(
// The attestation ID
attestationID string,
// Chainloop API token
token *dagger.Secret,
) *Attestation {
return &Attestation{
AttestationID: attestationID,
Token: token,
Client: m,
}
}
// Check the attestation status
//
// +cache="session"
func (att *Attestation) Status(ctx context.Context) (string, error) {
return att.
Container(0).
WithExec([]string{
"attestation", "status",
"--attestation-id", att.AttestationID,
"--full",
}, execOpts).
Stdout(ctx)
}
// Sync will force the client to send an actual query to the chainloop control plane
// This is specially important to be run right after Init
// for example
//
// att := chainloop.Init(ctx, token, "main")
//
// if err := att.Sync(ctx); err != nil {
// return nil, err
// }
func (att *Attestation) Sync(_ context.Context) error {
return nil
}
// Attach credentials for a container registry.
// Chainloop will use them to query the registry for container image pieces of evidences
func (att *Attestation) WithRegistryAuth(
_ context.Context,
// Registry address.
// Example: "index.docker.io"
address string,
// Registry username
username string,
// Registry password
password *dagger.Secret,
) *Attestation {
att.RegistryAuth.Address = address
att.RegistryAuth.Username = username
att.RegistryAuth.Password = password
return att
}
// Configure the Chainloop instance to use
func (m *Chainloop) WithInstance(
_ context.Context,
// Example: "api.controlplane.company.com:443"
controlplaneAPI string,
// Example: "api.cas.company.com:443"
casAPI string,
// Path to custom CA certificate for the CAS API
// +optional
casCA *dagger.File,
// Path to custom CA certificate for the Control Plane API
// +optional
controlplaneCA *dagger.File,
// Example: "api.app.chainloop.dev:443"
platformAPI string,
// Path to custom CA certificate for the Platform API
// +optional
platformCA *dagger.File,
// Whether to skip TLS verification
// +optional
insecure bool,
) *Chainloop {
m.Instance = InstanceInfo{
ControlplaneAPI: controlplaneAPI,
CASAPI: casAPI,
Insecure: insecure,
CASCAPath: casCA,
ControlplaneCAPath: controlplaneCA,
PlatformAPI: platformAPI,
PlatformCAPath: platformCA,
}
return m
}
// Add a raw string piece of evidence to the attestation
//
// +cache="session"
func (att *Attestation) AddRawEvidence(
ctx context.Context,
// Evidence name. Don't pass a name if the material
// being attested is not part of the contract
// Example: "my-blob"
// +optional
name string,
// The contents of the blob
value string,
// the material type of the evidence https://docs.chainloop.dev/concepts/material-types#material-types
// if not provided it will either be loaded from the contract or inferred automatically
// +optional
kind string,
// List of annotations to be attached to the evidence for example:
// "key1=value1,key2=value2"
// +optional
annotations []string,
// Skip strict schema validation for structured materials (SBOM_CYCLONEDX_JSON, OPENAPI_SPEC, ASYNCAPI_SPEC, OSSF_SCORECARD_JSON)
// +optional
noStrictValidation bool,
// Enable debug logging
// +optional
debugMode bool,
) (*Attestation, error) {
args := []string{
"attestation", "add",
"--attestation-id", att.AttestationID,
"--value", value,
}
if name != "" {
args = append(args,
"--name", name,
)
}
if kind != "" {
args = append(args,
"--kind", kind,
)
}
for _, annotation := range annotations {
args = append(args,
"--annotation", annotation,
)
}
if noStrictValidation {
args = append(args, "--no-strict-validation")
}
if debugMode {
args = append(args, "--debug")
}
_, err := att.
Container(0).
WithExec(args, execOpts).
Stdout(ctx)
return att, err
}
// Add a file type piece of evidence to the attestation
//
// +cache="session"
func (att *Attestation) AddFileEvidence(
ctx context.Context,
// Evidence name. Don't pass a name if the material
// being attested is not part of the contract
// Example: "my-binary"
// +optional
name string,
// The file to add
path *dagger.File,
// the material type of the evidence https://docs.chainloop.dev/concepts/material-types#material-types
// if not provided it will either be loaded from the contract or inferred automatically
// +optional
kind string,
// List of annotations to be attached to the evidence for example:
// "key1=value1,key2=value2"
// +optional
annotations []string,
// Skip strict schema validation for structured materials (SBOM_CYCLONEDX_JSON, OPENAPI_SPEC, ASYNCAPI_SPEC, OSSF_SCORECARD_JSON)
// +optional
noStrictValidation bool,
// Enable debug logging
// +optional
debugMode bool,
) (*Attestation, error) {
filename, err := path.Name(ctx)
if err != nil {
return att, err
}
mountPath := "/tmp/attestation/" + filename
args := []string{
"attestation", "add",
"--attestation-id", att.AttestationID,
"--value", mountPath,
}
for _, annotation := range annotations {
args = append(args,
"--annotation", annotation,
)
}
if kind != "" {
args = append(args,
"--kind", kind,
)
}
if name != "" {
args = append(args,
"--name", name,
)
}
if noStrictValidation {
args = append(args, "--no-strict-validation")
}
if debugMode {
args = append(args, "--debug")
}
_, err = att.
Container(0).
// Preserve the filename inside the container
WithFile(mountPath, path).
WithExec(args, execOpts).
Sync(ctx)
return att, err
}
// +cache="session"
func (att *Attestation) Debug() *dagger.Container {
return att.Container(0).Terminal()
}
func cliContainer(ttl int, token *dagger.Secret, instance InstanceInfo, parentCI *ParentCIContext, githubEventFile *dagger.File, enterprise bool) *dagger.Container {
image := "ghcr.io/chainloop-dev/chainloop/cli"
version := chainloopVersion
if enterprise {
image = "ghcr.io/chainloop-dev/platform/cli"
version = platformVersion
}
ctr := dag.Container().
From(fmt.Sprintf("%s:%s", image, version)).
WithEntrypoint([]string{"/chainloop"}). // Be explicit to prepare for possible API change
WithEnvVariable("CHAINLOOP_DAGGER_CLIENT", version).
WithUser(""). // Our images come with pre-defined user set, so we need to reset it
WithEnvVariable("DAGGER_CACHE_KEY", time.Now().Truncate(time.Duration(ttl)*time.Second).String()) // Cache TTL
// Inject parent CI context if provided
if parentCI != nil {
// Github Actions context
if parentCI.GithubRepository != "" {
ctr = ctr.WithEnvVariable("GITHUB_REPOSITORY", parentCI.GithubRepository)
}
if parentCI.GithubRunID != "" {
ctr = ctr.WithEnvVariable("GITHUB_RUN_ID", parentCI.GithubRunID)
}
if parentCI.GithubEventName != "" {
ctr = ctr.WithEnvVariable("GITHUB_EVENT_NAME", parentCI.GithubEventName)
}
if parentCI.GithubHeadRef != "" {
ctr = ctr.WithEnvVariable("GITHUB_HEAD_REF", parentCI.GithubHeadRef)
}
if parentCI.GithubBaseRef != "" {
ctr = ctr.WithEnvVariable("GITHUB_BASE_REF", parentCI.GithubBaseRef)
}
if parentCI.GithubToken != nil {
ctr = ctr.WithSecretVariable("GITHUB_TOKEN", parentCI.GithubToken)
}
// Handle Github event file (passed as separate parameter for CLI convenience)
if githubEventFile != nil {
ctr = ctr.WithFile("/tmp/github_event.json", githubEventFile).
WithEnvVariable("GITHUB_EVENT_PATH", "/tmp/github_event.json")
}
// Gitlab CI context
if parentCI.GitlabCI != "" {
ctr = ctr.WithEnvVariable("GITLAB_CI", parentCI.GitlabCI)
}
if parentCI.GitlabServerURL != "" {
ctr = ctr.WithEnvVariable("CI_SERVER_URL", parentCI.GitlabServerURL)
}
if parentCI.GitlabProjectPath != "" {
ctr = ctr.WithEnvVariable("CI_PROJECT_PATH", parentCI.GitlabProjectPath)
}
if parentCI.GitlabJobURL != "" {
ctr = ctr.WithEnvVariable("CI_JOB_URL", parentCI.GitlabJobURL)
}
if parentCI.GitlabPipelineSource != "" {
ctr = ctr.WithEnvVariable("CI_PIPELINE_SOURCE", parentCI.GitlabPipelineSource)
}
if parentCI.GitlabMRIID != "" {
ctr = ctr.WithEnvVariable("CI_MERGE_REQUEST_IID", parentCI.GitlabMRIID)
}
if parentCI.GitlabMRTitle != "" {
ctr = ctr.WithEnvVariable("CI_MERGE_REQUEST_TITLE", parentCI.GitlabMRTitle)
}
if parentCI.GitlabMRDescription != "" {
ctr = ctr.WithEnvVariable("CI_MERGE_REQUEST_DESCRIPTION", parentCI.GitlabMRDescription)
}
if parentCI.GitlabMRSourceBranch != "" {
ctr = ctr.WithEnvVariable("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME", parentCI.GitlabMRSourceBranch)
}
if parentCI.GitlabMRTargetBranch != "" {
ctr = ctr.WithEnvVariable("CI_MERGE_REQUEST_TARGET_BRANCH_NAME", parentCI.GitlabMRTargetBranch)
}
if parentCI.GitlabMRProjectURL != "" {
ctr = ctr.WithEnvVariable("CI_MERGE_REQUEST_PROJECT_URL", parentCI.GitlabMRProjectURL)
}
if parentCI.GitlabUserLogin != "" {
ctr = ctr.WithEnvVariable("GITLAB_USER_LOGIN", parentCI.GitlabUserLogin)
}
if parentCI.GitlabJobToken != nil {
ctr = ctr.WithSecretVariable("CI_JOB_TOKEN", parentCI.GitlabJobToken)
}
if parentCI.GitlabToken != nil {
ctr = ctr.WithSecretVariable("GITLAB_TOKEN", parentCI.GitlabToken)
}
if parentCI.GitlabCA != nil {
ctr = ctr.WithFile(gitlabCADir+"/ca.pem", parentCI.GitlabCA).
WithEnvVariable("SSL_CERT_DIR", gitlabCADir)
}
}
if token != nil {
ctr = ctr.WithSecretVariable("CHAINLOOP_TOKEN", token)
}
if api := instance.ControlplaneAPI; api != "" {
ctr = ctr.WithEnvVariable("CHAINLOOP_CONTROL_PLANE_API", api)
}
if ca := instance.ControlplaneCAPath; ca != nil {
ctr = ctr.WithFile("/controlplane-ca.pem", ca).WithEnvVariable("CHAINLOOP_CONTROL_PLANE_API_CA", "/controlplane-ca.pem")
}
if ca := instance.CASCAPath; ca != nil {
ctr = ctr.WithFile("/cas-ca.pem", ca).WithEnvVariable("CHAINLOOP_ARTIFACT_CAS_API_CA", "/cas-ca.pem")
}
if cas := instance.CASAPI; cas != "" {
ctr = ctr.WithEnvVariable("CHAINLOOP_ARTIFACT_CAS_API", cas)
}
if platformAPI := instance.PlatformAPI; platformAPI != "" {
ctr = ctr.WithEnvVariable("CHAINLOOP_PLATFORM_API", platformAPI)
}
if ca := instance.PlatformCAPath; ca != nil {
ctr = ctr.WithFile("/platform-ca.pem", ca).WithEnvVariable("CHAINLOOP_PLATFORM_API_CA", "/platform-ca.pem")
}
if instance.Insecure {
ctr = ctr.WithEnvVariable("CHAINLOOP_API_INSECURE", "true")
}
// Cache TTL
ctr = ctr.WithEnvVariable("DAGGER_CACHE_KEY", time.Now().Truncate(time.Duration(ttl)*time.Second).String())
return ctr
}
// Build an ephemeral container with everything needed to process the attestation
//
// +cache="session"
func (att *Attestation) Container(
// Cache TTL for chainloop commands, in seconds
// Defaults to 0: no caching
// +optional
// +default=0
ttl int,
) *dagger.Container {
ctr := cliContainer(ttl, att.Token, att.Client.Instance, att.parentCIContext, att.githubEventFile, att.Client.Enterprise)
if att.repository != nil {
ctr = ctr.WithDirectory(".", att.repository)
}
if addr := att.RegistryAuth.Address; addr != "" {
ctr = ctr.WithEnvVariable("CHAINLOOP_REGISTRY_SERVER", addr)
}
if user := att.RegistryAuth.Username; user != "" {
ctr = ctr.WithEnvVariable("CHAINLOOP_REGISTRY_USERNAME", user)
}
if pw := att.RegistryAuth.Password; pw != nil {
ctr = ctr.WithSecretVariable("CHAINLOOP_REGISTRY_PASSWORD", pw)
}
return ctr
}
type OutputFormat string
const (
OutputFormatTable OutputFormat = "table"
OutputFormatJSON OutputFormat = "json"
)
// MarkLatest controls whether a project version is promoted to "latest" during
// attestation init. It is modelled as an enum rather than a *bool because the
// Dagger v0.19.11 SDK collapses *bool parameters to bool and drops the false
// value before it reaches the wire, making the "skip promotion" state
// unreachable (see PFM-6269). A non-empty string survives that check.
type MarkLatest string
const (
// MarkLatestOnCreate keeps the server default: a newly created version
// becomes latest, while existing/pre-release versions are left unchanged.
MarkLatestOnCreate MarkLatest = "ON_CREATE"
// MarkLatestTrue force-promotes a pre-release version to latest.
MarkLatestTrue MarkLatest = "TRUE"
// MarkLatestFalse skips latest promotion, even for newly created versions.
MarkLatestFalse MarkLatest = "FALSE"
)
// Generate, sign and push the attestation to the chainloop control plane
//
// +cache="session"
func (att *Attestation) Push(
ctx context.Context,
// The private key to sign the attestation
// +optional
key *dagger.Secret,
// The passphrase to decrypt the private key
// +optional
passphrase *dagger.Secret,
// Whether not fail if the policy check fails
// +optional
exceptionBypassPolicyCheck *bool,
// Output format
// +default="table"
format OutputFormat,
// List of annotations to be attached to the attestation for example:
// "key1=value1,key2=value2"
// +optional
annotations []string,
) (string, error) {
container := att.Container(0)
args := []string{
"attestation", "push",
"--attestation-id", att.AttestationID,
"--output", string(format),
}
for _, annotation := range annotations {
args = append(args, "--annotation", annotation)
}
if key != nil {
container = container.WithMountedSecret("/tmp/key.pem", key)
args = append(args, "--key", "/tmp/key.pem")
}
if passphrase != nil {
container = container.WithSecretVariable("CHAINLOOP_SIGNING_PASSWORD", passphrase)
}
if exceptionBypassPolicyCheck != nil && *exceptionBypassPolicyCheck {
args = append(args, "--exception-bypass-policy-check")
}
return container.WithExec(args, execOpts).Stdout(ctx)
}
// Mark the attestation as failed
//
// +cache="session"
func (att *Attestation) MarkFailed(
ctx context.Context,
// The reason for canceling, in human-readable form
// +optional
reason string,
) error {
return att.reset(ctx, "failure", reason)
}
// Mark the attestation as canceled
//
// +cache="session"
func (att *Attestation) MarkCanceled(
ctx context.Context,
// The reason for canceling, in human-readable form
// +optional
reason string,
) error {
return att.reset(ctx, "cancellation", reason)
}
// Call `chainloop reset` to mark the attestation as either failed or cancelled.
func (att *Attestation) reset(ctx context.Context,
// +optional
// The trigger that caused the reset.
// May be "failure" or "cancellation"
trigger string,
// The reason for the reset, in human-readable form
// +optional
reason string,
) error {
args := []string{
"attestation", "reset",
"--attestation-id", att.AttestationID,
}
if reason != "" {
args = append(args, "--reason", reason)
}
if trigger != "" {
args = append(args, "--trigger", trigger)
}
_, err := att.
Container(0).
WithExec(args, execOpts).
Sync(ctx)
return err
}
/// standalone API calls
// Create a new workflow
//
// +cache="session"
func (m *Chainloop) WorkflowCreate(
ctx context.Context,
// Chainloop API token
token *dagger.Secret,
// Workflow name
name string,
// Workflow project
project string,
// +optional
team string,
// +optional
description string,
// name of an existing contract
// +optional
contractName string,
// Set workflow as public so other organizations can see it
// +optional
public bool,
// If the workflow already exists, skip the creation and return success
// +optional
skipIfExists bool,
) (string, error) {
return cliContainer(0, token, m.Instance, nil, nil, m.Enterprise).
WithExec([]string{
"workflow", "create",
"--name", name,
"--project", project,
"--team", team,
"--description", description,
"--contract", contractName,
"--public", fmt.Sprintf("%t", public),
"--skip-if-exists", fmt.Sprintf("%t", skipIfExists),
}, execOpts).
Stdout(ctx)
}