/
signing.go
175 lines (151 loc) · 5.78 KB
/
signing.go
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
// Copyright 2022 OpenSSF 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.
//
// SPDX-License-Identifier: Apache-2.0
package signing
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
sigOpts "github.com/sigstore/cosign/cmd/cosign/cli/options"
"github.com/sigstore/cosign/cmd/cosign/cli/sign"
"github.com/ossf/scorecard-action/entrypoint"
"github.com/ossf/scorecard-action/options"
)
var (
errorEmptyToken = errors.New("error token empty")
errorInvalidToken = errors.New("invalid token")
)
// Signing is a signing structure.
type Signing struct {
token string
}
// New creates a new Signing instance.
func New(token string) (*Signing, error) {
// Set the default GITHUB_TOKEN, because it's not available by default
// in a GitHub Action. We need it for OIDC.
if token == "" {
return nil, fmt.Errorf("%w", errorEmptyToken)
}
// Check for a workflow secret.
if !strings.HasPrefix(token, "ghs_") {
return nil, fmt.Errorf("%w: not a default GITHUB_TOKEN", errorInvalidToken)
}
if err := os.Setenv("GITHUB_TOKEN", token); err != nil {
return nil, fmt.Errorf("error setting GITHUB_TOKEN env var: %w", err)
}
if err := os.Setenv("COSIGN_EXPERIMENTAL", "true"); err != nil {
return nil, fmt.Errorf("error setting COSIGN_EXPERIMENTAL env var: %w", err)
}
return &Signing{
token: token,
}, nil
}
// SignScorecardResult signs the results file and uploads the attestation to the Rekor transparency log.
func (s *Signing) SignScorecardResult(scorecardResultsFile string) error {
// Prepare settings for SignBlobCmd.
rootOpts := &sigOpts.RootOptions{Timeout: sigOpts.DefaultTimeout} // Just the timeout.
keyOpts := sigOpts.KeyOpts{
FulcioURL: sigOpts.DefaultFulcioURL, // Signing certificate provider.
RekorURL: sigOpts.DefaultRekorURL, // Transparency log.
OIDCIssuer: sigOpts.DefaultOIDCIssuerURL, // OIDC provider to get ID token to auth for Fulcio.
OIDCClientID: "sigstore",
}
regOpts := sigOpts.RegistryOptions{} // Not necessary so we leave blank.
// This command will use the provided OIDCIssuer to authenticate into Fulcio, which will generate the
// signing certificate on the scorecard result. This attestation is then uploaded to the Rekor transparency log.
// The output bytes (signature) and certificate are discarded since verification can be done with just the payload.
if _, err := sign.SignBlobCmd(rootOpts, keyOpts, regOpts, scorecardResultsFile, true, "", ""); err != nil {
return fmt.Errorf("error signing payload: %w", err)
}
return nil
}
// GetJSONScorecardResults changes output settings to json and runs scorecard again.
// TODO: run scorecard only once and generate multiple formats together.
func GetJSONScorecardResults() ([]byte, error) {
defer os.Setenv(options.EnvInputResultsFile, os.Getenv(options.EnvInputResultsFile))
defer os.Setenv(options.EnvInputResultsFormat, os.Getenv(options.EnvInputResultsFormat))
os.Setenv(options.EnvInputResultsFile, "results.json")
os.Setenv(options.EnvInputResultsFormat, "json")
actionJSON, err := entrypoint.New()
if err != nil {
return nil, fmt.Errorf("creating scorecard entrypoint: %w", err)
}
if err := actionJSON.Execute(); err != nil {
return nil, fmt.Errorf("error during command execution: %w", err)
}
// Get json output data from file.
jsonPayload, err := os.ReadFile(os.Getenv(options.EnvInputResultsFile))
if err != nil {
return nil, fmt.Errorf("reading scorecard json results from file: %w", err)
}
return jsonPayload, nil
}
// ProcessSignature calls scorecard-api to process & upload signed scorecard results.
func (s *Signing) ProcessSignature(jsonPayload []byte, repoName, repoRef string) error {
// Prepare HTTP request body for scorecard-webapp-api call.
// TODO: Use the `ScorecardResult` struct from `scorecard-webapp`.
resultsPayload := struct {
Result string `json:"result"`
Branch string `json:"branch"`
AccessToken string `json:"accessToken"`
}{
Result: string(jsonPayload),
Branch: repoRef,
AccessToken: s.token,
}
payloadBytes, err := json.Marshal(resultsPayload)
if err != nil {
return fmt.Errorf("marshalling json results: %w", err)
}
// Call scorecard-webapp-api to process and upload signature.
// Setup HTTP request and context.
apiURL := os.Getenv(options.EnvInputInternalPublishBaseURL)
rawURL := fmt.Sprintf("%s/projects/github.com/%s", apiURL, repoName)
parsedURL, err := url.Parse(rawURL)
if err != nil {
return fmt.Errorf("parsing Scorecard API endpoint: %w", err)
}
req, err := http.NewRequest("POST", parsedURL.String(), bytes.NewBuffer(payloadBytes))
if err != nil {
return fmt.Errorf("creating HTTP request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
ctx, cancel := context.WithTimeout(req.Context(), 10*time.Second)
defer cancel()
req = req.WithContext(ctx)
// Execute request.
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("executing scorecard-api call: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading response body: %w", err)
}
return fmt.Errorf("http response %d, status: %v, error: %v", resp.StatusCode, resp.Status, string(bodyBytes)) //nolint
}
return nil
}