forked from cloudflare/cloudflare-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_shield_schemas.go
335 lines (278 loc) · 11.7 KB
/
api_shield_schemas.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
package cloudflare
import (
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"strconv"
"time"
"github.com/goccy/go-json"
)
// APIShieldSchema represents a schema stored in API Shield Schema Validation 2.0.
type APIShieldSchema struct {
// ID represents the ID of the schema
ID string `json:"schema_id"`
// Name represents the name of the schema
Name string `json:"name"`
// Kind of the schema
Kind string `json:"kind"`
// Source is the contents of the schema
Source string `json:"source,omitempty"`
// CreatedAt is the time the schema was created
CreatedAt *time.Time `json:"created_at,omitempty"`
// ValidationEnabled controls if schema is used for validation
ValidationEnabled bool `json:"validation_enabled,omitempty"`
}
// CreateAPIShieldSchemaParams represents the parameters to pass when creating a schema in Schema Validation 2.0.
//
// API documentation: https://developers.cloudflare.com/api/operations/api-shield-schema-validation-post-schema
type CreateAPIShieldSchemaParams struct {
// Source is a io.Reader containing the contents of the schema
Source io.Reader
// Name represents the name of the schema.
Name string
// Kind of the schema. This is always set to openapi_v3.
Kind string
// ValidationEnabled controls if schema is used for validation
ValidationEnabled *bool
}
// GetAPIShieldSchemaParams represents the parameters to pass when retrieving a schema with a given schema ID.
//
// API documentation: https://developers.cloudflare.com/api/operations/api-shield-schema-validation-retrieve-information-about-specific-schema
type GetAPIShieldSchemaParams struct {
// SchemaID is the ID of the schema to retrieve
SchemaID string `url:"-"`
// OmitSource specifies whether the contents of the schema should be returned in the "Source" field.
OmitSource *bool `url:"omit_source,omitempty"`
}
// ListAPIShieldSchemasParams represents the parameters to pass when retrieving all schemas.
//
// API documentation: https://developers.cloudflare.com/api/operations/api-shield-schema-validation-retrieve-information-about-all-schemas
type ListAPIShieldSchemasParams struct {
// OmitSource specifies whether the contents of the schema should be returned in the "Source" field.
OmitSource *bool `url:"omit_source,omitempty"`
// ValidationEnabled specifies whether to return only schemas that have validation enabled.
ValidationEnabled *bool `url:"validation_enabled,omitempty"`
// PaginationOptions to apply to the request.
PaginationOptions
}
// DeleteAPIShieldSchemaParams represents the parameters to pass to delete a schema.
//
// API documentation: https://developers.cloudflare.com/api/operations/api-shield-schema-delete-a-schema
type DeleteAPIShieldSchemaParams struct {
// SchemaID is the schema to be deleted
SchemaID string `url:"-"`
}
// UpdateAPIShieldSchemaParams represents the parameters to pass to patch certain fields on an existing schema
//
// API documentation: https://developers.cloudflare.com/api/operations/api-shield-schema-validation-enable-validation-for-a-schema
type UpdateAPIShieldSchemaParams struct {
// SchemaID is the schema to be patched
SchemaID string `json:"-" url:"-"`
// ValidationEnabled controls if schema is used for validation
ValidationEnabled *bool `json:"validation_enabled" url:"-"`
}
// APIShieldGetSchemaResponse represents the response from the GET api_gateway/user_schemas/{id} endpoint.
type APIShieldGetSchemaResponse struct {
Result APIShieldSchema `json:"result"`
Response
}
// APIShieldListSchemasResponse represents the response from the GET api_gateway/user_schemas endpoint.
type APIShieldListSchemasResponse struct {
Result []APIShieldSchema `json:"result"`
ResultInfo `json:"result_info"`
Response
}
// APIShieldCreateSchemaResponse represents the response from the POST api_gateway/user_schemas endpoint.
type APIShieldCreateSchemaResponse struct {
Result APIShieldCreateSchemaResult `json:"result"`
Response
}
// APIShieldDeleteSchemaResponse represents the response from the DELETE api_gateway/user_schemas/{id} endpoint.
type APIShieldDeleteSchemaResponse struct {
Result interface{} `json:"result"`
Response
}
// APIShieldPatchSchemaResponse represents the response from the PATCH api_gateway/user_schemas/{id} endpoint.
type APIShieldPatchSchemaResponse struct {
Result APIShieldSchema `json:"result"`
Response
}
// APIShieldCreateSchemaResult represents the successful result of creating a schema in Schema Validation 2.0.
type APIShieldCreateSchemaResult struct {
// APIShieldSchema is the schema that was created
Schema APIShieldSchema `json:"schema"`
// APIShieldCreateSchemaEvents are non-critical event logs that occurred during processing.
Events APIShieldCreateSchemaEvents `json:"upload_details"`
}
// APIShieldCreateSchemaEvents are event logs that occurred during processing.
//
// The logs are separated into levels of severity.
type APIShieldCreateSchemaEvents struct {
Critical *APIShieldCreateSchemaEventWithLocation `json:"critical,omitempty"`
Errors []APIShieldCreateSchemaEventWithLocations `json:"errors,omitempty"`
Warnings []APIShieldCreateSchemaEventWithLocations `json:"warnings,omitempty"`
}
// APIShieldCreateSchemaEvent is an event log that occurred during processing.
type APIShieldCreateSchemaEvent struct {
// Code identifies the event that occurred
Code uint `json:"code"`
// Message describes the event that occurred
Message string `json:"message"`
}
// APIShieldCreateSchemaEventWithLocation is an event log that occurred during processing, with the location
// in the schema where the event occurred.
type APIShieldCreateSchemaEventWithLocation struct {
APIShieldCreateSchemaEvent
// Location is where the event occurred
// See https://goessner.net/articles/JsonPath/ for JSONPath specification.
Location string `json:"location,omitempty"`
}
// APIShieldCreateSchemaEventWithLocations is an event log that occurred during processing, with the location(s)
// in the schema where the event occurred.
type APIShieldCreateSchemaEventWithLocations struct {
APIShieldCreateSchemaEvent
// Locations lists JSONPath locations where the event occurred
// See https://goessner.net/articles/JsonPath/ for JSONPath specification
Locations []string `json:"locations"`
}
func (cse APIShieldCreateSchemaEventWithLocations) String() string {
var s string
s += cse.Message
if len(cse.Locations) == 0 || (len(cse.Locations) == 1 && cse.Locations[0] == "") {
// append nothing
} else if len(cse.Locations) == 1 {
s += fmt.Sprintf(" (%s)", cse.Locations[0])
} else {
s += " (multiple locations)"
}
return s
}
// GetAPIShieldSchema retrieves information about a specific schema on a zone
//
// API documentation: https://developers.cloudflare.com/api/operations/api-shield-schema-validation-retrieve-information-about-specific-schema
func (api *API) GetAPIShieldSchema(ctx context.Context, rc *ResourceContainer, params GetAPIShieldSchemaParams) (*APIShieldSchema, error) {
if params.SchemaID == "" {
return nil, fmt.Errorf("schema ID must be provided")
}
path := fmt.Sprintf("/zones/%s/api_gateway/user_schemas/%s", rc.Identifier, params.SchemaID)
uri := buildURI(path, params)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return nil, err
}
var asResponse APIShieldGetSchemaResponse
err = json.Unmarshal(res, &asResponse)
if err != nil {
return nil, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return &asResponse.Result, nil
}
// ListAPIShieldSchemas retrieves all schemas for a zone
//
// API documentation: https://developers.cloudflare.com/api/operations/api-shield-schema-validation-retrieve-information-about-all-schemas
func (api *API) ListAPIShieldSchemas(ctx context.Context, rc *ResourceContainer, params ListAPIShieldSchemasParams) ([]APIShieldSchema, ResultInfo, error) {
path := fmt.Sprintf("/zones/%s/api_gateway/user_schemas", rc.Identifier)
uri := buildURI(path, params)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return nil, ResultInfo{}, err
}
var asResponse APIShieldListSchemasResponse
err = json.Unmarshal(res, &asResponse)
if err != nil {
return nil, ResultInfo{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return asResponse.Result, asResponse.ResultInfo, nil
}
// CreateAPIShieldSchema uploads a schema to a zone
//
// API documentation: https://developers.cloudflare.com/api/operations/api-shield-schema-validation-post-schema
func (api *API) CreateAPIShieldSchema(ctx context.Context, rc *ResourceContainer, params CreateAPIShieldSchemaParams) (*APIShieldCreateSchemaResult, error) {
uri := fmt.Sprintf("/zones/%s/api_gateway/user_schemas", rc.Identifier)
if params.Name == "" {
return nil, fmt.Errorf("name must not be empty")
}
if params.Source == nil {
return nil, fmt.Errorf("source must not be nil")
}
// Prepare the form to be submitted
var b bytes.Buffer
w := multipart.NewWriter(&b)
// write fields
if err := w.WriteField("name", params.Name); err != nil {
return nil, fmt.Errorf("error during multi-part form construction: %w", err)
}
if err := w.WriteField("kind", params.Kind); err != nil {
return nil, fmt.Errorf("error during multi-part form construction: %w", err)
}
if params.ValidationEnabled != nil {
if err := w.WriteField("validation_enabled", strconv.FormatBool(*params.ValidationEnabled)); err != nil {
return nil, fmt.Errorf("error during multi-part form construction: %w", err)
}
}
// write schema contents
part, err := w.CreateFormFile("file", params.Name)
if err != nil {
return nil, fmt.Errorf("error during multi-part form construction: %w", err)
}
if _, err := io.Copy(part, params.Source); err != nil {
return nil, fmt.Errorf("error during multi-part form construction: %w", err)
}
if err := w.Close(); err != nil {
return nil, fmt.Errorf("error during multi-part form construction: %w", err)
}
res, err := api.makeRequestContextWithHeaders(ctx, http.MethodPost, uri, &b, http.Header{
"Content-Type": []string{w.FormDataContentType()},
})
if err != nil {
return nil, err
}
var asResponse APIShieldCreateSchemaResponse
err = json.Unmarshal(res, &asResponse)
if err != nil {
return nil, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return &asResponse.Result, nil
}
// DeleteAPIShieldSchema deletes a single schema
//
// API documentation: https://developers.cloudflare.com/api/operations/api-shield-schema-delete-a-schema
func (api *API) DeleteAPIShieldSchema(ctx context.Context, rc *ResourceContainer, params DeleteAPIShieldSchemaParams) error {
if params.SchemaID == "" {
return fmt.Errorf("schema ID must be provided")
}
uri := fmt.Sprintf("/zones/%s/api_gateway/user_schemas/%s", rc.Identifier, params.SchemaID)
res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil)
if err != nil {
return err
}
var asResponse APIShieldDeleteSchemaResponse
err = json.Unmarshal(res, &asResponse)
if err != nil {
return fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return nil
}
// UpdateAPIShieldSchema updates certain fields on an existing schema.
//
// API documentation: https://developers.cloudflare.com/api/operations/api-shield-schema-validation-enable-validation-for-a-schema
func (api *API) UpdateAPIShieldSchema(ctx context.Context, rc *ResourceContainer, params UpdateAPIShieldSchemaParams) (*APIShieldSchema, error) {
if params.SchemaID == "" {
return nil, fmt.Errorf("schema ID must be provided")
}
uri := fmt.Sprintf("/zones/%s/api_gateway/user_schemas/%s", rc.Identifier, params.SchemaID)
res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, params)
if err != nil {
return nil, err
}
// Result should be the updated schema that was patched
var asResponse APIShieldPatchSchemaResponse
err = json.Unmarshal(res, &asResponse)
if err != nil {
return nil, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return &asResponse.Result, nil
}