indexer_file_safety.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package nginx_log
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. // safeGetFileInfo safely gets file information after validating the path
  7. func (li *LogIndexer) safeGetFileInfo(filePath string) (os.FileInfo, error) {
  8. // Validate path is under whitelist before accessing
  9. if !IsLogPathUnderWhiteList(filePath) {
  10. return nil, fmt.Errorf("file path not under whitelist: %s", filePath)
  11. }
  12. // Additional validation using isValidLogPath
  13. if !isValidLogPath(filePath) {
  14. return nil, fmt.Errorf("invalid log path: %s", filePath)
  15. }
  16. return os.Stat(filePath)
  17. }
  18. // safeOpenFile safely opens a file after validating the path
  19. func (li *LogIndexer) safeOpenFile(filePath string) (*os.File, error) {
  20. // Validate path is under whitelist before accessing
  21. if !IsLogPathUnderWhiteList(filePath) {
  22. return nil, fmt.Errorf("file path not under whitelist: %s", filePath)
  23. }
  24. // Additional validation using isValidLogPath
  25. if !isValidLogPath(filePath) {
  26. return nil, fmt.Errorf("invalid log path: %s", filePath)
  27. }
  28. return os.Open(filePath)
  29. }
  30. // safeReadDir safely reads a directory after validating the path
  31. func (li *LogIndexer) safeReadDir(dirPath string) ([]os.DirEntry, error) {
  32. // Validate directory path is under whitelist before accessing
  33. if !IsLogPathUnderWhiteList(dirPath) {
  34. return nil, fmt.Errorf("directory path not under whitelist: %s", dirPath)
  35. }
  36. return os.ReadDir(dirPath)
  37. }