From 6863e394f3e495b60b534f09e92c49ae7fe15b58 Mon Sep 17 00:00:00 2001 From: Hayden Blauzvern Date: Mon, 9 May 2022 23:18:59 +0000 Subject: [PATCH] Remove timestamping authority See #812 for more discussion. Signed-off-by: Hayden Blauzvern --- CODEOWNERS | 3 - FEATURES.md | 1 - cmd/rekor-cli/app/timestamp.go | 200 ------------- cmd/rekor-cli/app/timestamp_test.go | 130 --------- cmd/rekor-server/app/root.go | 1 - openapi.yaml | 62 ---- pkg/api/api.go | 53 +--- pkg/api/error.go | 19 -- pkg/api/timestamp.go | 94 ------ pkg/generated/client/rekor_client.go | 5 - .../get_timestamp_cert_chain_parameters.go | 142 ---------- .../get_timestamp_cert_chain_responses.go | 156 ---------- .../get_timestamp_response_parameters.go | 165 ----------- .../get_timestamp_response_responses.go | 244 ---------------- .../client/timestamp/timestamp_client.go | 135 --------- .../restapi/configure_rekor_server.go | 7 - pkg/generated/restapi/doc.go | 3 - .../restapi/operations/rekor_server_api.go | 58 ---- .../timestamp/get_timestamp_cert_chain.go | 74 ----- .../get_timestamp_cert_chain_parameters.go | 62 ---- .../get_timestamp_cert_chain_responses.go | 154 ---------- .../get_timestamp_cert_chain_urlbuilder.go | 100 ------- .../timestamp/get_timestamp_response.go | 72 ----- .../get_timestamp_response_parameters.go | 75 ----- .../get_timestamp_response_responses.go | 267 ------------------ .../get_timestamp_response_urlbuilder.go | 100 ------- pkg/pki/x509/x509.go | 45 --- pkg/pki/x509/x509_test.go | 49 ---- pkg/signer/memory.go | 107 ------- pkg/signer/memory_test.go | 63 +---- pkg/util/rfc3161.go | 259 ----------------- pkg/util/rfc3161_test.go | 182 ------------ tests/e2e_test.go | 124 -------- tests/test_request.tsq | Bin 59 -> 0 bytes 34 files changed, 8 insertions(+), 3203 deletions(-) delete mode 100644 cmd/rekor-cli/app/timestamp.go delete mode 100644 cmd/rekor-cli/app/timestamp_test.go delete mode 100644 pkg/api/timestamp.go delete mode 100644 pkg/generated/client/timestamp/get_timestamp_cert_chain_parameters.go delete mode 100644 pkg/generated/client/timestamp/get_timestamp_cert_chain_responses.go delete mode 100644 pkg/generated/client/timestamp/get_timestamp_response_parameters.go delete mode 100644 pkg/generated/client/timestamp/get_timestamp_response_responses.go delete mode 100644 pkg/generated/client/timestamp/timestamp_client.go delete mode 100644 pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain.go delete mode 100644 pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_parameters.go delete mode 100644 pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_responses.go delete mode 100644 pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_urlbuilder.go delete mode 100644 pkg/generated/restapi/operations/timestamp/get_timestamp_response.go delete mode 100644 pkg/generated/restapi/operations/timestamp/get_timestamp_response_parameters.go delete mode 100644 pkg/generated/restapi/operations/timestamp/get_timestamp_response_responses.go delete mode 100644 pkg/generated/restapi/operations/timestamp/get_timestamp_response_urlbuilder.go delete mode 100644 pkg/util/rfc3161.go delete mode 100644 pkg/util/rfc3161_test.go delete mode 100644 tests/test_request.tsq diff --git a/CODEOWNERS b/CODEOWNERS index 7d5e038e1..671aff174 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -5,9 +5,6 @@ /pkg/types/ @bobcallaway -/pkg/api/timestamp.go @asraa @loosebazooka -/pkg/types/rfc3161/ @asraa @loosebazooka - # The CODEOWNERS are managed via a GitHub team, but the current list is (in alphabetical order): # asraa diff --git a/FEATURES.md b/FEATURES.md index 6d81ddb20..4b938d43c 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -7,7 +7,6 @@ This doc covers feature stability in `rekor` as described in the [API Stability ## Beta * Rekor API, defined [here](https://github.com/sigstore/rekor/blob/main/openapi.yaml) -* The Rekor RFC 3161 timestamping service * `rekor-cli` CLI tool * The `rekor/pkg/client` client library diff --git a/cmd/rekor-cli/app/timestamp.go b/cmd/rekor-cli/app/timestamp.go deleted file mode 100644 index 816c16489..000000000 --- a/cmd/rekor-cli/app/timestamp.go +++ /dev/null @@ -1,200 +0,0 @@ -// -// Copyright 2021 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 app - -import ( - "bytes" - "crypto" - "encoding/asn1" - "encoding/hex" - "errors" - "fmt" - "io/ioutil" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/sassoftware/relic/lib/pkcs9" - "github.com/sassoftware/relic/lib/x509tools" - "github.com/sigstore/rekor/cmd/rekor-cli/app/format" - "github.com/sigstore/rekor/pkg/client" - "github.com/sigstore/rekor/pkg/generated/client/timestamp" - "github.com/sigstore/rekor/pkg/log" - "github.com/sigstore/rekor/pkg/util" - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -func addTimestampFlags(cmd *cobra.Command) error { - cmd.Flags().Var(NewFlagValue(fileFlag, ""), "artifact", "path to an artifact to timestamp") - cmd.Flags().Var(NewFlagValue(shaFlag, ""), "artifact-hash", "hex encoded SHA256 hash of the the artifact to timestamp") - cmd.Flags().Bool("nonce", true, "specify a pseudo-random nonce in the request") - cmd.Flags().Var(NewFlagValue(oidFlag, ""), "tsa-policy", "optional dotted OID notation for the policy that the TSA should use to create the response") - - cmd.Flags().String("out", "response.tsr", "path to a file to write response.") - - // TODO: Add a flag to indicate a JSON formatted timestamp request/response. - return nil -} - -func validateTimestampFlags() error { - artifactStr := viper.GetString("artifact") - digestStr := viper.GetString("artifact-hash") - - if artifactStr == "" && digestStr == "" { - return errors.New("artifact or hash to timestamp must be specified") - } - - return nil -} - -func createRequestFromFlags() (*pkcs9.TimeStampReq, error) { - var timestampReq *pkcs9.TimeStampReq - digestStr := viper.GetString("artifact-hash") - policyStr := viper.GetString("tsa-policy") - - opts := util.TimestampRequestOptions{ - // Always use a SHA256 right now. - Hash: crypto.SHA256, - } - if policyStr != "" { - var oidInts []int - for _, v := range strings.Split(policyStr, ".") { - i, _ := strconv.Atoi(v) - oidInts = append(oidInts, i) - } - opts.TSAPolicyOid = oidInts - } - if viper.GetBool("nonce") { - opts.Nonce = x509tools.MakeSerial() - } - - var digest []byte - if digestStr != "" { - decoded, err := hex.DecodeString(digestStr) - if err != nil { - return nil, err - } - digest = decoded - } - if digestStr == "" { - artifactStr := viper.GetString("artifact") - artifactBytes, err := ioutil.ReadFile(filepath.Clean(artifactStr)) - if err != nil { - return nil, fmt.Errorf("error reading request from file: %w", err) - } - h := opts.Hash.New() - if _, err := h.Write(artifactBytes); err != nil { - return nil, err - } - digest = h.Sum(nil) - } - - timestampReq, err := util.TimestampRequestFromDigest(digest, opts) - if err != nil { - return nil, fmt.Errorf("error creating timestamp request: %w", err) - } - - return timestampReq, nil -} - -type timestampCmdOutput struct { - Timestamp time.Time - Location string - UUID string - Index int64 -} - -func (t *timestampCmdOutput) String() string { - return fmt.Sprintf("Artifact timestamped at %s\nWrote timestamp response to %v\nCreated entry at index %d, available at: %v%v\n", - t.Timestamp, t.Location, t.Index, viper.GetString("rekor_server"), t.UUID) -} - -var timestampCmd = &cobra.Command{ - Use: "timestamp", - Short: "Rekor timestamp command", - Long: "Generates and uploads (WIP) an RFC 3161 timestamp response to the log. The timestamp response can be verified locally using Rekor's timestamping cert chain.", - PreRunE: func(cmd *cobra.Command, args []string) error { - if err := viper.BindPFlags(cmd.Flags()); err != nil { - log.CliLogger.Fatal("Error initializing cmd line args: ", err) - } - if err := validateTimestampFlags(); err != nil { - log.Logger.Error(err) - return err - } - return nil - }, - Run: format.WrapCmd(func(args []string) (interface{}, error) { - rekorClient, err := client.GetRekorClient(viper.GetString("rekor_server"), client.WithUserAgent(UserAgent())) - if err != nil { - return nil, err - } - - timestampReq, err := createRequestFromFlags() - if err != nil { - return nil, err - } - requestBytes, err := asn1.Marshal(*timestampReq) - if err != nil { - return nil, err - } - - params := timestamp.NewGetTimestampResponseParams() - params.SetTimeout(viper.GetDuration("timeout")) - params.Request = ioutil.NopCloser(bytes.NewReader(requestBytes)) - - var respBytes bytes.Buffer - resp, err := rekorClient.Timestamp.GetTimestampResponse(params, &respBytes) - if err != nil { - return nil, err - } - // Sanity check response and check if the TimeStampToken was successfully created - psd, err := timestampReq.ParseResponse(respBytes.Bytes()) - if err != nil { - return nil, err - } - genTime, err := util.GetSigningTime(psd) - if err != nil { - return nil, err - } - - // Write response to file - outStr := viper.GetString("out") - if outStr == "" { - outStr = "response.tsr" - } - if err := ioutil.WriteFile(outStr, respBytes.Bytes(), 0600); err != nil { - return nil, err - } - - return ×tampCmdOutput{ - Location: outStr, - UUID: string(resp.Location), - Timestamp: genTime.Round(time.Second), - Index: resp.Index, - }, nil - }), -} - -func init() { - initializePFlagMap() - if err := addTimestampFlags(timestampCmd); err != nil { - log.CliLogger.Fatal("Error parsing cmd line args: ", err) - } - - rootCmd.AddCommand(timestampCmd) -} diff --git a/cmd/rekor-cli/app/timestamp_test.go b/cmd/rekor-cli/app/timestamp_test.go deleted file mode 100644 index 957809f82..000000000 --- a/cmd/rekor-cli/app/timestamp_test.go +++ /dev/null @@ -1,130 +0,0 @@ -// -// Copyright 2021 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 app - -import ( - "testing" - - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -func TestTimestampFlags(t *testing.T) { - type test struct { - caseDesc string - artifact string - artifactHash string - oid string - expectParseSuccess bool - expectValidateSuccess bool - expectRequestSuccess bool - } - - tests := []test{ - { - caseDesc: "valid local artifact", - artifact: "../../../tests/test_file.txt", - expectParseSuccess: true, - expectValidateSuccess: true, - expectRequestSuccess: true, - }, - { - caseDesc: "nonexistant local artifact", - artifact: "../../../tests/not_a_file", - expectParseSuccess: false, - expectValidateSuccess: false, - expectRequestSuccess: false, - }, - { - caseDesc: "valid artifact hash", - artifactHash: "45c7b11fcbf07dec1694adecd8c5b85770a12a6c8dfdcf2580a2db0c47c31779", - expectParseSuccess: true, - expectValidateSuccess: true, - expectRequestSuccess: true, - }, - { - caseDesc: "invalid artifact hash", - artifactHash: "aaa", - expectParseSuccess: false, - expectValidateSuccess: false, - expectRequestSuccess: false, - }, - { - caseDesc: "nonexistant request artifact", - artifact: "../../../tests/not_a_request", - expectParseSuccess: false, - expectValidateSuccess: false, - expectRequestSuccess: false, - }, - { - caseDesc: "valid oid", - artifact: "../../../tests/test_file.txt", - oid: "1.2.3.4", - expectParseSuccess: true, - expectValidateSuccess: true, - expectRequestSuccess: true, - }, - { - caseDesc: "invalid oid", - artifact: "../../../tests/test_file.txt", - oid: "1.a.3.4", - expectParseSuccess: false, - expectValidateSuccess: true, - expectRequestSuccess: true, - }, - { - caseDesc: "no request or artifact specified", - expectParseSuccess: true, - expectValidateSuccess: false, - expectRequestSuccess: false, - }, - } - - for _, tc := range tests { - var blankCmd = &cobra.Command{} - if err := addTimestampFlags(blankCmd); err != nil { - t.Fatalf("unexpected error adding flags in '%v': %v", tc.caseDesc, err) - } - - args := []string{} - - if tc.artifact != "" { - args = append(args, "--artifact", tc.artifact) - } - if tc.artifactHash != "" { - args = append(args, "--artifact-hash", tc.artifactHash) - } - if tc.oid != "" { - args = append(args, "--tsa-policy", tc.oid) - } - if err := blankCmd.ParseFlags(args); (err == nil) != tc.expectParseSuccess { - t.Errorf("unexpected result parsing '%v': %v", tc.caseDesc, err) - continue - } - - if err := viper.BindPFlags(blankCmd.Flags()); err != nil { - t.Fatalf("unexpected result initializing viper in '%v': %v", tc.caseDesc, err) - } - if err := validateTimestampFlags(); (err == nil) != tc.expectValidateSuccess { - t.Errorf("unexpected result validating '%v': %v", tc.caseDesc, err) - continue - } - if _, err := createRequestFromFlags(); (err == nil) != tc.expectRequestSuccess { - t.Errorf("unexpected result creating timestamp request '%v': %v", tc.caseDesc, err) - continue - } - } -} diff --git a/cmd/rekor-server/app/root.go b/cmd/rekor-server/app/root.go index a354cb930..579bd2544 100644 --- a/cmd/rekor-server/app/root.go +++ b/cmd/rekor-server/app/root.go @@ -69,7 +69,6 @@ func init() { rootCmd.PersistentFlags().String("rekor_server.hostname", "rekor.sigstore.dev", "public hostname of instance") rootCmd.PersistentFlags().String("rekor_server.address", "127.0.0.1", "Address to bind to") rootCmd.PersistentFlags().String("rekor_server.signer", "memory", "Rekor signer to use. Current valid options include: [gcpkms, memory]") - rootCmd.PersistentFlags().String("rekor_server.timestamp_chain", "", "PEM encoded cert chain signing authorizing the signer to be a CA to sign a timestamping cert") rootCmd.PersistentFlags().Uint16("port", 3000, "Port to bind to") diff --git a/openapi.yaml b/openapi.yaml index b596fb6c2..578579869 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -250,66 +250,6 @@ paths: default: $ref: '#/responses/InternalServerError' - /api/v1/timestamp: - post: - summary: Generates a new timestamp response and creates a new log entry for the timestamp in the transparency log - operationId: getTimestampResponse - tags: - - timestamp - consumes: - - application/timestamp-query - produces: - - application/timestamp-reply - parameters: - - in: body - name: request - required: true - schema: - type: string - format: binary - responses: - 201: - description: Returns a timestamp response and the location of the log entry in the transprency log - schema: - type: string - format: binary - headers: - ETag: - type: string - description: UUID of the log entry made for the timestamp response - Location: - type: string - description: URI location of the log entry made for the timestamp response - format: uri - Index: - type: integer - description: Log index of the log entry made for the timestamp response - 400: - $ref: '#/responses/BadContent' - 501: - $ref: '#/responses/NotImplemented' - default: - $ref: '#/responses/InternalServerError' - - /api/v1/timestamp/certchain: - get: - summary: Retrieve the certfiicate chain for timestamping that can be used to validate trusted timestamps - description: Returns the certfiicate chain for timestamping that can be used to validate trusted timestamps - operationId: getTimestampCertChain - tags: - - timestamp - produces: - - application/pem-certificate-chain - responses: - 200: - description: The PEM encoded cert chain - schema: - type: string - 404: - $ref: '#/responses/NotFound' - default: - $ref: '#/responses/InternalServerError' - definitions: ProposedEntry: type: object @@ -699,8 +639,6 @@ responses: format: uri NotFound: description: The content requested could not be found - NotImplemented: - description: The content requested is not implemented InternalServerError: description: There was an internal error in the server while processing the request schema: diff --git a/pkg/api/api.go b/pkg/api/api.go index 537a9a0f3..cbfc77ab3 100644 --- a/pkg/api/api.go +++ b/pkg/api/api.go @@ -19,7 +19,6 @@ import ( "context" "crypto/sha256" "crypto/x509" - "encoding/base64" "encoding/hex" "fmt" "time" @@ -32,7 +31,6 @@ import ( "google.golang.org/grpc/credentials/insecure" "github.com/sigstore/rekor/pkg/log" - pki "github.com/sigstore/rekor/pkg/pki/x509" "github.com/sigstore/rekor/pkg/sharding" "github.com/sigstore/rekor/pkg/signer" "github.com/sigstore/rekor/pkg/storage" @@ -55,15 +53,12 @@ func dial(ctx context.Context, rpcServer string) (*grpc.ClientConn, error) { } type API struct { - logClient trillian.TrillianLogClient - logID int64 - logRanges sharding.LogRanges - pubkey string // PEM encoded public key - pubkeyHash string // SHA256 hash of DER-encoded public key - signer signature.Signer - tsaSigner signature.Signer // the signer to use for timestamping - certChain []*x509.Certificate // timestamping cert chain - certChainPem string // PEM encoded timestamping cert chain + logClient trillian.TrillianLogClient + logID int64 + logRanges sharding.LogRanges + pubkey string // PEM encoded public key + pubkeyHash string // SHA256 hash of DER-encoded public key + signer signature.Signer } func NewAPI(treeID uint) (*API, error) { @@ -112,38 +107,6 @@ func NewAPI(treeID uint) (*API, error) { pubkey := cryptoutils.PEMEncode(cryptoutils.PublicKeyPEMType, b) - // Use an in-memory key for timestamping - tsaSigner, err := signer.New(ctx, signer.MemoryScheme) - if err != nil { - return nil, errors.Wrap(err, "getting new tsa signer") - } - tsaPk, err := tsaSigner.PublicKey(options.WithContext(ctx)) - if err != nil { - return nil, errors.Wrap(err, "getting public key") - } - - var certChain []*x509.Certificate - b64CertChainStr := viper.GetString("rekor_server.timestamp_chain") - if b64CertChainStr != "" { - certChainStr, err := base64.StdEncoding.DecodeString(b64CertChainStr) - if err != nil { - return nil, errors.Wrap(err, "decoding timestamping cert") - } - if certChain, err = pki.ParseTimestampCertChain([]byte(certChainStr)); err != nil { - return nil, errors.Wrap(err, "parsing timestamp cert chain") - } - } - - // Generate a tsa certificate from the rekor signer and provided certificate chain - certChain, err = signer.NewTimestampingCertWithChain(ctx, tsaPk, rekorSigner, certChain) - if err != nil { - return nil, errors.Wrap(err, "generating timestamping cert chain") - } - certChainPem, err := pki.CertChainToPEM(certChain) - if err != nil { - return nil, errors.Wrap(err, "timestamping cert chain") - } - return &API{ // Transparency Log Stuff logClient: logClient, @@ -153,10 +116,6 @@ func NewAPI(treeID uint) (*API, error) { pubkey: string(pubkey), pubkeyHash: hex.EncodeToString(pubkeyHashBytes[:]), signer: rekorSigner, - // TSA signing stuff - tsaSigner: tsaSigner, - certChain: certChain, - certChainPem: string(certChainPem), }, nil } diff --git a/pkg/api/error.go b/pkg/api/error.go index b2a05c086..5fc6f2aeb 100644 --- a/pkg/api/error.go +++ b/pkg/api/error.go @@ -28,7 +28,6 @@ import ( "github.com/sigstore/rekor/pkg/generated/restapi/operations/entries" "github.com/sigstore/rekor/pkg/generated/restapi/operations/index" "github.com/sigstore/rekor/pkg/generated/restapi/operations/pubkey" - "github.com/sigstore/rekor/pkg/generated/restapi/operations/timestamp" "github.com/sigstore/rekor/pkg/generated/restapi/operations/tlog" "github.com/sigstore/rekor/pkg/log" ) @@ -147,24 +146,6 @@ func handleRekorAPIError(params interface{}, code int, err error, message string default: return index.NewSearchIndexDefault(code).WithPayload(errorMsg(message, code)) } - case timestamp.GetTimestampResponseParams: - logMsg(params.HTTPRequest) - switch code { - case http.StatusBadRequest: - return timestamp.NewGetTimestampResponseBadRequest().WithPayload(errorMsg(message, code)) - case http.StatusNotImplemented: - return timestamp.NewGetTimestampResponseNotImplemented() - default: - return timestamp.NewGetTimestampResponseDefault(code).WithPayload(errorMsg(message, code)) - } - case timestamp.GetTimestampCertChainParams: - logMsg(params.HTTPRequest) - switch code { - case http.StatusNotFound: - return timestamp.NewGetTimestampCertChainNotFound() - default: - return timestamp.NewGetTimestampCertChainDefault(code).WithPayload(errorMsg(message, code)) - } default: log.Logger.Errorf("unable to find method for type %T; error: %v", params, err) return middleware.Error(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) diff --git a/pkg/api/timestamp.go b/pkg/api/timestamp.go deleted file mode 100644 index 20f020940..000000000 --- a/pkg/api/timestamp.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright The Rekor 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 api - -import ( - "bytes" - "context" - "encoding/asn1" - "io/ioutil" - "net/http" - - "github.com/go-openapi/runtime/middleware" - "github.com/sassoftware/relic/lib/pkcs9" - "github.com/sigstore/rekor/pkg/generated/restapi/operations/entries" - "github.com/sigstore/rekor/pkg/generated/restapi/operations/timestamp" - rfc3161_v001 "github.com/sigstore/rekor/pkg/types/rfc3161/v0.0.1" - "github.com/sigstore/rekor/pkg/util" -) - -func RequestFromRekor(ctx context.Context, req pkcs9.TimeStampReq) ([]byte, error) { - resp, err := util.CreateRfc3161Response(ctx, req, api.certChain, api.tsaSigner) - if err != nil { - return nil, err - } - - body, err := asn1.Marshal(*resp) - if err != nil { - return nil, err - } - - return body, nil -} - -func TimestampResponseHandler(params timestamp.GetTimestampResponseParams) middleware.Responder { - // TODO: Add support for in-house JSON based timestamp response. - requestBytes, err := ioutil.ReadAll(params.Request) - if err != nil { - return handleRekorAPIError(params, http.StatusBadRequest, err, failedToGenerateTimestampResponse) - } - req, err := util.ParseTimestampRequest(requestBytes) - if err != nil { - return handleRekorAPIError(params, http.StatusBadRequest, err, failedToGenerateTimestampResponse) - } - - // Create response - httpReq := params.HTTPRequest - ctx := httpReq.Context() - resp, err := RequestFromRekor(ctx, *req) - if err != nil { - return handleRekorAPIError(params, http.StatusInternalServerError, err, failedToGenerateTimestampResponse) - } - - // Upload to transparency log and add entry UUID to location header. - cleReq := *httpReq - cleURL := entries.CreateLogEntryURL{} - cleReq.URL = cleURL.Must(cleURL.Build()) - entryParams := entries.CreateLogEntryParams{ - HTTPRequest: &cleReq, - ProposedEntry: rfc3161_v001.NewEntryFromBytes(resp), - } - - // If middleware is returned, this indicates an error. - logEntry, middleware := createLogEntry(entryParams) - if middleware != nil { - return middleware - } - - var uuid string - var newIndex int64 - for location, entry := range logEntry { - uuid = location - newIndex = *entry.LogIndex - } - - return timestamp.NewGetTimestampResponseCreated().WithPayload(ioutil.NopCloser(bytes.NewReader(resp))).WithLocation(getEntryURL(*cleReq.URL, uuid)).WithETag(uuid).WithIndex(newIndex) -} - -func GetTimestampCertChainHandler(params timestamp.GetTimestampCertChainParams) middleware.Responder { - return timestamp.NewGetTimestampCertChainOK().WithPayload(api.certChainPem) -} diff --git a/pkg/generated/client/rekor_client.go b/pkg/generated/client/rekor_client.go index d2b1cbc90..7cfeaec77 100644 --- a/pkg/generated/client/rekor_client.go +++ b/pkg/generated/client/rekor_client.go @@ -30,7 +30,6 @@ import ( "github.com/sigstore/rekor/pkg/generated/client/index" "github.com/sigstore/rekor/pkg/generated/client/pubkey" serverops "github.com/sigstore/rekor/pkg/generated/client/server" - "github.com/sigstore/rekor/pkg/generated/client/timestamp" "github.com/sigstore/rekor/pkg/generated/client/tlog" ) @@ -80,7 +79,6 @@ func New(transport runtime.ClientTransport, formats strfmt.Registry) *Rekor { cli.Index = index.New(transport, formats) cli.Pubkey = pubkey.New(transport, formats) cli.Server = serverops.New(transport, formats) - cli.Timestamp = timestamp.New(transport, formats) cli.Tlog = tlog.New(transport, formats) return cli } @@ -134,8 +132,6 @@ type Rekor struct { Server serverops.ClientService - Timestamp timestamp.ClientService - Tlog tlog.ClientService Transport runtime.ClientTransport @@ -148,6 +144,5 @@ func (c *Rekor) SetTransport(transport runtime.ClientTransport) { c.Index.SetTransport(transport) c.Pubkey.SetTransport(transport) c.Server.SetTransport(transport) - c.Timestamp.SetTransport(transport) c.Tlog.SetTransport(transport) } diff --git a/pkg/generated/client/timestamp/get_timestamp_cert_chain_parameters.go b/pkg/generated/client/timestamp/get_timestamp_cert_chain_parameters.go deleted file mode 100644 index 5fee86598..000000000 --- a/pkg/generated/client/timestamp/get_timestamp_cert_chain_parameters.go +++ /dev/null @@ -1,142 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewGetTimestampCertChainParams creates a new GetTimestampCertChainParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewGetTimestampCertChainParams() *GetTimestampCertChainParams { - return &GetTimestampCertChainParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewGetTimestampCertChainParamsWithTimeout creates a new GetTimestampCertChainParams object -// with the ability to set a timeout on a request. -func NewGetTimestampCertChainParamsWithTimeout(timeout time.Duration) *GetTimestampCertChainParams { - return &GetTimestampCertChainParams{ - timeout: timeout, - } -} - -// NewGetTimestampCertChainParamsWithContext creates a new GetTimestampCertChainParams object -// with the ability to set a context for a request. -func NewGetTimestampCertChainParamsWithContext(ctx context.Context) *GetTimestampCertChainParams { - return &GetTimestampCertChainParams{ - Context: ctx, - } -} - -// NewGetTimestampCertChainParamsWithHTTPClient creates a new GetTimestampCertChainParams object -// with the ability to set a custom HTTPClient for a request. -func NewGetTimestampCertChainParamsWithHTTPClient(client *http.Client) *GetTimestampCertChainParams { - return &GetTimestampCertChainParams{ - HTTPClient: client, - } -} - -/* GetTimestampCertChainParams contains all the parameters to send to the API endpoint - for the get timestamp cert chain operation. - - Typically these are written to a http.Request. -*/ -type GetTimestampCertChainParams struct { - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the get timestamp cert chain params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetTimestampCertChainParams) WithDefaults() *GetTimestampCertChainParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the get timestamp cert chain params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetTimestampCertChainParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the get timestamp cert chain params -func (o *GetTimestampCertChainParams) WithTimeout(timeout time.Duration) *GetTimestampCertChainParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get timestamp cert chain params -func (o *GetTimestampCertChainParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get timestamp cert chain params -func (o *GetTimestampCertChainParams) WithContext(ctx context.Context) *GetTimestampCertChainParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get timestamp cert chain params -func (o *GetTimestampCertChainParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get timestamp cert chain params -func (o *GetTimestampCertChainParams) WithHTTPClient(client *http.Client) *GetTimestampCertChainParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get timestamp cert chain params -func (o *GetTimestampCertChainParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WriteToRequest writes these params to a swagger request -func (o *GetTimestampCertChainParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/pkg/generated/client/timestamp/get_timestamp_cert_chain_responses.go b/pkg/generated/client/timestamp/get_timestamp_cert_chain_responses.go deleted file mode 100644 index 34bbf5284..000000000 --- a/pkg/generated/client/timestamp/get_timestamp_cert_chain_responses.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - - "github.com/sigstore/rekor/pkg/generated/models" -) - -// GetTimestampCertChainReader is a Reader for the GetTimestampCertChain structure. -type GetTimestampCertChainReader struct { - formats strfmt.Registry -} - -// ReadResponse reads a server response into the received o. -func (o *GetTimestampCertChainReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 200: - result := NewGetTimestampCertChainOK() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 404: - result := NewGetTimestampCertChainNotFound() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewGetTimestampCertChainDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetTimestampCertChainOK creates a GetTimestampCertChainOK with default headers values -func NewGetTimestampCertChainOK() *GetTimestampCertChainOK { - return &GetTimestampCertChainOK{} -} - -/* GetTimestampCertChainOK describes a response with status code 200, with default header values. - -The PEM encoded cert chain -*/ -type GetTimestampCertChainOK struct { - Payload string -} - -func (o *GetTimestampCertChainOK) Error() string { - return fmt.Sprintf("[GET /api/v1/timestamp/certchain][%d] getTimestampCertChainOK %+v", 200, o.Payload) -} -func (o *GetTimestampCertChainOK) GetPayload() string { - return o.Payload -} - -func (o *GetTimestampCertChainOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - // response payload - if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetTimestampCertChainNotFound creates a GetTimestampCertChainNotFound with default headers values -func NewGetTimestampCertChainNotFound() *GetTimestampCertChainNotFound { - return &GetTimestampCertChainNotFound{} -} - -/* GetTimestampCertChainNotFound describes a response with status code 404, with default header values. - -The content requested could not be found -*/ -type GetTimestampCertChainNotFound struct { -} - -func (o *GetTimestampCertChainNotFound) Error() string { - return fmt.Sprintf("[GET /api/v1/timestamp/certchain][%d] getTimestampCertChainNotFound ", 404) -} - -func (o *GetTimestampCertChainNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} - -// NewGetTimestampCertChainDefault creates a GetTimestampCertChainDefault with default headers values -func NewGetTimestampCertChainDefault(code int) *GetTimestampCertChainDefault { - return &GetTimestampCertChainDefault{ - _statusCode: code, - } -} - -/* GetTimestampCertChainDefault describes a response with status code -1, with default header values. - -There was an internal error in the server while processing the request -*/ -type GetTimestampCertChainDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the get timestamp cert chain default response -func (o *GetTimestampCertChainDefault) Code() int { - return o._statusCode -} - -func (o *GetTimestampCertChainDefault) Error() string { - return fmt.Sprintf("[GET /api/v1/timestamp/certchain][%d] getTimestampCertChain default %+v", o._statusCode, o.Payload) -} -func (o *GetTimestampCertChainDefault) GetPayload() *models.Error { - return o.Payload -} - -func (o *GetTimestampCertChainDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/pkg/generated/client/timestamp/get_timestamp_response_parameters.go b/pkg/generated/client/timestamp/get_timestamp_response_parameters.go deleted file mode 100644 index 896564766..000000000 --- a/pkg/generated/client/timestamp/get_timestamp_response_parameters.go +++ /dev/null @@ -1,165 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "context" - "io" - "net/http" - "time" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - cr "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" -) - -// NewGetTimestampResponseParams creates a new GetTimestampResponseParams object, -// with the default timeout for this client. -// -// Default values are not hydrated, since defaults are normally applied by the API server side. -// -// To enforce default values in parameter, use SetDefaults or WithDefaults. -func NewGetTimestampResponseParams() *GetTimestampResponseParams { - return &GetTimestampResponseParams{ - timeout: cr.DefaultTimeout, - } -} - -// NewGetTimestampResponseParamsWithTimeout creates a new GetTimestampResponseParams object -// with the ability to set a timeout on a request. -func NewGetTimestampResponseParamsWithTimeout(timeout time.Duration) *GetTimestampResponseParams { - return &GetTimestampResponseParams{ - timeout: timeout, - } -} - -// NewGetTimestampResponseParamsWithContext creates a new GetTimestampResponseParams object -// with the ability to set a context for a request. -func NewGetTimestampResponseParamsWithContext(ctx context.Context) *GetTimestampResponseParams { - return &GetTimestampResponseParams{ - Context: ctx, - } -} - -// NewGetTimestampResponseParamsWithHTTPClient creates a new GetTimestampResponseParams object -// with the ability to set a custom HTTPClient for a request. -func NewGetTimestampResponseParamsWithHTTPClient(client *http.Client) *GetTimestampResponseParams { - return &GetTimestampResponseParams{ - HTTPClient: client, - } -} - -/* GetTimestampResponseParams contains all the parameters to send to the API endpoint - for the get timestamp response operation. - - Typically these are written to a http.Request. -*/ -type GetTimestampResponseParams struct { - - // Request. - // - // Format: binary - Request io.ReadCloser - - timeout time.Duration - Context context.Context - HTTPClient *http.Client -} - -// WithDefaults hydrates default values in the get timestamp response params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetTimestampResponseParams) WithDefaults() *GetTimestampResponseParams { - o.SetDefaults() - return o -} - -// SetDefaults hydrates default values in the get timestamp response params (not the query body). -// -// All values with no default are reset to their zero value. -func (o *GetTimestampResponseParams) SetDefaults() { - // no default values defined for this parameter -} - -// WithTimeout adds the timeout to the get timestamp response params -func (o *GetTimestampResponseParams) WithTimeout(timeout time.Duration) *GetTimestampResponseParams { - o.SetTimeout(timeout) - return o -} - -// SetTimeout adds the timeout to the get timestamp response params -func (o *GetTimestampResponseParams) SetTimeout(timeout time.Duration) { - o.timeout = timeout -} - -// WithContext adds the context to the get timestamp response params -func (o *GetTimestampResponseParams) WithContext(ctx context.Context) *GetTimestampResponseParams { - o.SetContext(ctx) - return o -} - -// SetContext adds the context to the get timestamp response params -func (o *GetTimestampResponseParams) SetContext(ctx context.Context) { - o.Context = ctx -} - -// WithHTTPClient adds the HTTPClient to the get timestamp response params -func (o *GetTimestampResponseParams) WithHTTPClient(client *http.Client) *GetTimestampResponseParams { - o.SetHTTPClient(client) - return o -} - -// SetHTTPClient adds the HTTPClient to the get timestamp response params -func (o *GetTimestampResponseParams) SetHTTPClient(client *http.Client) { - o.HTTPClient = client -} - -// WithRequest adds the request to the get timestamp response params -func (o *GetTimestampResponseParams) WithRequest(request io.ReadCloser) *GetTimestampResponseParams { - o.SetRequest(request) - return o -} - -// SetRequest adds the request to the get timestamp response params -func (o *GetTimestampResponseParams) SetRequest(request io.ReadCloser) { - o.Request = request -} - -// WriteToRequest writes these params to a swagger request -func (o *GetTimestampResponseParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { - - if err := r.SetTimeout(o.timeout); err != nil { - return err - } - var res []error - if o.Request != nil { - if err := r.SetBodyParam(o.Request); err != nil { - return err - } - } - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/pkg/generated/client/timestamp/get_timestamp_response_responses.go b/pkg/generated/client/timestamp/get_timestamp_response_responses.go deleted file mode 100644 index 894570fa8..000000000 --- a/pkg/generated/client/timestamp/get_timestamp_response_responses.go +++ /dev/null @@ -1,244 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "fmt" - "io" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - - "github.com/sigstore/rekor/pkg/generated/models" -) - -// GetTimestampResponseReader is a Reader for the GetTimestampResponse structure. -type GetTimestampResponseReader struct { - formats strfmt.Registry - writer io.Writer -} - -// ReadResponse reads a server response into the received o. -func (o *GetTimestampResponseReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { - switch response.Code() { - case 201: - result := NewGetTimestampResponseCreated(o.writer) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return result, nil - case 400: - result := NewGetTimestampResponseBadRequest() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - case 501: - result := NewGetTimestampResponseNotImplemented() - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - return nil, result - default: - result := NewGetTimestampResponseDefault(response.Code()) - if err := result.readResponse(response, consumer, o.formats); err != nil { - return nil, err - } - if response.Code()/100 == 2 { - return result, nil - } - return nil, result - } -} - -// NewGetTimestampResponseCreated creates a GetTimestampResponseCreated with default headers values -func NewGetTimestampResponseCreated(writer io.Writer) *GetTimestampResponseCreated { - return &GetTimestampResponseCreated{ - - Payload: writer, - } -} - -/* GetTimestampResponseCreated describes a response with status code 201, with default header values. - -Returns a timestamp response and the location of the log entry in the transprency log -*/ -type GetTimestampResponseCreated struct { - - /* UUID of the log entry made for the timestamp response - */ - ETag string - - /* Log index of the log entry made for the timestamp response - */ - Index int64 - - /* URI location of the log entry made for the timestamp response - - Format: uri - */ - Location strfmt.URI - - Payload io.Writer -} - -func (o *GetTimestampResponseCreated) Error() string { - return fmt.Sprintf("[POST /api/v1/timestamp][%d] getTimestampResponseCreated %+v", 201, o.Payload) -} -func (o *GetTimestampResponseCreated) GetPayload() io.Writer { - return o.Payload -} - -func (o *GetTimestampResponseCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - // hydrates response header ETag - hdrETag := response.GetHeader("ETag") - - if hdrETag != "" { - o.ETag = hdrETag - } - - // hydrates response header Index - hdrIndex := response.GetHeader("Index") - - if hdrIndex != "" { - valindex, err := swag.ConvertInt64(hdrIndex) - if err != nil { - return errors.InvalidType("Index", "header", "int64", hdrIndex) - } - o.Index = valindex - } - - // hydrates response header Location - hdrLocation := response.GetHeader("Location") - - if hdrLocation != "" { - vallocation, err := formats.Parse("uri", hdrLocation) - if err != nil { - return errors.InvalidType("Location", "header", "strfmt.URI", hdrLocation) - } - o.Location = *(vallocation.(*strfmt.URI)) - } - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetTimestampResponseBadRequest creates a GetTimestampResponseBadRequest with default headers values -func NewGetTimestampResponseBadRequest() *GetTimestampResponseBadRequest { - return &GetTimestampResponseBadRequest{} -} - -/* GetTimestampResponseBadRequest describes a response with status code 400, with default header values. - -The content supplied to the server was invalid -*/ -type GetTimestampResponseBadRequest struct { - Payload *models.Error -} - -func (o *GetTimestampResponseBadRequest) Error() string { - return fmt.Sprintf("[POST /api/v1/timestamp][%d] getTimestampResponseBadRequest %+v", 400, o.Payload) -} -func (o *GetTimestampResponseBadRequest) GetPayload() *models.Error { - return o.Payload -} - -func (o *GetTimestampResponseBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} - -// NewGetTimestampResponseNotImplemented creates a GetTimestampResponseNotImplemented with default headers values -func NewGetTimestampResponseNotImplemented() *GetTimestampResponseNotImplemented { - return &GetTimestampResponseNotImplemented{} -} - -/* GetTimestampResponseNotImplemented describes a response with status code 501, with default header values. - -The content requested is not implemented -*/ -type GetTimestampResponseNotImplemented struct { -} - -func (o *GetTimestampResponseNotImplemented) Error() string { - return fmt.Sprintf("[POST /api/v1/timestamp][%d] getTimestampResponseNotImplemented ", 501) -} - -func (o *GetTimestampResponseNotImplemented) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - return nil -} - -// NewGetTimestampResponseDefault creates a GetTimestampResponseDefault with default headers values -func NewGetTimestampResponseDefault(code int) *GetTimestampResponseDefault { - return &GetTimestampResponseDefault{ - _statusCode: code, - } -} - -/* GetTimestampResponseDefault describes a response with status code -1, with default header values. - -There was an internal error in the server while processing the request -*/ -type GetTimestampResponseDefault struct { - _statusCode int - - Payload *models.Error -} - -// Code gets the status code for the get timestamp response default response -func (o *GetTimestampResponseDefault) Code() int { - return o._statusCode -} - -func (o *GetTimestampResponseDefault) Error() string { - return fmt.Sprintf("[POST /api/v1/timestamp][%d] getTimestampResponse default %+v", o._statusCode, o.Payload) -} -func (o *GetTimestampResponseDefault) GetPayload() *models.Error { - return o.Payload -} - -func (o *GetTimestampResponseDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { - - o.Payload = new(models.Error) - - // response payload - if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { - return err - } - - return nil -} diff --git a/pkg/generated/client/timestamp/timestamp_client.go b/pkg/generated/client/timestamp/timestamp_client.go deleted file mode 100644 index 6e098768e..000000000 --- a/pkg/generated/client/timestamp/timestamp_client.go +++ /dev/null @@ -1,135 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" -) - -// New creates a new timestamp API client. -func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { - return &Client{transport: transport, formats: formats} -} - -/* -Client for timestamp API -*/ -type Client struct { - transport runtime.ClientTransport - formats strfmt.Registry -} - -// ClientOption is the option for Client methods -type ClientOption func(*runtime.ClientOperation) - -// ClientService is the interface for Client methods -type ClientService interface { - GetTimestampCertChain(params *GetTimestampCertChainParams, opts ...ClientOption) (*GetTimestampCertChainOK, error) - - GetTimestampResponse(params *GetTimestampResponseParams, writer io.Writer, opts ...ClientOption) (*GetTimestampResponseCreated, error) - - SetTransport(transport runtime.ClientTransport) -} - -/* - GetTimestampCertChain retrieves the certfiicate chain for timestamping that can be used to validate trusted timestamps - - Returns the certfiicate chain for timestamping that can be used to validate trusted timestamps -*/ -func (a *Client) GetTimestampCertChain(params *GetTimestampCertChainParams, opts ...ClientOption) (*GetTimestampCertChainOK, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetTimestampCertChainParams() - } - op := &runtime.ClientOperation{ - ID: "getTimestampCertChain", - Method: "GET", - PathPattern: "/api/v1/timestamp/certchain", - ProducesMediaTypes: []string{"application/pem-certificate-chain"}, - ConsumesMediaTypes: []string{"application/json", "application/yaml"}, - Schemes: []string{"http"}, - Params: params, - Reader: &GetTimestampCertChainReader{formats: a.formats}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*GetTimestampCertChainOK) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*GetTimestampCertChainDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -/* - GetTimestampResponse generates a new timestamp response and creates a new log entry for the timestamp in the transparency log -*/ -func (a *Client) GetTimestampResponse(params *GetTimestampResponseParams, writer io.Writer, opts ...ClientOption) (*GetTimestampResponseCreated, error) { - // TODO: Validate the params before sending - if params == nil { - params = NewGetTimestampResponseParams() - } - op := &runtime.ClientOperation{ - ID: "getTimestampResponse", - Method: "POST", - PathPattern: "/api/v1/timestamp", - ProducesMediaTypes: []string{"application/timestamp-reply"}, - ConsumesMediaTypes: []string{"application/timestamp-query"}, - Schemes: []string{"http"}, - Params: params, - Reader: &GetTimestampResponseReader{formats: a.formats, writer: writer}, - Context: params.Context, - Client: params.HTTPClient, - } - for _, opt := range opts { - opt(op) - } - - result, err := a.transport.Submit(op) - if err != nil { - return nil, err - } - success, ok := result.(*GetTimestampResponseCreated) - if ok { - return success, nil - } - // unexpected success response - unexpectedSuccess := result.(*GetTimestampResponseDefault) - return nil, runtime.NewAPIError("unexpected success response: content available as default response in error", unexpectedSuccess, unexpectedSuccess.Code()) -} - -// SetTransport changes the transport on the client -func (a *Client) SetTransport(transport runtime.ClientTransport) { - a.transport = transport -} diff --git a/pkg/generated/restapi/configure_rekor_server.go b/pkg/generated/restapi/configure_rekor_server.go index f41b7cdf7..49ab7e02f 100644 --- a/pkg/generated/restapi/configure_rekor_server.go +++ b/pkg/generated/restapi/configure_rekor_server.go @@ -40,7 +40,6 @@ import ( "github.com/sigstore/rekor/pkg/generated/restapi/operations/index" "github.com/sigstore/rekor/pkg/generated/restapi/operations/pubkey" "github.com/sigstore/rekor/pkg/generated/restapi/operations/server" - "github.com/sigstore/rekor/pkg/generated/restapi/operations/timestamp" "github.com/sigstore/rekor/pkg/generated/restapi/operations/tlog" "github.com/sigstore/rekor/pkg/log" "github.com/sigstore/rekor/pkg/util" @@ -76,9 +75,6 @@ func configureAPI(api *operations.RekorServerAPI) http.Handler { api.YamlProducer = client.YamlProducer() api.ApplicationXPemFileProducer = runtime.TextProducer() - api.ApplicationPemCertificateChainProducer = runtime.TextProducer() - api.ApplicationTimestampQueryConsumer = runtime.ByteStreamConsumer() - api.ApplicationTimestampReplyProducer = runtime.ByteStreamProducer() api.EntriesCreateLogEntryHandler = entries.CreateLogEntryHandlerFunc(pkgapi.CreateLogEntryHandler) api.EntriesGetLogEntryByIndexHandler = entries.GetLogEntryByIndexHandlerFunc(pkgapi.GetLogEntryByIndexHandler) @@ -98,9 +94,6 @@ func configureAPI(api *operations.RekorServerAPI) http.Handler { api.IndexSearchIndexHandler = index.SearchIndexHandlerFunc(pkgapi.SearchIndexNotImplementedHandler) } - api.TimestampGetTimestampResponseHandler = timestamp.GetTimestampResponseHandlerFunc(pkgapi.TimestampResponseHandler) - api.TimestampGetTimestampCertChainHandler = timestamp.GetTimestampCertChainHandlerFunc(pkgapi.GetTimestampCertChainHandler) - api.RegisterFormat("signedCheckpoint", &util.SignedNote{}, util.SignedCheckpointValidator) api.PreServerShutdown = func() {} diff --git a/pkg/generated/restapi/doc.go b/pkg/generated/restapi/doc.go index 8c81a2acf..b2462c637 100644 --- a/pkg/generated/restapi/doc.go +++ b/pkg/generated/restapi/doc.go @@ -25,13 +25,10 @@ // Version: 0.0.1 // // Consumes: -// - application/timestamp-query // - application/json // - application/yaml // // Produces: -// - application/pem-certificate-chain -// - application/timestamp-reply // - application/x-pem-file // - application/json // - application/yaml diff --git a/pkg/generated/restapi/operations/rekor_server_api.go b/pkg/generated/restapi/operations/rekor_server_api.go index 22331105a..9be6e2458 100644 --- a/pkg/generated/restapi/operations/rekor_server_api.go +++ b/pkg/generated/restapi/operations/rekor_server_api.go @@ -41,7 +41,6 @@ import ( "github.com/sigstore/rekor/pkg/generated/restapi/operations/index" "github.com/sigstore/rekor/pkg/generated/restapi/operations/pubkey" serverops "github.com/sigstore/rekor/pkg/generated/restapi/operations/server" - "github.com/sigstore/rekor/pkg/generated/restapi/operations/timestamp" "github.com/sigstore/rekor/pkg/generated/restapi/operations/tlog" ) @@ -63,18 +62,9 @@ func NewRekorServerAPI(spec *loads.Document) *RekorServerAPI { APIKeyAuthenticator: security.APIKeyAuth, BearerAuthenticator: security.BearerAuth, - ApplicationTimestampQueryConsumer: runtime.ConsumerFunc(func(r io.Reader, target interface{}) error { - return errors.NotImplemented("applicationTimestampQuery consumer has not yet been implemented") - }), JSONConsumer: runtime.JSONConsumer(), YamlConsumer: yamlpc.YAMLConsumer(), - ApplicationPemCertificateChainProducer: runtime.ProducerFunc(func(w io.Writer, data interface{}) error { - return errors.NotImplemented("applicationPemCertificateChain producer has not yet been implemented") - }), - ApplicationTimestampReplyProducer: runtime.ProducerFunc(func(w io.Writer, data interface{}) error { - return errors.NotImplemented("applicationTimestampReply producer has not yet been implemented") - }), ApplicationXPemFileProducer: runtime.ProducerFunc(func(w io.Writer, data interface{}) error { return errors.NotImplemented("applicationXPemFile producer has not yet been implemented") }), @@ -102,12 +92,6 @@ func NewRekorServerAPI(spec *loads.Document) *RekorServerAPI { ServerGetRekorVersionHandler: serverops.GetRekorVersionHandlerFunc(func(params serverops.GetRekorVersionParams) middleware.Responder { return middleware.NotImplemented("operation server.GetRekorVersion has not yet been implemented") }), - TimestampGetTimestampCertChainHandler: timestamp.GetTimestampCertChainHandlerFunc(func(params timestamp.GetTimestampCertChainParams) middleware.Responder { - return middleware.NotImplemented("operation timestamp.GetTimestampCertChain has not yet been implemented") - }), - TimestampGetTimestampResponseHandler: timestamp.GetTimestampResponseHandlerFunc(func(params timestamp.GetTimestampResponseParams) middleware.Responder { - return middleware.NotImplemented("operation timestamp.GetTimestampResponse has not yet been implemented") - }), IndexSearchIndexHandler: index.SearchIndexHandlerFunc(func(params index.SearchIndexParams) middleware.Responder { return middleware.NotImplemented("operation index.SearchIndex has not yet been implemented") }), @@ -142,9 +126,6 @@ type RekorServerAPI struct { // It has a default implementation in the security package, however you can replace it for your particular usage. BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator - // ApplicationTimestampQueryConsumer registers a consumer for the following mime types: - // - application/timestamp-query - ApplicationTimestampQueryConsumer runtime.Consumer // JSONConsumer registers a consumer for the following mime types: // - application/json JSONConsumer runtime.Consumer @@ -152,12 +133,6 @@ type RekorServerAPI struct { // - application/yaml YamlConsumer runtime.Consumer - // ApplicationPemCertificateChainProducer registers a producer for the following mime types: - // - application/pem-certificate-chain - ApplicationPemCertificateChainProducer runtime.Producer - // ApplicationTimestampReplyProducer registers a producer for the following mime types: - // - application/timestamp-reply - ApplicationTimestampReplyProducer runtime.Producer // ApplicationXPemFileProducer registers a producer for the following mime types: // - application/x-pem-file ApplicationXPemFileProducer runtime.Producer @@ -182,10 +157,6 @@ type RekorServerAPI struct { PubkeyGetPublicKeyHandler pubkey.GetPublicKeyHandler // ServerGetRekorVersionHandler sets the operation handler for the get rekor version operation ServerGetRekorVersionHandler serverops.GetRekorVersionHandler - // TimestampGetTimestampCertChainHandler sets the operation handler for the get timestamp cert chain operation - TimestampGetTimestampCertChainHandler timestamp.GetTimestampCertChainHandler - // TimestampGetTimestampResponseHandler sets the operation handler for the get timestamp response operation - TimestampGetTimestampResponseHandler timestamp.GetTimestampResponseHandler // IndexSearchIndexHandler sets the operation handler for the search index operation IndexSearchIndexHandler index.SearchIndexHandler // EntriesSearchLogQueryHandler sets the operation handler for the search log query operation @@ -259,9 +230,6 @@ func (o *RekorServerAPI) RegisterFormat(name string, format strfmt.Format, valid func (o *RekorServerAPI) Validate() error { var unregistered []string - if o.ApplicationTimestampQueryConsumer == nil { - unregistered = append(unregistered, "ApplicationTimestampQueryConsumer") - } if o.JSONConsumer == nil { unregistered = append(unregistered, "JSONConsumer") } @@ -269,12 +237,6 @@ func (o *RekorServerAPI) Validate() error { unregistered = append(unregistered, "YamlConsumer") } - if o.ApplicationPemCertificateChainProducer == nil { - unregistered = append(unregistered, "ApplicationPemCertificateChainProducer") - } - if o.ApplicationTimestampReplyProducer == nil { - unregistered = append(unregistered, "ApplicationTimestampReplyProducer") - } if o.ApplicationXPemFileProducer == nil { unregistered = append(unregistered, "ApplicationXPemFileProducer") } @@ -306,12 +268,6 @@ func (o *RekorServerAPI) Validate() error { if o.ServerGetRekorVersionHandler == nil { unregistered = append(unregistered, "server.GetRekorVersionHandler") } - if o.TimestampGetTimestampCertChainHandler == nil { - unregistered = append(unregistered, "timestamp.GetTimestampCertChainHandler") - } - if o.TimestampGetTimestampResponseHandler == nil { - unregistered = append(unregistered, "timestamp.GetTimestampResponseHandler") - } if o.IndexSearchIndexHandler == nil { unregistered = append(unregistered, "index.SearchIndexHandler") } @@ -347,8 +303,6 @@ func (o *RekorServerAPI) ConsumersFor(mediaTypes []string) map[string]runtime.Co result := make(map[string]runtime.Consumer, len(mediaTypes)) for _, mt := range mediaTypes { switch mt { - case "application/timestamp-query": - result["application/timestamp-query"] = o.ApplicationTimestampQueryConsumer case "application/json": result["application/json"] = o.JSONConsumer case "application/yaml": @@ -368,10 +322,6 @@ func (o *RekorServerAPI) ProducersFor(mediaTypes []string) map[string]runtime.Pr result := make(map[string]runtime.Producer, len(mediaTypes)) for _, mt := range mediaTypes { switch mt { - case "application/pem-certificate-chain": - result["application/pem-certificate-chain"] = o.ApplicationPemCertificateChainProducer - case "application/timestamp-reply": - result["application/timestamp-reply"] = o.ApplicationTimestampReplyProducer case "application/x-pem-file": result["application/x-pem-file"] = o.ApplicationXPemFileProducer case "application/json": @@ -446,14 +396,6 @@ func (o *RekorServerAPI) initHandlerCache() { o.handlers["GET"] = make(map[string]http.Handler) } o.handlers["GET"]["/api/v1/version"] = serverops.NewGetRekorVersion(o.context, o.ServerGetRekorVersionHandler) - if o.handlers["GET"] == nil { - o.handlers["GET"] = make(map[string]http.Handler) - } - o.handlers["GET"]["/api/v1/timestamp/certchain"] = timestamp.NewGetTimestampCertChain(o.context, o.TimestampGetTimestampCertChainHandler) - if o.handlers["POST"] == nil { - o.handlers["POST"] = make(map[string]http.Handler) - } - o.handlers["POST"]["/api/v1/timestamp"] = timestamp.NewGetTimestampResponse(o.context, o.TimestampGetTimestampResponseHandler) if o.handlers["POST"] == nil { o.handlers["POST"] = make(map[string]http.Handler) } diff --git a/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain.go b/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain.go deleted file mode 100644 index de58dd312..000000000 --- a/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain.go +++ /dev/null @@ -1,74 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetTimestampCertChainHandlerFunc turns a function with the right signature into a get timestamp cert chain handler -type GetTimestampCertChainHandlerFunc func(GetTimestampCertChainParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetTimestampCertChainHandlerFunc) Handle(params GetTimestampCertChainParams) middleware.Responder { - return fn(params) -} - -// GetTimestampCertChainHandler interface for that can handle valid get timestamp cert chain params -type GetTimestampCertChainHandler interface { - Handle(GetTimestampCertChainParams) middleware.Responder -} - -// NewGetTimestampCertChain creates a new http.Handler for the get timestamp cert chain operation -func NewGetTimestampCertChain(ctx *middleware.Context, handler GetTimestampCertChainHandler) *GetTimestampCertChain { - return &GetTimestampCertChain{Context: ctx, Handler: handler} -} - -/* GetTimestampCertChain swagger:route GET /api/v1/timestamp/certchain timestamp getTimestampCertChain - -Retrieve the certfiicate chain for timestamping that can be used to validate trusted timestamps - -Returns the certfiicate chain for timestamping that can be used to validate trusted timestamps - -*/ -type GetTimestampCertChain struct { - Context *middleware.Context - Handler GetTimestampCertChainHandler -} - -func (o *GetTimestampCertChain) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetTimestampCertChainParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_parameters.go b/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_parameters.go deleted file mode 100644 index e177de49a..000000000 --- a/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_parameters.go +++ /dev/null @@ -1,62 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime/middleware" -) - -// NewGetTimestampCertChainParams creates a new GetTimestampCertChainParams object -// -// There are no default values defined in the spec. -func NewGetTimestampCertChainParams() GetTimestampCertChainParams { - - return GetTimestampCertChainParams{} -} - -// GetTimestampCertChainParams contains all the bound params for the get timestamp cert chain operation -// typically these are obtained from a http.Request -// -// swagger:parameters getTimestampCertChain -type GetTimestampCertChainParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetTimestampCertChainParams() beforehand. -func (o *GetTimestampCertChainParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_responses.go b/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_responses.go deleted file mode 100644 index 6611894ca..000000000 --- a/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_responses.go +++ /dev/null @@ -1,154 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime" - - "github.com/sigstore/rekor/pkg/generated/models" -) - -// GetTimestampCertChainOKCode is the HTTP code returned for type GetTimestampCertChainOK -const GetTimestampCertChainOKCode int = 200 - -/*GetTimestampCertChainOK The PEM encoded cert chain - -swagger:response getTimestampCertChainOK -*/ -type GetTimestampCertChainOK struct { - - /* - In: Body - */ - Payload string `json:"body,omitempty"` -} - -// NewGetTimestampCertChainOK creates GetTimestampCertChainOK with default headers values -func NewGetTimestampCertChainOK() *GetTimestampCertChainOK { - - return &GetTimestampCertChainOK{} -} - -// WithPayload adds the payload to the get timestamp cert chain o k response -func (o *GetTimestampCertChainOK) WithPayload(payload string) *GetTimestampCertChainOK { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get timestamp cert chain o k response -func (o *GetTimestampCertChainOK) SetPayload(payload string) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetTimestampCertChainOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(200) - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } -} - -// GetTimestampCertChainNotFoundCode is the HTTP code returned for type GetTimestampCertChainNotFound -const GetTimestampCertChainNotFoundCode int = 404 - -/*GetTimestampCertChainNotFound The content requested could not be found - -swagger:response getTimestampCertChainNotFound -*/ -type GetTimestampCertChainNotFound struct { -} - -// NewGetTimestampCertChainNotFound creates GetTimestampCertChainNotFound with default headers values -func NewGetTimestampCertChainNotFound() *GetTimestampCertChainNotFound { - - return &GetTimestampCertChainNotFound{} -} - -// WriteResponse to the client -func (o *GetTimestampCertChainNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(404) -} - -/*GetTimestampCertChainDefault There was an internal error in the server while processing the request - -swagger:response getTimestampCertChainDefault -*/ -type GetTimestampCertChainDefault struct { - _statusCode int - - /* - In: Body - */ - Payload *models.Error `json:"body,omitempty"` -} - -// NewGetTimestampCertChainDefault creates GetTimestampCertChainDefault with default headers values -func NewGetTimestampCertChainDefault(code int) *GetTimestampCertChainDefault { - if code <= 0 { - code = 500 - } - - return &GetTimestampCertChainDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get timestamp cert chain default response -func (o *GetTimestampCertChainDefault) WithStatusCode(code int) *GetTimestampCertChainDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get timestamp cert chain default response -func (o *GetTimestampCertChainDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WithPayload adds the payload to the get timestamp cert chain default response -func (o *GetTimestampCertChainDefault) WithPayload(payload *models.Error) *GetTimestampCertChainDefault { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get timestamp cert chain default response -func (o *GetTimestampCertChainDefault) SetPayload(payload *models.Error) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetTimestampCertChainDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(o._statusCode) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} diff --git a/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_urlbuilder.go b/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_urlbuilder.go deleted file mode 100644 index 25cb6134c..000000000 --- a/pkg/generated/restapi/operations/timestamp/get_timestamp_cert_chain_urlbuilder.go +++ /dev/null @@ -1,100 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" -) - -// GetTimestampCertChainURL generates an URL for the get timestamp cert chain operation -type GetTimestampCertChainURL struct { - _basePath string -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetTimestampCertChainURL) WithBasePath(bp string) *GetTimestampCertChainURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetTimestampCertChainURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetTimestampCertChainURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/api/v1/timestamp/certchain" - - _basePath := o._basePath - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetTimestampCertChainURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetTimestampCertChainURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetTimestampCertChainURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetTimestampCertChainURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetTimestampCertChainURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetTimestampCertChainURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/pkg/generated/restapi/operations/timestamp/get_timestamp_response.go b/pkg/generated/restapi/operations/timestamp/get_timestamp_response.go deleted file mode 100644 index 8eb530bbd..000000000 --- a/pkg/generated/restapi/operations/timestamp/get_timestamp_response.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "net/http" - - "github.com/go-openapi/runtime/middleware" -) - -// GetTimestampResponseHandlerFunc turns a function with the right signature into a get timestamp response handler -type GetTimestampResponseHandlerFunc func(GetTimestampResponseParams) middleware.Responder - -// Handle executing the request and returning a response -func (fn GetTimestampResponseHandlerFunc) Handle(params GetTimestampResponseParams) middleware.Responder { - return fn(params) -} - -// GetTimestampResponseHandler interface for that can handle valid get timestamp response params -type GetTimestampResponseHandler interface { - Handle(GetTimestampResponseParams) middleware.Responder -} - -// NewGetTimestampResponse creates a new http.Handler for the get timestamp response operation -func NewGetTimestampResponse(ctx *middleware.Context, handler GetTimestampResponseHandler) *GetTimestampResponse { - return &GetTimestampResponse{Context: ctx, Handler: handler} -} - -/* GetTimestampResponse swagger:route POST /api/v1/timestamp timestamp getTimestampResponse - -Generates a new timestamp response and creates a new log entry for the timestamp in the transparency log - -*/ -type GetTimestampResponse struct { - Context *middleware.Context - Handler GetTimestampResponseHandler -} - -func (o *GetTimestampResponse) ServeHTTP(rw http.ResponseWriter, r *http.Request) { - route, rCtx, _ := o.Context.RouteInfo(r) - if rCtx != nil { - *r = *rCtx - } - var Params = NewGetTimestampResponseParams() - if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params - o.Context.Respond(rw, r, route.Produces, route, err) - return - } - - res := o.Handler.Handle(Params) // actually handle the request - o.Context.Respond(rw, r, route.Produces, route, res) - -} diff --git a/pkg/generated/restapi/operations/timestamp/get_timestamp_response_parameters.go b/pkg/generated/restapi/operations/timestamp/get_timestamp_response_parameters.go deleted file mode 100644 index 231cfe059..000000000 --- a/pkg/generated/restapi/operations/timestamp/get_timestamp_response_parameters.go +++ /dev/null @@ -1,75 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/errors" - "github.com/go-openapi/runtime" - "github.com/go-openapi/runtime/middleware" -) - -// NewGetTimestampResponseParams creates a new GetTimestampResponseParams object -// -// There are no default values defined in the spec. -func NewGetTimestampResponseParams() GetTimestampResponseParams { - - return GetTimestampResponseParams{} -} - -// GetTimestampResponseParams contains all the bound params for the get timestamp response operation -// typically these are obtained from a http.Request -// -// swagger:parameters getTimestampResponse -type GetTimestampResponseParams struct { - - // HTTP Request Object - HTTPRequest *http.Request `json:"-"` - - /* - Required: true - In: body - */ - Request io.ReadCloser -} - -// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface -// for simple values it will use straight method calls. -// -// To ensure default values, the struct must have been initialized with NewGetTimestampResponseParams() beforehand. -func (o *GetTimestampResponseParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error { - var res []error - - o.HTTPRequest = r - - if runtime.HasBody(r) { - o.Request = r.Body - } else { - res = append(res, errors.Required("request", "body", "")) - } - if len(res) > 0 { - return errors.CompositeValidationError(res...) - } - return nil -} diff --git a/pkg/generated/restapi/operations/timestamp/get_timestamp_response_responses.go b/pkg/generated/restapi/operations/timestamp/get_timestamp_response_responses.go deleted file mode 100644 index ee0b3d431..000000000 --- a/pkg/generated/restapi/operations/timestamp/get_timestamp_response_responses.go +++ /dev/null @@ -1,267 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -import ( - "io" - "net/http" - - "github.com/go-openapi/runtime" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/swag" - - "github.com/sigstore/rekor/pkg/generated/models" -) - -// GetTimestampResponseCreatedCode is the HTTP code returned for type GetTimestampResponseCreated -const GetTimestampResponseCreatedCode int = 201 - -/*GetTimestampResponseCreated Returns a timestamp response and the location of the log entry in the transprency log - -swagger:response getTimestampResponseCreated -*/ -type GetTimestampResponseCreated struct { - /*UUID of the log entry made for the timestamp response - - */ - ETag string `json:"ETag"` - /*Log index of the log entry made for the timestamp response - - */ - Index int64 `json:"Index"` - /*URI location of the log entry made for the timestamp response - - */ - Location strfmt.URI `json:"Location"` - - /* - In: Body - */ - Payload io.ReadCloser `json:"body,omitempty"` -} - -// NewGetTimestampResponseCreated creates GetTimestampResponseCreated with default headers values -func NewGetTimestampResponseCreated() *GetTimestampResponseCreated { - - return &GetTimestampResponseCreated{} -} - -// WithETag adds the eTag to the get timestamp response created response -func (o *GetTimestampResponseCreated) WithETag(eTag string) *GetTimestampResponseCreated { - o.ETag = eTag - return o -} - -// SetETag sets the eTag to the get timestamp response created response -func (o *GetTimestampResponseCreated) SetETag(eTag string) { - o.ETag = eTag -} - -// WithIndex adds the index to the get timestamp response created response -func (o *GetTimestampResponseCreated) WithIndex(index int64) *GetTimestampResponseCreated { - o.Index = index - return o -} - -// SetIndex sets the index to the get timestamp response created response -func (o *GetTimestampResponseCreated) SetIndex(index int64) { - o.Index = index -} - -// WithLocation adds the location to the get timestamp response created response -func (o *GetTimestampResponseCreated) WithLocation(location strfmt.URI) *GetTimestampResponseCreated { - o.Location = location - return o -} - -// SetLocation sets the location to the get timestamp response created response -func (o *GetTimestampResponseCreated) SetLocation(location strfmt.URI) { - o.Location = location -} - -// WithPayload adds the payload to the get timestamp response created response -func (o *GetTimestampResponseCreated) WithPayload(payload io.ReadCloser) *GetTimestampResponseCreated { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get timestamp response created response -func (o *GetTimestampResponseCreated) SetPayload(payload io.ReadCloser) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetTimestampResponseCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - // response header ETag - - eTag := o.ETag - if eTag != "" { - rw.Header().Set("ETag", eTag) - } - - // response header Index - - index := swag.FormatInt64(o.Index) - if index != "" { - rw.Header().Set("Index", index) - } - - // response header Location - - location := o.Location.String() - if location != "" { - rw.Header().Set("Location", location) - } - - rw.WriteHeader(201) - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } -} - -// GetTimestampResponseBadRequestCode is the HTTP code returned for type GetTimestampResponseBadRequest -const GetTimestampResponseBadRequestCode int = 400 - -/*GetTimestampResponseBadRequest The content supplied to the server was invalid - -swagger:response getTimestampResponseBadRequest -*/ -type GetTimestampResponseBadRequest struct { - - /* - In: Body - */ - Payload *models.Error `json:"body,omitempty"` -} - -// NewGetTimestampResponseBadRequest creates GetTimestampResponseBadRequest with default headers values -func NewGetTimestampResponseBadRequest() *GetTimestampResponseBadRequest { - - return &GetTimestampResponseBadRequest{} -} - -// WithPayload adds the payload to the get timestamp response bad request response -func (o *GetTimestampResponseBadRequest) WithPayload(payload *models.Error) *GetTimestampResponseBadRequest { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get timestamp response bad request response -func (o *GetTimestampResponseBadRequest) SetPayload(payload *models.Error) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetTimestampResponseBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(400) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} - -// GetTimestampResponseNotImplementedCode is the HTTP code returned for type GetTimestampResponseNotImplemented -const GetTimestampResponseNotImplementedCode int = 501 - -/*GetTimestampResponseNotImplemented The content requested is not implemented - -swagger:response getTimestampResponseNotImplemented -*/ -type GetTimestampResponseNotImplemented struct { -} - -// NewGetTimestampResponseNotImplemented creates GetTimestampResponseNotImplemented with default headers values -func NewGetTimestampResponseNotImplemented() *GetTimestampResponseNotImplemented { - - return &GetTimestampResponseNotImplemented{} -} - -// WriteResponse to the client -func (o *GetTimestampResponseNotImplemented) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses - - rw.WriteHeader(501) -} - -/*GetTimestampResponseDefault There was an internal error in the server while processing the request - -swagger:response getTimestampResponseDefault -*/ -type GetTimestampResponseDefault struct { - _statusCode int - - /* - In: Body - */ - Payload *models.Error `json:"body,omitempty"` -} - -// NewGetTimestampResponseDefault creates GetTimestampResponseDefault with default headers values -func NewGetTimestampResponseDefault(code int) *GetTimestampResponseDefault { - if code <= 0 { - code = 500 - } - - return &GetTimestampResponseDefault{ - _statusCode: code, - } -} - -// WithStatusCode adds the status to the get timestamp response default response -func (o *GetTimestampResponseDefault) WithStatusCode(code int) *GetTimestampResponseDefault { - o._statusCode = code - return o -} - -// SetStatusCode sets the status to the get timestamp response default response -func (o *GetTimestampResponseDefault) SetStatusCode(code int) { - o._statusCode = code -} - -// WithPayload adds the payload to the get timestamp response default response -func (o *GetTimestampResponseDefault) WithPayload(payload *models.Error) *GetTimestampResponseDefault { - o.Payload = payload - return o -} - -// SetPayload sets the payload to the get timestamp response default response -func (o *GetTimestampResponseDefault) SetPayload(payload *models.Error) { - o.Payload = payload -} - -// WriteResponse to the client -func (o *GetTimestampResponseDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { - - rw.WriteHeader(o._statusCode) - if o.Payload != nil { - payload := o.Payload - if err := producer.Produce(rw, payload); err != nil { - panic(err) // let the recovery middleware deal with this - } - } -} diff --git a/pkg/generated/restapi/operations/timestamp/get_timestamp_response_urlbuilder.go b/pkg/generated/restapi/operations/timestamp/get_timestamp_response_urlbuilder.go deleted file mode 100644 index 9a3b72ff0..000000000 --- a/pkg/generated/restapi/operations/timestamp/get_timestamp_response_urlbuilder.go +++ /dev/null @@ -1,100 +0,0 @@ -// Code generated by go-swagger; DO NOT EDIT. - -// -// Copyright 2021 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 timestamp - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the generate command - -import ( - "errors" - "net/url" - golangswaggerpaths "path" -) - -// GetTimestampResponseURL generates an URL for the get timestamp response operation -type GetTimestampResponseURL struct { - _basePath string -} - -// WithBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetTimestampResponseURL) WithBasePath(bp string) *GetTimestampResponseURL { - o.SetBasePath(bp) - return o -} - -// SetBasePath sets the base path for this url builder, only required when it's different from the -// base path specified in the swagger spec. -// When the value of the base path is an empty string -func (o *GetTimestampResponseURL) SetBasePath(bp string) { - o._basePath = bp -} - -// Build a url path and query string -func (o *GetTimestampResponseURL) Build() (*url.URL, error) { - var _result url.URL - - var _path = "/api/v1/timestamp" - - _basePath := o._basePath - _result.Path = golangswaggerpaths.Join(_basePath, _path) - - return &_result, nil -} - -// Must is a helper function to panic when the url builder returns an error -func (o *GetTimestampResponseURL) Must(u *url.URL, err error) *url.URL { - if err != nil { - panic(err) - } - if u == nil { - panic("url can't be nil") - } - return u -} - -// String returns the string representation of the path with query string -func (o *GetTimestampResponseURL) String() string { - return o.Must(o.Build()).String() -} - -// BuildFull builds a full url with scheme, host, path and query string -func (o *GetTimestampResponseURL) BuildFull(scheme, host string) (*url.URL, error) { - if scheme == "" { - return nil, errors.New("scheme is required for a full url on GetTimestampResponseURL") - } - if host == "" { - return nil, errors.New("host is required for a full url on GetTimestampResponseURL") - } - - base, err := o.Build() - if err != nil { - return nil, err - } - - base.Scheme = scheme - base.Host = host - return base, nil -} - -// StringFull returns the string representation of a complete url -func (o *GetTimestampResponseURL) StringFull(scheme, host string) string { - return o.Must(o.BuildFull(scheme, host)).String() -} diff --git a/pkg/pki/x509/x509.go b/pkg/pki/x509/x509.go index a92d495d0..4f04f837f 100644 --- a/pkg/pki/x509/x509.go +++ b/pkg/pki/x509/x509.go @@ -215,48 +215,3 @@ func verifyCertChain(certChain []*x509.Certificate) error { } return nil } - -func CertChainToPEM(certChain []*x509.Certificate) ([]byte, error) { - var pemBytes bytes.Buffer - for _, cert := range certChain { - if err := pem.Encode(&pemBytes, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}); err != nil { - return nil, err - } - } - return pemBytes.Bytes(), nil -} - -func ParseTimestampCertChain(pemBytes []byte) ([]*x509.Certificate, error) { - certChain := []*x509.Certificate{} - var block *pem.Block - block, pemBytes = pem.Decode(pemBytes) - for ; block != nil; block, pemBytes = pem.Decode(pemBytes) { - if block.Type == "CERTIFICATE" { - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, err - } - certChain = append(certChain, cert) - } else { - return nil, errors.New("invalid block type") - } - } - if len(certChain) == 0 { - return nil, errors.New("no valid certificates in chain") - } - // Verify cert chain for timestamping - roots := x509.NewCertPool() - intermediates := x509.NewCertPool() - for _, cert := range certChain[1:(len(certChain) - 1)] { - intermediates.AddCert(cert) - } - roots.AddCert(certChain[len(certChain)-1]) - if _, err := certChain[0].Verify(x509.VerifyOptions{ - Roots: roots, - KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageTimeStamping}, - Intermediates: intermediates, - }); err != nil { - return nil, err - } - return certChain, nil -} diff --git a/pkg/pki/x509/x509_test.go b/pkg/pki/x509/x509_test.go index bb1f9ffd3..cd96fdf17 100644 --- a/pkg/pki/x509/x509_test.go +++ b/pkg/pki/x509/x509_test.go @@ -17,7 +17,6 @@ package x509 import ( "bytes" - "context" "crypto" "crypto/ecdsa" "crypto/x509" @@ -26,10 +25,8 @@ import ( "testing" "github.com/sigstore/rekor/pkg/pki/x509/testutils" - "github.com/sigstore/rekor/pkg/signer" "github.com/sigstore/sigstore/pkg/cryptoutils" "github.com/sigstore/sigstore/pkg/signature" - "github.com/sigstore/sigstore/pkg/signature/options" ) // Generated with: @@ -200,52 +197,6 @@ func TestSignature_VerifyFail(t *testing.T) { } } -func TestNilCertChainToPEM(t *testing.T) { - certChain := []*x509.Certificate{} - if _, err := CertChainToPEM(certChain); err != nil { - t.Fatal(err) - } -} - -func TestCertChain_Verify(t *testing.T) { - caSigner, err := signer.NewMemory() - if err != nil { - t.Fatal(err) - } - // A properly created cert chain should encode to PEM OK. - ctx := context.Background() - mem, err := signer.NewMemory() - if err != nil { - t.Fatal(err) - } - pk, err := mem.PublicKey(options.WithContext(ctx)) - if err != nil { - t.Fatal(err) - } - - certChain, err := signer.NewTimestampingCertWithChain(ctx, pk, caSigner, nil) - if err != nil { - t.Fatal(err) - } - certChainBytes, err := CertChainToPEM(certChain) - if err != nil { - t.Fatal(err) - } - - // Parse and verify timestamping cert chain - parsedCertChain, err := ParseTimestampCertChain(certChainBytes) - if err != nil { - t.Fatal(err) - } - - // Compare with original - for idx, cert := range parsedCertChain { - if !cert.Equal(certChain[idx]) { - t.Fatal("unexpected error comparing cert chain") - } - } -} - func TestPublicKeyWithCertChain(t *testing.T) { rootCert, rootKey, _ := testutils.GenerateRootCa() subCert, subKey, _ := testutils.GenerateSubordinateCa(rootCert, rootKey) diff --git a/pkg/signer/memory.go b/pkg/signer/memory.go index 434e9b312..61fe4ad89 100644 --- a/pkg/signer/memory.go +++ b/pkg/signer/memory.go @@ -17,21 +17,11 @@ limitations under the License. package signer import ( - "context" "crypto" "crypto/elliptic" "crypto/rand" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "math/big" - "net" - "time" - "github.com/pkg/errors" "github.com/sigstore/sigstore/pkg/signature" - "github.com/sigstore/sigstore/pkg/signature/kms/gcp" - "github.com/sigstore/sigstore/pkg/signature/options" ) const MemoryScheme = "memory" @@ -41,103 +31,6 @@ type Memory struct { signature.ECDSASignerVerifier } -// Generate a timestamping certificate for pub using the signer. The chain must verify the signer's public key if provided. -// Otherwise, a self-signed root CA will be generated. -func NewTimestampingCertWithChain(ctx context.Context, pub crypto.PublicKey, signer signature.Signer, chain []*x509.Certificate) ([]*x509.Certificate, error) { - // Get the signer's (rekor's) public key - signerPubKey, err := signer.PublicKey(options.WithContext(ctx)) - if err != nil { - return nil, err - } - - // If the signer is not in-memory, retrieve the crypto.Signer - var cryptoSigner crypto.Signer - if s, ok := signer.(*gcp.SignerVerifier); ok { - if cryptoSigner, _, err = s.CryptoSigner(ctx, func(err error) {}); err != nil { - return nil, errors.Wrap(err, "getting kms signer") - } - } else { - cryptoSigner = signer.(crypto.Signer) - } - - if len(chain) == 0 { - // Generate an in-memory self-signed root CA. - ca := &x509.Certificate{ - SerialNumber: big.NewInt(2019), - Subject: pkix.Name{ - Organization: []string{"rekor in-memory root CA"}, - }, - NotBefore: time.Now(), - NotAfter: time.Now().AddDate(10, 0, 0), - IsCA: true, - KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageContentCommitment | x509.KeyUsageCertSign, - BasicConstraintsValid: true, - } - caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, signerPubKey, cryptoSigner) - if err != nil { - return nil, errors.Wrap(err, "creating self-signed CA") - } - chain, err = x509.ParseCertificates(caBytes) - if err != nil { - return nil, err - } - } - - timestampExt, err := asn1.Marshal([]asn1.ObjectIdentifier{{1, 3, 6, 1, 5, 5, 7, 3, 8}}) - if err != nil { - return nil, err - } - - cert := &x509.Certificate{ - SerialNumber: big.NewInt(1658), - Subject: pkix.Name{ - Organization: []string{"Rekor Timestamping Cert"}, - }, - IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback}, - NotBefore: time.Now(), - NotAfter: time.Now().AddDate(10, 0, 0), - SubjectKeyId: []byte{1, 2, 3, 4, 6}, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageTimeStamping}, - KeyUsage: x509.KeyUsageDigitalSignature, - IsCA: false, - ExtraExtensions: []pkix.Extension{ - { - Id: asn1.ObjectIdentifier{2, 5, 29, 37}, - Critical: true, - Value: timestampExt, - }, - }, - BasicConstraintsValid: true, - } - - // Create the certificate - certBytes, err := x509.CreateCertificate(rand.Reader, cert, chain[0], pub, cryptoSigner) - if err != nil { - return nil, errors.Wrap(err, "creating tsa certificate") - } - tsaCert, err := x509.ParseCertificates(certBytes) - if err != nil { - return nil, err - } - - // Verify and return the certificate chain - root := x509.NewCertPool() - root.AddCert(chain[len(chain)-1]) - intermediates := x509.NewCertPool() - for _, intermediate := range chain[:len(chain)-1] { - intermediates.AddCert(intermediate) - } - verifyOptions := x509.VerifyOptions{ - Roots: root, - Intermediates: intermediates, - KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageTimeStamping}, - } - if _, err = tsaCert[0].Verify(verifyOptions); err != nil { - return nil, err - } - return append(tsaCert, chain...), nil -} - func NewMemory() (*Memory, error) { // generate a keypair sv, _, err := signature.NewECDSASignerVerifier(elliptic.P256(), rand.Reader, crypto.SHA256) diff --git a/pkg/signer/memory_test.go b/pkg/signer/memory_test.go index 2a2fe1659..6939dcba4 100644 --- a/pkg/signer/memory_test.go +++ b/pkg/signer/memory_test.go @@ -17,14 +17,8 @@ limitations under the License. package signer import ( - "bytes" "context" - "crypto" - "crypto/x509" "testing" - - "github.com/sigstore/sigstore/pkg/signature" - "github.com/sigstore/sigstore/pkg/signature/options" ) func TestMemory(t *testing.T) { @@ -34,61 +28,8 @@ func TestMemory(t *testing.T) { if err != nil { t.Fatalf("new memory: %v", err) } - tsaKey, err := New(ctx, "memory") - if err != nil { - t.Fatalf("new memory: %v", err) - } - - payload := []byte("payload") - - // sign a payload with the tsa key - sig, err := tsaKey.SignMessage(bytes.NewReader(payload), options.WithContext(ctx)) - if err != nil { - t.Fatalf("signing payload: %v", err) - } - - // verify the signature against public key - pubKey, err := tsaKey.PublicKey(options.WithContext(ctx)) - if err != nil { - t.Fatalf("public key: %v", err) - } - - verifier, err := signature.LoadVerifier(pubKey, crypto.SHA256) - if err != nil { - t.Fatalf("initializing verifier: %v", err) - } - - if err := verifier.VerifySignature(bytes.NewReader(sig), bytes.NewReader(payload), options.WithContext(ctx)); err != nil { - t.Fatalf("verification failed: %v", err) - } - - // verify signature using the cert's public key - certChain, err := NewTimestampingCertWithChain(ctx, pubKey, m, nil) - if err != nil { - t.Fatalf("generating timestamping cert: %v", err) - } - pkCert := certChain[0].PublicKey - - verifier, err = signature.LoadVerifier(pkCert, crypto.SHA256) - if err != nil { - t.Fatalf("initializing cert pub key verifier: %v", err) - } - if err := verifier.VerifySignature(bytes.NewReader(sig), bytes.NewReader(payload), options.WithContext(ctx)); err != nil { - t.Fatalf("verification failed: %v", err) - } - // verify that the cert chain is configured for timestamping - roots := x509.NewCertPool() - intermediates := x509.NewCertPool() - for _, cert := range certChain[1:(len(certChain) - 1)] { - intermediates.AddCert(cert) - } - roots.AddCert(certChain[len(certChain)-1]) - _, err = certChain[0].Verify(x509.VerifyOptions{ - Roots: roots, - KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageTimeStamping}, - Intermediates: intermediates, - }) + _, err = m.PublicKey() if err != nil { - t.Fatalf("invalid timestamping cert chain") + t.Fatalf("unexpected error creating public key") } } diff --git a/pkg/util/rfc3161.go b/pkg/util/rfc3161.go deleted file mode 100644 index 8d7bbad3d..000000000 --- a/pkg/util/rfc3161.go +++ /dev/null @@ -1,259 +0,0 @@ -// -// Copyright 2021 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 util - -import ( - "bytes" - "context" - "crypto" - "crypto/sha256" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "fmt" - "math/big" - "time" - - "github.com/sassoftware/relic/lib/pkcs7" - "github.com/sassoftware/relic/lib/pkcs9" - "github.com/sassoftware/relic/lib/x509tools" - "github.com/sigstore/sigstore/pkg/signature" - "github.com/sigstore/sigstore/pkg/signature/options" -) - -type GeneralName struct { - Name asn1.RawValue `asn1:"optional,tag:4"` -} - -type IssuerNameAndSerial struct { - IssuerName GeneralName - SerialNumber *big.Int -} - -type EssCertIDv2 struct { - HashAlgorithm pkix.AlgorithmIdentifier `asn1:"optional"` // SHA256 - CertHash []byte - IssuerNameAndSerial IssuerNameAndSerial `asn1:"optional"` -} - -type SigningCertificateV2 struct { - Certs []EssCertIDv2 -} - -func createSigningCertificate(certificate *x509.Certificate) ([]byte, error) { - h := sha256.Sum256(certificate.Raw) // TODO: Get from certificate, defaults to 256 - signingCert := SigningCertificateV2{ - Certs: []EssCertIDv2{{ - CertHash: h[:], - IssuerNameAndSerial: IssuerNameAndSerial{ - IssuerName: GeneralName{Name: asn1.RawValue{Tag: 4, Class: 2, IsCompound: true, Bytes: certificate.RawIssuer}}, - SerialNumber: certificate.SerialNumber, - }, - }}, - } - signingCertBytes, err := asn1.Marshal(signingCert) - if err != nil { - return nil, err - } - return signingCertBytes, nil -} - -func marshalCertificates(certs []*x509.Certificate) pkcs7.RawCertificates { - c := make(pkcs7.RawCertificates, len(certs)) - for i, cert := range certs { - c[i] = asn1.RawValue{FullBytes: cert.Raw} - } - return c -} - -func getPKIXPublicKeyAlgorithm(cert x509.Certificate) (*pkix.AlgorithmIdentifier, error) { - identifier := pkix.AlgorithmIdentifier{ - Parameters: asn1.NullRawValue, - } - switch alg := cert.PublicKeyAlgorithm; alg { - case x509.RSA: - identifier.Algorithm = x509tools.OidPublicKeyRSA - case x509.ECDSA: - identifier.Algorithm = x509tools.OidPublicKeyECDSA - case x509.Ed25519: - identifier.Algorithm = asn1.ObjectIdentifier{1, 3, 101, 112} - default: - return nil, fmt.Errorf("unknown public key algorithm") - } - - return &identifier, nil -} - -type TimestampRequestOptions struct { - // The policy that the client expects the TSA to use for creating the timestamp token. - // If no policy is specified the TSA uses its default policy. - TSAPolicyOid asn1.ObjectIdentifier - - // The nonce to specify in the request. - Nonce *big.Int - - // Hash function to use when constructing the timestamp request. Defaults to SHA-256. - Hash crypto.Hash -} - -func TimestampRequestFromDigest(digest []byte, opts TimestampRequestOptions) (*pkcs9.TimeStampReq, error) { - alg, _ := x509tools.PkixDigestAlgorithm(opts.Hash) - msg := pkcs9.TimeStampReq{ - Version: 1, - MessageImprint: pkcs9.MessageImprint{ - HashAlgorithm: alg, - HashedMessage: digest, - }, - CertReq: true, - } - if opts.Nonce != nil { - msg.Nonce = opts.Nonce - } - if opts.TSAPolicyOid != nil { - msg.ReqPolicy = opts.TSAPolicyOid - } - - return &msg, nil -} - -func ParseTimestampRequest(data []byte) (*pkcs9.TimeStampReq, error) { - msg := new(pkcs9.TimeStampReq) - if rest, err := asn1.Unmarshal(data, msg); err != nil { - return nil, fmt.Errorf("error umarshalling request") - } else if len(rest) != 0 { - return nil, fmt.Errorf("error umarshalling request, trailing bytes") - } - return msg, nil -} - -func GetSigningTime(psd *pkcs7.ContentInfoSignedData) (time.Time, error) { - // See sassoftware pkcs9 package for this code extracting TSTInfo - infobytes, err := psd.Content.ContentInfo.Bytes() - if err != nil { - return time.Time{}, fmt.Errorf("unpack TSTInfo: %w", err) - } else if infobytes[0] == 0x04 { - // unwrap dummy OCTET STRING - _, err = asn1.Unmarshal(infobytes, &infobytes) - if err != nil { - return time.Time{}, fmt.Errorf("unpack TSTInfo: %w", err) - } - } - info := new(pkcs9.TSTInfo) - if _, err := asn1.Unmarshal(infobytes, info); err != nil { - return time.Time{}, fmt.Errorf("unpack TSTInfo: %w", err) - } - - return pkcs7.ParseTime(info.GenTime) -} - -func CreateRfc3161Response(ctx context.Context, req pkcs9.TimeStampReq, certChain []*x509.Certificate, signer signature.Signer) (*pkcs9.TimeStampResp, error) { - // Populate TSTInfo. - genTimeBytes, err := asn1.MarshalWithParams(time.Now(), "generalized") - if err != nil { - return nil, err - } - policy := asn1.ObjectIdentifier{1, 2, 3, 4, 1} - if req.ReqPolicy.String() != "" { - policy = req.ReqPolicy - } - - info := pkcs9.TSTInfo{ - Version: req.Version, - MessageImprint: req.MessageImprint, - // directoryName is tag 4 https://datatracker.ietf.org/doc/html/rfc3280#section-4.2.1.7 - TSA: pkcs9.GeneralName{Value: asn1.RawValue{Tag: 4, Class: 2, IsCompound: true, Bytes: certChain[0].RawSubject}}, - // TODO: Ensure that every (SerialNumber, TSA name) identifies a unique token. - SerialNumber: x509tools.MakeSerial(), - GenTime: asn1.RawValue{FullBytes: genTimeBytes}, - Nonce: req.Nonce, - Policy: policy, - Extensions: req.Extensions, - } - - encoded, err := asn1.Marshal(info) - if err != nil { - return nil, err - } - contentInfo, err := pkcs7.NewContentInfo(pkcs9.OidTSTInfo, encoded) - if err != nil { - return nil, err - } - - // TODO: Does this need to match the hash algorithm in the request? - alg, _ := x509tools.PkixDigestAlgorithm(crypto.SHA256) - contentInfoBytes, _ := contentInfo.Bytes() - h := sha256.Sum256(contentInfoBytes) - - // Create SignerInfo and signature. - signingCert, err := createSigningCertificate(certChain[0]) - if err != nil { - return nil, err - } - attributes := new(pkcs7.AttributeList) - if err := attributes.Add(pkcs7.OidAttributeContentType, contentInfo.ContentType); err != nil { - return nil, err - } - if err := attributes.Add(pkcs7.OidAttributeMessageDigest, h[:]); err != nil { - return nil, err - } - if err := attributes.Add(asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 16, 2, 47}, signingCert); err != nil { - return nil, err - } - - // The signature is over the entire authenticated attributes, not just the TstInfo. - attrBytes, err := attributes.Bytes() - if err != nil { - return nil, err - } - // Get signature. - signature, err := signer.SignMessage(bytes.NewReader(attrBytes), options.WithContext(ctx)) - if err != nil { - return nil, err - } - - sigAlg, err := getPKIXPublicKeyAlgorithm(*certChain[0]) - if err != nil { - return nil, err - } - - response := pkcs9.TimeStampResp{ - Status: pkcs9.PKIStatusInfo{ - Status: 0, - }, - TimeStampToken: pkcs7.ContentInfoSignedData{ - ContentType: asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 7, 2}, // id-signedData - Content: pkcs7.SignedData{ - Version: 1, - DigestAlgorithmIdentifiers: []pkix.AlgorithmIdentifier{alg}, - ContentInfo: contentInfo, - Certificates: marshalCertificates(certChain), - CRLs: nil, - SignerInfos: []pkcs7.SignerInfo{{ - Version: 1, - IssuerAndSerialNumber: pkcs7.IssuerAndSerial{ - IssuerName: asn1.RawValue{FullBytes: certChain[0].RawIssuer}, - SerialNumber: certChain[0].SerialNumber, - }, - DigestAlgorithm: alg, - DigestEncryptionAlgorithm: *sigAlg, - AuthenticatedAttributes: *attributes, - EncryptedDigest: signature, - }}, - }, - }, - } - return &response, nil -} diff --git a/pkg/util/rfc3161_test.go b/pkg/util/rfc3161_test.go deleted file mode 100644 index 0e9539de0..000000000 --- a/pkg/util/rfc3161_test.go +++ /dev/null @@ -1,182 +0,0 @@ -// -// Copyright 2021 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 util - -import ( - "bytes" - "context" - "crypto" - "encoding/asn1" - "fmt" - "io/ioutil" - "math/big" - "testing" - "time" - - "github.com/sassoftware/relic/lib/pkcs9" - "github.com/sassoftware/relic/lib/x509tools" - "github.com/sigstore/rekor/pkg/signer" - "github.com/sigstore/sigstore/pkg/signature/options" -) - -func TestCreateTimestampRequest(t *testing.T) { - type TestCase struct { - caseDesc string - entry []byte - expectSuccess bool - nonce *big.Int - policy asn1.ObjectIdentifier - } - - fileBytes, _ := ioutil.ReadFile("../../tests/test_file.txt") - testCases := []TestCase{ - { - caseDesc: "valid timestamp request", - entry: fileBytes, - expectSuccess: true, - nonce: x509tools.MakeSerial(), - }, - { - caseDesc: "valid timestamp request no nonce", - entry: fileBytes, - expectSuccess: true, - }, - { - caseDesc: "valid timestamp request with TSA policy id", - entry: fileBytes, - expectSuccess: true, - policy: asn1.ObjectIdentifier{1, 2, 3, 4, 5}, - }, - } - for _, tc := range testCases { - opts := TimestampRequestOptions{ - Hash: crypto.SHA256, - Nonce: tc.nonce, - TSAPolicyOid: tc.policy, - } - h := opts.Hash.New() - h.Write(tc.entry) - digest := h.Sum(nil) - req, err := TimestampRequestFromDigest(digest, opts) - if (err == nil) != tc.expectSuccess { - t.Errorf("unexpected error in test case '%v': %v", tc.caseDesc, err) - } - // Validate that the message hash matches the original file has. - if !bytes.Equal(digest, req.MessageImprint.HashedMessage) { - t.Errorf("unexpected error in test case '%v': %v", tc.caseDesc, "hashes do not match") - } - if tc.nonce != nil { - if tc.nonce.Cmp(req.Nonce) != 0 { - t.Errorf("unexpected error in test case '%v': %v", tc.caseDesc, "nonce does not match") - } - } else if req.Nonce != nil { - t.Errorf("unexpected error in test case '%v': %v", tc.caseDesc, fmt.Sprintf("nonce does not match got (%s) expected nil", req.Nonce.String())) - } - if tc.policy != nil { - if !tc.policy.Equal(req.ReqPolicy) { - t.Errorf("unexpected error in test case '%v': %v", tc.caseDesc, "policy does not match") - } - } else if req.ReqPolicy != nil { - t.Errorf("unexpected error in test case '%v': %v", tc.caseDesc, "policy does not match") - } - } -} - -func TestParseTimestampRequest(t *testing.T) { - type TestCase struct { - caseDesc string - entry []byte - expectSuccess bool - } - - requestBytes, _ := ioutil.ReadFile("../../tests/test_request.tsq") - fileBytes, _ := ioutil.ReadFile("../../tests/test_file.txt") - - testCases := []TestCase{ - { - caseDesc: "valid timestamp request", - entry: requestBytes, - expectSuccess: true, - }, - { - caseDesc: "invalid timestamp request", - entry: fileBytes, - expectSuccess: false, - }, - } - - for _, tc := range testCases { - if _, err := ParseTimestampRequest(tc.entry); (err == nil) != tc.expectSuccess { - t.Errorf("unexpected error in test case '%v': %v", tc.caseDesc, err) - } - } -} - -// Create an in-memory CA and TSA and verify the response. -func TestCreateRFC3161Response(t *testing.T) { - ctx := context.Background() - mem, err := signer.NewMemory() - if err != nil { - t.Error(err) - } - tsa, err := signer.NewMemory() - if err != nil { - t.Error(err) - } - pk, err := tsa.PublicKey(options.WithContext(ctx)) - if err != nil { - t.Fatal(err) - } - certChain, err := signer.NewTimestampingCertWithChain(ctx, pk, mem, nil) - if err != nil { - t.Error(err) - } - - fileBytes, _ := ioutil.ReadFile("../../tests/test_file.txt") - opts := TimestampRequestOptions{ - Hash: crypto.SHA256, - Nonce: x509tools.MakeSerial(), - } - h := opts.Hash.New() - h.Write(fileBytes) - digest := h.Sum(nil) - req, err := TimestampRequestFromDigest(digest, opts) - if err != nil { - t.Error(err) - } - - resp, err := CreateRfc3161Response(ctx, *req, certChain, tsa) - if err != nil { - t.Error(err) - } - - before := time.Now().Add(-time.Second) - timestamp, err := GetSigningTime(&resp.TimeStampToken) - if err != nil { - t.Error(err) - } - after := time.Now().Add(time.Second) - - if !timestamp.After(before) || !timestamp.Before(after) { - t.Errorf("generated bad time %s, should be after %s and before %s", timestamp, before, after) - } - - _, err = pkcs9.Verify(&resp.TimeStampToken, fileBytes, certChain) - if err != nil { - t.Error(err) - } - -} diff --git a/tests/e2e_test.go b/tests/e2e_test.go index ddafc569b..2f12e1276 100644 --- a/tests/e2e_test.go +++ b/tests/e2e_test.go @@ -47,9 +47,7 @@ import ( slsa "github.com/in-toto/in-toto-golang/in_toto/slsa_provenance/v0.2" "github.com/secure-systems-lab/go-securesystemslib/dsse" "github.com/sigstore/rekor/pkg/client" - genclient "github.com/sigstore/rekor/pkg/generated/client" "github.com/sigstore/rekor/pkg/generated/client/entries" - "github.com/sigstore/rekor/pkg/generated/client/timestamp" "github.com/sigstore/rekor/pkg/generated/models" "github.com/sigstore/rekor/pkg/sharding" "github.com/sigstore/rekor/pkg/signer" @@ -483,40 +481,6 @@ func TestIntoto(t *testing.T) { } -func TestTimestampArtifact(t *testing.T) { - payload := []byte("tell me when to go") - filePath := filepath.Join(t.TempDir(), "file.txt") - tsrPath := filepath.Join(t.TempDir(), "file.tsr") - tsr2Path := filepath.Join(t.TempDir(), "file2.tsr") - if err := ioutil.WriteFile(filePath, payload, 0644); err != nil { - t.Fatal(err) - } - - var out string - out = runCli(t, "timestamp", "--artifact", filePath, "--out", tsrPath) - outputContains(t, out, "Created entry at") - uuid := getUUIDFromTimestampOutput(t, out) - - artifactBytes, err := ioutil.ReadFile(tsrPath) - if err != nil { - t.Error(err) - } - sha := sha256.Sum256(artifactBytes) - - out = runCli(t, "upload", "--type", "rfc3161", "--artifact", tsrPath) - outputContains(t, out, "Entry already exists") - - out = runCli(t, "search", "--artifact", tsrPath) - outputContains(t, out, uuid) - - out = runCli(t, "search", "--sha", fmt.Sprintf("sha256:%s", hex.EncodeToString(sha[:]))) - outputContains(t, out, uuid) - - // Generates a fresh timestamp on the same artifact - out = runCli(t, "timestamp", "--artifact", filePath, "--out", tsr2Path) - outputContains(t, out, "Created entry at") -} - func TestX509(t *testing.T) { td := t.TempDir() artifactPath := filepath.Join(td, "artifact") @@ -696,66 +660,6 @@ func TestSignedEntryTimestamp(t *testing.T) { } } -func TestTimestampResponseCLI(t *testing.T) { - ctx := context.Background() - payload := []byte("i am a cat") - // Create files for data, response, and CA. - - filePath := filepath.Join(t.TempDir(), "file.txt") - CAPath := filepath.Join(t.TempDir(), "ca.pem") - responsePath := filepath.Join(t.TempDir(), "response.tsr") - if err := ioutil.WriteFile(filePath, payload, 0644); err != nil { - t.Fatal(err) - } - - out := runCli(t, "timestamp", "--artifact", filePath, "--out", responsePath) - outputContains(t, out, "Wrote timestamp response to") - - rekorClient, err := client.GetRekorClient("http://localhost:3000") - if err != nil { - t.Fatal(err) - } - - certChain := rekorTimestampCertChain(t, ctx, rekorClient) - var rootCABytes bytes.Buffer - if err := pem.Encode(&rootCABytes, &pem.Block{Type: "CERTIFICATE", Bytes: certChain[len(certChain)-1].Raw}); err != nil { - t.Fatal(err) - } - if err := ioutil.WriteFile(CAPath, rootCABytes.Bytes(), 0644); err != nil { - t.Fatal(err) - } - - // Use openssl to verify - cmd := exec.Command("openssl", "ts", "-verify", "-data", filePath, "-in", responsePath, "-CAfile", CAPath) - errs := &bytes.Buffer{} - - cmd.Stderr = errs - if err := cmd.Run(); err != nil { - // Check that the result was OK. - if len(errs.Bytes()) > 0 { - t.Fatalf("error verifying with openssl %s", errs.String()) - } - - } - - // Now try with the digest. - h := sha256.Sum256(payload) - hexDigest := hex.EncodeToString(h[:]) - out = runCli(t, "timestamp", "--artifact-hash", hexDigest, "--out", responsePath) - outputContains(t, out, "Wrote timestamp response to") - cmd = exec.Command("openssl", "ts", "-verify", "-digest", hexDigest, "-in", responsePath, "-CAfile", CAPath) - errs = &bytes.Buffer{} - - cmd.Stderr = errs - if err := cmd.Run(); err != nil { - // Check that the result was OK. - if len(errs.Bytes()) > 0 { - t.Fatalf("error verifying with openssl %s", errs.String()) - } - - } -} - func TestGetNonExistantIndex(t *testing.T) { // this index is extremely likely to not exist out := runCliErr(t, "get", "--log-index", "100000000") @@ -768,34 +672,6 @@ func TestGetNonExistantUUID(t *testing.T) { outputContains(t, out, "404") } -func rekorTimestampCertChain(t *testing.T, ctx context.Context, c *genclient.Rekor) []*x509.Certificate { - resp, err := c.Timestamp.GetTimestampCertChain(×tamp.GetTimestampCertChainParams{Context: ctx}) - if err != nil { - t.Fatal(err) - } - certChainBytes := []byte(resp.GetPayload()) - - var block *pem.Block - block, certChainBytes = pem.Decode(certChainBytes) - certificates := []*x509.Certificate{} - for ; block != nil; block, certChainBytes = pem.Decode(certChainBytes) { - if block.Type == "CERTIFICATE" { - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - t.Fatal(err) - } - certificates = append(certificates, cert) - } else { - t.Fatal(err) - } - } - - if len(certificates) == 0 { - t.Fatal("could not find certificates") - } - return certificates -} - func TestEntryUpload(t *testing.T) { artifactPath := filepath.Join(t.TempDir(), "artifact") sigPath := filepath.Join(t.TempDir(), "signature.asc") diff --git a/tests/test_request.tsq b/tests/test_request.tsq deleted file mode 100644 index 134012f642a2087f73c3e4842e3ee8c436d0a38d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 59 zcmV-B0L1?=IRXIzFflL<1_@w>NC9O71OfpC00bcI>aX+hcS_QThI4leZDa|4IUB=b R*Vg+qm@VH9{TRyu0srvx6(axu