go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/cipd/appengine/impl/gs/path.go (about)

     1  // Copyright 2017 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 gs
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  	"unicode"
    21  )
    22  
    23  // ValidatePath returns an error if p doesn't look like "/bucket/path".
    24  //
    25  // Additionally it verifies p is using only printable ASCII characters, since
    26  // all Google Storage paths used by CIPD are ASCII (assembled from constants
    27  // fetched from validated configs and hex digests, there are no user-supplied
    28  // path elements). We want to assert no fancy unicode characters sneak in.
    29  func ValidatePath(p string) error {
    30  	chunks := strings.Split(p, "/")
    31  	if len(chunks) < 3 || chunks[0] != "" {
    32  		return fmt.Errorf("a Google Storage path must have format /<bucket>/<path>")
    33  	}
    34  	for i := 1; i < len(chunks); i++ {
    35  		if chunks[i] == "" {
    36  			return fmt.Errorf("a Google Storage path components must not be empty")
    37  		}
    38  	}
    39  	for _, r := range p {
    40  		if r > unicode.MaxASCII || !unicode.IsPrint(r) {
    41  			return fmt.Errorf("forbidden symbol %q in the google storage path", r)
    42  		}
    43  	}
    44  	return nil
    45  }
    46  
    47  // SplitPath given "/a/b/c" returns ("a", "b/c") or panics.
    48  //
    49  // Use ValidatePath for prior validation if you are concerned.
    50  func SplitPath(p string) (bucket, path string) {
    51  	if err := ValidatePath(p); err != nil {
    52  		panic(err)
    53  	}
    54  	sep := strings.IndexByte(p[1:], '/') + 1
    55  	return p[1:sep], p[sep+1:]
    56  }