Debian Codegraph @

fastly/waf.go

raw symbols SCIP
1 package fastly
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "net/http"
10 "reflect"
11 "strconv"
12 "strings"
13 "time"
14
15 "github.com/google/jsonapi"
16 )
17
18 // WAFConfigurationSet represents information about a configuration_set.
19 type WAFConfigurationSet struct {
20 ID string `jsonapi:"primary,configuration_set"`
21 }
22
23 // WAF is the information about a firewall object.
24 type WAF struct {
25 ID string `jsonapi:"primary,waf"`
26 Version int `jsonapi:"attr,version"`
27 PrefetchCondition string `jsonapi:"attr,prefetch_condition"`
28 Response string `jsonapi:"attr,response"`
29 LastPush *time.Time `jsonapi:"attr,last_push,iso8601"`
30
31 ConfigurationSet *WAFConfigurationSet `jsonapi:"relation,configuration_set"`
32 }
33
34 // wafType is used for reflection because JSONAPI wants to know what it's
35 // decoding into.
36 var wafType = reflect.TypeOf(new(WAF))
37
38 // ListWAFsInput is used as input to the ListWAFs function.
39 type ListWAFsInput struct {
40 // Service is the ID of the service (required).
41 Service string
42
43 // Version is the specific configuration version (required).
44 Version int
45 }
46
47 // ListWAFs returns the list of wafs for the configuration version.
48 func (c *Client) ListWAFs(i *ListWAFsInput) ([]*WAF, error) {
49 if i.Service == "" {
50 return nil, ErrMissingService
51 }
52
53 if i.Version == 0 {
54 return nil, ErrMissingVersion
55 }
56
57 path := fmt.Sprintf("/service/%s/version/%d/wafs", i.Service, i.Version)
58 resp, err := c.Get(path, nil)
59 if err != nil {
60 return nil, err
61 }
62
63 data, err := jsonapi.UnmarshalManyPayload(resp.Body, wafType)
64 if err != nil {
65 return nil, err
66 }
67
68 wafs := make([]*WAF, len(data))
69 for i := range data {
70 typed, ok := data[i].(*WAF)
71 if !ok {
72 return nil, fmt.Errorf("got back a non-WAF response")
73 }
74 wafs[i] = typed
75 }
76 return wafs, nil
77 }
78
79 // CreateWAFInput is used as input to the CreateWAF function.
80 type CreateWAFInput struct {
81 // Service is the ID of the service. Version is the specific configuration
82 // version. Both fields are required.
83 Service string
84 Version int
85
86 ID string `jsonapi:"primary,waf"`
87 PrefetchCondition string `jsonapi:"attr,prefetch_condition,omitempty"`
88 Response string `jsonapi:"attr,response,omitempty"`
89 }
90
91 // CreateWAF creates a new Fastly WAF.
92 func (c *Client) CreateWAF(i *CreateWAFInput) (*WAF, error) {
93 if i.Service == "" {
94 return nil, ErrMissingService
95 }
96
97 if i.Version == 0 {
98 return nil, ErrMissingVersion
99 }
100
101 path := fmt.Sprintf("/service/%s/version/%d/wafs", i.Service, i.Version)
102 resp, err := c.PostJSONAPI(path, i, nil)
103 if err != nil {
104 return nil, err
105 }
106
107 var waf WAF
108 if err := jsonapi.UnmarshalPayload(resp.Body, &waf); err != nil {
109 return nil, err
110 }
111 return &waf, nil
112 }
113
114 // GetWAFInput is used as input to the GetWAF function.
115 type GetWAFInput struct {
116 // Service is the ID of the service. Version is the specific configuration
117 // version. Both fields are required.
118 Service string
119 Version int
120
121 // ID is the id of the WAF to get.
122 ID string
123 }
124
125 func (c *Client) GetWAF(i *GetWAFInput) (*WAF, error) {
126 if i.Service == "" {
127 return nil, ErrMissingService
128 }
129
130 if i.Version == 0 {
131 return nil, ErrMissingVersion
132 }
133
134 if i.ID == "" {
135 return nil, ErrMissingWAFID
136 }
137
138 path := fmt.Sprintf("/service/%s/version/%d/wafs/%s", i.Service, i.Version, i.ID)
139 resp, err := c.Get(path, nil)
140 if err != nil {
141 return nil, err
142 }
143
144 var waf WAF
145 if err := jsonapi.UnmarshalPayload(resp.Body, &waf); err != nil {
146 return nil, err
147 }
148 return &waf, nil
149 }
150
151 // UpdateWAFInput is used as input to the UpdateWAF function.
152 type UpdateWAFInput struct {
153 // Service is the ID of the service. Version is the specific configuration
154 // version. Both fields are required.
155 Service string
156 Version int
157
158 ID string `jsonapi:"primary,waf"`
159 PrefetchCondition string `jsonapi:"attr,prefetch_condition,omitempty"`
160 Response string `jsonapi:"attr,response,omitempty"`
161 }
162
163 // UpdateWAF updates a specific WAF.
164 func (c *Client) UpdateWAF(i *UpdateWAFInput) (*WAF, error) {
165 if i.Service == "" {
166 return nil, ErrMissingService
167 }
168
169 if i.Version == 0 {
170 return nil, ErrMissingVersion
171 }
172
173 if i.ID == "" {
174 return nil, ErrMissingWAFID
175 }
176
177 path := fmt.Sprintf("/service/%s/version/%d/wafs/%s", i.Service, i.Version, i.ID)
178 resp, err := c.PatchJSONAPI(path, i, nil)
179 if err != nil {
180 return nil, err
181 }
182
183 var waf WAF
184 if err := jsonapi.UnmarshalPayload(resp.Body, &waf); err != nil {
185 return nil, err
186 }
187 return &waf, nil
188 }
189
190 // DeleteWAFInput is used as input to the DeleteWAFInput function.
191 type DeleteWAFInput struct {
192 // Service is the ID of the service. Version is the specific configuration
193 // version. Both fields are required.
194 Service string
195 Version int
196
197 // ID is the id of the WAF to delete.
198 ID string
199 }
200
201 func (c *Client) DeleteWAF(i *DeleteWAFInput) error {
202 if i.Service == "" {
203 return ErrMissingService
204 }
205
206 if i.Version == 0 {
207 return ErrMissingVersion
208 }
209
210 if i.ID == "" {
211 return ErrMissingWAFID
212 }
213
214 path := fmt.Sprintf("/service/%s/version/%d/wafs/%s", i.Service, i.Version, i.ID)
215 _, err := c.Delete(path, nil)
216 return err
217 }
218
219 // OWASP is the information about an OWASP object.
220 type OWASP struct {
221 ID string `jsonapi:"primary,owasp"`
222 AllowedHTTPVersions string `jsonapi:"attr,allowed_http_versions"`
223 AllowedMethods string `jsonapi:"attr,allowed_methods"`
224 AllowedRequestContentType string `jsonapi:"attr,allowed_request_content_type"`
225 AllowedRequestContentTypeCharset string `jsonapi:"attr,allowed_request_content_type_charset"`
226 ArgLength int `jsonapi:"attr,arg_length"`
227 ArgNameLength int `jsonapi:"attr,arg_name_length"`
228 CombinedFileSizes int `jsonapi:"attr,combined_file_sizes"`
229 CreatedAt *time.Time `jsonapi:"attr,created_at,iso8601"`
230 CriticalAnomalyScore int `jsonapi:"attr,critical_anomaly_score"`
231 CRSValidateUTF8Encoding bool `jsonapi:"attr,crs_validate_utf8_encoding"`
232 ErrorAnomalyScore int `jsonapi:"attr,error_anomaly_score"`
233 HighRiskCountryCodes string `jsonapi:"attr,high_risk_country_codes"`
234 HTTPViolationScoreThreshold int `jsonapi:"attr,http_violation_score_threshold"`
235 InboundAnomalyScoreThreshold int `jsonapi:"attr,inbound_anomaly_score_threshold"`
236 LFIScoreThreshold int `jsonapi:"attr,lfi_score_threshold"`
237 MaxFileSize int `jsonapi:"attr,max_file_size"`
238 MaxNumArgs int `jsonapi:"attr,max_num_args"`
239 NoticeAnomalyScore int `jsonapi:"attr,notice_anomaly_score"`
240 ParanoiaLevel int `jsonapi:"attr,paranoia_level"`
241 PHPInjectionScoreThreshold int `jsonapi:"attr,php_injection_score_threshold"`
242 RCEScoreThreshold int `jsonapi:"attr,rce_score_threshold"`
243 RestrictedExtensions string `jsonapi:"attr,restricted_extensions"`
244 RestrictedHeaders string `jsonapi:"attr,restricted_headers"`
245 RFIScoreThreshold int `jsonapi:"attr,rfi_score_threshold"`
246 SessionFixationScoreThreshold int `jsonapi:"attr,session_fixation_score_threshold"`
247 SQLInjectionScoreThreshold int `jsonapi:"attr,sql_injection_score_threshold"`
248 TotalArgLength int `jsonapi:"attr,total_arg_length"`
249 UpdatedAt *time.Time `jsonapi:"attr,updated_at,iso8601"`
250 WarningAnomalyScore int `jsonapi:"attr,warning_anomaly_score"`
251 XSSScoreThreshold int `jsonapi:"attr,xss_score_threshold"`
252 }
253
254 // GetOWASPInput is used as input to the GetOWASP function.
255 type GetOWASPInput struct {
256 // Service is the ID of the service. ID is the ID of the firewall.
257 // Both fields are required.
258 Service string
259 ID string
260 }
261
262 // GetOWASP gets OWASP settings for a service firewall object.
263 func (c *Client) GetOWASP(i *GetOWASPInput) (*OWASP, error) {
264 if i.Service == "" {
265 return nil, ErrMissingService
266 }
267
268 if i.ID == "" {
269 return nil, ErrMissingWAFID
270 }
271
272 path := fmt.Sprintf("/service/%s/wafs/%s/owasp", i.Service, i.ID)
273
274 resp, err := c.Get(path, nil)
275 if err != nil {
276 return nil, err
277 }
278
279 var owasp OWASP
280 if err := jsonapi.UnmarshalPayload(resp.Body, &owasp); err != nil {
281 return nil, err
282 }
283 return &owasp, nil
284 }
285
286 // CreateOWASPInput is used as input to the CreateOWASP function.
287 type CreateOWASPInput struct {
288 // Service is the ID of the service. ID is the ID of the firewall.
289 // Both fields are required.
290 Service string
291 ID string `jsonapi:"primary,owasp"`
292 Type string `jsonapi:"attr,type"`
293 }
294
295 // CreateOWASP creates an OWASP settings object for a service firewall object.
296 func (c *Client) CreateOWASP(i *CreateOWASPInput) (*OWASP, error) {
297 if i.Service == "" {
298 return nil, ErrMissingService
299 }
300
301 if i.ID == "" {
302 return nil, ErrMissingWAFID
303 }
304
305 path := fmt.Sprintf("/service/%s/wafs/%s/owasp", i.Service, i.ID)
306 resp, err := c.PostJSONAPI(path, i, nil)
307 if err != nil {
308 return nil, err
309 }
310
311 var owasp OWASP
312 if err := jsonapi.UnmarshalPayload(resp.Body, &owasp); err != nil {
313 return nil, err
314 }
315 return &owasp, nil
316 }
317
318 // UpdateOWASPInput is used as input to the CreateOWASP function.
319 type UpdateOWASPInput struct {
320 // Service is the ID of the service. ID is the ID of the firewall.
321 // Both fields are required.
322 Service string
323 ID string
324 OWASPID string `jsonapi:"primary,owasp,omitempty"`
325
326 Type string `jsonapi:"attr,type"`
327 AllowedHTTPVersions string `jsonapi:"attr,allowed_http_versions,omitempty"`
328 AllowedMethods string `jsonapi:"attr,allowed_methods,omitempty"`
329 AllowedRequestContentType string `jsonapi:"attr,allowed_request_content_type,omitempty"`
330 AllowedRequestContentTypeCharset string `jsonapi:"attr,allowed_request_content_type_charset,omitempty"`
331 ArgLength int `jsonapi:"attr,arg_length,omitempty"`
332 ArgNameLength int `jsonapi:"attr,arg_name_length,omitempty"`
333 CombinedFileSizes int `jsonapi:"attr,combined_file_sizes,omitempty"`
334 CreatedAt *time.Time `jsonapi:"attr,created_at,omitempty,iso8601"`
335 CriticalAnomalyScore int `jsonapi:"attr,critical_anomaly_score,omitempty"`
336 CRSValidateUTF8Encoding bool `jsonapi:"attr,crs_validate_utf8_encoding,omitempty"`
337 ErrorAnomalyScore int `jsonapi:"attr,error_anomaly_score,omitempty"`
338 HighRiskCountryCodes string `jsonapi:"attr,high_risk_country_codes,omitempty"`
339 HTTPViolationScoreThreshold int `jsonapi:"attr,http_violation_score_threshold,omitempty"`
340 InboundAnomalyScoreThreshold int `jsonapi:"attr,inbound_anomaly_score_threshold,omitempty"`
341 LFIScoreThreshold int `jsonapi:"attr,lfi_score_threshold,omitempty"`
342 MaxFileSize int `jsonapi:"attr,max_file_size,omitempty"`
343 MaxNumArgs int `jsonapi:"attr,max_num_args,omitempty"`
344 NoticeAnomalyScore int `jsonapi:"attr,notice_anomaly_score,omitempty"`
345 ParanoiaLevel int `jsonapi:"attr,paranoia_level,omitempty"`
346 PHPInjectionScoreThreshold int `jsonapi:"attr,php_injection_score_threshold,omitempty"`
347 RCEScoreThreshold int `jsonapi:"attr,rce_score_threshold,omitempty"`
348 RestrictedExtensions string `jsonapi:"attr,restricted_extensions,omitempty"`
349 RestrictedHeaders string `jsonapi:"attr,restricted_headers,omitempty"`
350 RFIScoreThreshold int `jsonapi:"attr,rfi_score_threshold,omitempty"`
351 SessionFixationScoreThreshold int `jsonapi:"attr,session_fixation_score_threshold,omitempty"`
352 SQLInjectionScoreThreshold int `jsonapi:"attr,sql_injection_score_threshold,omitempty"`
353 TotalArgLength int `jsonapi:"attr,total_arg_length,omitempty"`
354 UpdatedAt *time.Time `jsonapi:"attr,updated_at,omitempty,iso8601"`
355 WarningAnomalyScore int `jsonapi:"attr,warning_anomaly_score,omitempty"`
356 XSSScoreThreshold int `jsonapi:"attr,xss_score_threshold,omitempty"`
357 }
358
359 // CreateOWASP creates an OWASP settings object for a service firewall object.
360 func (c *Client) UpdateOWASP(i *UpdateOWASPInput) (*OWASP, error) {
361 if i.Service == "" {
362 return nil, ErrMissingService
363 }
364
365 if i.ID == "" {
366 return nil, ErrMissingWAFID
367 }
368
369 if i.OWASPID == "" {
370 return nil, ErrMissingOWASPID
371 }
372
373 path := fmt.Sprintf("/service/%s/wafs/%s/owasp", i.Service, i.ID)
374 resp, err := c.PatchJSONAPI(path, i, nil)
375 if err != nil {
376 return nil, err
377 }
378
379 var owasp OWASP
380 if err := jsonapi.UnmarshalPayload(resp.Body, &owasp); err != nil {
381 return nil, err
382 }
383 return &owasp, nil
384 }
385
386 // Rule is the information about a WAF rule.
387 type Rule struct {
388 ID string `jsonapi:"primary,rule"`
389 RuleID string `jsonapi:"attr,rule_id,omitempty"`
390 Severity int `jsonapi:"attr,severity,omitempty"`
391 Message string `jsonapi:"attr,message,omitempty"`
392 }
393
394 // rulesType is used for reflection because JSONAPI wants to know what it's
395 // decoding into.
396 var rulesType = reflect.TypeOf(new(Rule))
397
398 // GetRules returns the list of wafs for the configuration version.
399 func (c *Client) GetRules() ([]*Rule, error) {
400 path := fmt.Sprintf("/wafs/rules")
401 resp, err := c.Get(path, nil)
402 if err != nil {
403 return nil, err
404 }
405
406 data, err := jsonapi.UnmarshalManyPayload(resp.Body, rulesType)
407 if err != nil {
408 return nil, err
409 }
410
411 rules := make([]*Rule, len(data))
412 for i := range data {
413 typed, ok := data[i].(*Rule)
414 if !ok {
415 return nil, fmt.Errorf("got back a non-Rules response")
416 }
417 rules[i] = typed
418 }
419
420 return rules, nil
421 }
422
423 // GetRuleVCLInput is used as input to the GetRuleVCL function.
424 type GetRuleInput struct {
425 // RuleID is the ID of the rule and is required.
426 RuleID string
427 }
428
429 // GetRule gets a Rule using the Rule ID.
430 func (c *Client) GetRule(i *GetRuleInput) (*Rule, error) {
431 if i.RuleID == "" {
432 return nil, ErrMissingRuleID
433 }
434
435 path := fmt.Sprintf("/wafs/rules/%s", i.RuleID)
436 resp, err := c.Get(path, nil)
437 if err != nil {
438 return nil, err
439 }
440
441 var rule Rule
442 if err := jsonapi.UnmarshalPayload(resp.Body, &rule); err != nil {
443 return nil, err
444 }
445 return &rule, nil
446 }
447
448 // RuleVCL is the information about a Rule's VCL.
449 type RuleVCL struct {
450 ID string `jsonapi:"primary,rule_vcl"`
451 VCL string `jsonapi:"attr,vcl,omitempty"`
452 }
453
454 // GetRuleVCL gets the VCL for a Rule.
455 func (c *Client) GetRuleVCL(i *GetRuleInput) (*RuleVCL, error) {
456 if i.RuleID == "" {
457 return nil, ErrMissingRuleID
458 }
459
460 path := fmt.Sprintf("/wafs/rules/%s/vcl", i.RuleID)
461 resp, err := c.Get(path, nil)
462 if err != nil {
463 return nil, err
464 }
465
466 var vcl RuleVCL
467 if err := jsonapi.UnmarshalPayload(resp.Body, &vcl); err != nil {
468 return nil, err
469 }
470 return &vcl, nil
471 }
472
473 // GetWAFRuleVCLInput is used as input to the GetWAFRuleVCL function.
474 type GetWAFRuleVCLInput struct {
475 // ID is the ID of the firewall. RuleID is the ID of the rule.
476 // Both are required.
477 ID string
478 RuleID string
479 }
480
481 // GetWAFRuleVCL gets the VCL for a role associated with a firewall WAF.
482 func (c *Client) GetWAFRuleVCL(i *GetWAFRuleVCLInput) (*RuleVCL, error) {
483 if i.ID == "" {
484 return nil, ErrMissingWAFID
485 }
486
487 if i.RuleID == "" {
488 return nil, ErrMissingRuleID
489 }
490
491 path := fmt.Sprintf("/wafs/%s/rules/%s/vcl", i.ID, i.RuleID)
492 resp, err := c.Get(path, nil)
493 if err != nil {
494 return nil, err
495 }
496
497 var vcl RuleVCL
498 if err := jsonapi.UnmarshalPayload(resp.Body, &vcl); err != nil {
499 return nil, err
500 }
501 return &vcl, nil
502 }
503
504 // Ruleset is the information about a firewall object's ruleset.
505 type Ruleset struct {
506 ID string `jsonapi:"primary,ruleset"`
507 VCL string `jsonapi:"attr,vcl,omitempty"`
508 LastPush *time.Time `jsonapi:"attr,last_push,omitempty,iso8601"`
509 }
510
511 // GetWAFRuleRuleSetsInput is used as input to the GetWAFRuleRuleSets function.
512 type GetWAFRuleRuleSetsInput struct {
513 // Service is the ID of the service. ID is the ID of the firewall.
514 // Both fields are required.
515 Service string
516 ID string
517 }
518
519 // GetWAFRuleRuleSets gets the VCL for rulesets associated with a firewall WAF.
520 func (c *Client) GetWAFRuleRuleSets(i *GetWAFRuleRuleSetsInput) (*Ruleset, error) {
521 if i.Service == "" {
522 return nil, ErrMissingService
523 }
524
525 if i.ID == "" {
526 return nil, ErrMissingWAFID
527 }
528
529 path := fmt.Sprintf("/service/%s/wafs/%s/ruleset", i.Service, i.ID)
530 resp, err := c.Get(path, nil)
531 if err != nil {
532 return nil, err
533 }
534
535 var ruleset Ruleset
536 if err := jsonapi.UnmarshalPayload(resp.Body, &ruleset); err != nil {
537 return nil, err
538 }
539 return &ruleset, nil
540 }
541
542 // UpdateWAFRuleRuleSetsInput is used as input to the UpdateWAFRuleSets function.
543 type UpdateWAFRuleRuleSetsInput struct {
544 // Service is the ID of the service. ID is the ID of the firewall.
545 // Both fields are required.
546 Service string
547 ID string `jsonapi:"primary,ruleset"`
548 }
549
550 // UpdateWAFRuleSets updates the rulesets for a role associated with a firewall WAF.
551 func (c *Client) UpdateWAFRuleSets(i *UpdateWAFRuleRuleSetsInput) (*Ruleset, error) {
552 if i.Service == "" {
553 return nil, ErrMissingService
554 }
555
556 if i.ID == "" {
557 return nil, ErrMissingWAFID
558 }
559
560 path := fmt.Sprintf("/service/%s/wafs/%s/ruleset", i.Service, i.ID)
561 resp, err := c.PatchJSONAPI(path, i, nil)
562 if err != nil {
563 return nil, err
564 }
565
566 var ruleset Ruleset
567 if err := jsonapi.UnmarshalPayload(resp.Body, &ruleset); err != nil {
568 return nil, err
569 }
570 return &ruleset, nil
571 }
572
573 // GetWAFRuleStatusesInput specifies the parameters for the GetWAFRuleStatuses call
574 type GetWAFRuleStatusesInput struct {
575 Service string
576 WAF string
577 Filters GetWAFRuleStatusesFilters
578 }
579
580 // WAFRuleStatus stores the information about a rule received from Fastly
581 type WAFRuleStatus struct {
582 ID string `jsonapi:"primary,rule_status"` // This is the ID of the status, not the ID of the rule. Currently, it is of the format ${WAF_ID}-${rule_ID}, if you want to infer those based on this field.
583 Status string `jsonapi:"attr,status"`
584
585 Tag string `jsonapi:"attr,name,omitempty"` // This will only be set in a response for modifying rules based on tag.
586
587 // HACK: These two fields are supposed to be sent in response
588 // to requests for rule status data, but the entire "Relationships"
589 // field is currently missing from Fastly responses, so they are
590 // instead inferred from the status ID (see inferIDs method).
591 // WAF newTypeThatDoesntExistNow `jsonapi:"relation,waf"`
592 // Rule newTypeThatDoesntExistNow `jsonapi:"relation,rule"`
593 }
594
595 // GetWAFRuleStatusesFilters provides a set of parameters for filtering the
596 // results of the call to get the rules associated with a WAF.
597 type GetWAFRuleStatusesFilters struct {
598 Status string
599 Accuracy int
600 Maturity int
601 Message string
602 Revision int
603 RuleID string
604 TagID int // Filter by a single tag ID.
605 TagName string // Filter by single tag name.
606 Version string
607 Tags []int // Return all rules with any of the specified tag IDs.
608 MaxResults int // Max number of returned results per request.
609 Page int // Which page of results to return.
610 }
611
612 // formatFilters converts user input into query parameters for filtering
613 // Fastly results for rules in a WAF.
614 func (i *GetWAFRuleStatusesInput) formatFilters() map[string]string {
615 input := i.Filters
616 result := map[string]string{}
617 pairings := map[string]interface{}{
618 "filter[status]": input.Status,
619 "filter[rule][accuracy]": input.Accuracy,
620 "filter[rule][maturity]": input.Maturity,
621 "filter[rule][message]": input.Message,
622 "filter[rule][revision]": input.Revision,
623 "filter[rule][rule_id]": input.RuleID,
624 "filter[rule][tags]": input.TagID,
625 "filter[rule][tags][name]": input.TagName,
626 "filter[rule][version]": input.Version,
627 "include": input.Tags,
628 "page[size]": input.MaxResults,
629 "page[number]": input.Page, // starts at 1, not 0
630 }
631 // NOTE: This setup means we will not be able to send the zero value
632 // of any of these filters. It doesn't appear we would need to at present.
633 for key, value := range pairings {
634 switch t := reflect.TypeOf(value).String(); t {
635 case "string":
636 if value != "" {
637 result[key] = value.(string)
638 }
639 case "int":
640 if value != 0 {
641 result[key] = strconv.Itoa(value.(int))
642 }
643 case "[]int":
644 // convert ints to strings
645 toStrings := []string{}
646 values := value.([]int)
647 for _, i := range values {
648 toStrings = append(toStrings, strconv.Itoa(i))
649 }
650 // concat strings
651 if len(values) > 0 {
652 result[key] = strings.Join(toStrings, ",")
653 }
654 }
655 }
656 return result
657 }
658
659 // GetWAFRuleStatuses fetches the status of a subset of rules associated with a WAF.
660 func (c *Client) GetWAFRuleStatuses(i *GetWAFRuleStatusesInput) (GetWAFRuleStatusesResponse, error) {
661 statusResponse := GetWAFRuleStatusesResponse{Rules: []*WAFRuleStatus{}}
662 if i.Service == "" {
663 return statusResponse, ErrMissingService
664 }
665 if i.WAF == "" {
666 return statusResponse, ErrMissingWAFID
667 }
668
669 path := fmt.Sprintf("/service/%s/wafs/%s/rule_statuses", i.Service, i.WAF)
670 filters := &RequestOptions{Params: i.formatFilters()}
671
672 resp, err := c.Get(path, filters)
673 if err != nil {
674 return statusResponse, err
675 }
676 err = c.interpretWAFRuleStatusesPage(&statusResponse, resp)
677 // NOTE: It's possible for statusResponse to be partially completed before an error
678 // was encountered, so the presence of a statusResponse doesn't preclude the presence of
679 // an error.
680 return statusResponse, err
681 }
682
683 // interpretWAFRuleStatusesPage accepts a Fastly response for a set of WAF rule statuses
684 // and unmarshals the results. If there are more pages of results, it fetches the next
685 // page, adds that response to the array of results, and repeats until all results have
686 // been fetched.
687 func (c *Client) interpretWAFRuleStatusesPage(answer *GetWAFRuleStatusesResponse, received *http.Response) error {
688 // before we pull the status info out of the response body, fetch
689 // pagination info from it:
690 pages, body, err := getPages(received.Body)
691 if err != nil {
692 return err
693 }
694 data, err := jsonapi.UnmarshalManyPayload(body, reflect.TypeOf(new(WAFRuleStatus)))
695 if err != nil {
696 return err
697 }
698
699 for i := range data {
700 typed, ok := data[i].(*WAFRuleStatus)
701 if !ok {
702 return fmt.Errorf("got back response of unexpected type")
703 }
704 answer.Rules = append(answer.Rules, typed)
705 }
706 if pages.Next != "" {
707 // NOTE: pages.Next URL includes filters already
708 resp, err := c.SimpleGet(pages.Next)
709 if err != nil {
710 return err
711 }
712 c.interpretWAFRuleStatusesPage(answer, resp)
713 }
714 return nil
715 }
716
717 // linksResponse is used to pull the "Links" pagination fields from
718 // a call to Fastly; these are excluded from the results of the jsonapi
719 // call to `UnmarshalManyPayload()`, so we have to fetch them separately.
720 type linksResponse struct {
721 Links paginationInfo `json:"links"`
722 }
723
724 // paginationInfo stores links to searches related to the current one, showing
725 // any information about additional results being stored on another page
726 type paginationInfo struct {
727 First string `json:"first,omitempty"`
728 Last string `json:"last,omitempty"`
729 Next string `json:"next,omitempty"`
730 }
731
732 // GetWAFRuleStatusesResponse is the data returned to the user from a GetWAFRuleStatus call
733 type GetWAFRuleStatusesResponse struct {
734 Rules []*WAFRuleStatus
735 }
736
737 // getPages parses a response to get the pagination data without destroying
738 // the reader we receive as "resp.Body"; this essentially copies resp.Body
739 // and returns it so we can use it again.
740 func getPages(body io.Reader) (paginationInfo, io.Reader, error) {
741 var buf bytes.Buffer
742 tee := io.TeeReader(body, &buf)
743
744 bodyBytes, err := ioutil.ReadAll(tee)
745 if err != nil {
746 return paginationInfo{}, nil, err
747 }
748
749 var pages linksResponse
750 json.Unmarshal(bodyBytes, &pages)
751 return pages.Links, bytes.NewReader(buf.Bytes()), nil
752 }
753
754 // GetWAFRuleStatusInput specifies the parameters for the GetWAFRuleStatus call.
755 type GetWAFRuleStatusInput struct {
756 ID int
757 Service string
758 WAF string
759 }
760
761 // GetWAFRuleStatus fetches the status of a single rule associated with a WAF.
762 func (c *Client) GetWAFRuleStatus(i *GetWAFRuleStatusInput) (WAFRuleStatus, error) {
763 if i.ID == 0 {
764 return WAFRuleStatus{}, ErrMissingRuleID
765 }
766 if i.Service == "" {
767 return WAFRuleStatus{}, ErrMissingService
768 }
769 if i.WAF == "" {
770 return WAFRuleStatus{}, ErrMissingWAFID
771 }
772
773 path := fmt.Sprintf("/service/%s/wafs/%s/rules/%d/rule_status", i.Service, i.WAF, i.ID)
774 resp, err := c.Get(path, nil)
775 if err != nil {
776 return WAFRuleStatus{}, err
777 }
778
779 var status WAFRuleStatus
780 err = jsonapi.UnmarshalPayload(resp.Body, &status)
781 return status, err
782 }
783
784 // UpdateWAFRuleStatusInput specifies the parameters for the UpdateWAFRuleStatus call.
785 type UpdateWAFRuleStatusInput struct {
786 ID string `jsonapi:"primary,rule_status"` // The ID of the rule status. Currently in the format ${WAF_ID}-${rule_ID}.
787 RuleID int
788 Service string
789 WAF string
790 Status string `jsonapi:"attr,status"`
791 }
792
793 // validate makes sure the UpdateWAFRuleStatusInput instance has all
794 // fields we need to request a change.
795 func (i UpdateWAFRuleStatusInput) validate() error {
796 if i.ID == "" {
797 return ErrMissingID
798 }
799 if i.RuleID == 0 {
800 return ErrMissingRuleID
801 }
802 if i.Service == "" {
803 return ErrMissingService
804 }
805 if i.WAF == "" {
806 return ErrMissingWAFID
807 }
808 if i.Status == "" {
809 return ErrMissingStatus
810 }
811 return nil
812 }
813
814 // UpdateWAFRuleStatus changes the status of a single rule associated with a WAF.
815 func (c *Client) UpdateWAFRuleStatus(i *UpdateWAFRuleStatusInput) (WAFRuleStatus, error) {
816 if err := i.validate(); err != nil {
817 return WAFRuleStatus{}, err
818 }
819
820 path := fmt.Sprintf("/service/%s/wafs/%s/rules/%d/rule_status", i.Service, i.WAF, i.RuleID)
821
822 var buf bytes.Buffer
823 err := jsonapi.MarshalPayload(&buf, i)
824 if err != nil {
825 return WAFRuleStatus{}, err
826 }
827
828 options := &RequestOptions{
829 Body: &buf,
830 Headers: map[string]string{
831 "Content-Type": jsonapi.MediaType,
832 "Accept": jsonapi.MediaType,
833 },
834 }
835
836 resp, err := c.Patch(path, options)
837 if err != nil {
838 return WAFRuleStatus{}, err
839 }
840
841 var status WAFRuleStatus
842 err = jsonapi.UnmarshalPayload(resp.Body, &status)
843 return status, err
844 }
845
846 // UpdateWAFRuleTagStatusInput specifies the parameters for the UpdateWAFRuleStatus call.
847 type UpdateWAFRuleTagStatusInput struct {
848 Service string
849 WAF string
850 Status string `json:"status"` // `jsonapi:"attr,status"`
851 Tag string `json:"name"` // `jsonapi:"attr,name"`
852 Force bool `json:"force"` // `jsonapi:"attr,force"`
853 // HACK: This won't work with the jsonapi struct tags, because the POST body expected by
854 // Fastly doesn't conform to the jsonapi spec -- there's no ID field at the top level,
855 // and there's no way for us to indicate the "type" of the entity without a primary key.
856 // ID field is required: http://jsonapi.org/format/#document-resource-objects
857 }
858
859 // updateWAFRuleTagStatusBody is the top-level object sent to Fastly based on
860 // UpdateWAFRuleTagStatusInput from the user.
861 type updateWAFRuleTagStatusBody struct {
862 Data updateWAFRuleTagStatusData `json:"data"`
863 }
864
865 type updateWAFRuleTagStatusData struct {
866 Type string `json:"type"` // hard-coded because we can't use jsonapi
867 Attributes *UpdateWAFRuleTagStatusInput `json:"attributes"` // supplied by user as input
868 }
869
870 // validate makes sure the UpdateWAFRuleStatusInput instance has all
871 // fields we need to request a change. Almost, but not quite, identical to
872 // UpdateWAFRuleStatusInput.validate()
873 func (i UpdateWAFRuleTagStatusInput) validate() error {
874 if i.Tag == "" {
875 return ErrMissingTag
876 }
877 if i.Service == "" {
878 return ErrMissingService
879 }
880 if i.WAF == "" {
881 return ErrMissingWAFID
882 }
883 if i.Status == "" {
884 return ErrMissingStatus
885 }
886 return nil
887 }
888
889 // UpdateWAFRuleTagStatus changes the status of a single rule associated with a WAF.
890 // NOTE: This call currently appears to return *all* rules attached to the WAF, rather
891 // than just the ones that were modified by the call.
892 func (c *Client) UpdateWAFRuleTagStatus(input *UpdateWAFRuleTagStatusInput) (GetWAFRuleStatusesResponse, error) {
893 if err := input.validate(); err != nil {
894 return GetWAFRuleStatusesResponse{}, err
895 }
896
897 path := fmt.Sprintf("/service/%s/wafs/%s/rule_statuses", input.Service, input.WAF)
898
899 body := updateWAFRuleTagStatusBody{
900 Data: updateWAFRuleTagStatusData{
901 Type: "rule_status",
902 Attributes: input,
903 },
904 }
905 encoded, err := json.Marshal(body)
906 if err != nil {
907 return GetWAFRuleStatusesResponse{}, err
908 }
909
910 options := &RequestOptions{
911 Body: bytes.NewReader(encoded),
912 Headers: map[string]string{
913 "Content-Type": jsonapi.MediaType,
914 "Accept": jsonapi.MediaType,
915 },
916 }
917
918 resp, err := c.Post(path, options)
919 if err != nil {
920 return GetWAFRuleStatusesResponse{}, err
921 }
922
923 statusResponse := GetWAFRuleStatusesResponse{Rules: []*WAFRuleStatus{}}
924 err = c.interpretWAFRuleStatusesPage(&statusResponse, resp)
925
926 return statusResponse, err
927 }
928
929 // UpdateWAFConfigSetInput is used as input to the UpdateWAFConfigSet function.
930 type UpdateWAFConfigSetInput struct {
931 WAFList []ConfigSetWAFs
932 ConfigSetID string
933 }
934
935 // ConfigSetWAFs used to store the ID of a WAF needed to update config set relationships
936 type ConfigSetWAFs struct {
937 ID string `jsonapi:"primary,waf"`
938 }
939
940 // UpdateWAFConfigSetResponse stores the list of WAFs returned from the call to update its config set
941 type UpdateWAFConfigSetResponse struct {
942 IDs []ConfigSetWAFs `jsonapi:"primary,waf"`
943 }
944
945 // UpdateWAFConfigSet updates a list of WAFs with the given configset
946 func (c *Client) UpdateWAFConfigSet(i *UpdateWAFConfigSetInput) (UpdateWAFConfigSetResponse, error) {
947 if err := i.validate(); err != nil {
948 return UpdateWAFConfigSetResponse{}, err
949 }
950 var wafs []interface{}
951 for _, w := range i.WAFList {
952 wafs = append(wafs, &w)
953 }
954
955 path := fmt.Sprintf("/wafs/configuration_sets/%s/relationships/wafs", i.ConfigSetID)
956 resp, err := c.PatchJSONAPI(path, wafs, nil)
957 if err != nil {
958 return UpdateWAFConfigSetResponse{}, err
959 }
960
961 wafConfigSetResponse := UpdateWAFConfigSetResponse{}
962
963 err = c.interpretWAFCongfigSetResponse(&wafConfigSetResponse, resp)
964 if err != nil {
965 return UpdateWAFConfigSetResponse{}, err
966 }
967
968 return wafConfigSetResponse, nil
969 }
970
971 // validate makes sure the UpdateWAFConfigSetInput instance has all
972 // fields we need to assign the config set to the WAF(s)
973 func (i UpdateWAFConfigSetInput) validate() error {
974 if i.ConfigSetID == "" {
975 return ErrMissingConfigSetID
976 }
977
978 if len(i.WAFList) == 0 {
979 return ErrMissingWAFList
980 }
981
982 return nil
983 }
984
985 // interpretWAFCongfigSetResponse accepts a Fastly response containing a set of WAF ID's that
986 // where given to associate with the config set and unmarshals the results.
987 // If there are more pages of results, it fetches the next
988 // page, adds that response to the array of results, and repeats until all results have
989 // been fetched.
990 func (c *Client) interpretWAFCongfigSetResponse(answer *UpdateWAFConfigSetResponse, received *http.Response) error {
991 pages, body, err := getPages(received.Body)
992 if err != nil {
993 return err
994 }
995 data, err := jsonapi.UnmarshalManyPayload(body, reflect.TypeOf([]ConfigSetWAFs{}))
996 if err != nil {
997 return err
998 }
999
1000 for i := range data {
1001 typed, ok := data[i].(*ConfigSetWAFs)
1002 if !ok {
1003 return fmt.Errorf("got back response of unexpected type")
1004 }
1005 answer.IDs = append(answer.IDs, *typed)
1006 }
1007
1008 if pages.Next != "" {
1009 resp, err := c.SimpleGet(pages.Next)
1010 if err != nil {
1011 return err
1012 }
1013 c.interpretWAFCongfigSetResponse(answer, resp)
1014 }
1015
1016 return nil
1017 }