-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathprovider.go
More file actions
371 lines (344 loc) · 10.8 KB
/
provider.go
File metadata and controls
371 lines (344 loc) · 10.8 KB
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// Package provider for Terraform for OWASP DependencyTrack https://dependencytrack.org
package provider
import (
"context"
"fmt"
"net/http"
"os"
"strings"
dtrack "github.com/DependencyTrack/client-go"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/provider"
"github.com/hashicorp/terraform-plugin-framework/provider/schema"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-log/tflog"
)
// Ensure satisfies various provider interfaces.
var (
_ provider.Provider = &dependencyTrackProvider{}
)
type (
dependencyTrackProvider struct {
// Version is set to the provider version on release, "dev" when the
// provider is built and ran locally, and "test" when running acceptance
// testing.
version string
}
dependencyTrackProviderModel struct {
Host types.String `tfsdk:"host"`
Key types.String `tfsdk:"key"`
Auth *providerAuthModel `tfsdk:"auth"`
RootCA types.String `tfsdk:"root_ca"`
MTLS *dependencyTrackProviderMtlsModel `tfsdk:"mtls"`
Headers []dependencyTrackProviderHeadersModel `tfsdk:"headers"`
}
dependencyTrackProviderHeadersModel struct {
Name types.String `tfsdk:"name"`
Value types.String `tfsdk:"value"`
}
dependencyTrackProviderMtlsModel struct {
KeyPath types.String `tfsdk:"key_path"`
CertPath types.String `tfsdk:"cert_path"`
}
providerAuthModel struct {
Type types.String `tfsdk:"type"`
Key types.String `tfsdk:"key"`
Bearer types.String `tfsdk:"bearer"`
}
clientInfo struct {
client *dtrack.Client
semver *Semver
}
)
func (p *dependencyTrackProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "dependencytrack"
resp.Version = p.version
}
func (*dependencyTrackProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Interact with DependencyTrack.",
Attributes: map[string]schema.Attribute{
"host": schema.StringAttribute{
Description: "URI for DependencyTrack API.",
Required: true,
},
"key": schema.StringAttribute{
Description: "API Key for authentication to DependencyTrack. " +
"Must have permissions for all attempted actions. " +
"Set to 'OS_ENV' to read from 'DEPENDENCYTRACK_API_KEY' environment variable. " +
"If unset, then 'auth' block must be provided.",
Optional: true,
Sensitive: true,
},
"headers": schema.ListNestedAttribute{
Description: "Add additional headers to client API requests. Useful for proxy authentication.",
Optional: true,
NestedObject: schema.NestedAttributeObject{
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Description: "Name of the header to specify.",
Required: true,
},
"value": schema.StringAttribute{
Description: "Value of the header to specify.",
Required: true,
},
},
},
},
"auth": schema.SingleNestedAttribute{
Description: "Auth credentials to use to connect to DependencyTrack API. Must be provided if root 'key' attribute is not provided.",
Optional: true,
Attributes: map[string]schema.Attribute{
"type": schema.StringAttribute{
Description: "The authentication method to use. Valid values are: 'NONE', 'KEY', 'BEARER'.",
Required: true,
},
"key": schema.StringAttribute{
Description: "API Key for DependencyTrack. Set to 'OS_ENV' to read from 'DEPENDENCYTRACK_API_KEY' environment variable. " +
"Must be provided if 'type' is set to 'KEY'.",
Optional: true,
Sensitive: true,
},
"bearer": schema.StringAttribute{
Description: "Bearer token from DependencyTrack. Must be provided if 'type' is set to 'BEARER'.",
Optional: true,
Sensitive: true,
},
},
},
"root_ca": schema.StringAttribute{
Description: "Root CA Certificate(s) used for TLS connection to DependencyTrack API in PEM format.",
Optional: true,
},
"mtls": schema.SingleNestedAttribute{
Description: "Client Key and Certificate paths to use for mTLS connection to DependencyTrack API.",
Optional: true,
Attributes: map[string]schema.Attribute{
"key_path": schema.StringAttribute{
Description: "Path to the file containing the client key.",
Required: true,
},
"cert_path": schema.StringAttribute{
Description: "Path to the file containing the client certificate.",
Required: true,
},
},
},
},
}
}
func (*dependencyTrackProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
// Get provider data from config.
var config dependencyTrackProviderModel
diags := req.Config.Get(ctx, &config)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
host := config.Host.ValueString()
if host == "" {
resp.Diagnostics.AddAttributeError(
path.Root("host"),
"Missing DependencyTrack Host",
"Host for DependencyTrack was provided, but it was empty.",
)
}
authClientOption := getAuthClientOption(config, &resp.Diagnostics)
httpClient := getHTTPClient(config, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Creating DependencyTrack client")
client, err := dtrack.NewClient(host, dtrack.WithHttpClient(httpClient), authClientOption)
if err != nil {
resp.Diagnostics.AddError(
"Unable to Create DependencyTrack API Client",
"An Unexpected error occurred when creating the DependencyTrack API Client. "+err.Error(),
)
return
}
version, err := client.About.Get(ctx)
if err != nil {
resp.Diagnostics.AddError(
"Unable to retrieve DependencyTrack API Version",
"Error from: "+err.Error(),
)
return
}
semver, err := ParseSemver(version.Version)
if err != nil {
resp.Diagnostics.AddError(
"Unable to parse DependencyTrack API Version",
"Error from: "+err.Error(),
)
return
}
resp.DataSourceData = clientInfo{
client: client,
semver: semver,
}
resp.ResourceData = clientInfo{
client: client,
semver: semver,
}
tflog.Debug(ctx, "Configured DependencyTrack client", map[string]any{
"success": true,
})
}
func (*dependencyTrackProvider) Resources(_ context.Context) []func() resource.Resource {
return []func() resource.Resource{
NewProjectResource,
NewProjectPropertyResource,
NewTeamResource,
NewTeamPermissionResource,
NewTeamAPIKeyResource,
NewConfigPropertyResource,
NewConfigPropertiesResource,
NewRepositoryResource,
NewOidcGroupResource,
NewOidcGroupMappingResource,
NewTeamPermissionsResource,
NewPolicyResource,
NewPolicyConditionResource,
NewPolicyProjectResource,
NewPolicyTagResource,
NewACLMappingResource,
NewLDAPTeamMappingResource,
NewTagResource,
NewTagProjectsResource,
NewTagPoliciesResource,
NewComponentResource,
NewComponentPropertyResource,
NewUserResource,
NewUserTeamResource,
NewUserPermissionResource,
NewOIDCUserResource,
NewLDAPUserResource,
NewNotificationPublisherResource,
NewNotificationRuleResource,
NewNotificationRuleProjectResource,
NewNotificationRuleTeamResource,
NewTagNotificationRulesResource,
}
}
func (*dependencyTrackProvider) DataSources(_ context.Context) []func() datasource.DataSource {
return []func() datasource.DataSource{
NewProjectDataSource,
NewProjectPropertyDataSource,
NewTeamDataSource,
NewConfigPropertyDataSource,
NewComponentsDataSource,
NewOidcAvailableDataSource,
NewOidcGroupMappingsDataSource,
NewOidcUsersDataSource,
NewOidcLoginDataSource,
}
}
func New(version string) func() provider.Provider {
return func() provider.Provider {
return &dependencyTrackProvider{
version: version,
}
}
}
func getHTTPClient(config dependencyTrackProviderModel, diagnostics *diag.Diagnostics) *http.Client {
headers := loadHeaders(config.Headers, diagnostics)
if diagnostics.HasError() {
return nil
}
// Set mTLS variables from Config.
clientCertFile := ""
clientKeyFile := ""
rootCAs := config.RootCA.ValueString()
if config.MTLS != nil {
clientCertFile = config.MTLS.CertPath.ValueString()
clientKeyFile = config.MTLS.KeyPath.ValueString()
}
httpClient, err := NewHTTPClient(headers, []byte(rootCAs), clientCertFile, clientKeyFile)
if err != nil {
diagnostics.AddError(
"Unable to Create HTTP Client",
"An unexpected error occurred when creating the HTTP Client in error: "+err.Error(),
)
return nil
}
return httpClient
}
func loadHeaders(modelHeaders []dependencyTrackProviderHeadersModel, diagnostics *diag.Diagnostics) []Header {
headers := make([]Header, 0, len(modelHeaders))
for _, header := range modelHeaders {
name := header.Name.ValueString()
value := header.Value.ValueString()
if name == "" || value == "" {
diagnostics.AddAttributeError(
path.Root("headers"),
"Missing header attributes",
fmt.Sprintf("Found Header Name: '%s', and Value: '%s'.", name, value),
)
continue
}
headers = append(headers, Header{name, value})
}
return headers
}
func getAuthClientOption(config dependencyTrackProviderModel, diagnostics *diag.Diagnostics) dtrack.ClientOption {
if !config.Key.IsNull() && !config.Key.IsUnknown() {
key := getAPIKey(config.Key, diagnostics)
return dtrack.WithAPIKey(key)
}
if config.Auth == nil {
diagnostics.AddAttributeError(
path.Root("auth"),
"Missing authentication configuration.",
"If 'key' is not provided, then 'auth' block is required.",
)
return nopClientOption
}
switch config.Auth.Type.ValueString() {
case "NONE":
return nopClientOption
case "KEY":
{
key := getAPIKey(config.Auth.Key, diagnostics)
return dtrack.WithAPIKey(key)
}
case "BEARER":
{
bearer := config.Auth.Bearer.ValueString()
bearer = strings.TrimPrefix(bearer, "Bearer ")
return dtrack.WithBearerToken(bearer)
}
default:
{
diagnostics.AddAttributeError(
path.Root("auth.type"),
"Invalid auth type provided.",
fmt.Sprintf("Unexpected value of: '%s'", config.Auth.Type.ValueString()),
)
return nopClientOption
}
}
}
func getAPIKey(value types.String, diagnostics *diag.Diagnostics) string {
key := value.ValueString()
// If key is the magic value 'OS_ENV', load from environment variable.
if key == "OS_ENV" {
key = os.Getenv("DEPENDENCYTRACK_API_KEY")
}
if key == "" {
diagnostics.AddAttributeError(
path.Root("key"),
"Missing DependencyTrack API Key",
"API Key for DependencyTrack was provided, but it was empty.",
)
return ""
}
return key
}
func nopClientOption(_ *dtrack.Client) error {
return nil
}