-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
530 lines (466 loc) · 16.2 KB
/
main.go
File metadata and controls
530 lines (466 loc) · 16.2 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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"slices"
"strconv"
"strings"
policyManager "github.com/compliance-framework/agent/policy-manager"
"github.com/compliance-framework/agent/runner"
"github.com/compliance-framework/agent/runner/proto"
"github.com/compliance-framework/plugin-jira/internal/jira"
"github.com/hashicorp/go-hclog"
goplugin "github.com/hashicorp/go-plugin"
"github.com/mitchellh/mapstructure"
)
type Validator interface {
Validate() error
}
type PluginConfig struct {
BaseURL string `mapstructure:"base_url"`
AuthType string `mapstructure:"auth_type"` // "oauth2" or "token"
ClientID string `mapstructure:"client_id"`
ClientSecret string `mapstructure:"client_secret"`
APIToken string `mapstructure:"api_token"`
UserEmail string `mapstructure:"user_email"`
ProjectKeys string `mapstructure:"project_keys"` // Comma-separated list
ChangeRequestIssueTypes string `mapstructure:"change_request_issue_types"` // Comma-separated list of issue types to consider as change requests
// Hack to configure policy labels and generate correct evidence UUIDs
PolicyLabels string `mapstructure:"policy_labels"`
}
// ParsedConfig holds the parsed and processed configuration
type ParsedConfig struct {
BaseURL string `mapstructure:"base_url"`
AuthType string `mapstructure:"auth_type"`
ClientID string `mapstructure:"client_id"`
ClientSecret string `mapstructure:"client_secret"`
APIToken string `mapstructure:"api_token"`
UserEmail string `mapstructure:"user_email"`
ProjectKeys []string `mapstructure:"project_keys"`
ChangeRequestIssueTypes []string `mapstructure:"change_request_issue_types"`
PolicyLabels map[string]string `mapstructure:"policy_labels"`
}
func (c *PluginConfig) Parse() (*ParsedConfig, error) {
policyLabels := map[string]string{}
if c.PolicyLabels != "" {
if err := json.Unmarshal([]byte(c.PolicyLabels), &policyLabels); err != nil {
return nil, fmt.Errorf("could not parse policy labels: %w", err)
}
}
parsed := &ParsedConfig{
BaseURL: c.BaseURL,
AuthType: c.AuthType,
ClientID: c.ClientID,
ClientSecret: c.ClientSecret,
APIToken: c.APIToken,
UserEmail: c.UserEmail,
PolicyLabels: policyLabels,
}
if c.ProjectKeys != "" {
parts := strings.Split(c.ProjectKeys, ",")
for _, p := range parts {
if s := strings.TrimSpace(p); s != "" {
parsed.ProjectKeys = append(parsed.ProjectKeys, s)
}
}
}
// Parse change request issue types with defaults
if c.ChangeRequestIssueTypes != "" {
parts := strings.Split(c.ChangeRequestIssueTypes, ",")
for _, p := range parts {
if s := strings.TrimSpace(p); s != "" {
parsed.ChangeRequestIssueTypes = append(parsed.ChangeRequestIssueTypes, s)
}
}
} else {
// Default values
parsed.ChangeRequestIssueTypes = []string{"Change Request", "Change"}
}
return parsed, nil
}
func (c *PluginConfig) Validate() error {
if c.BaseURL == "" {
return errors.New("base_url is required")
}
if c.AuthType != "oauth2" && c.AuthType != "token" {
return errors.New("auth_type must be either 'oauth2' or 'token'")
}
if c.AuthType == "oauth2" {
if c.ClientID == "" || c.ClientSecret == "" {
return errors.New("client_id and client_secret are required for oauth2")
}
}
if c.AuthType == "token" {
if c.APIToken == "" || c.UserEmail == "" {
return errors.New("api_token and user_email are required for token auth")
}
}
return nil
}
// JiraPlugin implements the Jira integration plugin, managing configuration and the Jira HTTP client.
type JiraPlugin struct {
Logger hclog.Logger
config *PluginConfig
parsedConfig *ParsedConfig
client *http.Client
}
func (l *JiraPlugin) initClient(ctx context.Context) error {
if l.parsedConfig.AuthType == "oauth2" {
l.Logger.Debug("Initializing Jira client with OAuth2")
l.client = jira.NewOAuth2Client(l.parsedConfig.ClientID, l.parsedConfig.ClientSecret, l.parsedConfig.BaseURL, l.Logger)
} else {
l.Logger.Debug("Initializing Jira client with Token")
// Token auth
l.client = jira.NewTokenAuthClient(l.parsedConfig.UserEmail, l.parsedConfig.APIToken)
}
return nil
}
func (l *JiraPlugin) Configure(req *proto.ConfigureRequest) (*proto.ConfigureResponse, error) {
l.Logger.Info("Configuring Jira Plugin")
config := &PluginConfig{}
if err := mapstructure.Decode(req.Config, config); err != nil {
l.Logger.Error("Error decoding config", "error", err)
return nil, err
}
l.Logger.Debug("configuration decoded", "baseURL", config.BaseURL, "authType", config.AuthType)
if err := config.Validate(); err != nil {
l.Logger.Error("Error validating config", "error", err)
return nil, err
}
l.config = config
// Parse JSON-encoded configuration fields
parsed, err := config.Parse()
if err != nil {
l.Logger.Error("Error parsing config", "error", err)
return nil, err
}
l.parsedConfig = parsed
return &proto.ConfigureResponse{}, nil
}
func (l *JiraPlugin) Init(req *proto.InitRequest, apiHelper runner.ApiHelper) (*proto.InitResponse, error) {
ctx := context.Background()
subjectTemplates := []*proto.SubjectTemplate{
{
Name: "jira-project",
Type: proto.SubjectType_SUBJECT_TYPE_COMPONENT,
TitleTemplate: "Jira Project: {{ .project_key }}",
DescriptionTemplate: "Jira project {{ .project_name }} ({{ .project_key }})",
PurposeTemplate: "Represents a Jira project being monitored for compliance",
IdentityLabelKeys: []string{"project_key"},
// No extra labels except for the _plugin - added through the agent runner
SelectorLabels: []*proto.SubjectLabelSelector{},
LabelSchema: []*proto.SubjectLabelSchema{
{Key: "project_key", Description: "The unique key identifying the Jira project (e.g. MYPROJ)"},
{Key: "project_name", Description: "The display name of the Jira project"},
{Key: "project_id", Description: "The internal numeric ID of the Jira project"},
{Key: "project_category", Description: "The category assigned to the Jira project, if any"},
{Key: "jira_url", Description: "The base URL of the Jira instance"},
},
},
}
return runner.InitWithSubjectsAndRisksFromPolicies(ctx, l.Logger, req, apiHelper, subjectTemplates)
}
func (l *JiraPlugin) Eval(req *proto.EvalRequest, apiHelper runner.ApiHelper) (*proto.EvalResponse, error) {
ctx := context.Background()
if err := l.initClient(ctx); err != nil {
l.Logger.Error("Error initializing Jira client", "error", err)
return nil, err
}
client, err := jira.NewClient(l.parsedConfig.BaseURL, l.client, l.Logger)
if err != nil {
l.Logger.Error("Error creating JIRA client", "error", err)
return nil, err
}
jiraData, err := l.collectData(ctx, client)
if err != nil {
l.Logger.Error("Error collecting Jira data", "error", err)
return &proto.EvalResponse{
Status: proto.ExecutionStatus_FAILURE,
}, err
}
converted := jiraData.ToProjectCentric()
l.Logger.Debug("Collected Jira data", "projectCount", len(converted.Projects))
evidences, err := l.EvaluatePolicies(ctx, converted, req)
if err != nil {
l.Logger.Error("Error evaluating policies", "error", err)
return &proto.EvalResponse{
Status: proto.ExecutionStatus_FAILURE,
}, err
}
l.Logger.Debug("calculated evidences", "count", len(evidences))
if err := apiHelper.CreateEvidence(ctx, evidences); err != nil {
l.Logger.Error("Error creating evidence", "error", err)
return &proto.EvalResponse{
Status: proto.ExecutionStatus_FAILURE,
}, err
}
return &proto.EvalResponse{
Status: proto.ExecutionStatus_SUCCESS,
}, nil
}
func (l *JiraPlugin) collectData(ctx context.Context, client *jira.Client) (*jira.JiraData, error) {
data := &jira.JiraData{}
// 1. Fetch Global Metadata
var err error
data.Workflows, err = client.FetchWorkflows(ctx)
if err != nil {
l.Logger.Warn("failed to fetch workflows", "error", err)
}
// Fetch workflow capabilities for each workflow
if len(data.Workflows) > 0 {
// For now, fetch capabilities for the first workflow as an example
// In the future, we could fetch for all workflows or specific ones
firstWorkflow := data.Workflows[0]
data.WorkflowCapabilities, err = client.FetchWorkflowCapabilities(ctx, firstWorkflow.ID)
if err != nil {
l.Logger.Warn("failed to fetch workflow capabilities", "workflowId", firstWorkflow.ID, "error", err)
}
}
data.WorkflowSchemes, err = client.FetchWorkflowSchemes(ctx)
if err != nil {
l.Logger.Warn("failed to fetch workflow schemes", "error", err)
}
data.IssueTypes, err = client.FetchIssueTypes(ctx)
if err != nil {
l.Logger.Warn("failed to fetch issue types", "error", err)
}
data.Fields, err = client.FetchFields(ctx)
if err != nil {
l.Logger.Warn("failed to fetch fields", "error", err)
}
data.AuditRecords, err = client.FetchAuditRecords(ctx)
if err != nil {
l.Logger.Warn("failed to fetch audit records", "error", err)
}
data.GlobalPermissions, err = client.FetchGlobalPermissions(ctx)
if err != nil {
l.Logger.Warn("failed to fetch global permissions", "error", err)
}
data.Statuses, err = client.GetAllStatuses(ctx)
if err != nil {
l.Logger.Warn("failed to fetch statuses", "error", err)
}
// 2. Fetch Projects
projects, err := client.FetchProjects(ctx)
if err != nil {
return nil, fmt.Errorf("failed to fetch projects: %w", err)
}
// Filter by project keys if configured
if len(l.parsedConfig.ProjectKeys) > 0 {
filtered := []jira.JiraProject{}
for _, p := range projects {
for _, key := range l.parsedConfig.ProjectKeys {
if p.Key == key {
filtered = append(filtered, p)
break
}
}
}
data.Projects = filtered
} else {
data.Projects = projects
}
// 3. Projects are already fetched with all available details
l.Logger.Debug("Project details fetched", "count", len(data.Projects))
// Fetch workflow scheme project associations for all projects
if len(data.Projects) > 0 {
projectIds := make([]int64, 0, len(data.Projects))
for _, project := range data.Projects {
if project.ID != "" {
// Convert string ID to int64
if id, err := strconv.ParseInt(project.ID, 10, 64); err == nil {
projectIds = append(projectIds, id)
}
}
}
if len(projectIds) > 0 {
data.WorkflowSchemeProjectAssociations, err = client.GetWorkflowSchemeProjectAssociations(ctx, projectIds)
if err != nil {
l.Logger.Warn("failed to fetch workflow scheme project associations", "error", err)
}
}
}
// 4. Search for Change Request issues
issues, err := client.SearchChangeRequests(ctx, l.parsedConfig.ProjectKeys, l.parsedConfig.ChangeRequestIssueTypes)
if err != nil {
return nil, fmt.Errorf("failed to search issues: %w", err)
}
data.Issues = issues
// Enrich issues with field metadata (name, type, value)
jira.EnrichIssuesWithFieldMetadata(data.Issues, data.Fields)
l.Logger.Debug("Enriched issues with field metadata", "issueCount", len(data.Issues))
// 5. Fetch Details, Approvals, SLAs, DevInfo, and Deployments for each issue
for i, issue := range data.Issues {
l.Logger.Info("Fetching details for issue", "issue", issue.Key)
// Note: Changelog is already fetched via expand=changelog in SearchChangeRequests
// No need to fetch it separately unless we need additional pagination
approvals, err := client.FetchIssueApprovals(ctx, issue.Key)
if err != nil {
l.Logger.Warn("failed to fetch approvals for issue", "issue", issue.Key, "error", err)
} else {
data.Issues[i].Approvals = approvals
}
slas, err := client.FetchIssueSLAs(ctx, issue.Key)
if err != nil {
l.Logger.Warn("failed to fetch SLAs for issue", "issue", issue.Key, "error", err)
} else {
data.Issues[i].SLAs = slas
}
devInfo, err := client.FetchIssueDevInfo(ctx, issue.Key)
if err != nil {
l.Logger.Warn("failed to fetch dev info for issue", "issue", issue.Key, "error", err)
} else {
data.Issues[i].DevInfo = devInfo
}
deployments, err := client.FetchIssueDeployments(ctx, issue.Key)
if err != nil {
l.Logger.Warn("failed to fetch deployments for issue", "issue", issue.Key, "error", err)
} else {
data.Issues[i].Deployments = deployments
}
}
return data, nil
}
func (l *JiraPlugin) EvaluatePolicies(ctx context.Context, data *jira.ProjectCentricData, req *proto.EvalRequest) ([]*proto.Evidence, error) {
var accumulatedErrors error
activities := make([]*proto.Activity, 0)
evidences := make([]*proto.Evidence, 0)
activities = append(activities, &proto.Activity{
Title: "Collect Jira Compliance Data",
Steps: []*proto.Step{
{
Title: "Authenticate with Jira",
Description: "Authenticate with Jira Platform and Service Management APIs.",
},
{
Title: "Fetch Jira Projects and Workflows",
Description: "Retrieve project metadata, workflow configurations, and issue types.",
},
{
Title: "Search and Analyze Change Requests",
Description: "Search for Change Request issues and analyze their transitions, approvals, and linked development data.",
},
},
})
actors := []*proto.OriginActor{
{
Title: "The Continuous Compliance Framework",
Type: "assessment-platform",
Links: []*proto.Link{
{
Href: "https://compliance-framework.github.io/docs/",
Rel: policyManager.Pointer("reference"),
Text: policyManager.Pointer("The Continuous Compliance Framework"),
},
},
Props: nil,
},
{
Title: "Continuous Compliance Framework - Jira Plugin",
Type: "tool",
Links: []*proto.Link{
{
Href: "https://github.com/compliance-framework/plugin-jira",
Rel: policyManager.Pointer("reference"),
Text: policyManager.Pointer("The Continuous Compliance Framework Jira Plugin"),
},
},
Props: nil,
},
}
components := []*proto.Component{
{
Identifier: "jira-platform",
Type: "service",
Title: "Jira Platform",
Description: "Atlassian Jira Platform providing project and workflow management.",
Purpose: "To serve as the system of record for change management and workflows.",
Links: []*proto.Link{
{
Href: l.config.BaseURL,
Rel: policyManager.Pointer("component"),
Text: policyManager.Pointer("Jira Instance"),
},
},
},
}
inventory := []*proto.InventoryItem{
{
Identifier: "jira-data-collection",
Type: "jira-compliance-data",
Title: "Jira Compliance Data",
Props: []*proto.Property{},
Links: []*proto.Link{
{
Href: l.config.BaseURL,
Text: policyManager.Pointer("Jira Base URL"),
},
},
ImplementedComponents: []*proto.InventoryItemImplementedComponent{
{
Identifier: "jira-platform",
},
},
},
}
subjects := []*proto.Subject{
{
Type: proto.SubjectType_SUBJECT_TYPE_COMPONENT,
Identifier: "jira-platform",
},
}
baseLabels := map[string]string{}
maps.Copy(baseLabels, l.parsedConfig.PolicyLabels)
baseLabels["provider"] = "jira"
for _, project := range data.Projects {
labels := maps.Clone(baseLabels)
labels["project_key"] = project.Project.Key
labels["project_name"] = project.Project.Name
labels["jira_url"] = l.parsedConfig.BaseURL
projectData := &jira.ProjectCentricData{
Projects: []jira.ProjectData{project},
GlobalPermissions: data.GlobalPermissions,
AuditRecords: data.AuditRecords,
}
for _, policyPath := range req.GetPolicyPaths() {
processor := policyManager.NewPolicyProcessor(
l.Logger,
labels,
subjects,
components,
inventory,
actors,
activities,
)
evidence, err := processor.GenerateResults(ctx, policyPath, projectData)
evidences = slices.Concat(evidences, evidence)
if err != nil {
accumulatedErrors = errors.Join(accumulatedErrors, err)
}
}
}
return evidences, accumulatedErrors
}
func main() {
logger := hclog.New(&hclog.LoggerOptions{
Level: hclog.Trace,
JSONFormat: true,
})
jiraPlugin := &JiraPlugin{
Logger: logger,
}
logger.Info("Starting Jira Plugin")
goplugin.Serve(&goplugin.ServeConfig{
HandshakeConfig: runner.HandshakeConfig,
Plugins: map[string]goplugin.Plugin{
"runner": &runner.RunnerV2GRPCPlugin{
Impl: jiraPlugin,
},
},
GRPCServer: goplugin.DefaultGRPCServer,
})
}