|
| 1 | +// Copyright 2022, 2026 The kpt 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 util |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + "path/filepath" |
| 20 | + "strings" |
| 21 | +) |
| 22 | + |
| 23 | +// Relevant: https://github.com/golang/go/issues/20126 |
| 24 | + |
| 25 | +// FilepathSafeJoin joins dir and relative, returning an error if relative is |
| 26 | +// not a clean, canonical relative path within dir. It rejects path traversal |
| 27 | +// (.. sequences), absolute paths, the bare "." and ".." entries, and any path |
| 28 | +// that would be altered by filepath.Clean (e.g. leading "./", redundant |
| 29 | +// separators, or internal "a/../b" segments). |
| 30 | +func FilepathSafeJoin(dir, relative string) (string, error) { |
| 31 | + p := filepath.Join(dir, relative) |
| 32 | + p = filepath.Clean(p) |
| 33 | + |
| 34 | + rel, err := filepath.Rel(dir, p) |
| 35 | + if err != nil { |
| 36 | + return "", fmt.Errorf("invalid relative path %q", relative) |
| 37 | + } |
| 38 | + if rel == "." || rel == ".." || rel != relative || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || strings.HasPrefix(rel, "."+string(filepath.Separator)) { |
| 39 | + return "", fmt.Errorf("invalid relative path %q", relative) |
| 40 | + } |
| 41 | + return p, nil |
| 42 | +} |
| 43 | + |
| 44 | +// ValidateResourcePaths checks that all keys in a resource map are valid |
| 45 | +// relative file paths within a package. It rejects path traversal sequences, |
| 46 | +// absolute paths, and non-canonical paths (e.g. leading "./", bare "." or ".."). |
| 47 | +// Returns an error on the first invalid key. |
| 48 | +func ValidateResourcePaths(resources map[string]string) error { |
| 49 | + for k := range resources { |
| 50 | + if _, err := FilepathSafeJoin(".", k); err != nil { |
| 51 | + return fmt.Errorf("invalid resource path %q: %w", k, err) |
| 52 | + } |
| 53 | + } |
| 54 | + return nil |
| 55 | +} |
0 commit comments