file_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. package fileacquisition_test
  2. import (
  3. "fmt"
  4. "os"
  5. "runtime"
  6. "testing"
  7. "time"
  8. log "github.com/sirupsen/logrus"
  9. "github.com/sirupsen/logrus/hooks/test"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. "gopkg.in/tomb.v2"
  13. "github.com/crowdsecurity/go-cs-lib/cstest"
  14. fileacquisition "github.com/crowdsecurity/crowdsec/pkg/acquisition/modules/file"
  15. "github.com/crowdsecurity/crowdsec/pkg/types"
  16. )
  17. func TestBadConfiguration(t *testing.T) {
  18. tests := []struct {
  19. name string
  20. config string
  21. expectedErr string
  22. }{
  23. {
  24. name: "extra configuration key",
  25. config: "foobar: asd.log",
  26. expectedErr: "line 1: field foobar not found in type fileacquisition.FileConfiguration",
  27. },
  28. {
  29. name: "missing filenames",
  30. config: "mode: tail",
  31. expectedErr: "no filename or filenames configuration provided",
  32. },
  33. {
  34. name: "glob syntax error",
  35. config: `filename: "[asd-.log"`,
  36. expectedErr: "glob failure: syntax error in pattern",
  37. },
  38. {
  39. name: "bad exclude regexp",
  40. config: `filenames: ["asd.log"]
  41. exclude_regexps: ["as[a-$d"]`,
  42. expectedErr: "could not compile regexp as",
  43. },
  44. }
  45. subLogger := log.WithFields(log.Fields{
  46. "type": "file",
  47. })
  48. for _, tc := range tests {
  49. tc := tc
  50. t.Run(tc.name, func(t *testing.T) {
  51. f := fileacquisition.FileSource{}
  52. err := f.Configure([]byte(tc.config), subLogger)
  53. cstest.RequireErrorContains(t, err, tc.expectedErr)
  54. })
  55. }
  56. }
  57. func TestConfigureDSN(t *testing.T) {
  58. file := "/etc/passwd"
  59. if runtime.GOOS == "windows" {
  60. file = `C:\Windows\System32\drivers\etc\hosts`
  61. }
  62. tests := []struct {
  63. dsn string
  64. expectedErr string
  65. }{
  66. {
  67. dsn: "asd://",
  68. expectedErr: "invalid DSN asd:// for file source, must start with file://",
  69. },
  70. {
  71. dsn: "file://",
  72. expectedErr: "empty file:// DSN",
  73. },
  74. {
  75. dsn: fmt.Sprintf("file://%s?log_level=warn", file),
  76. },
  77. {
  78. dsn: fmt.Sprintf("file://%s?log_level=foobar", file),
  79. expectedErr: "unknown level foobar: not a valid logrus Level:",
  80. },
  81. }
  82. subLogger := log.WithFields(log.Fields{
  83. "type": "file",
  84. })
  85. for _, tc := range tests {
  86. tc := tc
  87. t.Run(tc.dsn, func(t *testing.T) {
  88. f := fileacquisition.FileSource{}
  89. err := f.ConfigureByDSN(tc.dsn, map[string]string{"type": "testtype"}, subLogger, "")
  90. cstest.RequireErrorContains(t, err, tc.expectedErr)
  91. })
  92. }
  93. }
  94. func TestOneShot(t *testing.T) {
  95. permDeniedFile := "/etc/shadow"
  96. permDeniedError := "failed opening /etc/shadow: open /etc/shadow: permission denied"
  97. if runtime.GOOS == "windows" {
  98. // Technically, this is not a permission denied error, but we just want to test what happens
  99. // if we do not have access to the file
  100. permDeniedFile = `C:\Windows\System32\config\SAM`
  101. permDeniedError = `failed opening C:\Windows\System32\config\SAM: open C:\Windows\System32\config\SAM: The process cannot access the file because it is being used by another process.`
  102. }
  103. tests := []struct {
  104. name string
  105. config string
  106. expectedConfigErr string
  107. expectedErr string
  108. expectedOutput string
  109. expectedLines int
  110. logLevel log.Level
  111. setup func()
  112. afterConfigure func()
  113. teardown func()
  114. }{
  115. {
  116. name: "permission denied",
  117. config: fmt.Sprintf(`
  118. mode: cat
  119. filename: %s`, permDeniedFile),
  120. expectedErr: permDeniedError,
  121. logLevel: log.WarnLevel,
  122. expectedLines: 0,
  123. },
  124. {
  125. name: "ignored directory",
  126. config: `
  127. mode: cat
  128. filename: /`,
  129. expectedOutput: "/ is a directory, ignoring it",
  130. logLevel: log.WarnLevel,
  131. expectedLines: 0,
  132. },
  133. {
  134. name: "glob syntax error",
  135. config: `
  136. mode: cat
  137. filename: "[*-.log"`,
  138. expectedConfigErr: "glob failure: syntax error in pattern",
  139. logLevel: log.WarnLevel,
  140. expectedLines: 0,
  141. },
  142. {
  143. name: "no matching files",
  144. config: `
  145. mode: cat
  146. filename: /do/not/exist`,
  147. expectedOutput: "No matching files for pattern /do/not/exist",
  148. logLevel: log.WarnLevel,
  149. expectedLines: 0,
  150. },
  151. {
  152. name: "test.log",
  153. config: `
  154. mode: cat
  155. filename: test_files/test.log`,
  156. expectedLines: 5,
  157. logLevel: log.WarnLevel,
  158. },
  159. {
  160. name: "test.log.gz",
  161. config: `
  162. mode: cat
  163. filename: test_files/test.log.gz`,
  164. expectedLines: 5,
  165. logLevel: log.WarnLevel,
  166. },
  167. {
  168. name: "unexpected end of gzip stream",
  169. config: `
  170. mode: cat
  171. filename: test_files/bad.gz`,
  172. expectedErr: "failed to read gz test_files/bad.gz: unexpected EOF",
  173. expectedLines: 0,
  174. logLevel: log.WarnLevel,
  175. },
  176. {
  177. name: "deleted file",
  178. config: `
  179. mode: cat
  180. filename: test_files/test_delete.log`,
  181. setup: func() {
  182. f, _ := os.Create("test_files/test_delete.log")
  183. f.Close()
  184. },
  185. afterConfigure: func() {
  186. os.Remove("test_files/test_delete.log")
  187. },
  188. expectedErr: "could not stat file test_files/test_delete.log",
  189. },
  190. }
  191. for _, tc := range tests {
  192. tc := tc
  193. t.Run(tc.name, func(t *testing.T) {
  194. logger, hook := test.NewNullLogger()
  195. logger.SetLevel(tc.logLevel)
  196. subLogger := logger.WithFields(log.Fields{
  197. "type": "file",
  198. })
  199. tomb := tomb.Tomb{}
  200. out := make(chan types.Event, 100)
  201. f := fileacquisition.FileSource{}
  202. if tc.setup != nil {
  203. tc.setup()
  204. }
  205. err := f.Configure([]byte(tc.config), subLogger)
  206. cstest.RequireErrorContains(t, err, tc.expectedConfigErr)
  207. if tc.expectedConfigErr != "" {
  208. return
  209. }
  210. if tc.afterConfigure != nil {
  211. tc.afterConfigure()
  212. }
  213. err = f.OneShotAcquisition(out, &tomb)
  214. actualLines := len(out)
  215. cstest.RequireErrorContains(t, err, tc.expectedErr)
  216. if tc.expectedLines != 0 {
  217. assert.Equal(t, tc.expectedLines, actualLines)
  218. }
  219. if tc.expectedOutput != "" {
  220. assert.Contains(t, hook.LastEntry().Message, tc.expectedOutput)
  221. hook.Reset()
  222. }
  223. if tc.teardown != nil {
  224. tc.teardown()
  225. }
  226. })
  227. }
  228. }
  229. func TestLiveAcquisition(t *testing.T) {
  230. permDeniedFile := "/etc/shadow"
  231. permDeniedError := "unable to read /etc/shadow : open /etc/shadow: permission denied"
  232. testPattern := "test_files/*.log"
  233. if runtime.GOOS == "windows" {
  234. // Technically, this is not a permission denied error, but we just want to test what happens
  235. // if we do not have access to the file
  236. permDeniedFile = `C:\Windows\System32\config\SAM`
  237. permDeniedError = `unable to read C:\Windows\System32\config\SAM : open C:\Windows\System32\config\SAM: The process cannot access the file because it is being used by another process`
  238. testPattern = `test_files\*.log`
  239. }
  240. tests := []struct {
  241. name string
  242. config string
  243. expectedErr string
  244. expectedOutput string
  245. expectedLines int
  246. logLevel log.Level
  247. setup func()
  248. afterConfigure func()
  249. teardown func()
  250. }{
  251. {
  252. config: fmt.Sprintf(`
  253. mode: tail
  254. filename: %s`, permDeniedFile),
  255. expectedOutput: permDeniedError,
  256. logLevel: log.InfoLevel,
  257. expectedLines: 0,
  258. name: "PermissionDenied",
  259. },
  260. {
  261. config: `
  262. mode: tail
  263. filename: /`,
  264. expectedOutput: "/ is a directory, ignoring it",
  265. logLevel: log.WarnLevel,
  266. expectedLines: 0,
  267. name: "Directory",
  268. },
  269. {
  270. config: `
  271. mode: tail
  272. filename: /do/not/exist`,
  273. expectedOutput: "No matching files for pattern /do/not/exist",
  274. logLevel: log.WarnLevel,
  275. expectedLines: 0,
  276. name: "badPattern",
  277. },
  278. {
  279. config: fmt.Sprintf(`
  280. mode: tail
  281. filenames:
  282. - %s
  283. force_inotify: true`, testPattern),
  284. expectedLines: 5,
  285. logLevel: log.DebugLevel,
  286. name: "basicGlob",
  287. },
  288. {
  289. config: fmt.Sprintf(`
  290. mode: tail
  291. filenames:
  292. - %s
  293. force_inotify: true`, testPattern),
  294. expectedLines: 0,
  295. logLevel: log.DebugLevel,
  296. name: "GlobInotify",
  297. afterConfigure: func() {
  298. f, _ := os.Create("test_files/a.log")
  299. f.Close()
  300. time.Sleep(1 * time.Second)
  301. os.Remove("test_files/a.log")
  302. },
  303. },
  304. {
  305. config: fmt.Sprintf(`
  306. mode: tail
  307. filenames:
  308. - %s
  309. force_inotify: true`, testPattern),
  310. expectedLines: 5,
  311. logLevel: log.DebugLevel,
  312. name: "GlobInotifyChmod",
  313. afterConfigure: func() {
  314. f, _ := os.Create("test_files/a.log")
  315. f.Close()
  316. time.Sleep(1 * time.Second)
  317. os.Chmod("test_files/a.log", 0o000)
  318. },
  319. teardown: func() {
  320. os.Chmod("test_files/a.log", 0o644)
  321. os.Remove("test_files/a.log")
  322. },
  323. },
  324. {
  325. config: fmt.Sprintf(`
  326. mode: tail
  327. filenames:
  328. - %s
  329. force_inotify: true`, testPattern),
  330. expectedLines: 5,
  331. logLevel: log.DebugLevel,
  332. name: "InotifyMkDir",
  333. afterConfigure: func() {
  334. os.Mkdir("test_files/pouet/", 0o700)
  335. },
  336. teardown: func() {
  337. os.Remove("test_files/pouet/")
  338. },
  339. },
  340. }
  341. for _, tc := range tests {
  342. tc := tc
  343. t.Run(tc.name, func(t *testing.T) {
  344. logger, hook := test.NewNullLogger()
  345. logger.SetLevel(tc.logLevel)
  346. subLogger := logger.WithFields(log.Fields{
  347. "type": "file",
  348. })
  349. tomb := tomb.Tomb{}
  350. out := make(chan types.Event)
  351. f := fileacquisition.FileSource{}
  352. if tc.setup != nil {
  353. tc.setup()
  354. }
  355. err := f.Configure([]byte(tc.config), subLogger)
  356. require.NoError(t, err)
  357. if tc.afterConfigure != nil {
  358. tc.afterConfigure()
  359. }
  360. actualLines := 0
  361. if tc.expectedLines != 0 {
  362. go func() {
  363. for {
  364. select {
  365. case <-out:
  366. actualLines++
  367. case <-time.After(2 * time.Second):
  368. return
  369. }
  370. }
  371. }()
  372. }
  373. err = f.StreamingAcquisition(out, &tomb)
  374. cstest.RequireErrorContains(t, err, tc.expectedErr)
  375. if tc.expectedLines != 0 {
  376. fd, err := os.Create("test_files/stream.log")
  377. require.NoError(t, err, "could not create test file")
  378. for i := 0; i < 5; i++ {
  379. _, err = fmt.Fprintf(fd, "%d\n", i)
  380. if err != nil {
  381. t.Fatalf("could not write test file : %s", err)
  382. os.Remove("test_files/stream.log")
  383. }
  384. }
  385. fd.Close()
  386. // we sleep to make sure we detect the new file
  387. time.Sleep(3 * time.Second)
  388. os.Remove("test_files/stream.log")
  389. assert.Equal(t, tc.expectedLines, actualLines)
  390. }
  391. if tc.expectedOutput != "" {
  392. if hook.LastEntry() == nil {
  393. t.Fatalf("expected output %s, but got nothing", tc.expectedOutput)
  394. }
  395. assert.Contains(t, hook.LastEntry().Message, tc.expectedOutput)
  396. hook.Reset()
  397. }
  398. if tc.teardown != nil {
  399. tc.teardown()
  400. }
  401. tomb.Kill(nil)
  402. })
  403. }
  404. }
  405. func TestExclusion(t *testing.T) {
  406. config := `filenames: ["test_files/*.log*"]
  407. exclude_regexps: ["\\.gz$"]`
  408. logger, hook := test.NewNullLogger()
  409. // logger.SetLevel(ts.logLevel)
  410. subLogger := logger.WithFields(log.Fields{
  411. "type": "file",
  412. })
  413. f := fileacquisition.FileSource{}
  414. if err := f.Configure([]byte(config), subLogger); err != nil {
  415. subLogger.Fatalf("unexpected error: %s", err)
  416. }
  417. expectedLogOutput := "Skipping file test_files/test.log.gz as it matches exclude pattern"
  418. if runtime.GOOS == "windows" {
  419. expectedLogOutput = `Skipping file test_files\test.log.gz as it matches exclude pattern \.gz`
  420. }
  421. if hook.LastEntry() == nil {
  422. t.Fatalf("expected output %s, but got nothing", expectedLogOutput)
  423. }
  424. assert.Contains(t, hook.LastEntry().Message, expectedLogOutput)
  425. hook.Reset()
  426. }