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
|
//
// 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.
package tests
import (
"bytes"
"crypto"
"encoding/asn1"
"encoding/json"
"errors"
"io"
"math/big"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
ts "github.com/digitorus/timestamp"
"github.com/sigstore/sigstore/pkg/cryptoutils"
"github.com/sigstore/timestamp-authority/pkg/client"
"github.com/sigstore/timestamp-authority/pkg/generated/client/timestamp"
)
const (
cli = "../../bin/timestamp-cli"
)
func TestInspect(t *testing.T) {
serverURL := createServer(t)
tsrPath := getTimestamp(t, serverURL, "blob", big.NewInt(0), nil, true)
// It should create timestamp successfully.
out := runCli(t, "inspect", "--timestamp", tsrPath, "--format", "json")
// test that output can be parsed as a timestamp
resp := struct {
TimestampResponse ts.Timestamp
}{}
err := json.Unmarshal([]byte(out), &resp)
if err != nil {
t.Errorf("failed to parse CLI response to a timestamp: %v", err)
}
}
func TestTimestamp(t *testing.T) {
restapiURL := createServer(t)
tsrPath := filepath.Join(t.TempDir(), "response.tsr")
artifactPath := makeArtifact(t, "blob")
// It should create timestamp successfully.
out := runCli(t, "--timestamp_server", restapiURL, "timestamp", "--artifact", artifactPath, "--hash", "sha256", "--out", tsrPath)
outputContains(t, out, "Artifact timestamped at")
if _, err := os.Stat(tsrPath); errors.Is(err, os.ErrNotExist) {
t.Errorf("expected TSR file does not exist at path %s", tsrPath)
}
}
func TestVerify_CertificateChainFlag(t *testing.T) {
restapiURL := createServer(t)
artifactContent := "blob"
artifactPath := makeArtifact(t, artifactContent)
// this is the common name for the in-memory leaf certificate, copied
// from pkg/signer/memory.go
commonName := "Test TSA Timestamping"
nonce := big.NewInt(456)
policyOID := asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 57264, 2}
tsrContainsCerts := true
tsrPath := getTimestamp(t, restapiURL, artifactContent, nonce, policyOID, tsrContainsCerts)
// write the cert chain to a PEM file
pemFiles := writeCertChainToPEMFiles(t, restapiURL)
// It should verify timestamp successfully.
out := runCli(t, "--timestamp_server", restapiURL, "verify", "--timestamp", tsrPath, "--artifact", artifactPath, "--certificate-chain", pemFiles.certChainPath, "--nonce", nonce.String(), "--oid", policyOID.String(), "--common-name", commonName)
outputContains(t, out, "Successfully verified timestamp")
}
func TestVerify_RootAndIntermediateCertificateFlags(t *testing.T) {
restapiURL := createServer(t)
artifactContent := "blob"
artifactPath := makeArtifact(t, artifactContent)
// this is the common name for the in-memory leaf certificate, copied
// from pkg/signer/memory.go
commonName := "Test TSA Timestamping"
nonce := big.NewInt(456)
policyOID := asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 57264, 2}
tsrContainsCerts := true
tsrPath := getTimestamp(t, restapiURL, artifactContent, nonce, policyOID, tsrContainsCerts)
// write the cert chain to a PEM file
pemFiles := writeCertChainToPEMFiles(t, restapiURL)
// It should verify timestamp successfully.
out := runCli(t, "--timestamp_server", restapiURL, "verify", "--timestamp", tsrPath, "--artifact", artifactPath, "--root-certificates", pemFiles.rootCertsPath, "--intermediate-certificates", pemFiles.intermediateCertsPath, "--nonce", nonce.String(), "--oid", policyOID.String(), "--common-name", commonName)
outputContains(t, out, "Successfully verified timestamp")
}
func TestVerify_AllCertFlagsIncluded(t *testing.T) {
restapiURL := createServer(t)
artifactContent := "blob"
artifactPath := makeArtifact(t, artifactContent)
// this is the common name for the in-memory leaf certificate, copied
// from pkg/signer/memory.go
commonName := "Test TSA Timestamping"
nonce := big.NewInt(456)
policyOID := asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 57264, 2}
tsrContainsCerts := true
tsrPath := getTimestamp(t, restapiURL, artifactContent, nonce, policyOID, tsrContainsCerts)
// write the cert chain to a PEM file
pemFiles := writeCertChainToPEMFiles(t, restapiURL)
// It should fail to verify.
out := runCliErr(t, "--timestamp_server", restapiURL, "verify", "--timestamp", tsrPath, "--artifact", artifactPath, "--certificate-chain", pemFiles.certChainPath, "--root-certificates", pemFiles.rootCertsPath, "--intermediate-certificates", pemFiles.intermediateCertsPath, "--nonce", nonce.String(), "--oid", policyOID.String(), "--common-name", commonName)
outputContains(t, out, "the verify command must be called with either only the --certificate-chain flag or with the --root-certificates and --intermediate-certificates flags")
}
func TestVerify_NoCertFlagsIncluded(t *testing.T) {
restapiURL := createServer(t)
artifactContent := "blob"
artifactPath := makeArtifact(t, artifactContent)
// this is the common name for the in-memory leaf certificate, copied
// from pkg/signer/memory.go
commonName := "Test TSA Timestamping"
nonce := big.NewInt(456)
policyOID := asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 57264, 2}
tsrContainsCerts := true
tsrPath := getTimestamp(t, restapiURL, artifactContent, nonce, policyOID, tsrContainsCerts)
// It should fail to verify.
out := runCliErr(t, "--timestamp_server", restapiURL, "verify", "--timestamp", tsrPath, "--artifact", artifactPath, "--nonce", nonce.String(), "--oid", policyOID.String(), "--common-name", commonName)
outputContains(t, out, "the verify command must be called with either only the --certificate-chain flag or with the --root-certificates and --intermediate-certificates flags")
}
func TestVerify_PassLeafCertificate(t *testing.T) {
restapiURL := createServer(t)
artifactContent := "blob"
artifactPath := makeArtifact(t, artifactContent)
// this is the common name for the in-memory leaf certificate, copied
// from pkg/signer/memory.go
commonName := "Test TSA Timestamping"
nonce := big.NewInt(456)
policyOID := asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 57264, 2}
tsrContainsCerts := false
tsrPath := getTimestamp(t, restapiURL, artifactContent, nonce, policyOID, tsrContainsCerts)
// write the cert chain to a PEM file
pemFiles := writeCertChainToPEMFiles(t, restapiURL)
// It should verify timestamp successfully.
out := runCli(t, "--timestamp_server", restapiURL, "verify", "--timestamp", tsrPath, "--artifact", artifactPath, "--certificate-chain", pemFiles.certChainPath, "--nonce", nonce.String(), "--oid", policyOID.String(), "--common-name", commonName, "--certificate", pemFiles.leafCertPath)
outputContains(t, out, "Successfully verified timestamp")
}
func TestVerify_InvalidTSR(t *testing.T) {
restapiURL := createServer(t)
pemFiles := writeCertChainToPEMFiles(t, restapiURL)
artifactContent := "blob"
artifactPath := makeArtifact(t, artifactContent)
// Create invalid pem
invalidTSR := filepath.Join(t.TempDir(), "response.tsr")
if err := os.WriteFile(invalidTSR, []byte("invalid TSR"), 0600); err != nil {
t.Fatal(err)
}
// It should return a message that the PEM is not valid
out := runCliErr(t, "--timestamp_server", restapiURL, "verify", "--timestamp", invalidTSR, "--artifact", artifactPath, "--certificate-chain", pemFiles.certChainPath)
outputContains(t, out, "error parsing response into Timestamp")
}
func TestVerify_InvalidPEM(t *testing.T) {
restapiURL := createServer(t)
artifactContent := "blob"
artifactPath := makeArtifact(t, artifactContent)
tsrPath := getTimestamp(t, restapiURL, artifactContent, big.NewInt(0), nil, true)
// Create invalid pem
invalidPEMPath := filepath.Join(t.TempDir(), "invalid_pem_path")
if err := os.WriteFile(invalidPEMPath, []byte("invalid PEM"), 0600); err != nil {
t.Fatal(err)
}
// It should return a message that the PEM is not valid
out := runCliErr(t, "--timestamp_server", restapiURL, "verify", "--timestamp", tsrPath, "--artifact", artifactPath, "--certificate-chain", invalidPEMPath)
outputContains(t, out, "failed to parse intermediate and root certs from PEM file")
}
func runCliErr(t *testing.T, arg ...string) string {
t.Helper()
// use a blank config file to ensure no collision
if os.Getenv("TSATMPDIR") != "" {
arg = append(arg, "--config="+os.Getenv("TSATMPDIR")+".timestamp-server.yaml")
}
cmd := exec.Command(cli, arg...)
b, err := cmd.CombinedOutput()
if err == nil {
t.Log(string(b))
t.Fatalf("expected error, got %s", string(b))
}
return string(b)
}
func runCli(t *testing.T, arg ...string) string {
t.Helper()
// use a blank config file to ensure no collision
if os.Getenv("TSATMPDIR") != "" {
arg = append(arg, "--config="+os.Getenv("TSATMPDIR")+".timestamp-server.yaml")
}
return run(t, "", cli, arg...)
}
func run(t *testing.T, stdin, cmd string, arg ...string) string {
t.Helper()
c := exec.Command(cmd, arg...)
if stdin != "" {
c.Stdin = strings.NewReader(stdin)
}
if os.Getenv("TSATMPDIR") != "" {
// ensure that we use a clean state.json file for each run
c.Env = append(c.Env, "HOME="+os.Getenv("TSATMPDIR"))
}
b, err := c.CombinedOutput()
if err != nil {
t.Log(string(b))
t.Fatal(err)
}
return string(b)
}
func outputContains(t *testing.T, output, sub string) {
t.Helper()
if !strings.Contains(output, sub) {
t.Errorf("Expected [%s] in response, got %s", sub, output)
}
}
func getTimestamp(t *testing.T, url string, artifactContent string, nonce *big.Int, policyOID asn1.ObjectIdentifier, tsrContainsCerts bool) string {
c, err := client.GetTimestampClient(url, client.WithUserAgent("test user agent"), client.WithContentType(client.TimestampQueryMediaType))
if err != nil {
t.Fatalf("unexpected error creating client: %v", err)
}
tsNonce := big.NewInt(1234)
if nonce != nil {
tsNonce = nonce
}
tsPolicyOID := asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 57264, 2}
if policyOID != nil {
tsPolicyOID = policyOID
}
tsq, err := ts.CreateRequest(strings.NewReader(artifactContent), &ts.RequestOptions{
Hash: crypto.SHA256,
Certificates: tsrContainsCerts,
Nonce: tsNonce,
TSAPolicyOID: tsPolicyOID,
})
if err != nil {
t.Fatalf("unexpected error creating request: %v", err)
}
params := timestamp.NewGetTimestampResponseParams()
params.Request = io.NopCloser(bytes.NewReader(tsq))
var respBytes bytes.Buffer
_, err = c.Timestamp.GetTimestampResponse(params, &respBytes)
if err != nil {
t.Fatalf("unexpected error getting timestamp chain: %v", err)
}
path := filepath.Join(t.TempDir(), "response.tsr")
if err := os.WriteFile(path, respBytes.Bytes(), 0600); err != nil {
t.Fatalf("unexpected error while writing timestamp to file: %v", err)
}
return path
}
type certChainPEMFiles struct {
leafCertPath string
intermediateCertsPath string
rootCertsPath string
certChainPath string
}
// getCertChainPEM returns the path of a pem file containing
// the leaf certificate and the path of a pem file containing the
// root and intermediate certificates. Used to verify a signed timestamp
func writeCertChainToPEMFiles(t *testing.T, restapiURL string) certChainPEMFiles {
c, err := client.GetTimestampClient(restapiURL)
if err != nil {
t.Fatalf("unexpected error creating client: %v", err)
}
chain, err := c.Timestamp.GetTimestampCertChain(nil)
if err != nil {
t.Fatalf("unexpected error getting timestamp chain: %v", err)
}
// create PEM file containing intermediate and root certificates
certChainPath := filepath.Join(t.TempDir(), "ts_certchain.pem")
file, err := os.Create(certChainPath)
if err != nil {
t.Fatal(err)
}
defer file.Close()
// Remove the non-CA certificate from the chain
certs, err := cryptoutils.UnmarshalCertificatesFromPEM([]byte(chain.Payload))
if err != nil {
t.Fatalf("unexpected error unmarshalling cert chain: %v", err)
}
caCertsPEM, err := cryptoutils.MarshalCertificatesToPEM(certs[1:])
if err != nil {
t.Fatalf("unexpected error marshalling cert chain: %v", err)
}
reader := bytes.NewReader(caCertsPEM)
file.ReadFrom(reader)
// create intermediates certificate PEM file
intermediateCertsPath := filepath.Join(t.TempDir(), "ts_intermediates.pem")
file, err = os.Create(intermediateCertsPath)
if err != nil {
t.Fatal(err)
}
defer file.Close()
lastCertIndex := len(certs) - 1
intermediatesPEM, err := cryptoutils.MarshalCertificatesToPEM(certs[1:lastCertIndex])
if err != nil {
t.Fatalf("unexpected error marshalling intermediate certificates: %v", err)
}
reader = bytes.NewReader(intermediatesPEM)
file.ReadFrom(reader)
// create roots certificate PEM file
rootCertsPath := filepath.Join(t.TempDir(), "ts_roots.pem")
file, err = os.Create(rootCertsPath)
if err != nil {
t.Fatal(err)
}
defer file.Close()
rootsPEM, err := cryptoutils.MarshalCertificatesToPEM(certs[lastCertIndex:])
if err != nil {
t.Fatalf("unexpected error marshalling root certificates: %v", err)
}
reader = bytes.NewReader(rootsPEM)
file.ReadFrom(reader)
// create PEM file containing the leaf certificate
leafCertPath := filepath.Join(t.TempDir(), "ts_leafcert.pem")
file, err = os.Create(leafCertPath)
if err != nil {
t.Fatal(err)
}
defer file.Close()
leafCertPEM, err := cryptoutils.MarshalCertificatesToPEM(certs[0:1])
if err != nil {
t.Fatalf("unexpected error marshalling leaf cert: %v", err)
}
reader = bytes.NewReader(leafCertPEM)
file.ReadFrom(reader)
return certChainPEMFiles{
leafCertPath: leafCertPath,
intermediateCertsPath: intermediateCertsPath,
rootCertsPath: rootCertsPath,
certChainPath: certChainPath,
}
}
// Create a random artifact to sign
func makeArtifact(t *testing.T, content string) string {
artifactPath := filepath.Join(t.TempDir(), "artifact")
if err := os.WriteFile(artifactPath, []byte(content), 0600); err != nil {
t.Fatal(err)
}
return artifactPath
}
|