securitydeployment

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MPL-2.0 Imports: 44 Imported by: 0

Documentation

Overview

Package securitydeployment replaces one explicitly enrolled deployment using installation-owned authority. Feed metadata supplies an authenticated release identity and image digest, never a command, credential, workload or path.

Supported adapters are host-owned Compose/SQLite and directly owned singleton Kubernetes/PostgreSQL, plus an explicit Fargate/ALB/EFS/PostgreSQL contract. A chart release is accepted only when it opts in through its own values. GitOps, other Helm-owned releases, HA and other managed services deliberately refuse.

Index

Constants

View Source
const DefaultTimeout = 30 * time.Minute

DefaultTimeout bounds a Compose or Kubernetes replacement or rollback when none is configured. The coordinator waits that long, so a one-shot must be allowed the same: a large restore ends in it. ECS keeps its own 900 seconds, which its health grace contract is built on.

View Source
const RollbackReportFormat = "hikyo.security-rollback/v1"

RollbackReportFormat names the one line the target's one-shot prints.

Variables

View Source
var (
	ErrPreconditionRefused = errors.New("security deployment: precondition refused before workload mutation")
	ErrInvalid             = errors.New("security deployment: invalid installation contract")
	ErrUnsupported         = errors.New("security deployment: deployment requires a dedicated adapter")
	ErrConflict            = errors.New("security deployment: enrolled source or desired state changed")
	ErrNotReady            = errors.New("security deployment: exact running target is not healthy")
	ErrRecoveryRequired    = errors.New("security deployment: replacement outcome requires operator reconciliation")
	ErrEligibilityExpired  = errors.New("security deployment: authenticated eligibility expired before replacement")
)
View Source
var ErrFollowsRollback = errors.New("the release follows an earlier rollback")

ErrFollowsRollback is what Reconcile returns, after it released the pin, when the journal says a rollback had begun: the source is serving because that rollback put it back, not because it never stopped.

Functions

func RequireInstalledExecutable

func RequireInstalledExecutable(path string) error

RequireInstalledExecutable applies the same root-installed test to the coordinator's own executable that the adapters apply to their host programs.

func Validate

func Validate(c Config) error

Types

type Command

type Command struct {
	Path  string
	Args  []string
	Input []byte
	// Env adds variables to the coordinator's own environment; nil inherits it unchanged.
	Env []string
}

type CommandRunner

type CommandRunner struct {
	Secrets func() ([]string, error)
}

CommandRunner runs installed tools. Secrets lists exact values to remove from diagnostics, read before a command runs and again when it fails, so a value rotated while it ran is covered either way. An error from either read withholds the diagnostics, because they could then carry a value.

func (CommandRunner) Run

func (r CommandRunner) Run(ctx context.Context, command Command) ([]byte, error)

type ComposeConfig

type ComposeConfig struct {
	Docker          string `json:"docker"`
	Directory       string `json:"directory"`
	Project         string `json:"project"`
	File            string `json:"file"`
	EnvironmentFile string `json:"environment_file"`
	Service         string `json:"service"`
	Binary          string `json:"binary"`
}

type Config

type Config struct {
	Kind            Kind              `json:"kind"`
	StateDirectory  string            `json:"state_directory"`
	ImageRepository string            `json:"image_repository"`
	TimeoutSeconds  int               `json:"timeout_seconds"`
	Compose         *ComposeConfig    `json:"compose,omitempty"`
	Kubernetes      *KubernetesConfig `json:"kubernetes,omitempty"`
	ECS             *ECSConfig        `json:"ecs,omitempty"`
}

type ECSConfig

type ECSConfig struct {
	AWS                     string    `json:"aws"`
	Profile                 string    `json:"profile"`
	Region                  string    `json:"region"`
	ClusterARN              string    `json:"cluster_arn"`
	ServiceARN              string    `json:"service_arn"`
	ServiceCreatedAt        time.Time `json:"service_created_at"`
	Container               string    `json:"container"`
	Binary                  string    `json:"binary"`
	TaskFamily              string    `json:"task_family"`
	TaskRoleARN             string    `json:"task_role_arn"`
	ExecutionRoleARN        string    `json:"execution_role_arn"`
	DatabaseSecretARN       string    `json:"database_secret_arn"`
	ScratchSecretARN        string    `json:"scratch_secret_arn"`
	UpgradeVolume           string    `json:"upgrade_volume"`
	UpgradeFileSystemID     string    `json:"upgrade_file_system_id"`
	UpgradeAccessPointID    string    `json:"upgrade_access_point_id"`
	UpgradeMountPath        string    `json:"upgrade_mount_path"`
	RootVolume              string    `json:"root_volume"`
	RootFileSystemID        string    `json:"root_file_system_id"`
	RootAccessPointID       string    `json:"root_access_point_id"`
	RootMountPath           string    `json:"root_mount_path"`
	TemporaryVolume         string    `json:"temporary_volume"`
	LogGroup                string    `json:"log_group"`
	LogPrefix               string    `json:"log_prefix"`
	ReadinessTargetGroupARN string    `json:"readiness_target_group_arn"`
	ReadinessPort           int       `json:"readiness_port"`
	OwnerTag                string    `json:"owner_tag"`
	ExclusiveServiceOwner   bool      `json:"exclusive_service_owner"`
}

