-
Notifications
You must be signed in to change notification settings - Fork 1
/
rule_script_resource.go
345 lines (296 loc) · 10 KB
/
rule_script_resource.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
336
337
338
339
340
341
342
343
344
345
package provider
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"os"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
openapiclient "github.com/impart-security/terraform-provider-impart/internal/client"
)
// Ensure the implementation satisfies the expected interfaces.
var (
_ resource.Resource = &ruleScriptResource{}
_ resource.ResourceWithConfigure = &ruleScriptResource{}
_ resource.ResourceWithImportState = &ruleScriptResource{}
)
// NewRuleScriptResource is a helper function to simplify the provider implementation.
func NewRuleScriptResource() resource.Resource {
return &ruleScriptResource{}
}
// ruleScriptResource is the resource implementation.
type ruleScriptResource struct {
client *impartAPIClient
}
// ruleScriptResourceModel maps the resource schema data.
type ruleScriptResourceModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
Description types.String `tfsdk:"description"`
Disabled types.Bool `tfsdk:"disabled"`
SourceFile types.String `tfsdk:"source_file"`
SourceHash types.String `tfsdk:"source_hash"`
}
// Configure adds the provider configured client to the resource.
func (r *ruleScriptResource) Configure(ctx context.Context, req resource.ConfigureRequest, _ *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*impartAPIClient)
if !ok {
tflog.Error(ctx, "Unable to prepare the client")
return
}
r.client = client
}
// Metadata returns the resource type name.
func (r *ruleScriptResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_rule_script"
}
// Schema defines the schema for the resource.
func (r *ruleScriptResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manage a rule script.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Description: "Identifier for the rule script.",
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"name": schema.StringAttribute{
Description: "The name for this rule script.",
Required: true,
},
"description": schema.StringAttribute{
Description: "The description for this rule script.",
Optional: true,
},
"disabled": schema.BoolAttribute{
Description: "Set true to disable the rule script.",
Required: true,
},
"source_file": schema.StringAttribute{
Description: "The rule source file.",
Required: true,
},
"source_hash": schema.StringAttribute{
Description: "The rule source hash.",
Optional: true,
},
},
}
}
func (r *ruleScriptResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
// Create a new resource.
func (r *ruleScriptResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
tflog.Debug(ctx, "Preparing to create the rule script resource")
// Retrieve values from plan
var plan ruleScriptResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
rule, err := os.ReadFile(plan.SourceFile.ValueString())
if err != nil {
resp.Diagnostics.AddError(
"Unable to read the rule script source file",
err.Error(),
)
return
}
ruleb64 := base64.StdEncoding.EncodeToString(rule)
rulesScriptPostBody := openapiclient.RulesScriptPostBody{
Name: plan.Name.ValueString(),
Src: ruleb64,
Disabled: plan.Disabled.ValueBool(),
}
if !plan.Description.IsNull() {
description := plan.Description.ValueString()
rulesScriptPostBody.Description = &description
}
// Create new rule
ruleRequest := r.client.RulesScriptsApi.CreateRulesScript(ctx, r.client.OrgID).
RulesScriptPostBody(rulesScriptPostBody)
ruleResponse, _, err := ruleRequest.Execute()
if err != nil {
message := err.Error()
if apiErr, ok := err.(*openapiclient.GenericOpenAPIError); ok {
message = fmt.Sprintf("%s %s", apiErr.Error(), string(apiErr.Body()))
}
resp.Diagnostics.AddError(
"Unable to create the rule script",
message,
)
return
}
// Map response body to model
plan.ID = types.StringValue(ruleResponse.Id)
plan.Name = types.StringValue(ruleResponse.Name)
plan.Description = types.StringValue(ruleResponse.Description)
plan.Disabled = types.BoolValue(ruleResponse.Disabled)
// Set state to fully populated data
diags = resp.State.Set(ctx, plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Created the rule script resource", map[string]any{"success": true})
}
// Read resource information.
func (r *ruleScriptResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
tflog.Debug(ctx, "Preparing to read the rule script resource")
// Get current state
var state ruleScriptResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
currentHash := state.SourceHash
ruleResponse, httpResp, err := r.client.RulesScriptsApi.GetRulesScript(ctx, r.client.OrgID, state.ID.ValueString()).Execute()
if err != nil {
// Treat HTTP 404 Not Found status as a signal to remove/recreate resource
if httpResp.StatusCode == http.StatusNotFound {
resp.State.RemoveResource(ctx)
return
}
message := err.Error()
if apiErr, ok := err.(*openapiclient.GenericOpenAPIError); ok {
message = fmt.Sprintf("%s %s", apiErr.Error(), string(apiErr.Body()))
}
resp.Diagnostics.AddError(
"Unable to read the rule script",
message,
)
return
}
// Map response body to model
state = ruleScriptResourceModel{
ID: types.StringValue(ruleResponse.Id),
Name: types.StringValue(ruleResponse.Name),
SourceFile: state.SourceFile,
Description: types.StringValue(ruleResponse.Description),
Disabled: types.BoolValue(ruleResponse.Disabled),
}
// track hash only if user originally set it
if !currentHash.IsNull() {
bytes, err := base64.StdEncoding.DecodeString(ruleResponse.Src)
if err != nil {
resp.Diagnostics.AddError(
"Unable to base64 decode the rule script",
err.Error(),
)
}
hash, err := calculateSha256(string(bytes))
if err != nil {
resp.Diagnostics.AddError(
"Unable to calculate sha256",
err.Error(),
)
}
state.SourceHash = types.StringValue(hash)
}
// Set refreshed state
diags = resp.State.Set(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Finished reading the rule script resource", map[string]any{"success": true})
}
func (r *ruleScriptResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
tflog.Debug(ctx, "Preparing to update the rule script resource")
// Retrieve values from plan
var plan ruleScriptResourceModel
diags := req.Plan.Get(ctx, &plan)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
rule, err := os.ReadFile(plan.SourceFile.ValueString())
if err != nil {
resp.Diagnostics.AddError(
"Unable to read the rule script source file",
err.Error(),
)
return
}
ruleb64 := base64.StdEncoding.EncodeToString(rule)
rulesScriptPostBody := openapiclient.RulesScriptPostBody{
Name: plan.Name.ValueString(),
Src: ruleb64,
Disabled: plan.Disabled.ValueBool(),
}
if !plan.Description.IsNull() {
description := plan.Description.ValueString()
rulesScriptPostBody.Description = &description
}
ruleRequest := r.client.RulesScriptsApi.UpdateRulesScript(ctx, r.client.OrgID, plan.ID.ValueString()).
RulesScriptPostBody(rulesScriptPostBody)
// update rule
ruleResponse, _, err := ruleRequest.Execute()
if err != nil {
message := err.Error()
if apiErr, ok := err.(*openapiclient.GenericOpenAPIError); ok {
message = fmt.Sprintf("%s %s", apiErr.Error(), string(apiErr.Body()))
}
resp.Diagnostics.AddError(
"Unable to update the rule script",
message,
)
return
}
// Overwrite the rules with refreshed state
state := ruleScriptResourceModel{
ID: types.StringValue(ruleResponse.Id),
Name: types.StringValue(ruleResponse.Name),
SourceFile: plan.SourceFile,
Disabled: types.BoolValue(ruleResponse.Disabled),
SourceHash: plan.SourceHash,
}
if !plan.Description.IsNull() {
state.Description = types.StringValue(ruleResponse.Description)
}
// Set refreshed state
diags = resp.State.Set(ctx, state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Updated the rule script resource", map[string]any{"success": true})
}
func (r *ruleScriptResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
tflog.Debug(ctx, "Preparing to delete the rule script resource")
// Retrieve values from the state
var state ruleScriptResourceModel
diags := req.State.Get(ctx, &state)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// delete the rule
_, err := r.client.RulesScriptsApi.DeleteRulesScript(ctx, r.client.OrgID, state.ID.ValueString()).Execute()
if err != nil {
message := err.Error()
if apiErr, ok := err.(*openapiclient.GenericOpenAPIError); ok {
message = fmt.Sprintf("%s %s", apiErr.Error(), string(apiErr.Body()))
}
resp.Diagnostics.AddError(
"Unable to delete the rule script",
message,
)
return
}
tflog.Debug(ctx, "Deleted the rule script resource", map[string]any{"success": true})
}