Repository navigation
Expand file tree
/
Copy pathapikey.go
More file actions
440 lines (398 loc) · 16.8 KB
/
Copy pathapikey.go
File metadata and controls
440 lines (398 loc) · 16.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
package kernel
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"time"
"github.com/kernel/kernel-go-sdk/internal/apijson"
"github.com/kernel/kernel-go-sdk/internal/apiquery"
"github.com/kernel/kernel-go-sdk/internal/requestconfig"
"github.com/kernel/kernel-go-sdk/option"
"github.com/kernel/kernel-go-sdk/packages/pagination"
"github.com/kernel/kernel-go-sdk/packages/param"
"github.com/kernel/kernel-go-sdk/packages/respjson"
)
// Create and manage API keys for organization and project-scoped access.
//
// APIKeyService contains methods and other services that help with interacting
// with the kernel API.
//
// Note, unlike clients, this service does not read variables from the environment
// automatically. You should not instantiate this service directly, and instead use
// the [NewAPIKeyService] method instead.
type APIKeyService struct {
Options []option.RequestOption
}
// NewAPIKeyService generates a new service that applies the given options to each
// request. These options are applied after the parent client's options (if there
// is one), and before any request-specific options.
func NewAPIKeyService(opts ...option.RequestOption) (r APIKeyService) {
r = APIKeyService{}
r.Options = opts
return
}
// Create a new API key. API keys may be scoped by project and may include a
// policy.
func (r *APIKeyService) New(ctx context.Context, body APIKeyNewParams, opts ...option.RequestOption) (res *CreatedAPIKey, err error) {
opts = slices.Concat(r.Options, opts)
path := "org/api_keys"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
// Retrieve an API key by ID for the authenticated organization. API keys are
// masked.
func (r *APIKeyService) Get(ctx context.Context, id string, query APIKeyGetParams, opts ...option.RequestOption) (res *APIKey, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("org/api_keys/%s", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return res, err
}
// Update an API key's name.
func (r *APIKeyService) Update(ctx context.Context, id string, body APIKeyUpdateParams, opts ...option.RequestOption) (res *APIKey, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("org/api_keys/%s", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPatch, path, body, &res, opts...)
return res, err
}
// List API keys for the authenticated organization. API keys are masked.
func (r *APIKeyService) List(ctx context.Context, query APIKeyListParams, opts ...option.RequestOption) (res *pagination.OffsetPagination[APIKey], err error) {
var raw *http.Response
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...)
path := "org/api_keys"
cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, query, &res, opts...)
if err != nil {
return nil, err
}
err = cfg.Execute()
if err != nil {
return nil, err
}
res.SetPageConfig(cfg, raw)
return res, nil
}
// List API keys for the authenticated organization. API keys are masked.
func (r *APIKeyService) ListAutoPaging(ctx context.Context, query APIKeyListParams, opts ...option.RequestOption) *pagination.OffsetPaginationAutoPager[APIKey] {
return pagination.NewOffsetPaginationAutoPager(r.List(ctx, query, opts...))
}
// Delete an API key. A key cannot delete itself; use a different key to delete
// this one.
func (r *APIKeyService) Delete(ctx context.Context, id string, opts ...option.RequestOption) (err error) {
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithHeader("Accept", "*/*")}, opts...)
if id == "" {
err = errors.New("missing required id parameter")
return err
}
path := fmt.Sprintf("org/api_keys/%s", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, nil, nil, opts...)
return err
}
// Rotate an API key. Issues a new key that copies the name and project of the
// rotated key, and schedules the rotated key to expire after a grace period so
// in-flight callers can swap over. The new plaintext key is returned once.
func (r *APIKeyService) Rotate(ctx context.Context, id string, body APIKeyRotateParams, opts ...option.RequestOption) (res *CreatedAPIKey, err error) {
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("org/api_keys/%s/rotate", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return res, err
}
type APIKey struct {
// Unique API key identifier
ID string `json:"id" api:"required"`
// When the API key was created
CreatedAt time.Time `json:"created_at" api:"required" format:"date-time"`
CreatedBy APIKeyCreatedBy `json:"created_by" api:"required"`
// When the API key was deleted (soft-deleted). Null for keys that have not been
// deleted.
DeletedAt time.Time `json:"deleted_at" api:"required" format:"date-time"`
// When the API key expires
ExpiresAt time.Time `json:"expires_at" api:"required" format:"date-time"`
// When the API key last authenticated a request, accurate to within about 20
// minutes. Null if the key has not been used since last-use tracking began.
LastUsedAt time.Time `json:"last_used_at" api:"required" format:"date-time"`
// Masked version of the API key
MaskedKey string `json:"masked_key" api:"required"`
// Label for the API key. API keys are not addressable by name; use the ID or key
// identifier for stable references.
Name string `json:"name" api:"required"`
// Project identifier for project-scoped API keys. Null means org-wide.
ProjectID string `json:"project_id" api:"required"`
// Project name for project-scoped API keys. Null means the key is org-wide or the
// project name is unavailable.
ProjectName string `json:"project_name" api:"required"`
// Permissions granted to a scoped API key. Absent for an ordinary key, which keeps
// unrestricted access within its organization or project.
Policy APIKeyPolicy `json:"policy" api:"nullable"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ID respjson.Field
CreatedAt respjson.Field
CreatedBy respjson.Field
DeletedAt respjson.Field
ExpiresAt respjson.Field
LastUsedAt respjson.Field
MaskedKey respjson.Field
Name respjson.Field
ProjectID respjson.Field
ProjectName respjson.Field
Policy respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r APIKey) RawJSON() string { return r.JSON.raw }
func (r *APIKey) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type APIKeyCreatedBy struct {
// Kernel user ID of the creator.
ID string `json:"id" api:"required"`
// Email address of the creator.
Email string `json:"email" api:"required" format:"email"`
// Display name of the creator, if available.
Name string `json:"name" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ID respjson.Field
Email respjson.Field
Name respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r APIKeyCreatedBy) RawJSON() string { return r.JSON.raw }
func (r *APIKeyCreatedBy) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Permissions granted to a scoped API key. Absent for an ordinary key, which keeps
// unrestricted access within its organization or project.
type APIKeyPolicy struct {
// Allow statements. Every action and resource not listed is denied.
Statements []APIKeyPolicyStatement `json:"statements" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Statements respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r APIKeyPolicy) RawJSON() string { return r.JSON.raw }
func (r *APIKeyPolicy) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type APIKeyPolicyStatement struct {
// Permitted action, such as browsers:use or vaults:read.
Action string `json:"action" api:"required"`
// Resource the action applies to, in the format projects/{project_id}/{kind}/{id}.
// Wildcards are supported.
Resource string `json:"resource" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Action respjson.Field
Resource respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r APIKeyPolicyStatement) RawJSON() string { return r.JSON.raw }
func (r *APIKeyPolicyStatement) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// API key returned immediately after creation. Includes the plaintext key once.
type CreatedAPIKey struct {
// Plaintext API key. Only returned once when the key is created.
Key string `json:"key" api:"required"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Key respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
APIKey
}
// Returns the unmodified JSON received from the API
func (r CreatedAPIKey) RawJSON() string { return r.JSON.raw }
func (r *CreatedAPIKey) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type APIKeyNewParams struct {
// Label for the API key (1-255 characters). API keys are not addressable by name.
Name string `json:"name" api:"required"`
// Number of days until expiry, up to 3650. Use null for never. Cannot be combined
// with expires_at.
DaysToExpire param.Opt[int64] `json:"days_to_expire,omitzero"`
// Exact expiry time. Must be in the future and no later than the issuing
// credential's own expiry. Cannot be combined with days_to_expire.
ExpiresAt param.Opt[time.Time] `json:"expires_at,omitzero" format:"date-time"`
// Unique project identifier
ProjectID param.Opt[string] `json:"project_id,omitzero"`
// Issue a scoped key that may only perform the listed actions on the listed
// resources.
Policy APIKeyNewParamsPolicy `json:"policy,omitzero"`
paramObj
}
func (r APIKeyNewParams) MarshalJSON() (data []byte, err error) {
type shadow APIKeyNewParams
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *APIKeyNewParams) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Issue a scoped key that may only perform the listed actions on the listed
// resources.
//
// The property Statements is required.
type APIKeyNewParamsPolicy struct {
// Allow statements. Every action and resource not listed is denied.
Statements []APIKeyNewParamsPolicyStatement `json:"statements,omitzero" api:"required"`
paramObj
}
func (r APIKeyNewParamsPolicy) MarshalJSON() (data []byte, err error) {
type shadow APIKeyNewParamsPolicy
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *APIKeyNewParamsPolicy) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// The properties Action, Resource are required.
type APIKeyNewParamsPolicyStatement struct {
// Permitted action, such as browsers:use or vaults:read.
Action string `json:"action" api:"required"`
// Resource the action applies to, in the format projects/{project_id}/{kind}/{id}.
// Wildcards are supported.
Resource string `json:"resource" api:"required"`
paramObj
}
func (r APIKeyNewParamsPolicyStatement) MarshalJSON() (data []byte, err error) {
type shadow APIKeyNewParamsPolicyStatement
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *APIKeyNewParamsPolicyStatement) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type APIKeyGetParams struct {
// When true, return the API key even if it has been deleted (soft-deleted), for
// audit purposes. Defaults to false, which returns 404 for a deleted key.
IncludeDeleted param.Opt[bool] `query:"include_deleted,omitzero" json:"-"`
paramObj
}
// URLQuery serializes [APIKeyGetParams]'s query parameters as `url.Values`.
func (r APIKeyGetParams) URLQuery() (v url.Values, err error) {
return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
ArrayFormat: apiquery.ArrayQueryFormatComma,
NestedFormat: apiquery.NestedQueryFormatBrackets,
})
}
type APIKeyUpdateParams struct {
// New API key name
Name string `json:"name" api:"required"`
paramObj
}
func (r APIKeyUpdateParams) MarshalJSON() (data []byte, err error) {
type shadow APIKeyUpdateParams
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *APIKeyUpdateParams) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type APIKeyListParams struct {
// Deprecated: use status=all instead. When true, include deleted (soft-deleted)
// API keys in the results for audit purposes.
IncludeDeleted param.Opt[bool] `query:"include_deleted,omitzero" json:"-"`
// Maximum number of results to return
Limit param.Opt[int64] `query:"limit,omitzero" json:"-"`
// Exact-match filter on API key name using the database collation. In production,
// matching is case- and accent-insensitive. Names are not required to be unique,
// so multiple keys may match. When status=all or include_deleted=true is set,
// soft-deleted keys with the same name may also match.
Name param.Opt[string] `query:"name,omitzero" json:"-"`
// Number of results to skip
Offset param.Opt[int64] `query:"offset,omitzero" json:"-"`
// Case-insensitive substring match against API key name, creator, and project. API
// key identifiers and masked keys match by exact value or prefix.
Query param.Opt[string] `query:"query,omitzero" json:"-"`
// Field to sort API keys by. Keys with no expiry or no recorded use sort last for
// expires_at and last_used_at in either direction.
//
// Any of "created_at", "name", "expires_at", "last_used_at".
SortBy APIKeyListParamsSortBy `query:"sort_by,omitzero" json:"-"`
// Sort direction for API keys.
//
// Any of "asc", "desc".
SortDirection APIKeyListParamsSortDirection `query:"sort_direction,omitzero" json:"-"`
// Filter API keys by status. "active" returns keys that are not deleted (default;
// expired-but-not-deleted keys are still included), "deleted" returns only
// soft-deleted keys, "all" returns both.
//
// Any of "active", "deleted", "all".
Status APIKeyListParamsStatus `query:"status,omitzero" json:"-"`
paramObj
}
// URLQuery serializes [APIKeyListParams]'s query parameters as `url.Values`.
func (r APIKeyListParams) URLQuery() (v url.Values, err error) {
return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
ArrayFormat: apiquery.ArrayQueryFormatComma,
NestedFormat: apiquery.NestedQueryFormatBrackets,
})
}
// Field to sort API keys by. Keys with no expiry or no recorded use sort last for
// expires_at and last_used_at in either direction.
type APIKeyListParamsSortBy string
const (
APIKeyListParamsSortByCreatedAt APIKeyListParamsSortBy = "created_at"
APIKeyListParamsSortByName APIKeyListParamsSortBy = "name"
APIKeyListParamsSortByExpiresAt APIKeyListParamsSortBy = "expires_at"
APIKeyListParamsSortByLastUsedAt APIKeyListParamsSortBy = "last_used_at"
)
// Sort direction for API keys.
type APIKeyListParamsSortDirection string
const (
APIKeyListParamsSortDirectionAsc APIKeyListParamsSortDirection = "asc"
APIKeyListParamsSortDirectionDesc APIKeyListParamsSortDirection = "desc"
)
// Filter API keys by status. "active" returns keys that are not deleted (default;
// expired-but-not-deleted keys are still included), "deleted" returns only
// soft-deleted keys, "all" returns both.
type APIKeyListParamsStatus string
const (
APIKeyListParamsStatusActive APIKeyListParamsStatus = "active"
APIKeyListParamsStatusDeleted APIKeyListParamsStatus = "deleted"
APIKeyListParamsStatusAll APIKeyListParamsStatus = "all"
)
type APIKeyRotateParams struct {
// Lifetime in days for the new key, up to 3650. Omit to reuse the rotated key's
// original lifetime, or never-expires if it had none.
DaysToExpire param.Opt[int64] `json:"days_to_expire,omitzero"`
// Grace period in days before the rotated key expires. Use 0 to expire it
// immediately. Omit for the default grace period of 7 days.
ExpireInDays param.Opt[int64] `json:"expire_in_days,omitzero"`
paramObj
}
func (r APIKeyRotateParams) MarshalJSON() (data []byte, err error) {
type shadow APIKeyRotateParams
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *APIKeyRotateParams) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}