ECSConfig is a customer-owned Fargate/ALB/EFS contract. It deliberately excludes external deployment controllers and shared desired-state writers. ECS UpdateService has no resource-version precondition: customer IAM must enforce ExclusiveServiceOwner independently of this process's local lock.

type Executor

type Executor struct {
	// contains filtered or unexported fields
}

Executor is single-owner. The enclosing maintenance coordinator must hold its persistent installation lock across Prepare, policy evaluation, Apply and observation. An interrupted applying journal never grants automatic rollback.

func New

func New(c Config) (*Executor, error)

func NewWithDependencies

func NewWithDependencies(c Config, runner Runner, client kubernetes.Interface) (*Executor, error)

NewWithDependencies provides the command and Kubernetes seams used by the same adapter code in production and adversarial tests.

func (*Executor) Apply

func (e *Executor) Apply(ctx context.Context, target Target) error

Apply changes only the locally enrolled workload. It never restores an old image or clears database maintenance. A lost reply requires Observe/recovery.

func (*Executor) FollowCoordinator

func (e *Executor) FollowCoordinator(ctx context.Context, image string) error

FollowCoordinator moves this coordinator's own CronJob to image, the running image the owner observed. It is a workload write, so only an applying run may call it, never Observe, which check, enroll and reconcile also reach. The caller has already authenticated image as the signed inventory of the release it names. Comparing first makes a repeat free.

func (*Executor) IdentityPinned

func (e *Executor) IdentityPinned() (bool, error)

IdentityPinned reports, with no cluster access, whether an identity is recorded.

func (*Executor) NoFinalGate

func (e *Executor) NoFinalGate(ctx context.Context, source Observation) (bool, error)

NoFinalGate proves no gate was crossed unless the control row says the target is healthy at a release other than the source, or belongs to another installation. Only when no row can be read does the rollback marker answer, and only while the journal is still applying: the target was stopped after the gate decision, the one-shot re-checks rule 2 under its lock, and a crash while the database is absent leaves no row. The marker vouches only for that stop: a target running again was started by a person, who may have taken it through the gate. Compose reads the row through a one-off container, which runs while the service is restarting and cannot be exec'd into. Kubernetes reads it through a stage Pod on the node the source ran on.

func (*Executor) Observe

func (e *Executor) Observe(ctx context.Context) (Observation, error)

func (*Executor) PinIdentity

func (e *Executor) PinIdentity(ctx context.Context) error

PinIdentity records the live Deployment's UID at explicit enrollment, so a replaced Deployment is refused afterwards. Repeating it for the same Deployment changes nothing; a different one is never adopted silently.

func (*Executor) Prepare

func (e *Executor) Prepare(ctx context.Context, target Target) (Observation, error)

Prepare stages the complete target route while the enrolled source still serves. It returns the authenticated local route impact for policy evaluation.

func (*Executor) PublishStatus

func (e *Executor) PublishStatus(ctx context.Context, status []byte) error

PublishStatus copies the coordinator's public status into the ConfigMap the serving Pod mounts, since the coordinator's volume is not visible to it. The caller treats a failure as non-fatal; the ConfigMap is created by the chart, so the coordinator's Role needs only get and update on that one name.

func (*Executor) Reconcile

func (e *Executor) Reconcile(_ context.Context, observed Observation) error

Reconcile releases a recovery pin once the coordinator has established that the installation is healthy and the pin no longer describes live work: the source after a failed stop or refused update, or a restored installation. A fresh Prepare is then required. An unhealthy observation keeps the pin; an unpinned journal has nothing to clear. If a rollback marker was set it reports ErrFollowsRollback once the pin is released, and leaves the journal at "rolled-back" so that a coordinator dying before it records that is told again; the next Prepare replaces it. Compose publishes desired state only after target health, so no file needs restoring.

func (*Executor) RestoreSource

func (e *Executor) RestoreSource(ctx context.Context, aborted Observation) error

RestoreSource puts the enrolled source image back after its target reported that it failed before the live database was written. The source starts again from the prepared snapshot, never from anything the target controls, and refuses on its own if the database was written after all. Compose and Kubernetes have this path; ECS reports ErrUnsupported and keeps the replacement pinned.

func (*Executor) RollBack

func (e *Executor) RollBack(ctx context.Context) (restored bool, err error)

