...

Source file src/github.com/sigstore/cosign/v2/pkg/blob/load.go

Documentation: github.com/sigstore/cosign/v2/pkg/blob

     1  // Copyright 2021 The Sigstore 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 blob
    16  
    17  import (
    18  	"fmt"
    19  	"io"
    20  	"net/http"
    21  	"os"
    22  	"path/filepath"
    23  	"strings"
    24  )
    25  
    26  type UnrecognizedSchemeError struct {
    27  	Scheme string
    28  }
    29  
    30  func (e *UnrecognizedSchemeError) Error() string {
    31  	return fmt.Sprintf("loading URL: unrecognized scheme: %s", e.Scheme)
    32  }
    33  
    34  func LoadFileOrURL(fileRef string) ([]byte, error) {
    35  	var raw []byte
    36  	var err error
    37  	parts := strings.SplitAfterN(fileRef, "://", 2)
    38  	if len(parts) == 2 {
    39  		scheme := parts[0]
    40  		switch scheme {
    41  		case "http://":
    42  			fallthrough
    43  		case "https://":
    44  			// #nosec G107
    45  			resp, err := http.Get(fileRef)
    46  			if err != nil {
    47  				return nil, err
    48  			}
    49  			defer resp.Body.Close()
    50  			raw, err = io.ReadAll(resp.Body)
    51  			if err != nil {
    52  				return nil, err
    53  			}
    54  		case "env://":
    55  			envVar := parts[1]
    56  			// Most of Cosign should use `env.LookupEnv` (see #2236) to restrict us to known environment variables
    57  			// (usually `$COSIGN_*`). However, in this case, `envVar` is user-provided and not one of the allow-listed
    58  			// env vars.
    59  			value, found := os.LookupEnv(envVar) //nolint:forbidigo
    60  			if !found {
    61  				return nil, fmt.Errorf("loading URL: env var $%s not found", envVar)
    62  			}
    63  			raw = []byte(value)
    64  		default:
    65  			return nil, &UnrecognizedSchemeError{Scheme: scheme}
    66  		}
    67  	} else {
    68  		raw, err = os.ReadFile(filepath.Clean(fileRef))
    69  		if err != nil {
    70  			return nil, err
    71  		}
    72  	}
    73  	return raw, nil
    74  }
    75  

View as plain text