SanitizedPathJoin performs filepath.Join(root, reqPath) that is safe against directory traversal attacks. It uses logic similar to that in the Go standard library, specifically in the implementation of http.Dir. The root is assumed to be a trusted path, but reqPath is not; and the output will never
(root, reqPath string)
| 337 | // Adapted from https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go |
| 338 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 339 | func sanitizedPathJoin(root, reqPath string) string { |
| 340 | if root == "" { |
| 341 | root = "." |
| 342 | } |
| 343 | |
| 344 | path := filepath.Join(root, filepath.Clean("/"+reqPath)) |
| 345 | |
| 346 | // filepath.Join also cleans the path, and cleaning strips |
| 347 | // the trailing slash, so we need to re-add it afterward. |
| 348 | // if the length is 1, then it's a path to the root, |
| 349 | // and that should return ".", so we don't append the separator. |
| 350 | if strings.HasSuffix(reqPath, "/") && len(reqPath) > 1 { |
| 351 | path += separator |
| 352 | } |
| 353 | |
| 354 | return path |
| 355 | } |
| 356 | |
| 357 | const separator = string(filepath.Separator) |
| 358 |
no outgoing calls
no test coverage detected