cloudpolicy

package
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Overview

Package cloudpolicy holds the client side of SafeDep Cloud policy management that more than one command tree uses: the YAML form of the policy settings document, the display of contract values, labels and label selectors, and the policy of one subject. The policy, project and endpoint command packages read it, because sibling command packages must not import each other.

Index

Constants

View Source
const (
	// CustomPrefix is the one label prefix that an admin writes. Each other
	// prefix has its own write path, and LabelService rejects it.
	CustomPrefix = "custom/"
)
View Source
const Separator = " · "

Separator joins the parts of a summary line, as in "revision 47", separator, "published 6m ago by alice". It is a middle dot with spaces.

Variables

View Source
var ErrEmptyDocument = errors.New("the file is empty")

ErrEmptyDocument is the error for a saved file with no content.

View Source
var ErrUnknownFields = errors.New("the policy holds fields that this safedep CLI does not know")

ErrUnknownFields is the error for a policy with fields that the SDK of this CLI does not know.

Functions

func ActorName

func ActorName(a *messagescontroltowerv1.Actor) string

ActorName names an actor for people: the display name, or the id.

func Capabilities

func Capabilities() []string

Capabilities lists the settings capabilities of the contract: the fields of PolicySpec other than the package rules, as in "scan_gate".

func CheckKnownFields

func CheckKnownFields(m proto.Message) error

CheckKnownFields walks every level of a message and fails when one holds fields that the SDK of this CLI does not know. An edit cannot show such a field, and a save would drop it from the policy, so the edit must stop.

func CommentBlock

func CommentBlock(lines []string) string

CommentBlock turns lines into YAML comment lines and ends the block with a blank line. An empty line becomes a bare "#".

func DeleteLabels

func DeleteLabels(
	ctx context.Context,
	client policyv1grpc.LabelServiceClient,
	kind specv1.SubjectKind,
	ids []string,
	keys []string,
) error

DeleteLabels removes "custom/" labels from subjects of one kind.

func DocumentDurations

func DocumentDurations(text string) string

DocumentDurations writes each duration in text that is a whole number of days in the form of the document notes, as "31536000s" to "365d". protovalidate writes a duration limit in seconds, which a person cannot compare with the "from 0s to 365d" note of the file.

func DocumentPath

func DocumentPath(path string) (string, bool)

DocumentPath maps a dotted field path of a Policy, with proto field names as a server error gives it, to the keys of the edit document, as "overrides[0].selector.matchLabels". Indexes and map keys stay as they are. It also reports whether the field is a duration. A path that does not parse, or a part below a name that the Policy does not have, stays as it is, so a person still sees what the server sent.

func EmptyDash

func EmptyDash(s string) string

EmptyDash keeps a table cell readable when a value is absent.

func FormatJSONValue

func FormatJSONValue(path, raw string) (string, string)

FormatJSONValue turns a value of a contract path, as a preview returns it, into the document form and the table form. The server writes a message in protojson and an enum by its value name with no quotes, as SEVERITY_MEDIUM. Both get the short form of the document, as "7d" and "medium". An empty raw value means that the layer did not set the field, and shows as "-".

func FormatLabels

func FormatLabels(labels []*messagescontroltowerv1.Label) []string

FormatLabels writes labels as sorted "key=value" items.

func FormatSelector

func FormatSelector(selector *messagescontroltowerv1.LabelSelector) string

FormatSelector writes a label selector in the text form that ParseSelector reads. An empty selector matches every subject.

func HasUserComments

func HasUserComments(data, written []byte) bool

HasUserComments reports whether the saved file holds a comment that the CLI did not write. The policy keeps no comments, so a person loses them on save. written is the text that the CLI wrote: its header, the commented fields and their notes. A field line that a person uncomments keeps its note, so each part of a written comment line from a "#" on counts too.

func KeyValues

func KeyValues(rows [][2]string) string

