-
Notifications
You must be signed in to change notification settings - Fork 20
/
toe.go
445 lines (369 loc) · 17.1 KB
/
toe.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
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
441
442
443
444
445
// Copyright 2016-2022 Fraunhofer AISEC
//
// 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.
//
// $$\ $$\ $$\ $$\
// $$ | $$ |\__| $$ |
// $$$$$$$\ $$ | $$$$$$\ $$\ $$\ $$$$$$$ |$$\ $$$$$$\ $$$$$$\ $$$$$$\
// $$ _____|$$ |$$ __$$\ $$ | $$ |$$ __$$ |$$ |\_$$ _| $$ __$$\ $$ __$$\
// $$ / $$ |$$ / $$ |$$ | $$ |$$ / $$ |$$ | $$ | $$ / $$ |$$ | \__|
// $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ | $$ |$$ |
// \$$$$$$\ $$ |\$$$$$ |\$$$$$ |\$$$$$$ |$$ | \$$$ |\$$$$$ |$$ |
// \_______|\__| \______/ \______/ \_______|\__| \____/ \______/ \__|
//
// This file is part of Clouditor Community Edition.
package orchestrator
import (
"context"
"errors"
"fmt"
"sort"
"clouditor.io/clouditor/api"
"clouditor.io/clouditor/api/orchestrator"
"clouditor.io/clouditor/internal/logging"
"clouditor.io/clouditor/persistence"
"clouditor.io/clouditor/persistence/gorm"
"clouditor.io/clouditor/service"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
)
func (svc *Service) CreateTargetOfEvaluation(ctx context.Context, req *orchestrator.CreateTargetOfEvaluationRequest) (res *orchestrator.TargetOfEvaluation, err error) {
var (
c *orchestrator.Catalog
controls []*orchestrator.Control
)
// Validate request
err = service.ValidateRequest(req)
if err != nil {
return nil, err
}
// Check, if this request has access to the cloud service according to our authorization strategy.
if !svc.authz.CheckAccess(ctx, service.AccessCreate, req) {
return nil, service.ErrPermissionDenied
}
// We need to retrieve some additional meta-data about the security catalog, so we need to query it as well
c, err = svc.GetCatalog(ctx, &orchestrator.GetCatalogRequest{CatalogId: req.TargetOfEvaluation.CatalogId})
if err != nil {
// The error is already a gRPC error, so we can just return it
return nil, err
}
// Certain catalogs do not allow scoping, in this case we need to pre-populate all controls into the scope.
if c.AllInScope {
controls, err = api.ListAllPaginated(&orchestrator.ListControlsRequest{CatalogId: c.Id}, func(ctx context.Context, req *orchestrator.ListControlsRequest, opts ...grpc.CallOption) (*orchestrator.ListControlsResponse, error) {
return svc.ListControls(ctx, req)
}, func(res *orchestrator.ListControlsResponse) []*orchestrator.Control {
return res.Controls
})
if err != nil {
// The error is already a gRPC error, so we can just return it
return nil, err
}
// If the catalog allows assurance levels, add only controls with the corresponsing assurance level.
// Note: The upper assurance level includes the underlying assurance levels. Substantial includes basic and substantial and high include all control.
if len(c.AssuranceLevels) > 0 {
req.TargetOfEvaluation.ControlsInScope, err = getControls(controls, c.GetAssuranceLevels(), req.TargetOfEvaluation.GetAssuranceLevel())
if err != nil {
return nil, status.Errorf(codes.Internal, "assurance level error: %v", err)
}
} else {
// The catalog does not allow assurance levels, add all controls.
req.TargetOfEvaluation.ControlsInScope = controls
}
}
// Create the ToE
err = svc.storage.Create(&req.TargetOfEvaluation)
if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
go svc.informToeHooks(ctx, &orchestrator.TargetOfEvaluationChangeEvent{Type: orchestrator.TargetOfEvaluationChangeEvent_TYPE_TARGET_OF_EVALUATION_CREATED, TargetOfEvaluation: req.TargetOfEvaluation}, nil)
res = req.TargetOfEvaluation
logging.LogRequest(log, logrus.DebugLevel, logging.Create, req, fmt.Sprintf("and Catalog '%s'", req.TargetOfEvaluation.GetCatalogId()))
return
}
// GetTargetOfEvaluation implements method for getting a TargetOfEvaluation, e.g. to show its state in the UI
func (svc *Service) GetTargetOfEvaluation(ctx context.Context, req *orchestrator.GetTargetOfEvaluationRequest) (response *orchestrator.TargetOfEvaluation, err error) {
// Validate request
err = service.ValidateRequest(req)
if err != nil {
return nil, err
}
// Check, if this request has access to the cloud service according to our authorization strategy.
if !svc.authz.CheckAccess(ctx, service.AccessRead, req) {
return nil, service.ErrPermissionDenied
}
response = new(orchestrator.TargetOfEvaluation)
err = svc.storage.Get(response, gorm.WithPreload("ControlsInScope"), "cloud_service_id = ? AND catalog_id = ?", req.CloudServiceId, req.CatalogId)
if errors.Is(err, persistence.ErrRecordNotFound) {
return nil, status.Errorf(codes.NotFound, "ToE not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
return response, nil
}
// ListTargetsOfEvaluation implements method for getting a TargetOfEvaluation
func (svc *Service) ListTargetsOfEvaluation(ctx context.Context, req *orchestrator.ListTargetsOfEvaluationRequest) (res *orchestrator.ListTargetsOfEvaluationResponse, err error) {
var conds = []any{gorm.WithPreload("ControlsInScope")}
// Validate request
err = service.ValidateRequest(req)
if err != nil {
return nil, err
}
// Check, if this request has access to the cloud service according to our authorization strategy.
if !svc.authz.CheckAccess(ctx, service.AccessRead, req) {
return nil, service.ErrPermissionDenied
}
// Either the cloud_service_id or the catalog_id is set and the conds are added accordingly.
if req.GetCloudServiceId() != "" {
conds = append(conds, "cloud_service_id = ?", req.CloudServiceId)
} else if req.GetCatalogId() != "" {
conds = append(conds, "catalog_id = ?", req.CatalogId)
}
res = new(orchestrator.ListTargetsOfEvaluationResponse)
res.TargetOfEvaluation, res.NextPageToken, err = service.PaginateStorage[*orchestrator.TargetOfEvaluation](req, svc.storage, service.DefaultPaginationOpts, conds...)
if err != nil {
return nil, status.Errorf(codes.Internal, "could not paginate results: %v", err)
}
return
}
// UpdateTargetOfEvaluation implements method for updating an existing TargetOfEvaluation
func (svc *Service) UpdateTargetOfEvaluation(ctx context.Context, req *orchestrator.UpdateTargetOfEvaluationRequest) (res *orchestrator.TargetOfEvaluation, err error) {
// Validate request
err = service.ValidateRequest(req)
if err != nil {
return nil, err
}
// Check, if this request has access to the cloud service according to our authorization strategy.
if !svc.authz.CheckAccess(ctx, service.AccessUpdate, req) {
return nil, service.ErrPermissionDenied
}
res = req.TargetOfEvaluation
err = svc.storage.Update(res, "cloud_service_id = ? AND catalog_id = ?", req.TargetOfEvaluation.GetCloudServiceId(), req.TargetOfEvaluation.GetCatalogId())
if err != nil && errors.Is(err, persistence.ErrRecordNotFound) {
return nil, status.Error(codes.NotFound, "ToE not found")
} else if err != nil && errors.Is(err, persistence.ErrConstraintFailed) {
return nil, status.Error(codes.NotFound, "ToE not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
go svc.informToeHooks(ctx, &orchestrator.TargetOfEvaluationChangeEvent{Type: orchestrator.TargetOfEvaluationChangeEvent_TYPE_TARGET_OF_EVALUATION_UPDATED, TargetOfEvaluation: req.TargetOfEvaluation}, nil)
logging.LogRequest(log, logrus.DebugLevel, logging.Update, req, fmt.Sprintf("and Catalog '%s'", req.TargetOfEvaluation.GetCatalogId()))
return
}
// RemoveTargetOfEvaluation implements method for removing a TargetOfEvaluation
func (svc *Service) RemoveTargetOfEvaluation(ctx context.Context, req *orchestrator.RemoveTargetOfEvaluationRequest) (response *emptypb.Empty, err error) {
// Validate request
err = service.ValidateRequest(req)
if err != nil {
return nil, err
}
// Check, if this request has access to the cloud service according to our authorization strategy.
if !svc.authz.CheckAccess(ctx, service.AccessDelete, req) {
return nil, service.ErrPermissionDenied
}
err = svc.storage.Delete(&orchestrator.TargetOfEvaluation{}, "cloud_service_id = ? AND catalog_id = ?", req.CloudServiceId, req.CatalogId)
if errors.Is(err, persistence.ErrRecordNotFound) {
return nil, status.Errorf(codes.NotFound, "ToE not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
// Since we don't have a TargetOfEvaluation object, we create one to be able to inform the hook about the deleted TargetOfEvaluation.
toe := &orchestrator.TargetOfEvaluation{
CloudServiceId: req.GetCloudServiceId(),
CatalogId: req.GetCatalogId(),
}
go svc.informToeHooks(ctx, &orchestrator.TargetOfEvaluationChangeEvent{Type: orchestrator.TargetOfEvaluationChangeEvent_TYPE_TARGET_OF_EVALUATION_REMOVED, TargetOfEvaluation: toe}, nil)
logging.LogRequest(log, logrus.DebugLevel, logging.Remove, req, fmt.Sprintf("and Catalog '%s'", req.GetCatalogId()))
return &emptypb.Empty{}, nil
}
// informToeHooks informs the registered hook function either of a event change for the Target of Evaluation or Control Monitoring Status
func (s *Service) informToeHooks(ctx context.Context, event *orchestrator.TargetOfEvaluationChangeEvent, err error) {
s.hookMutex.RLock()
hooks := s.toeHooks
defer s.hookMutex.RUnlock()
// Inform our hook, if we have any
if len(hooks) > 0 {
for _, hook := range hooks {
// We could do hook concurrent again (assuming different hooks don't interfere with each other)
hook(ctx, event, err)
}
}
}
// RegisterToeHook registers the Target of Evaluation hook function
func (s *Service) RegisterToeHook(hook orchestrator.TargetOfEvaluationHookFunc) {
s.hookMutex.Lock()
defer s.hookMutex.Unlock()
s.toeHooks = append(s.toeHooks, hook)
}
func (svc *Service) ListControlsInScope(ctx context.Context, req *orchestrator.ListControlsInScopeRequest) (res *orchestrator.ListControlsInScopeResponse, err error) {
var conds = []any{gorm.WithoutPreload()}
// Validate request
err = service.ValidateRequest(req)
if err != nil {
return nil, err
}
// Check, if this request has access to the cloud service according to our authorization strategy.
if !svc.authz.CheckAccess(ctx, service.AccessRead, req) {
return nil, service.ErrPermissionDenied
}
conds = append(conds, "target_of_evaluation_cloud_service_id = ? AND target_of_evaluation_catalog_id = ?", req.CloudServiceId, req.CatalogId)
res = new(orchestrator.ListControlsInScopeResponse)
res.ControlsInScope, res.NextPageToken, err = service.PaginateStorage[*orchestrator.ControlInScope](req, svc.storage, service.DefaultPaginationOpts, conds...)
if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
return
}
func (svc *Service) AddControlToScope(ctx context.Context, req *orchestrator.AddControlToScopeRequest) (res *orchestrator.ControlInScope, err error) {
// Validate request
err = service.ValidateRequest(req)
if err != nil {
return nil, err
}
// Check, if this request has access to the cloud service according to our authorization strategy.
if !svc.authz.CheckAccess(ctx, service.AccessUpdate, req) {
return nil, service.ErrPermissionDenied
}
err = svc.storage.Create(req.Scope)
if err != nil && errors.Is(err, persistence.ErrUniqueConstraintFailed) {
return nil, status.Error(codes.AlreadyExists, "entry already exists")
} else if err != nil && errors.Is(err, persistence.ErrConstraintFailed) {
return nil, status.Error(codes.NotFound, "ToE not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
res = req.Scope
go svc.informToeHooks(ctx, &orchestrator.TargetOfEvaluationChangeEvent{Type: orchestrator.TargetOfEvaluationChangeEvent_TYPE_CONTROL_IN_SCOPE_ADDED, ControlInScope: req.GetScope()}, nil)
logging.LogRequest(log, logrus.DebugLevel, logging.Add, req, fmt.Sprintf("with Control ID '%s'", req.Scope.GetControlId()))
return
}
func (svc *Service) UpdateControlInScope(ctx context.Context, req *orchestrator.UpdateControlInScopeRequest) (res *orchestrator.ControlInScope, err error) {
// Validate request
err = service.ValidateRequest(req)
if err != nil {
return nil, err
}
// Check, if this request has access to the cloud service according to our authorization strategy.
if !svc.authz.CheckAccess(ctx, service.AccessUpdate, req) {
return nil, service.ErrPermissionDenied
}
err = svc.storage.Update(req.Scope,
"target_of_evaluation_cloud_service_id = ? AND "+
"target_of_evaluation_catalog_id = ? AND "+
"control_category_catalog_id = ? AND "+
"control_category_name = ? AND "+
"control_id = ?",
req.Scope.TargetOfEvaluationCloudServiceId,
req.Scope.TargetOfEvaluationCatalogId,
req.Scope.ControlCategoryCatalogId,
req.Scope.ControlCategoryName,
req.Scope.ControlId)
if err != nil && errors.Is(err, persistence.ErrRecordNotFound) {
return nil, status.Error(codes.NotFound, "ToE not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
res = req.Scope
go svc.informToeHooks(ctx, &orchestrator.TargetOfEvaluationChangeEvent{Type: orchestrator.TargetOfEvaluationChangeEvent_TYPE_CONTROL_IN_SCOPE_UPDATED, ControlInScope: req.GetScope()}, nil)
logging.LogRequest(log, logrus.DebugLevel, logging.Update, req, fmt.Sprintf("with Control ID '%s'", req.Scope.GetControlId()))
return
}
func (svc *Service) RemoveControlFromScope(ctx context.Context, req *orchestrator.RemoveControlFromScopeRequest) (res *emptypb.Empty, err error) {
// Validate request
err = service.ValidateRequest(req)
if err != nil {
return nil, err
}
// Check, if this request has access to the cloud service according to our authorization strategy.
if !svc.authz.CheckAccess(ctx, service.AccessDelete, req) {
return nil, service.ErrPermissionDenied
}
err = svc.storage.Delete(orchestrator.ControlInScope{},
"target_of_evaluation_cloud_service_id = ? AND "+
"target_of_evaluation_catalog_id = ? AND "+
"control_category_catalog_id = ? AND "+
"control_category_name = ? AND "+
"control_id = ?",
req.CloudServiceId,
req.CatalogId,
req.CatalogId,
req.ControlCategoryName,
req.ControlId)
if err != nil && errors.Is(err, persistence.ErrRecordNotFound) {
return nil, status.Error(codes.NotFound, "ToE not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
res = &emptypb.Empty{}
go svc.informToeHooks(ctx, &orchestrator.TargetOfEvaluationChangeEvent{Type: orchestrator.TargetOfEvaluationChangeEvent_TYPE_CONTROL_IN_SCOPE_REMOVED, ControlInScope: nil}, nil)
logging.LogRequest(log, logrus.DebugLevel, logging.Remove, req, fmt.Sprintf("with Control ID '%s'", req.GetControlId()))
return
}
// getControls returns all controls based on the assurance level
func getControls(controls []*orchestrator.Control, levels []string, level string) ([]*orchestrator.Control, error) {
var (
levelControls = make(map[string][]*orchestrator.Control)
c = []*orchestrator.Control{}
)
// Check that levels and level is not empty
if len(levels) == 0 {
err := errors.New("assurance levels are empty")
return c, err
}
if level == "" {
err := errors.New("assurance level is empty")
return c, err
}
// Add controls based on their assurance level to the map. If a controls is not defined regarding the assurance level it is dropped.
for _, control := range controls {
if control.AssuranceLevel == nil {
continue
}
levelControls[control.GetAssuranceLevel()] = append(levelControls[control.GetAssuranceLevel()], control)
}
// Add all needed controls based on the assurance level.
// Note: The assurance levels must be sorted in ascending order, e.g., low, medium, high, because the controls of the lower assurance levels must be present in the higger assurance levels. If this is not the case, the controls with assurance levels low will not be included in medium.
for i := range levels {
c = append(c, levelControls[levels[i]]...)
if level == levels[i] {
break
}
}
// Add parent controls to the sub-control included in the list. That results in duplicates that we can remove later.
for i := range c {
for j := range controls {
if c[i].GetParentControlId() == controls[j].GetId() {
c = append(c, controls[j])
}
}
}
// Deduplicate controls
dedupControls := deduplicate(c)
return dedupControls, nil
}
// deduplicate removes all duplicates
func deduplicate(result []*orchestrator.Control) []*orchestrator.Control {
// Sort slice by ID
sort.Slice(result, func(i, j int) bool {
return result[i].GetId() > result[j].GetId()
})
// Compare elements and delete if it is a duplicate
for i := len(result) - 1; i > 0; i-- {
if result[i] == result[i-1] {
result = append(result[:i], result[i+1:]...)
}
}
return result
}