RollBack is the owner's answer to a target that wrote nothing it should keep or never reported: stop the target with proof, restore the fenced snapshot in a one-shot of the target's own image, and write the source back. The source image stays the authority, so a failed one-shot still writes it back. ECS stays pinned. restored is whether the one-shot restored the snapshot, as opposed to finding the source untouched. The marker is durable once the target is proven stopped and before the one-shot.

type Kind

type Kind string
const (
	Compose    Kind = "compose"
	Kubernetes Kind = "kubernetes"
	ECS        Kind = "ecs"
)

type KubernetesConfig

type KubernetesConfig struct {
	Kubeconfig string `json:"kubeconfig,omitempty"`
	Context    string `json:"context,omitempty"`
	Namespace  string `json:"namespace"`
	Deployment string `json:"deployment"`
	// DeploymentUID may be empty: explicit enrollment then pins the live Deployment's
	// UID in private state, because a chart user cannot know it before installing.
	DeploymentUID string `json:"deployment_uid,omitempty"`
	Container     string `json:"container"`
	StagePod      string `json:"stage_pod"`
	Binary        string `json:"binary"`
	// CronJob, when set, is this coordinator's own CronJob; its image follows the
	// proven server image. StatusConfigMap, when set, receives the public status;
	// in-cluster only, because only the chart mounts it into the server.
	CronJob         string `json:"cron_job,omitempty"`
	StatusConfigMap string `json:"status_config_map,omitempty"`
	// VolumeRoot is the mounted volume that holds the coordinator state. Kubelet
	// applies fsGroup to a volume root, making it group-writable, which would
	// otherwise fail the ancestor check. In-cluster only.
	VolumeRoot string `json:"volume_root,omitempty"`
	// AcceptWorldWritableVolumeRoot accepts a 0777 VolumeRoot (local-path), where another user could replace the state.
	AcceptWorldWritableVolumeRoot bool `json:"accept_world_writable_volume_root,omitempty"`
}

KubernetesConfig selects the cluster by kubeconfig and context, or, with both empty, by the pod's own service account when the coordinator runs in the cluster.

type Observation

type Observation struct {
	Platform            string                   `json:"platform"`
	Engine              releaseidentity.Engine   `json:"engine"`
	Identity            releaseidentity.Identity `json:"identity"`
	StagedTarget        releaseidentity.Identity `json:"staged_target,omitzero"`
	Image               string                   `json:"image"`
	RuntimeImageSHA256  string                   `json:"runtime_image_sha256,omitempty"`
	Instance            string                   `json:"instance"`
	Generation          int64                    `json:"generation"`
	RestoreEpoch        int64                    `json:"restore_epoch"`
	Incarnation         string                   `json:"incarnation"`
	RouteSHA256         releaseidentity.Digest   `json:"route_sha256,omitempty"`
	RequiresMaintenance bool                     `json:"requires_maintenance"`
	SchemaChanges       bool                     `json:"schema_changes"`
	Phase               string                   `json:"phase"`
	Maintenance         bool                     `json:"maintenance"`
	Ready               bool                     `json:"ready"`
	// AbortedBeforeMutation is reported by the target image after its own
	// preparation failed before the live database was written. The other fields
	// then describe the untouched source release.
	AbortedBeforeMutation bool `json:"aborted_before_mutation,omitempty"`
}

Observation is local operator evidence, never a project heartbeat. Identity ALWAYS names the actual applied database release, including during staging.

func (Observation) PastFinalGate

func (o Observation) PastFinalGate(source releaseidentity.Identity) bool

PastFinalGate is whether this row shows a target that may have served: healthy at a release other than source, ready or not. From there a stop is a person's decision.

type RollbackReport

type RollbackReport struct {
	Format string `json:"format"`
	Result string `json:"result"`
	Reason string `json:"reason"`
}

RollbackReport is the one line the target's one-shot prints. It is the only thing that authorizes writing the source back while the target is gone.

type Runner

type Runner interface {
	Run(context.Context, Command) ([]byte, error)
}

type Target

type Target struct {
	BeforeMutation func() error             `json:"-"`
	Identity       releaseidentity.Identity `json:"identity"`
	Image          string                   `json:"image"`
	// A multiarchitecture index requires an independently verified platform
	// manifest digest. Omit only when Image itself names the platform manifest.
	RuntimeImageSHA256 string `json:"runtime_image_sha256,omitempty"`
	// EligibilityUntil is local authorization context supplied from freshly
	// authenticated metadata, never an image selector or a migration timeout.
	// Prepare permits zero; Apply requires it before starting replacement.
	EligibilityUntil time.Time `json:"eligibility_until,omitzero"`
}

Target is already independently release-verified by the caller. This package checks exact platform replacement and does not substitute for release trust.

Jump to

Keyboard shortcuts

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