|
| 1 | +package handler |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/jacobbednarz/go-csp-collector/internal/utils" |
| 10 | + log "github.com/sirupsen/logrus" |
| 11 | +) |
| 12 | + |
| 13 | +// CSPReport is the structure of the HTTP payload the system receives. |
| 14 | +type ReportAPIReports struct { |
| 15 | + Reports []ReportAPIReport `json:"reports"` |
| 16 | +} |
| 17 | + |
| 18 | +type ReportAPIReport struct { |
| 19 | + Age int `json:"age"` |
| 20 | + Body ReportAPIViolation `json:"body"` |
| 21 | + Type string `json:"type"` |
| 22 | + URL string `json:"url"` |
| 23 | + UserAgent string `json:"user_agent"` |
| 24 | +} |
| 25 | + |
| 26 | +type ReportAPIViolation struct { |
| 27 | + BlockedURL string `json:"blockedURL"` |
| 28 | + ColumnNumber int `json:"columnNumber,omitempty"` |
| 29 | + Disposition string `json:"disposition"` |
| 30 | + DocumentURL string `json:"documentURL"` |
| 31 | + EffectiveDirective string `json:"effectiveDirective"` |
| 32 | + LineNumber int `json:"lineNumber"` |
| 33 | + OriginalPolicy string `json:"originalPolicy"` |
| 34 | + Referrer string `json:"referrer"` |
| 35 | + Sample string `json:"sample,omitempty"` |
| 36 | + SourceFile string `json:"sourceFile"` |
| 37 | + StatusCode int `json:"statusCode"` |
| 38 | +} |
| 39 | + |
| 40 | +type ReportAPIViolationReportHandler struct { |
| 41 | + TruncateQueryStringFragment bool |
| 42 | + BlockedURIs []string |
| 43 | + |
| 44 | + LogClientIP bool |
| 45 | + LogTruncatedClientIP bool |
| 46 | + MetadataObject bool |
| 47 | + |
| 48 | + Logger *log.Logger |
| 49 | +} |
| 50 | + |
| 51 | +func (vrh *ReportAPIViolationReportHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 52 | + if r.Method != http.MethodPost { |
| 53 | + w.WriteHeader(http.StatusMethodNotAllowed) |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + decoder := json.NewDecoder(r.Body) |
| 58 | + var reports_raw []ReportAPIReport |
| 59 | + |
| 60 | + err := decoder.Decode(&reports_raw) |
| 61 | + if err != nil { |
| 62 | + w.WriteHeader(http.StatusUnprocessableEntity) |
| 63 | + vrh.Logger.Debugf("unable to decode invalid JSON payload: %s", err) |
| 64 | + return |
| 65 | + } |
| 66 | + |
| 67 | + defer r.Body.Close() |
| 68 | + |
| 69 | + reports := ReportAPIReports{ |
| 70 | + Reports: reports_raw, |
| 71 | + } |
| 72 | + |
| 73 | + reportValidation := vrh.validateViolation(reports) |
| 74 | + if reportValidation != nil { |
| 75 | + http.Error(w, reportValidation.Error(), http.StatusBadRequest) |
| 76 | + vrh.Logger.Debugf("received invalid payload: %s", reportValidation.Error()) |
| 77 | + return |
| 78 | + } |
| 79 | + |
| 80 | + var metadata interface{} |
| 81 | + if vrh.MetadataObject { |
| 82 | + metadataMap := make(map[string]string) |
| 83 | + query := r.URL.Query() |
| 84 | + |
| 85 | + for k, v := range query { |
| 86 | + metadataMap[k] = v[0] |
| 87 | + } |
| 88 | + |
| 89 | + metadata = metadataMap |
| 90 | + } else { |
| 91 | + metadatas, gotMetadata := r.URL.Query()["metadata"] |
| 92 | + if gotMetadata { |
| 93 | + metadata = metadatas[0] |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + for _, violation := range reports.Reports { |
| 98 | + report_only := violation.Body.Disposition == "report" |
| 99 | + lf := log.Fields{ |
| 100 | + "report_only": report_only, |
| 101 | + "document_uri": violation.Body.DocumentURL, |
| 102 | + "referrer": violation.Body.Referrer, |
| 103 | + "blocked_uri": violation.Body.BlockedURL, |
| 104 | + "violated_directive": violation.Body.EffectiveDirective, |
| 105 | + "effective_directive": violation.Body.EffectiveDirective, |
| 106 | + "original_policy": violation.Body.OriginalPolicy, |
| 107 | + "disposition": violation.Body.Disposition, |
| 108 | + "status_code": violation.Body.StatusCode, |
| 109 | + "source_file": violation.Body.SourceFile, |
| 110 | + "line_number": violation.Body.LineNumber, |
| 111 | + "column_number": violation.Body.ColumnNumber, |
| 112 | + "metadata": metadata, |
| 113 | + "path": r.URL.Path, |
| 114 | + } |
| 115 | + |
| 116 | + if vrh.TruncateQueryStringFragment { |
| 117 | + lf["document_uri"] = utils.TruncateQueryStringFragment(violation.Body.DocumentURL) |
| 118 | + lf["referrer"] = utils.TruncateQueryStringFragment(violation.Body.Referrer) |
| 119 | + lf["blocked_uri"] = utils.TruncateQueryStringFragment(violation.Body.BlockedURL) |
| 120 | + lf["source_file"] = utils.TruncateQueryStringFragment(violation.Body.SourceFile) |
| 121 | + } |
| 122 | + |
| 123 | + if vrh.LogClientIP { |
| 124 | + ip, err := utils.GetClientIP(r) |
| 125 | + if err != nil { |
| 126 | + vrh.Logger.Warnf("unable to parse client ip: %s", err) |
| 127 | + } |
| 128 | + lf["client_ip"] = ip.String() |
| 129 | + } |
| 130 | + |
| 131 | + if vrh.LogTruncatedClientIP { |
| 132 | + ip, err := utils.GetClientIP(r) |
| 133 | + if err != nil { |
| 134 | + vrh.Logger.Warnf("unable to parse client ip: %s", err) |
| 135 | + } |
| 136 | + lf["client_ip"] = utils.TruncateClientIP(ip) |
| 137 | + } |
| 138 | + |
| 139 | + vrh.Logger.WithFields(lf).Info() |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +func (vrh *ReportAPIViolationReportHandler) validateViolation(r ReportAPIReports) error { |
| 144 | + for _, violation := range r.Reports { |
| 145 | + if violation.Type != "csp-violation" { |
| 146 | + continue // Skip the rest of the loop and move to the next iteration |
| 147 | + } |
| 148 | + for _, value := range vrh.BlockedURIs { |
| 149 | + if strings.HasPrefix(violation.Body.BlockedURL, value) { |
| 150 | + err := fmt.Errorf("blocked URI ('%s') is an invalid resource", value) |
| 151 | + return err |
| 152 | + } |
| 153 | + } |
| 154 | + if !strings.HasPrefix(violation.Body.DocumentURL, "http") { |
| 155 | + return fmt.Errorf("document URI ('%s') is invalid", violation.Body.DocumentURL) |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + return nil |
| 160 | +} |
| 161 | + |
| 162 | +func ReportAPICorsHandler(w http.ResponseWriter, r *http.Request) { |
| 163 | + origin := r.Header.Get("Origin") |
| 164 | + method := r.Header.Get("Access-Control-Request-Method") |
| 165 | + header := r.Header.Get("Access-Control-Request-Headers") |
| 166 | + allow_origin := utils.Ternary(origin != "" && utils.ValidateOrigin(origin), origin, "*") |
| 167 | + allow_method := utils.Ternary(method != "", method, "*") |
| 168 | + allow_header := utils.Ternary(header != "", header, "*") |
| 169 | + // Special handling due to bug in Chrome |
| 170 | + // https://bugs.chromium.org/p/chromium/issues/detail?id=1152867 |
| 171 | + w.Header().Set("Access-Control-Allow-Origin", allow_origin) |
| 172 | + w.Header().Set("Access-Control-Allow-Methods", allow_method) |
| 173 | + w.Header().Set("Access-Control-Max-Age", "60") |
| 174 | + w.Header().Set("Access-Control-Allow-Headers", allow_header) |
| 175 | + w.Header().Set("vary", "Origin, Access-Control-Request-Method, Access-Control-Request-Headers") |
| 176 | + |
| 177 | + w.Header().Set("Cross-Origin-Resource-Policy", "cross-origin") |
| 178 | + w.Header().Set("Content-Type", "text/plain;charset=UTF-8") |
| 179 | + w.Header().Set("Server", "go-csp-collector") |
| 180 | + w.WriteHeader(http.StatusOK) |
| 181 | + _, _ = w.Write([]byte("OK")) |
| 182 | +} |
0 commit comments