func FromBundle()

in pkg/bundle/ruleset/bundle.go [30:98]


func FromBundle(b *bundlev1.Bundle) (*bundlev1.RuleSet, error) {
	// Check arguments
	if b == nil {
		return nil, errors.New("unable to process nil bundle")
	}
	if len(b.Packages) == 0 {
		return nil, errors.New("unable to generate rule from an empty bundle")
	}

	// Retrieve MTR
	root, _, err := bundle.Tree(b)
	if err != nil {
		return nil, fmt.Errorf("unable to compute bundle identifier: %w", err)
	}

	// Encode MTR as Base64
	b64Root := base64.RawURLEncoding.EncodeToString(root.Root())

	// Create ruleset
	rs := &bundlev1.RuleSet{
		ApiVersion: "harp.elastic.co/v1",
		Kind:       "RuleSet",
		Meta: &bundlev1.RuleSetMeta{
			Name:        b64Root,
			Description: "Generated from bundle content",
		},
		Spec: &bundlev1.RuleSetSpec{
			Rules: []*bundlev1.Rule{},
		},
	}

	// Iterate over bundle package
	ruleIdx := 1
	for _, p := range b.Packages {
		if p == nil || p.Secrets == nil || len(p.Secrets.Data) == 0 {
			// Skip invalid package
			continue
		}

		// Prepare a rule
		r := &bundlev1.Rule{
			Name:        fmt.Sprintf("LINT-%s-%d", b64Root[:6], ruleIdx),
			Path:        p.Name,
			Constraints: []string{},
		}

		// Process the labels for each secret
		for label := range p.Labels {
			r.Constraints = append(r.Constraints, fmt.Sprintf(`p.match_label(%q)`, label))
		}

		// Process the annotations for each secret
		for annotation := range p.Annotations {
			r.Constraints = append(r.Constraints, fmt.Sprintf(`p.match_annotation(%q)`, annotation))
		}

		// Process each secret
		for _, s := range p.Secrets.Data {
			r.Constraints = append(r.Constraints, fmt.Sprintf(`p.has_secret(%q)`, s.Key))
		}

		// Add the rules
		rs.Spec.Rules = append(rs.Spec.Rules, r)
		ruleIdx++
	}

	// No error
	return rs, nil
}