KeyValues writes label and value rows with the values in one column. The column uses the display width of the labels. Each value is escaped as one line, because a value can come from the server. A value that needs more lines takes more rows: a row with an empty label continues the row above.

func LeafPaths

func LeafPaths() []string

LeafPaths lists every settings path of the contract that the SDK knows, in descriptor order, as in "scan_gate.fail_on".

func MarshalOverrideTemplate

func MarshalOverrideTemplate(o *policyv1.Override, header string, def DefaultLayer, base *specv1.PolicySpec) ([]byte, error)

MarshalOverrideTemplate writes one policy override for an edit, in the form of MarshalPolicyTemplate. base is the policy base of the document, for the notes of the fields that the override does not set.

func MarshalPolicy

func MarshalPolicy(p *policyv1.Policy, header string) ([]byte, error)

MarshalPolicy writes the policy settings document as YAML, after the header.

func MarshalPolicyTemplate

func MarshalPolicyTemplate(p *policyv1.Policy, header string, def DefaultLayer) ([]byte, error)

MarshalPolicyTemplate writes the policy settings document for an edit: the header, the set fields, every other settings field as a commented line with a note, and an example policy override when the policy has none.

func MatchesFieldFilter

func MatchesFieldFilter(paths, filter []string) bool

MatchesFieldFilter reports whether any path in paths is selected by the filter. A filter entry selects its own path and every path below it. An empty filter selects every path.

func NewLabelClient

NewLabelClient returns the LabelService client of a control plane connection.

func NewPolicyClient

NewPolicyClient returns the PolicyService client of a control plane connection.

func NewSubject

func NewSubject(kind specv1.SubjectKind, id string) *specv1.Subject

NewSubject builds a subject of the policy.

func ParseCustomLabels

func ParseCustomLabels(values []string) ([]*messagescontroltowerv1.Label, error)

ParseCustomLabels reads "custom/key=value" pairs. It rejects any other prefix before the RPC, with the reason.

func ParseSelector

func ParseSelector(text string) (*messagescontroltowerv1.LabelSelector, error)

ParseSelector reads a label selector in the Kubernetes text form. The terms are separated by commas, and they AND together:

key=value, key==value   the key has the value
key!=value              the key does not have the value
key in (a,b)            the key has one of the values
key notin (a,b)         the key has none of the values
key                     the key exists
!key                    the key does not exist

func ParseTime

func ParseTime(s string) (time.Time, error)

ParseTime reads an RFC 3339 time or a date, as in "2027-01-26". A date is midnight UTC.

func Plural

func Plural(n int, singular, plural string) string

Plural picks the singular or the plural form for n.

func PolicyMap

func PolicyMap(p *policyv1.Policy) (any, error)

PolicyMap returns the policy settings document as plain maps and lists, in the same form as the YAML, for JSON output.

func PruneEmpty

func PruneEmpty(m proto.Message) proto.Message

PruneEmpty returns a copy of m with every message field that holds no field cleared, at every level. A label selector, a duration, a time and a list setting stay, because their empty value means something: every subject, zero, or a list with no items. An edit compares pruned messages, so a parent key that a person uncomments with no field below it is no change.

func RFC3339

func RFC3339(t *time.Time) string

RFC3339 writes an optional time in UTC, or "" when it is absent.

func SetLabels

func SetLabels(
	ctx context.Context,
	client policyv1grpc.LabelServiceClient,
	kind specv1.SubjectKind,
	ids []string,
	labels []*messagescontroltowerv1.Label,
) error

SetLabels sets "custom/" labels on subjects of one kind.

func TimeOf

func TimeOf(ts *timestamppb.Timestamp) *time.Time

TimeOf returns a timestamp in UTC, or nil when it is absent.

func UnmarshalOverride

func UnmarshalOverride(data []byte) (*policyv1.Override, error)

UnmarshalOverride reads one policy override.

func UnmarshalPolicy

