/
catalogs.go
303 lines (254 loc) · 9.62 KB
/
catalogs.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
package orchestrator
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"clouditor.io/clouditor/v2/api"
"clouditor.io/clouditor/v2/api/orchestrator"
"clouditor.io/clouditor/v2/internal/logging"
"clouditor.io/clouditor/v2/internal/util"
"clouditor.io/clouditor/v2/persistence"
"clouditor.io/clouditor/v2/persistence/gorm"
"clouditor.io/clouditor/v2/service"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
)
// CreateCatalog implements a method for creating a new catalog.
func (svc *Service) CreateCatalog(_ context.Context, req *orchestrator.CreateCatalogRequest) (
*orchestrator.Catalog, error) {
// Validate request
err := api.Validate(req)
if err != nil {
return nil, err
}
// Persist the new catalog in our database
err = svc.storage.Create(req.Catalog)
if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
logging.LogRequest(log, logrus.DebugLevel, logging.Create, req)
// Return catalog
return req.Catalog, nil
}
// GetCatalog retrieves a control specified by the catalog ID, the control's category
// name and the control ID. If present, it also includes a list of sub-controls and any metrics associated to any
// controls.
func (svc *Service) GetCatalog(_ context.Context, req *orchestrator.GetCatalogRequest) (response *orchestrator.Catalog, err error) {
// Validate request
err = api.Validate(req)
if err != nil {
return nil, err
}
response = new(orchestrator.Catalog)
err = svc.storage.Get(response,
// Preload fills in associated entities, in this case controls. We want to only select those controls which do
// not have a parent, e.g., the top-level
gorm.WithPreload("Categories.Controls", "parent_control_id IS NULL"),
// Select catalog by ID
"Id = ?", req.CatalogId)
if errors.Is(err, persistence.ErrRecordNotFound) {
return nil, status.Errorf(codes.NotFound, "catalog not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
return response, nil
}
// ListCatalogs Lists all security controls catalogs. Each catalog includes a list of its
// categories but no additional sub-resources.
func (svc *Service) ListCatalogs(_ context.Context, req *orchestrator.ListCatalogsRequest) (res *orchestrator.ListCatalogsResponse, err error) {
// Validate request
err = api.Validate(req)
if err != nil {
return nil, err
}
res = new(orchestrator.ListCatalogsResponse)
res.Catalogs, res.NextPageToken, err = service.PaginateStorage[*orchestrator.Catalog](req, svc.storage,
service.DefaultPaginationOpts)
if err != nil {
return nil, status.Errorf(codes.Internal, "could not paginate results: %v", err)
}
return
}
// UpdateCatalog implements a method for updating an existing catalog
func (svc *Service) UpdateCatalog(_ context.Context, req *orchestrator.UpdateCatalogRequest) (res *orchestrator.Catalog, err error) {
// Validate request
err = api.Validate(req)
if err != nil {
return nil, err
}
res = req.Catalog
err = svc.storage.Update(res, "id = ?", res.Id)
if err != nil && errors.Is(err, persistence.ErrRecordNotFound) {
return nil, status.Error(codes.NotFound, "catalog not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
logging.LogRequest(log, logrus.DebugLevel, logging.Update, req)
return
}
// RemoveCatalog implements a method for removing a catalog
func (svc *Service) RemoveCatalog(_ context.Context, req *orchestrator.RemoveCatalogRequest) (response *emptypb.Empty, err error) {
// Validate request
err = api.Validate(req)
if err != nil {
return nil, err
}
err = svc.storage.Delete(&orchestrator.Catalog{}, "Id = ?", req.CatalogId)
if errors.Is(err, persistence.ErrRecordNotFound) {
return nil, status.Errorf(codes.NotFound, "catalog not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
logging.LogRequest(log, logrus.DebugLevel, logging.Remove, req)
return &emptypb.Empty{}, nil
}
// GetCategory retrieves a category of a catalog specified by the catalog ID and the category name. It includes the
// first level of controls within each category.
func (srv *Service) GetCategory(_ context.Context, req *orchestrator.GetCategoryRequest) (res *orchestrator.Category, err error) {
// Validate request
err = api.Validate(req)
if err != nil {
return nil, err
}
res = new(orchestrator.Category)
err = srv.storage.Get(&res,
// Preload fills in associated entities, in this case controls. We want to only select those controls which do
// not have a parent, e.g., the top-level
gorm.WithPreload("Controls", "parent_control_id IS NULL"),
// Select the category by name and catalog ID
"name = ? AND catalog_id = ?", req.CategoryName, req.CatalogId)
if errors.Is(err, persistence.ErrRecordNotFound) {
return nil, status.Errorf(codes.NotFound, "category not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
return res, nil
}
// GetControl retrieves a control specified by the catalog ID, the control's category name and the control ID. If
// present, it also includes a list of sub-controls and any metrics associated to the control.
func (srv *Service) GetControl(_ context.Context, req *orchestrator.GetControlRequest) (res *orchestrator.Control, err error) {
// Validate request
err = api.Validate(req)
if err != nil {
return nil, err
}
res = new(orchestrator.Control)
err = srv.storage.Get(&res,
// We only want to select controls for the specified category and catalog
"Id = ? AND category_name = ? AND category_catalog_id = ?", req.ControlId, req.CategoryName, req.CatalogId)
if errors.Is(err, persistence.ErrRecordNotFound) {
return nil, status.Errorf(codes.NotFound, "control not found")
} else if err != nil {
return nil, status.Errorf(codes.Internal, "database error: %v", err)
}
return res, nil
}
// ListControls lists controls. If no additional parameters are specified, this lists all controls. If a catalog ID and
// a category name is specified, then only controls containing in this category are returned.
func (srv *Service) ListControls(_ context.Context, req *orchestrator.ListControlsRequest) (res *orchestrator.ListControlsResponse, err error) {
var (
args []any
query []string
)
// Validate request
err = api.Validate(req)
if err != nil {
return nil, err
}
res = new(orchestrator.ListControlsResponse)
// If the category name is set (additional binding), forward it as a condition to the pagination method
if req.CategoryName != "" && req.CatalogId != "" {
query = append(query, "category_name = ?")
args = append(args, req.CategoryName)
}
if req.CatalogId != "" {
query = append(query, "category_catalog_id = ?")
args = append(args, req.CatalogId)
}
// Apply additional filter
if req.Filter != nil {
if len(req.Filter.AssuranceLevels) > 0 {
query = append(query, "(assurance_level IN ? OR assurance_level IS NULL)")
args = append(args, req.Filter.AssuranceLevels)
}
}
// Join query with AND and prepend the query
args = append([]any{strings.Join(query, " AND ")}, args...)
res.Controls, res.NextPageToken, err = service.PaginateStorage[*orchestrator.Control](req, srv.storage,
service.DefaultPaginationOpts, args...)
if err != nil {
return nil, status.Errorf(codes.Internal, "could not paginate results: %v", err)
}
return
}
// loadCatalogs loads catalog definitions from a JSON file.
func (svc *Service) loadCatalogs() (err error) {
var catalogs []*orchestrator.Catalog
// Default to loading catalogs from our embedded file system
if svc.loadCatalogsFunc == nil {
svc.loadCatalogsFunc = svc.loadEmbeddedCatalogs
}
// Execute our catalogs loading function
catalogs, err = svc.loadCatalogsFunc()
if err != nil {
return fmt.Errorf("could not load catalogs: %w", err)
}
err = svc.storage.Save(catalogs)
if err != nil {
log.Errorf("Error while saving catalog %v", err)
}
log.Debug("Catalogs successfully stored.")
return
}
func (svc *Service) loadEmbeddedCatalogs() (catalogs []*orchestrator.Catalog, err error) {
var (
b []byte
fileList []string
)
// Get all filenames
fileList, err = util.GetJSONFilenames(svc.catalogsFolder)
log.Infof("Loading catalogs from files %s.", strings.Join(fileList, ", "))
// Get catalog for each file
for i := range fileList {
var catalogsFromFile []*orchestrator.Catalog
b, err = os.ReadFile(filepath.Join(fileList[i]))
if err != nil {
log.Errorf("error while loading %s: %v", fileList[i], err)
continue
}
err = json.Unmarshal(b, &catalogsFromFile)
if err != nil {
log.Errorf("error in JSON marshal for file %s: %v", fileList[i], err)
continue
}
catalogs = append(catalogs, catalogsFromFile...)
}
// We need to make sure that sub-controls have the category_name and category_catalog_id of their parents set,
// otherwise we are failing a constraint.
for _, catalog := range catalogs {
for _, category := range catalog.Categories {
for _, control := range category.Controls {
for _, sub := range control.Controls {
sub.CategoryName = category.Name
sub.CategoryCatalogId = catalog.Id
// Make sure we are dealing with a copy of control when we
// take an address of its property and not the loop var,
// which gets overridden in each loop.
control := control
// Also set the parent information, so we do not need to set
// it in the original file to make it easier
sub.ParentControlCategoryCatalogId = &control.CategoryCatalogId
sub.ParentControlCategoryName = &control.CategoryName
sub.ParentControlId = &control.Id
}
}
}
}
return
}