Documentation
¶
Overview ¶
Package declarative implements `oa apply`, `oa diff` and `oa export`: it loads Kubernetes-style YAML manifests, validates them against per-kind schemas, diffs them against the live server state fetched through the REST API and applies the difference in dependency order.
Index ¶
- Constants
- Variables
- func Bool(spec map[string]any, key string) bool
- func Canon(v any) any
- func ChangedTop(changes []Change) map[string]bool
- func CheckSecrets(plan *Plan, r SecretResolver) []error
- func FormatValue(v any) string
- func Ident(kind, key string) string
- func IsStatus(err error, status int) bool
- func KindFilter(reg *Registry, names []string) (map[string]bool, error)
- func Omit(spec map[string]any, keys ...string) map[string]any
- func PatchBody(changes []Change) map[string]any
- func PathEscape(s string) string
- func Pick(spec map[string]any, keys ...string) map[string]any
- func SortObjects(reg *Registry, objs []*Object)
- func SortedStrings(s []string) []string
- func SpecHash(o *Object) string
- func Str(spec map[string]any, key string) string
- func StrList(spec map[string]any, key string) []string
- func TopField(path string) string
- func WriteDiff(w io.Writer, plan *Plan)
- func WriteDir(dir string, docs []ExportDoc) ([]string, error)
- func WriteJSON(w io.Writer, plan *Plan, outcomes []Outcome) error
- func WriteStream(w io.Writer, docs []ExportDoc) error
- func WriteSummary(w io.Writer, plan *Plan)
- func WriteTable(w io.Writer, plan *Plan, outcomes []Outcome)
- type APIError
- type Action
- type Change
- type Client
- type Env
- func (e *Env) ForgetIdents()
- func (e *Env) GroupID(ctx context.Context, name string) (string, error)
- func (e *Env) GroupNames(ctx context.Context) (map[string]string, error)
- func (e *Env) ServiceAccountID(ctx context.Context, name string) (string, error)
- func (e *Env) UserID(ctx context.Context, username string) (string, error)
- func (e *Env) UserNames(ctx context.Context) (map[string]string, error)
- type ExportDoc
- type ExportOmitter
- type ExportOptions
- type Field
- type Identifier
- type Idents
- type Item
- type JSONReport
- type Kind
- func NewGroupKind() Kind
- func NewOIDCTrustPolicyKind() Kind
- func NewPermissionTargetKind() Kind
- func NewProjectKind() Kind
- func NewRepositoryKind() Kind
- func NewSSOProviderKind() Kind
- func NewServiceAccountKind() Kind
- func NewStorageTierKind() Kind
- func NewTierPolicyKind() Kind
- func NewUserKind() Kind
- func NewWebhookKind() Kind
- type Live
- type LoadOptions
- type Marker
- type Markers
- type Object
- type Options
- type Outcome
- type Plan
- type PlanInput
- type Pos
- type Prepared
- type Prunable
- type Ref
- type Registry
- type SecretRef
- type SecretResolver
- type Status
- type Type
- type ValidationError
- type ValidationErrors
- type Validator
Constants ¶
const ( KindUser = "User" KindServiceAccount = "ServiceAccount" KindProject = "Project" KindGroup = "Group" KindRepository = "Repository" KindPermissionTarget = "PermissionTarget" KindOIDCTrustPolicy = "OIDCTrustPolicy" KindSSOProvider = "SSOProvider" KindWebhook = "Webhook" KindStorageTier = "StorageTier" KindTierPolicy = "TierPolicy" )
Manifest kinds.
const APIVersion = "openartifact.io/v1"
APIVersion is the only manifest apiVersion.
Variables ¶
var ErrNotAdmin = errors.New("oa apply needs an administrator token (manage permission)")
ErrNotAdmin is returned when the token lacks the manage permission.
var ErrPrincipalNotFound = errors.New("not found on the server")
ErrPrincipalNotFound is wrapped when a manifest names a user, service account or group that does not exist.
var ErrSecretUnresolved = errors.New("secret cannot be resolved")
ErrSecretUnresolved is wrapped by every resolution failure.
var ErrServerTooOld = errors.New("server does not support declarative configuration")
ErrServerTooOld is wrapped when the server lacks the declarative API.
var ErrUnknownKind = errors.New("unknown kind")
ErrUnknownKind is wrapped when --kind names a kind that does not exist.
Functions ¶
func Canon ¶
Canon converts v into the canonical JSON-typed form the engine compares: all numbers become float64, maps become map[string]any, slices become []any. SecretRef values pass through unchanged.
func ChangedTop ¶
ChangedTop returns the set of top-level field names touched by changes.
func CheckSecrets ¶
func CheckSecrets(plan *Plan, r SecretResolver) []error
CheckSecrets resolves every secret the plan will send, before anything is changed, so a missing environment variable or file aborts the run early.
func FormatValue ¶
FormatValue renders a value for reports: secrets as "(secret)", whole numbers without a decimal point, strings quoted, containers as compact JSON.
func KindFilter ¶
KindFilter resolves --kind names to a set of canonical kind names. A nil set means no restriction.
func PatchBody ¶
PatchBody builds the request body of a PATCH/PUT from changes: dotted paths become nested objects, so {oidc_config.issuer, public} yields {"oidc_config": {"issuer": ...}, "public": ...}. Top-level fields not in changes are absent, which the REST PATCH endpoints treat as unchanged.
func PathEscape ¶
PathEscape escapes one URL path segment (names may contain unusual runes).
func SortObjects ¶
SortObjects orders objects for apply: kind rank, kind order, key.
func SortedStrings ¶
SortedStrings returns a sorted copy of s.
func SpecHash ¶
SpecHash is the digest recorded in the ownership marker: sha256 of the canonical desired spec, secrets replaced by their reference (never values).
func TopField ¶
TopField returns the top-level field of a change path ("members[bob].role" -> "members", "oidc_config.issuer" -> "oidc_config").
func WriteDiff ¶
WriteDiff prints the plan as a field-level diff: one header per changed object, then "-" (live) and "+" (desired) lines per field. Unchanged objects are omitted.
func WriteDir ¶
WriteDir writes one file per object at <dir>/<kind>/<key>.yaml and returns the paths written.
func WriteStream ¶
WriteStream writes the documents as one multi-document YAML stream.
func WriteSummary ¶
WriteSummary prints the one-line totals.
Types ¶
type Change ¶
type Change struct {
// Path is the dotted spec path, e.g. "public" or "oidc_config.issuer".
Path string `json:"path"`
Old any `json:"old,omitempty"`
New any `json:"new,omitempty"`
// Secret changes never carry values in reports; New holds the resolved
// secret only for the kind's Update call.
Secret bool `json:"secret,omitempty"`
}
Change is one field-level difference between the live and the desired state.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the minimal authenticated JSON client the engine talks to the OpenArtifact REST API with.
func NewClient ¶
NewClient returns a client for the server at baseURL authenticated with an API token. httpClient may be nil (http.DefaultClient). Every call is bounded by defaultRequestTimeout, whichever http client carries it.
type Env ¶
type Env struct {
Client *Client
// Cache is scratch space for kinds (e.g. account name to id lookups). Kinds
// must delete entries they invalidate by creating objects.
Cache map[string]any
}
Env is the per-run context handed to kinds.
func (*Env) ForgetIdents ¶
func (e *Env) ForgetIdents()
ForgetIdents drops the cached account/group lookups; kinds that create or delete users, service accounts or groups call it so later lookups see them.
func (*Env) GroupNames ¶
GroupNames returns id to name for every group.
func (*Env) ServiceAccountID ¶ added in v0.16.0
ServiceAccountID resolves a service account name to its id.
type ExportOmitter ¶
type ExportOmitter interface {
ExportOmit() []string
}
ExportOmitter is implemented by kinds whose Live.Spec carries fields that `oa export` leaves out by default because they are usually filled by other systems (Group "members", populated by SSO group sync). The fields are emitted with `oa export --with-members`.
type ExportOptions ¶
type ExportOptions struct {
Registry *Registry
Client *Client
// Kinds restricts the export; empty means every kind except User. Naming
// User explicitly includes the human users.
Kinds []string
// WithMembers includes fields kinds omit by default (Group members).
WithMembers bool
}
ExportOptions select what `oa export` emits.
type Field ¶
type Field struct {
Type Type
Required bool
// Nullable accepts an explicit null (the server then inherits a default).
Nullable bool
// Enum restricts a TString.
Enum []string
// Min is the lower bound of a TInt/TNumber when HasMin is set.
Min float64
HasMin bool
// Secret marks a write-only field: manifests give a {secretRef: ...}
// instead of a value and the server never returns it.
Secret bool
// Immutable fields cannot change on an existing object.
Immutable bool
// FromMeta takes the value from metadata.<field name> instead of spec
// (Repository project).
FromMeta bool
// Fields are the keys of a TObject.
Fields map[string]*Field
// Elem is the element type of a TList/TSet/TMap.
Elem *Field
// KeyBy names the identity key of TSet/TList elements that are objects. A
// comma-separated list names a composite key: the elements are identified by
// their values of those fields, joined with "|" (an absent field is "").
KeyBy string
}
Field is a node of a kind's spec schema.
type Identifier ¶
Identifier is implemented by kinds whose natural key is not just the metadata name (Webhook: "<repository>/<name>"). `oa export` uses it to split a live object back into metadata.name and the extra metadata keys.
type Idents ¶
type Idents struct {
// Users maps the name of every account a user reference may name (human
// users and service accounts) to its id; Groups maps group name to group id.
Users map[string]string
Groups map[string]string
// ServiceAccounts maps service account name to id: the subset of Users that
// can be the target of a trust policy.
ServiceAccounts map[string]string
}
Idents is the account and group lookup shared by kinds that reference them.
type Item ¶
type Item struct {
Action Action
Kind string
Key string
Desired *Object
Live *Live
Changes []Change
// Adopt marks an existing object without a valid ownership marker that
// apply will take over (writing the marker) even when nothing changes.
Adopt bool
// Managed is set on delete items: the object carries a valid marker.
Managed bool
// Err is a plan-time problem with this item; any Err makes the whole plan
// unapplicable.
Err error
}
Item is one planned operation.
type JSONReport ¶
type JSONReport struct {
Summary map[Action]int `json:"summary"`
Items []jsonItem `json:"items"`
Changes bool `json:"changes"`
Errors []string `json:"errors,omitempty"`
}
JSONReport is the machine-readable form of a plan (and its execution).
func BuildJSON ¶
func BuildJSON(plan *Plan, outcomes []Outcome) *JSONReport
BuildJSON converts a plan (and optional outcomes) into a JSONReport. Secret values never appear: secret changes carry only the flag.
type Kind ¶
type Kind interface {
// Name is the manifest kind, e.g. "Repository".
Name() string
// Rank orders kinds for apply (ascending) and prune (descending).
Rank() int
// Schema describes the manifest spec of this kind.
Schema() *Field
// MetaKeys lists the metadata keys besides name this kind accepts that stay
// in Object.Meta (Webhook: "repository"). Keys mapped into the spec through
// Field.FromMeta are not listed.
MetaKeys() []string
// Key returns the natural key of o: the name, or scope/name where names are
// only unique within a scope.
Key(o *Object) string
// Order orders objects of this kind within an apply pass (ascending); e.g.
// group repositories after their members.
Order(o *Object) int
// Refs lists the objects o depends on.
Refs(o *Object) []Ref
// List returns every object of this kind that exists on the server.
List(ctx context.Context, env *Env) ([]*Live, error)
// Create creates o. Secrets in o.Spec are already resolved to strings.
// It returns the server-side id for the ownership marker.
Create(ctx context.Context, env *Env, o *Object) (id string, err error)
// Update applies changes to live. Only the changes may be sent; secret
// changes carry their resolved value in New. It returns the id for the
// ownership marker (normally live.ID).
Update(ctx context.Context, env *Env, live *Live, o *Object, changes []Change) (id string, err error)
// Delete removes live from the server.
Delete(ctx context.Context, env *Env, live *Live) error
}
Kind implements one manifest kind against the REST API.
func NewOIDCTrustPolicyKind ¶ added in v0.16.0
func NewOIDCTrustPolicyKind() Kind
NewOIDCTrustPolicyKind returns the OIDCTrustPolicy kind.
func NewPermissionTargetKind ¶
func NewPermissionTargetKind() Kind
NewPermissionTargetKind returns the PermissionTarget kind.
func NewRepositoryKind ¶
func NewRepositoryKind() Kind
NewRepositoryKind returns the Repository kind. Its natural key is the repository name (metadata.name); the owning project is metadata.project.
func NewSSOProviderKind ¶
func NewSSOProviderKind() Kind
NewSSOProviderKind returns the SSOProvider kind. Its natural key is the provider slug (metadata.name); the slug and the provider kind are immutable.
func NewServiceAccountKind ¶ added in v0.16.0
func NewServiceAccountKind() Kind
NewServiceAccountKind returns the ServiceAccount kind.
func NewStorageTierKind ¶
func NewStorageTierKind() Kind
NewStorageTierKind returns the StorageTier kind. The key is the tier name. spec.backend names a storage backend that must already exist (StorageBackend is not a managed kind); the server-created primary tier has a null backend, is never pruned and cannot be created declaratively.
func NewTierPolicyKind ¶
func NewTierPolicyKind() Kind
NewTierPolicyKind returns the TierPolicy kind. The key is the policy name, which the server enforces to be unique.
type Live ¶
type Live struct {
Kind string
// Key is the natural key (see Kind.Key).
Key string
// ID is the server-side identifier (uuid, slug or name) recorded in the
// ownership marker.
ID string
Spec map[string]any
// Secrets reports, per write-only field path, whether a value is set on
// the server. A path missing from the map means presence is unknown.
Secrets map[string]bool
// Seeded marks objects created by the server itself (admin-all,
// anonymous-read, the system project, the bootstrap admin). They are never
// pruned.
Seeded bool
}
Live is one object as it exists on the server, normalized into manifest shape: Spec only contains fields the kind's schema declares.
type LoadOptions ¶
type LoadOptions struct {
// Paths are files or directories; "-" reads Stdin.
Paths []string
// Recursive descends into subdirectories of directory paths.
Recursive bool
// Stdin is read for the path "-".
Stdin io.Reader
}
LoadOptions selects the manifest files to load.
type Marker ¶
type Marker struct {
Kind string `json:"kind"`
Name string `json:"name"`
ObjectID string `json:"object_id"`
AppliedHash string `json:"applied_hash"`
AppliedAt time.Time `json:"applied_at"`
}
Marker is the server-side ownership record of an object created or adopted by `oa apply`.
type Object ¶
type Object struct {
Kind string
Name string
// Meta holds the metadata keys other than name that the kind allows and
// that are not mapped into the spec (e.g. Webhook "repository").
Meta map[string]string
Spec map[string]any
Pos Pos
// FieldPos maps a dotted spec path to the position of its value.
FieldPos map[string]Pos
}
Object is one desired object loaded from a manifest document.
Spec holds JSON-typed values (string, float64, bool, []any, map[string]any, nil) in the same shape and snake_case names as the REST API. Fields the schema marks Secret hold a SecretRef until the engine resolves it.
type Options ¶
type Options struct {
Registry *Registry
Client *Client
Load LoadOptions
// Kinds restricts manifests and pruning to these kinds (case-insensitive
// names); empty means every kind.
Kinds []string
Prune bool
PruneAll bool
ForceSecrets bool
ContinueOnError bool
Resolver SecretResolver
}
Options configure a plan or apply run.
type Outcome ¶
Outcome is the result of executing one plan item.
type Plan ¶
type Plan struct {
Items []*Item
}
Plan is the ordered list of operations: creates/updates/unchanged in dependency order, then deletes in reverse dependency order.
func (*Plan) HasChanges ¶
HasChanges reports whether applying the plan would modify the server (adoption alone only writes ownership markers and is not a change).
type PlanInput ¶
type PlanInput struct {
Registry *Registry
Desired []*Object
// Live holds the objects found on the server per kind. A kind without an
// entry was not fetched: references to it are not checked and it is never
// pruned.
Live map[string][]*Live
Markers Markers
// Prune deletes managed objects absent from Desired; PruneAll also deletes
// unmanaged ones (never seeded objects, never Users or ServiceAccounts
// unless the kind filter names that kind).
Prune bool
PruneAll bool
ForceSecrets bool
// Kinds restricts pruning to these kinds (nil = every fetched kind).
Kinds map[string]bool
}
PlanInput is everything BuildPlan needs; it performs no I/O.
type Prunable ¶
Prunable is implemented by kinds where some live objects are not worth deleting: User "deletion" only disables the account, so an already disabled user would show up as a pending deletion forever.
type Ref ¶
type Ref struct {
Kind string
// Also lists the further kinds that satisfy the reference when Kind has no
// object with this key (a user reference accepts a ServiceAccount: account
// names are unique across both).
Also []string
Key string
// Field is the spec path holding the reference, for error messages.
Field string
}
Ref is a reference from one object to another that must exist (in the manifests or on the server) for the object to be applied.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is the set of kinds the engine manages, keyed by manifest kind.
func DefaultRegistry ¶
func DefaultRegistry() *Registry
DefaultRegistry returns the registry with every supported kind.
func NewRegistry ¶
NewRegistry returns a registry of the given kinds.
type SecretRef ¶
SecretRef points at a secret resolved on the machine running oa. Exactly one field is set. File is already absolute (relative paths are resolved against the manifest's directory when the manifest is loaded).
func PlanSecretRefs ¶ added in v0.16.1
PlanSecretRefs lists the distinct secret references the plan is going to send (creates and updates), sorted by their String form. A caller that cannot read the environment or files itself uses it to ask for the values.
type SecretResolver ¶
type SecretResolver struct {
// LookupEnv defaults to os.LookupEnv.
LookupEnv func(string) (string, bool)
// ReadFile defaults to a bounded os.ReadFile.
ReadFile func(string) ([]byte, error)
}
SecretResolver turns SecretRefs into values on the machine running oa. The zero value reads the process environment and the file system.
type Type ¶
type Type int
Type is the type of a manifest field.
const ( // TObject is a mapping with the fixed keys in Field.Fields. TObject Type = iota TString TInt TNumber TBool // TList is an ordered list of Field.Elem. TList // TSet is an unordered list of Field.Elem (compared sorted; Elem objects // are ordered by Field.KeyBy). TSet // TMap is a mapping with free string keys and Field.Elem values; it is // replaced as a whole. TMap // TAny accepts any JSON-typed value; it is compared as a whole. TAny )
Field types.
type ValidationError ¶
type ValidationError struct {
Pos Pos
// Ident is "Kind/name" of the object, empty for file-level problems.
Ident string
// Path is the dotted field path, empty for the object itself.
Path string
Msg string
}
ValidationError is one problem in a manifest, positioned at file:line.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type ValidationErrors ¶
type ValidationErrors []error
ValidationErrors is the aggregate returned by Load.
func (ValidationErrors) Error ¶
func (v ValidationErrors) Error() string
func (ValidationErrors) Unwrap ¶
func (v ValidationErrors) Unwrap() []error
Unwrap lets errors.Is/As see the individual errors.