1
// This Source Code Form is subject to the terms of the Mozilla Public
2
// License, v. 2.0. If a copy of the MPL was not distributed with this
3
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
// Package safepath provides a set of functions to make paths safe for use with.
13
// CleanPath makes a path safe for use with filepath.Join. This is done by not
14
// only cleaning the path, but also (if the path is relative) adding a leading
15
// '/' and cleaning it (then removing the leading '/'). This ensures that a
16
// path resulting from prepending another path will always resolve to lexically
17
// be a subdirectory of the prefixed path. This is all done lexically, so paths
18
// that include symlinks won't be safe as a result of using CleanPath.
19
func CleanPath(path string) string {
20
// Deal with empty strings nicely.
25
// Ensure that all paths are cleaned (especially problematic ones like
26
// "/../../../../../" which can cause lots of issues).
27
path = filepath.Clean(path)
29
// If the path isn't absolute, we need to do more processing to fix paths
30
// such as "../../../../<etc>/some/path". We also shouldn't convert absolute
31
// paths to relative ones.
32
if !filepath.IsAbs(path) {
33
path = filepath.Clean(string(os.PathSeparator) + path)
34
// This can't fail, as (by definition) all paths are relative to root.
35
path, _ = filepath.Rel(string(os.PathSeparator), path) //nolint:errcheck
38
// Clean the path again for good measure.
39
return filepath.Clean(path)