func UnmarshalPolicy(data []byte) (*policyv1.Policy, error)

UnmarshalPolicy reads a policy settings document.

func ValidateCustomKey

func ValidateCustomKey(key string) error

ValidateCustomKey checks that an admin can write the label key.

func ValidateCustomKeys

func ValidateCustomKeys(keys []string) error

ValidateCustomKeys checks label keys for a delete.

func ValidateFieldPaths

func ValidateFieldPaths(paths []string) error

ValidateFieldPaths checks that each path is a settings path or a capability of the contract, so a typo fails before the RPC.

Types

type AppliedPolicy

type AppliedPolicy struct {
	Implementer     string
	Version         string
	Revision        uint64
	DefaultRevision uint64
	State           string
	RejectedReason  string
	FetchedAt       *time.Time
	AppliedAt       *time.Time
	ReportedAt      *time.Time
	Exceptions      []FieldException
}

AppliedPolicy is the last policy that one tool or check reported.

type DefaultLayer

type DefaultLayer struct {
	Revision uint64
	Spec     *specv1.PolicySpec
}

DefaultLayer is the SafeDep default policy, the layer below the base.

type FieldException

type FieldException struct {
	Path   string `json:"path"`
	Reason string `json:"reason"`
	Detail string `json:"detail,omitempty"`
}

FieldException is one field that a tool did not apply as the policy says.

type FieldValue

type FieldValue struct {
	// Path is the contract path, as in "scan_gate.fail_on".
	Path string
	// Value is the exact value, in the form of the policy document, as
	// "168h" or "medium".
	Value string
	// Human is the value for a table, as "7d".
	Human string
}

FieldValue is one set field of a PolicySpec.

func Fields

func Fields(spec *specv1.PolicySpec) []FieldValue

Fields lists the set fields of a PolicySpec, other than package rules, in descriptor order.

type MatchedOverride

type MatchedOverride struct {
	ID       string `json:"override_id"`
	Name     string `json:"name"`
	Priority uint32 `json:"priority"`
}

MatchedOverride is a policy override that matches the subject.

type SubjectField

type SubjectField struct {
	Path       string
	Value      string
	Human      string
	Source     string
	Exceptions []string
}

SubjectField is one field of the intended policy.

type SubjectPolicy

type SubjectPolicy struct {
	Kind            string
	Name            string
	ID              string
	Revision        uint64
	DefaultRevision uint64
	Matched         []MatchedOverride
	Labels          []string
	TrustRules      int
	BlockRules      int
	Fields          []SubjectField
	Applied         []AppliedPolicy
	Filtered        bool
}

SubjectPolicy is the intended policy of one subject, the source of each value, and the policy that each tool or check applied.

func GetSubjectPolicy

func GetSubjectPolicy(
	ctx context.Context,
	client SubjectPolicyClient,
	subject *specv1.Subject,
	name string,
	fields []string,
) (*SubjectPolicy, error)

GetSubjectPolicy reads the policy of a subject. name labels the subject in the output. fields limits the output to these contract paths and the paths below them.

func (*SubjectPolicy) PolicyLine

func (p *SubjectPolicy) PolicyLine() string

PolicyLine summarises the intended policy in one line: the revision and the matched policy overrides, or "no override matches" and "base only".

func (*SubjectPolicy) RenderJSON

func (p *SubjectPolicy) RenderJSON() ([]byte, error)

func (*SubjectPolicy) RenderPlain

func (p *SubjectPolicy) RenderPlain() string

func (*SubjectPolicy) RenderTable

func (p *SubjectPolicy) RenderTable() string

type SubjectPolicyClient

type SubjectPolicyClient interface {
	GetSubjectPolicy(
		context.Context,
		*policyv1.GetSubjectPolicyRequest,
		...grpc.CallOption,
	) (*policyv1.GetSubjectPolicyResponse, error)
}

SubjectPolicyClient reads the policy of one subject.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL