go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/client/cmd/cloudkms/sign.go (about)

     1  // Copyright 2020 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"context"
    19  	"crypto/sha256"
    20  	"io"
    21  	"os"
    22  
    23  	"github.com/maruel/subcommands"
    24  
    25  	cloudkms "cloud.google.com/go/kms/apiv1"
    26  	"cloud.google.com/go/kms/apiv1/kmspb"
    27  
    28  	"go.chromium.org/luci/auth"
    29  	"go.chromium.org/luci/common/logging"
    30  )
    31  
    32  func doSign(ctx context.Context, client *cloudkms.KeyManagementClient, input *os.File, keyPath string) ([]byte, error) {
    33  	digest := sha256.New()
    34  	if _, err := io.Copy(digest, input); err != nil {
    35  		logging.Warningf(ctx, "Error while reading input")
    36  		return nil, err
    37  	}
    38  
    39  	// Set up request, including a SHA256 hash of the plaintext.
    40  	req := &kmspb.AsymmetricSignRequest{
    41  		Name: keyPath,
    42  		Digest: &kmspb.Digest{
    43  			Digest: &kmspb.Digest_Sha256{
    44  				Sha256: digest.Sum(nil),
    45  			},
    46  		},
    47  	}
    48  
    49  	resp, err := client.AsymmetricSign(ctx, req)
    50  	if err != nil {
    51  		logging.Errorf(ctx, "Error while making request")
    52  		return nil, err
    53  	}
    54  
    55  	return resp.Signature, nil
    56  }
    57  
    58  func cmdSign(authOpts auth.Options) *subcommands.Command {
    59  	return &subcommands.Command{
    60  		UsageLine: "sign <options> <path>",
    61  		ShortDesc: "signs some plaintext",
    62  		LongDesc: `Processes a plaintext and uploads the digest for signing by Cloud KMS.
    63  
    64  At this time, this tool assumes that all signatures are on SHA-256 digests and
    65  all keys are EC_SIGN_P256_SHA256.
    66  
    67  <path> refers to the path to the crypto key. e.g.
    68  
    69  projects/<project>/locations/<location>/keyRings/<keyRing>/cryptoKeys/<cryptoKey>/cryptoKeyVersions/<version>
    70  
    71  -output will be the signature`,
    72  		CommandRun: func() subcommands.CommandRun {
    73  			c := signRun{doSign: doSign}
    74  			c.Init(authOpts)
    75  			return &c
    76  		},
    77  	}
    78  }