-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
https_writer.go
71 lines (62 loc) · 1.61 KB
/
https_writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright 2023 Juan Pablo Tosso and the OWASP Coraza contributors
// SPDX-License-Identifier: Apache-2.0
//go:build !tinygo
// +build !tinygo
package auditlog
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"time"
"github.com/appsentinels/coraza/v3/experimental/plugins/plugintypes"
)
// httpsWriter is used to store logs in a single file
type httpsWriter struct {
io.Closer
formatter plugintypes.AuditLogFormatter
url string
client *http.Client
}
func (h *httpsWriter) Init(c plugintypes.AuditLogConfig) error {
h.formatter = c.Formatter
h.url = c.Target
// now we validate h.url is a valid url
// Although the writer type is HTTPS, we allow HTTP as well
_, err := url.Parse(h.url)
if err != nil {
return err
}
h.client = &http.Client{
Timeout: time.Duration(1 * time.Second),
}
return nil
}
func (h *httpsWriter) Write(al plugintypes.AuditLog) error {
body, err := h.formatter.Format(al)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, h.url, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("User-Agent", "Coraza+v3")
req.Header.Set("Content-Type", h.formatter.MIME())
res, err := h.client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode >= 300 || res.StatusCode < 200 {
return fmt.Errorf("unexpected status code %d", res.StatusCode)
}
if _, err := io.Copy(io.Discard, res.Body); err != nil {
// the stream failed, but the log was received, we don't return error
// we cannot generate a log using the current api
return nil
}
return nil
}
var _ plugintypes.AuditLogWriter = (*httpsWriter)(nil)