safeTemplateFilepath builds and return the template filepath within the provided dir. This function also performs a security check to make sure the provided templateName doesn't contain a relative path escaping the provided dir.
(dir, templateName string)
| 1408 | // This function also performs a security check to make sure the provided templateName |
| 1409 | // doesn't contain a relative path escaping the provided dir. |
| 1410 | func safeTemplateFilepath(dir, templateName string) (string, error) { |
| 1411 | // We expect all template files to be stored and referenced within the provided directory. |
| 1412 | containerDir, err := filepath.Abs(dir) |
| 1413 | if err != nil { |
| 1414 | return "", err |
| 1415 | } |
| 1416 | |
| 1417 | // Build the actual path of the template. |
| 1418 | actualPath, err := filepath.Abs(filepath.Join(containerDir, templateName)) |
| 1419 | if err != nil { |
| 1420 | return "", err |
| 1421 | } |
| 1422 | |
| 1423 | // Ensure the actual path of the template is within the expected directory. |
| 1424 | // This check is a counter-measure to make sure the tenant is not trying to |
| 1425 | // escape its own directory on disk. |
| 1426 | if !strings.HasPrefix(actualPath, containerDir) { |
| 1427 | return "", fmt.Errorf("invalid template name %q: the template filepath is escaping the per-tenant local directory", templateName) |
| 1428 | } |
| 1429 | |
| 1430 | return actualPath, nil |
| 1431 | } |
| 1432 | |
| 1433 | // storeTemplateFile stores template file at the given templateFilepath. |
| 1434 | // Returns true, if file content has changed (new or updated file), false if file with the same name |