1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
package captokens
import (
"fmt"
"path/filepath"
)
// NormalizePath returns the canonical absolute path.
// Security properties:
// - Must be absolute path
// - Removes .., //, ./, trailing slashes via Clean
// - Resolves symlinks to canonical path
// - Returns error if path doesn't exist or can't be resolved
func NormalizePath(path string) (string, error) {
// 1. Must be absolute path
if !filepath.IsAbs(path) {
return "", fmt.Errorf("path must be absolute: %s", path)
}
// 2. Clean path (removes .., //, ./, trailing slashes)
path = filepath.Clean(path)
// 3. Resolve symlinks to canonical path
resolved, err := filepath.EvalSymlinks(path)
if err != nil {
return "", fmt.Errorf("cannot resolve path %s: %w", path, err)
}
// 4. Clean again after symlink resolution
resolved = filepath.Clean(resolved)
return resolved, nil
}
// NormalizePathString is a convenience function for normalizing
// a single path string (used in method validation).
func NormalizePathString(path string) (string, error) {
return NormalizePath(path)
}
// NormalizePathsInFields normalizes path values in specified fields of a scope map.
// The caller explicitly declares which fields contain paths.
// This should be called before signing tokens to ensure paths are canonical.
// Returns error if any specified field contains an invalid path.
func NormalizePathsInFields(scope map[string]any, pathFields []string) error {
for _, field := range pathFields {
if value, exists := scope[field]; exists {
if pathStr, ok := value.(string); ok {
normalized, err := NormalizePath(pathStr)
if err != nil {
return fmt.Errorf("invalid path in %s: %w", field, err)
}
scope[field] = normalized
}
}
}
return nil
}
|