-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathresource_apikey.go
More file actions
261 lines (231 loc) · 6.89 KB
/
Copy pathresource_apikey.go
File metadata and controls
261 lines (231 loc) · 6.89 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
package ns1
import (
"fmt"
"log"
"regexp"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
ns1 "gopkg.in/ns1/ns1-go.v2/rest"
"gopkg.in/ns1/ns1-go.v2/rest/model/account"
)
func apikeyResource() *schema.Resource {
s := map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"key": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
},
"teams": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"ip_whitelist": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"ip_whitelist_strict": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"expiry_duration": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringMatch(
regexp.MustCompile(`^\d+d$`),
"must be a duration in format '<number>d' (e.g., '10d', '30d', '90d')",
),
Description: "Duration for automatic secret expiration (e.g., '10d', '30d', '90d'). Accepts any duration in '<number>d' format. When set, API key secrets will automatically expire after the specified period. Changing this value will force recreation of the API key.",
},
"secrets": {
Type: schema.TypeList,
Computed: true,
Description: "List of secrets associated with this API key when expiry_duration is set.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
Description: "The unique identifier for this secret.",
},
"expires_at": {
Type: schema.TypeString,
Computed: true,
Description: "The expiration date/time of this secret in ISO 8601 format.",
},
"last_access": {
Type: schema.TypeString,
Computed: true,
Description: "The last time this secret was used for authentication.",
},
"enabled": {
Type: schema.TypeBool,
Computed: true,
Description: "Whether this secret is currently enabled for authentication.",
},
},
},
},
}
s = addPermsSchema(s)
return &schema.Resource{
Schema: s,
Create: ApikeyCreate,
Read: ApikeyRead,
Update: ApikeyUpdate,
Delete: ApikeyDelete,
Importer: &schema.ResourceImporter{},
SchemaVersion: 1,
StateUpgraders: []schema.StateUpgrader{
{
Type: apikeyResourceV0().CoreConfigSchema().ImpliedType(),
Upgrade: permissionInstanceStateUpgradeV0,
Version: 0,
},
},
}
}
func apikeyToResourceData(d *schema.ResourceData, k *account.APIKey) error {
d.SetId(k.ID)
d.Set("name", k.Name)
d.Set("teams", k.TeamIDs)
d.Set("ip_whitelist", k.IPWhitelist)
d.Set("ip_whitelist_strict", k.IPWhitelistStrict)
permissionsToResourceData(d, k.Permissions)
// keep the existing key in the state file when there's no key in the response
if k.Key != "" {
d.Set("key", k.Key)
}
// Set expiry_duration if present
if k.ExpiryDuration != "" {
if err := d.Set("expiry_duration", k.ExpiryDuration); err != nil {
return fmt.Errorf("error setting expiry_duration: %w", err)
}
}
// Set secrets if present
if len(k.Secrets) > 0 {
secrets := make([]map[string]interface{}, len(k.Secrets))
for i, secret := range k.Secrets {
secretMap := map[string]interface{}{
"id": secret.ID,
"expires_at": secret.ExpiresAt,
}
if secret.LastAccess != "" {
secretMap["last_access"] = secret.LastAccess
}
if secret.Enabled != nil {
secretMap["enabled"] = *secret.Enabled
}
secrets[i] = secretMap
}
if err := d.Set("secrets", secrets); err != nil {
return fmt.Errorf("error setting secrets: %w", err)
}
}
return nil
}
func resourceDataToApikey(k *account.APIKey, d *schema.ResourceData) error {
k.ID = d.Id()
k.Name = d.Get("name").(string)
if v, ok := d.GetOk("teams"); ok {
teamsRaw := v.([]interface{})
k.TeamIDs = make([]string, len(teamsRaw))
for i, team := range teamsRaw {
k.TeamIDs[i] = team.(string)
}
} else {
k.TeamIDs = make([]string, 0)
}
k.Permissions = resourceDataToPermissions(d)
if v, ok := d.GetOk("ip_whitelist"); ok {
ipWhitelistRaw := v.(*schema.Set)
k.IPWhitelist = make([]string, ipWhitelistRaw.Len())
for i, ip := range ipWhitelistRaw.List() {
k.IPWhitelist[i] = ip.(string)
}
} else {
// This still needs to be initialized to a zero value,
// otherwise it can't be removed.
k.IPWhitelist = make([]string, 0)
}
k.IPWhitelistStrict = d.Get("ip_whitelist_strict").(bool)
// Set expiry_duration if provided
if v, ok := d.GetOk("expiry_duration"); ok {
k.ExpiryDuration = v.(string)
}
return nil
}
// ApikeyCreate creates ns1 API key
func ApikeyCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ns1.Client)
k := account.APIKey{}
if err := resourceDataToApikey(&k, d); err != nil {
return err
}
if resp, err := client.APIKeys.Create(&k); err != nil {
return ConvertToNs1Error(resp, err)
}
// If a key is assigned to at least one team, then it's permissions need to be refreshed
// because the current key permissions in Terraform state will be out of date.
if len(k.TeamIDs) > 0 {
updatedKey, resp, err := client.APIKeys.Get(k.ID)
if err != nil {
return ConvertToNs1Error(resp, err)
}
// Key attribute only avail on initial GET
updatedKey.Key = k.Key
return apikeyToResourceData(d, updatedKey)
}
return apikeyToResourceData(d, &k)
}
// ApikeyRead reads API key from ns1
func ApikeyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ns1.Client)
k, resp, err := client.APIKeys.Get(d.Id())
if err != nil {
if err == ns1.ErrKeyMissing {
log.Printf("[DEBUG] NS1 API key (%s) not found", d.Id())
d.SetId("")
return nil
}
return ConvertToNs1Error(resp, err)
}
return apikeyToResourceData(d, k)
}
// ApikeyDelete deletes the given ns1 api key
func ApikeyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ns1.Client)
resp, err := client.APIKeys.Delete(d.Id())
d.SetId("")
return ConvertToNs1Error(resp, err)
}
// ApikeyUpdate updates the given api key in ns1
func ApikeyUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ns1.Client)
k := account.APIKey{
ID: d.Id(),
}
if err := resourceDataToApikey(&k, d); err != nil {
return err
}
if resp, err := client.APIKeys.Update(&k); err != nil {
return ConvertToNs1Error(resp, err)
}
// If a key's teams have changed then the permissions on the key need to be refreshed
// because the current key permissions in Terraform state will be out of date.
if d.HasChange("teams") {
updatedKey, resp, err := client.APIKeys.Get(d.Id())
if err != nil {
return ConvertToNs1Error(resp, err)
}
return apikeyToResourceData(d, updatedKey)
}
return apikeyToResourceData(d, &k)
}