-
Notifications
You must be signed in to change notification settings - Fork 24
/
integration.go
354 lines (300 loc) · 10.8 KB
/
integration.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
346
347
348
349
350
351
352
353
354
//
// Copyright 2023 The Chainloop Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package biz
import (
"context"
"errors"
"fmt"
"io"
"time"
"github.com/chainloop-dev/chainloop/app/controlplane/plugins/sdk/v1"
"github.com/chainloop-dev/chainloop/internal/credentials"
"github.com/chainloop-dev/chainloop/internal/servicelogger"
"github.com/go-kratos/kratos/v2/log"
"github.com/google/uuid"
"google.golang.org/protobuf/types/known/structpb"
)
type IntegrationAttachment struct {
ID uuid.UUID
CreatedAt *time.Time
Config []byte
WorkflowID, IntegrationID uuid.UUID
}
type Integration struct {
ID uuid.UUID
// Kind is the type of the integration, it matches the registered plugin ID
Kind string
// Name is a unique identifier for the integration registration
Name string
// Description is a human readable description of the integration registration
// It helps to differentiate different instances of the same kind
Description string
// Registration Configuration, usually JSON marshalled
Config []byte
// Identifier to the external provider where any secret information is stored
SecretName string
CreatedAt *time.Time
}
type IntegrationAndAttachment struct {
*Integration
*IntegrationAttachment
}
type IntegrationCreateOpts struct {
// Unique name of the registration
// used to declaratively reference the integration
Name string
Kind, Description, SecretName string
OrgID uuid.UUID
Config []byte
}
type IntegrationRepo interface {
Create(ctx context.Context, opts *IntegrationCreateOpts) (*Integration, error)
List(ctx context.Context, orgID uuid.UUID) ([]*Integration, error)
FindByIDInOrg(ctx context.Context, orgID, ID uuid.UUID) (*Integration, error)
SoftDelete(ctx context.Context, ID uuid.UUID) error
}
type IntegrationAttachmentRepo interface {
Create(ctx context.Context, integrationID, workflowID uuid.UUID, config []byte) (*IntegrationAttachment, error)
List(ctx context.Context, orgID, workflowID uuid.UUID) ([]*IntegrationAttachment, error)
FindByIDInOrg(ctx context.Context, orgID, ID uuid.UUID) (*IntegrationAttachment, error)
SoftDelete(ctx context.Context, ID uuid.UUID) error
}
type IntegrationUseCase struct {
integrationRepo IntegrationRepo
integrationARepo IntegrationAttachmentRepo
workflowRepo WorkflowRepo
credsRW credentials.ReaderWriter
logger *log.Helper
}
type NewIntegrationUseCaseOpts struct {
IRepo IntegrationRepo
IaRepo IntegrationAttachmentRepo
WfRepo WorkflowRepo
CredsRW credentials.ReaderWriter
Logger log.Logger
}
func NewIntegrationUseCase(opts *NewIntegrationUseCaseOpts) *IntegrationUseCase {
if opts.Logger == nil {
opts.Logger = log.NewStdLogger(io.Discard)
}
return &IntegrationUseCase{opts.IRepo, opts.IaRepo, opts.WfRepo, opts.CredsRW, servicelogger.ScopedHelper(opts.Logger, "biz/integration")}
}
// Persist the secret and integration with its configuration in the database
func (uc *IntegrationUseCase) RegisterAndSave(ctx context.Context, orgID, name, description string, i sdk.FanOut, regConfig *structpb.Struct) (*Integration, error) {
if name == "" {
return nil, NewErrValidationStr("name is required")
}
// validate format of the name
if err := ValidateIsDNS1123(name); err != nil {
return nil, NewErrValidation(err)
}
orgUUID, err := uuid.Parse(orgID)
if err != nil {
return nil, NewErrInvalidUUID(err)
}
// 1 - Extract JSON from proto struct
pluginRequest, err := regConfig.MarshalJSON()
if err != nil {
return nil, NewErrValidation(err)
}
// 2 - validate JSON against the schema
if err := i.ValidateRegistrationRequest(pluginRequest); err != nil {
return nil, NewErrValidation(err)
}
registrationResponse, err := i.Register(ctx, &sdk.RegistrationRequest{Payload: pluginRequest})
if err != nil {
return nil, NewErrValidation(err)
}
var secretID string
if registrationResponse.Credentials != nil {
// Create the secret in the external secrets manager
secretID, err = uc.credsRW.SaveCredentials(ctx, orgID, registrationResponse.Credentials)
if err != nil {
return nil, fmt.Errorf("saving credentials: %w", err)
}
}
// Persist the integration configuration
reg, err := uc.integrationRepo.Create(ctx, &IntegrationCreateOpts{
Name: name,
OrgID: orgUUID, Kind: i.Describe().ID, Description: description,
SecretName: secretID, Config: registrationResponse.Configuration,
})
if err != nil {
if errors.Is(err, ErrAlreadyExists) {
return nil, NewErrValidationStr("name already taken")
}
return nil, fmt.Errorf("failed to register integration: %w", err)
}
return reg, nil
}
type AttachOpts struct {
IntegrationID, WorkflowID, OrgID string
// The integration that is being attached
FanOutIntegration sdk.FanOut
// The attachment configuration
AttachmentConfig *structpb.Struct
}
// - Integration and workflows exists in current organization
// - Run specific validation for the integration
// - Persist integration attachment
func (uc *IntegrationUseCase) AttachToWorkflow(ctx context.Context, opts *AttachOpts) (*IntegrationAttachment, error) {
if opts.FanOutIntegration == nil {
return nil, NewErrValidation(errors.New("integration not provided"))
}
orgUUID, err := uuid.Parse(opts.OrgID)
if err != nil {
return nil, NewErrInvalidUUID(err)
}
workflowUUID, err := uuid.Parse(opts.WorkflowID)
if err != nil {
return nil, NewErrInvalidUUID(err)
}
// Get workflow in the scope of this organization
wf, err := uc.workflowRepo.GetOrgScoped(ctx, orgUUID, workflowUUID)
if err != nil {
return nil, err
} else if wf == nil {
return nil, NewErrNotFound("workflow")
}
integrationUUID, err := uuid.Parse(opts.IntegrationID)
if err != nil {
return nil, NewErrInvalidUUID(err)
}
// Make sure that the integration is from this org
integration, err := uc.integrationRepo.FindByIDInOrg(ctx, orgUUID, integrationUUID)
if err != nil {
return nil, err
} else if integration == nil {
return nil, NewErrNotFound("integration")
}
// Retrieve credentials from the external secrets manager
creds := &sdk.Credentials{}
if integration.SecretName != "" {
if err := uc.credsRW.ReadCredentials(ctx, integration.SecretName, creds); err != nil {
return nil, fmt.Errorf("reading credentials: %w", err)
}
}
// 1 - Extract JSON from struct
pluginRequest, err := opts.AttachmentConfig.MarshalJSON()
if err != nil {
return nil, NewErrValidation(err)
}
// 2 - validate JSON against the schema
if err := opts.FanOutIntegration.ValidateAttachmentRequest(pluginRequest); err != nil {
return nil, NewErrValidation(err)
}
// Execute integration pre-attachment logic
attachResponse, err := opts.FanOutIntegration.Attach(ctx,
&sdk.AttachmentRequest{
Payload: pluginRequest,
RegistrationInfo: &sdk.RegistrationResponse{Credentials: creds, Configuration: integration.Config},
})
if err != nil {
return nil, NewErrValidation(err)
}
// Persist the attachment
attachment, err := uc.integrationARepo.Create(ctx, integrationUUID, workflowUUID, attachResponse.Configuration)
if err != nil {
return nil, fmt.Errorf("persisting attachment: %w", err)
}
return attachment, nil
}
func (uc *IntegrationUseCase) List(ctx context.Context, orgID string) ([]*Integration, error) {
orgUUID, err := uuid.Parse(orgID)
if err != nil {
return nil, NewErrInvalidUUID(err)
}
return uc.integrationRepo.List(ctx, orgUUID)
}
func (uc *IntegrationUseCase) FindByIDInOrg(ctx context.Context, orgID, id string) (*Integration, error) {
orgUUID, err := uuid.Parse(orgID)
if err != nil {
return nil, NewErrInvalidUUID(err)
}
uuid, err := uuid.Parse(id)
if err != nil {
return nil, NewErrInvalidUUID(err)
}
return uc.integrationRepo.FindByIDInOrg(ctx, orgUUID, uuid)
}
func (uc *IntegrationUseCase) Delete(ctx context.Context, orgID, integrationID string) error {
orgUUID, err := uuid.Parse(orgID)
if err != nil {
return NewErrInvalidUUID(err)
}
integrationUUID, err := uuid.Parse(integrationID)
if err != nil {
return NewErrInvalidUUID(err)
}
uc.logger.Infow("msg", "deleting integration", "ID", integrationID)
// Make sure that the integration is from this org and it has not associated workflows
integration, err := uc.integrationRepo.FindByIDInOrg(ctx, orgUUID, integrationUUID)
if err != nil {
return err
} else if integration == nil {
return NewErrNotFound("integration")
}
if integration.SecretName != "" {
uc.logger.Infow("msg", "deleting integration external secrets", "ID", integrationID, "secretName", integration.SecretName)
if err := uc.credsRW.DeleteCredentials(ctx, integration.SecretName); err != nil {
uc.logger.Warnw("msg", "can't delete credentials", "name", integration.SecretName, "err", err)
}
}
uc.logger.Infow("msg", "integration deleted", "ID", integrationID)
// Check that the workflow to delete belongs to the provided organization
return uc.integrationRepo.SoftDelete(ctx, integrationUUID)
}
// List attachments returns the list of attachments for a given organization and optionally workflow
func (uc *IntegrationUseCase) ListAttachments(ctx context.Context, orgID, workflowID string) ([]*IntegrationAttachment, error) {
orgUUID, err := uuid.Parse(orgID)
if err != nil {
return nil, NewErrInvalidUUID(err)
}
workflowUUID := uuid.Nil
if workflowID != "" {
var err error
workflowUUID, err = uuid.Parse(workflowID)
if err != nil {
return nil, NewErrInvalidUUID(err)
}
// We check that the workflow belongs to the provided organization
// This check is mostly informative to the user
wf, err := uc.workflowRepo.GetOrgScoped(ctx, orgUUID, workflowUUID)
if err != nil {
return nil, err
} else if wf == nil {
return nil, NewErrNotFound("workflow")
}
}
return uc.integrationARepo.List(ctx, orgUUID, workflowUUID)
}
// Detach integration from workflow
func (uc *IntegrationUseCase) Detach(ctx context.Context, orgID, attachmentID string) error {
orgUUID, err := uuid.Parse(orgID)
if err != nil {
return NewErrInvalidUUID(err)
}
attachmentUUID, err := uuid.Parse(attachmentID)
if err != nil {
return NewErrInvalidUUID(err)
}
// Make sure that the attachment is part of the provided organization
if attachment, err := uc.integrationARepo.FindByIDInOrg(ctx, orgUUID, attachmentUUID); err != nil {
return err
} else if attachment == nil {
return NewErrNotFound("attachment")
}
return uc.integrationARepo.SoftDelete(ctx, attachmentUUID)
}