backup_filename_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package service
  2. import (
  3. "regexp"
  4. "testing"
  5. "time"
  6. )
  7. // getDb (controller) only accepts a Content-Disposition filename matching this
  8. // pattern, so every sanitizeBackupHost output must satisfy it.
  9. var backupFilenameRegex = regexp.MustCompile(`^[a-zA-Z0-9_\-.]+$`)
  10. func TestSanitizeBackupHost(t *testing.T) {
  11. cases := []struct {
  12. name string
  13. in string
  14. want string
  15. }{
  16. {"domain", "panel.example.com", "panel.example.com"},
  17. {"ipv4", "203.0.113.5", "203.0.113.5"},
  18. {"ipv6", "2001:db8::1", "2001-db8--1"},
  19. {"ipv6 bracketed", "[fe80::1]", "fe80--1"},
  20. {"domain with port", "example.com:8443", "example.com-8443"},
  21. {"trims edge dots and dashes", "-.example.com.-", "example.com"},
  22. {"empty falls back", "", "x-ui"},
  23. {"all invalid falls back", ":::", "x-ui"},
  24. }
  25. for _, tc := range cases {
  26. t.Run(tc.name, func(t *testing.T) {
  27. got := sanitizeBackupHost(tc.in)
  28. if got != tc.want {
  29. t.Errorf("sanitizeBackupHost(%q) = %q, want %q", tc.in, got, tc.want)
  30. }
  31. if !backupFilenameRegex.MatchString(got) {
  32. t.Errorf("sanitizeBackupHost(%q) = %q, not a valid download filename", tc.in, got)
  33. }
  34. })
  35. }
  36. }
  37. // dateSuffixRegex narrows backupFilenameRegex to the exact _YYYY-MM-DD_HHMMSS shape.
  38. var dateSuffixRegex = regexp.MustCompile(`^_\d{4}-\d{2}-\d{2}_\d{6}$`)
  39. func TestBackupDateSuffix(t *testing.T) {
  40. cases := []struct {
  41. name string
  42. now time.Time
  43. want string
  44. }{
  45. {"utc midnight", time.Date(2026, 6, 27, 0, 0, 0, 0, time.UTC), "_2026-06-27_000000"},
  46. {"end of year", time.Date(2025, 12, 31, 23, 59, 59, 0, time.UTC), "_2025-12-31_235959"},
  47. {"single digit month/day padded", time.Date(2026, 1, 5, 9, 4, 0, 0, time.UTC), "_2026-01-05_090400"},
  48. }
  49. for _, tc := range cases {
  50. t.Run(tc.name, func(t *testing.T) {
  51. got := backupDateSuffix(tc.now)
  52. if got != tc.want {
  53. t.Errorf("backupDateSuffix(%v) = %q, want %q", tc.now, got, tc.want)
  54. }
  55. if !dateSuffixRegex.MatchString(got) {
  56. t.Errorf("backupDateSuffix(%v) = %q, not a valid date suffix", tc.now, got)
  57. }
  58. if !backupFilenameRegex.MatchString(got) {
  59. t.Errorf("backupDateSuffix(%v) = %q, not a valid download filename char", tc.now, got)
  60. }
  61. })
  62. }
  63. }