-
Notifications
You must be signed in to change notification settings - Fork 25
/
policy.go
85 lines (73 loc) · 2.16 KB
/
policy.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
package iface
import (
"bytes"
"encoding/json"
"fmt"
"time"
policylangv1 "github.com/fluxninja/aperture/v2/api/gen/proto/go/aperture/policy/language/v1"
"google.golang.org/protobuf/encoding/protojson"
"github.com/fluxninja/aperture/v2/pkg/config"
"github.com/fluxninja/aperture/v2/pkg/status"
)
const (
// PoliciesRoot - path in config and status registry for policies results.
PoliciesRoot = "policies"
)
// FxOptionsFuncTag allows sub-modules to provide their options to per policy apps independently.
var FxOptionsFuncTag = config.GroupTag("policy-fx-funcs")
// PolicyBase is for read only access to base policy info.
type PolicyBase interface {
GetPolicyName() string
GetPolicyHash() string
}
// Policy is for read only access to full policy state.
type Policy interface {
PolicyBase
GetEvaluationInterval() time.Duration
GetStatusRegistry() status.Registry
}
// GetSelectorsShortDescription returns a short description of the selectors.
func GetSelectorsShortDescription(selectors []*policylangv1.Selector) string {
return fmt.Sprintf("%d selectors", len(selectors))
}
// PolicyMessage is used for passing policies to be wrapped.
type PolicyMessage struct {
*policylangv1.Policy
PolicyMetadata *policylangv1.PolicyMetadata `json:"policy_metadata"`
}
// MarshalJSON implements the json.Marshaler interface.
func (m *PolicyMessage) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
pb, err := m.Policy.MarshalJSON()
if err != nil {
return nil, err
}
buf.Write(pb[:len(pb)-1])
if m.PolicyMetadata != nil {
buf.WriteString(`,"policy_metadata":`)
pmb, err := m.PolicyMetadata.MarshalJSON()
if err != nil {
return nil, err
}
buf.Write(pmb)
}
buf.WriteString("}")
return buf.Bytes(), nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (m *PolicyMessage) UnmarshalJSON(b []byte) error {
unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true}
err := unmarshaler.Unmarshal(b, m.Policy)
if err != nil {
return err
}
tmp := struct {
PolicyMetadata *policylangv1.PolicyMetadata `json:"policy_metadata"`
}{}
err = json.Unmarshal(b, &tmp)
if err != nil {
return err
}
m.PolicyMetadata = tmp.PolicyMetadata
return nil
}