service

package
v1.10.4 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 53 Imported by: 0

Documentation

Overview

Package service manages the host service boundary for sandbox recovery.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthorizeAt

func AuthorizeAt(ctx context.Context, path string, claim WorkerClaim) error

AuthorizeAt checks the private endpoint and root daemon before sending a claim. Success is a point-in-time decision, not a lease or completion proof. Use a verified launch credential, keep the socket outside guest mounts and call again after staging immediately before guest execution. ErrPending means the verified worker still has an outstanding service job. No retry occurs.

func PutArtifactAt

func PutArtifactAt(ctx context.Context, path string, claim WorkerClaim, a evidence.Artifact) (evidence.Ref, error)

PutArtifactAt sends one bounded artifact. Success acknowledges the stored reference only; readback and capture confirmation remain separate operations.

func ReadEvidenceAt

func ReadEvidenceAt(ctx context.Context, path string, claim WorkerClaim, ref evidence.Ref, artifact bool, destination io.Writer) error

ReadEvidenceAt copies a bounded input or output readback through the private daemon. Bytes remain provisional until a bound final receipt and EOF arrive. The caller must unblock destination writes on cancellation. No retry occurs.

func ReadImageAt

func ReadImageAt(ctx context.Context, path string, claim WorkerClaim, pin string, maximum int64, destination io.Writer) error

ReadImageAt copies one pinned image blob through the private daemon. Its completion receipt binds the request, worker claim, digest and observed size. Destination writes must unblock on cancellation. No retry occurs.

func RunInstalledDaemon

func RunInstalledDaemon(ctx context.Context, name string, verify QualificationVerifier) error

RunInstalledDaemon owns one configured Linux broker lifetime. It loads pinned credentials and current policies, opens storage and systemd, recovers worker state, checks live qualification, then opens the bounded public mTLS listener. It joins the daemon before closing owned services. A verifier is mandatory; configuration has no way to manufacture qualification or bypass its checks. Directory/policy provisioning and the trusted live verifier remain host duties.

func RunQualificationAuthority

func RunQualificationAuthority(ctx context.Context, name string) error

RunQualificationAuthority serves protected retained evidence on a Linux root host. Cancellation closes connections and joins handlers. It never runs probes.

Types

type BrokerConfig

type BrokerConfig struct {
	SchemaVersion  int                   `json:"schema_version"`
	WorkerConfig   string                `json:"worker_config"`
	Credentials    DaemonCredentialFiles `json:"credentials"`
	HostPolicy     string                `json:"host_policy"`
	EvidencePolicy string                `json:"evidence_policy"`
	Listen         string                `json:"listen"`
	Storage        BrokerStorage         `json:"storage"`
	Images         []string              `json:"images"`
	ImageRoot      string                `json:"image_root"`
	ImageLimits    image.LocalLimits     `json:"image_limits"`
	InputRoot      string                `json:"input_root"`
	InputReaders   int                   `json:"input_readers"`
	EvidenceBytes  int64                 `json:"evidence_bytes"`
	MaxJobs        int                   `json:"max_jobs"`
	MaxActive      int                   `json:"max_active"`
	CleanupActor   string                `json:"cleanup_actor"`
	PublicLimits   broker.ServerLimits   `json:"public_limits"`
	Control        ControlLimits         `json:"control"`
	Interval       time.Duration         `json:"interval_ns"`
	PageSize       int                   `json:"page_size"`
	DiscoveryLimit int                   `json:"discovery_limit"`
}

BrokerConfig is protected canonical JSON for one installed daemon lifetime. Limits are explicit. This document contains credential pins, never private key bytes or a qualification override. Host/evidence policy files remain current on each request; changing other settings requires a new daemon lifetime.

type BrokerConfiguration

type BrokerConfiguration struct {
	Settings BrokerConfig
	Worker   WorkerConfiguration
	SHA256   string
}

BrokerConfiguration binds startup settings to exact bytes and a verified worker installation. It proves no runtime qualification or source permission.

func ReadBrokerConfig

func ReadBrokerConfig(ctx context.Context, name string) (BrokerConfiguration, error)

ReadBrokerConfig loads a root-owned mode-0600 file of at most one MiB and verifies its worker installation. It opens no journals, service connections or listeners and does not read credential material. Startup must still load the pinned credentials, current policies and providers and require qualification.

type BrokerStorage

type BrokerStorage struct {
	BrokerJournal string `json:"broker_journal"`
	WorkerJournal string `json:"worker_journal"`
	Evidence      string `json:"evidence"`
}

BrokerStorage assigns distinct files directly inside the worker state directory. SQLite sidecar names and the evidence ownership file are reserved too.

type CaptureGrant

type CaptureGrant struct {
	MaxBytes     int64         `json:"max_bytes"`
	MaxRetention time.Duration `json:"max_retention_ns"`
}

CaptureGrant caps each declared output at one MiB and retention at one day. It grants neither publication nor access to undeclared artifacts.

type CapturePolicy

type CapturePolicy func(context.Context, sandbox.Job, evidence.Action, evidence.Ref) error

CapturePolicy authorizes a declared artifact for the signed job subject. Callbacks receive detached values and must honor cancellation.

type CaptureRecovery

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

CaptureRecovery reconciles terminal captures without re-executing work or manufacturing successful results. Live jobs and unexpired reported evidence are retained. Abandoned or expired captures require durable deletion proof.

func NewCaptureRecovery

func NewCaptureRecovery(cfg CaptureRecoveryConfig) (*CaptureRecovery, error)

NewCaptureRecovery requires explicit cleanup authority and bounded pages.

func (*CaptureRecovery) Recover

Recover visits the full index, including terminal jobs, with bounded memory. It retains the first failure and continues to later pages while time remains.

func (*CaptureRecovery) Sweep

Sweep rechecks terminal state before contacting the repository. Execution expiry alone never proves whole-service cleanup or authorizes deletion.

type CaptureRecoveryConfig

type CaptureRecoveryConfig struct {
	Store      *workerstore.Store
	Repository evidence.Repository
	Audit      evidence.TombstoneReader
	Authorize  func(context.Context, sandbox.Job, evidence.Ref) error
	Actor      string
	PageSize   int
	Now        func() time.Time
}

CaptureRecoveryConfig supplies independent cleanup authority. Authorize must permit deletion and tombstone audit for Actor under the signed job's subject. It must not depend on the original execution grant remaining valid. Repository deletion must fence delayed uploads, including identities with no stored bytes. Every callback must honor its context. Audit is trusted repository metadata.

type CaptureRecoveryPage

type CaptureRecoveryPage struct {
	CaptureRecoveryReport
	Next string
	Done bool
}

CaptureRecoveryPage advances past individual failures. Start a new pass with an empty cursor after Done to revisit unresolved or retained artifacts.

type CaptureRecoveryReport

type CaptureRecoveryReport struct{ Examined, Deferred, Retained, Discarded, Unresolved int }

CaptureRecoveryReport counts observations, not unique lifetime events. Examined, Deferred and Unresolved count jobs; other fields count artifacts.

type CleanupPage

type CleanupPage struct {
	CleanupReport
	Next string
	Done bool
}

CleanupPage advances by canonical job ID. Restart with an empty cursor after Done to discover entries inserted before the cursor during the previous pass.

type CleanupReport

type CleanupReport struct{ Examined, Managed, Cleaned, Unresolved int }

CleanupReport counts observations, not unique lifetime jobs. Cleaned means service fencing and the selected cleanup operation succeeded, never a result.

type ControlLimits

type ControlLimits struct {
	Connections int
	// Reports permits up to four concurrent report, capture or content
	// exchanges and must be less than Connections. Zero disables those exchanges.
	Reports int
	Timeout time.Duration
}

ControlLimits bounds private worker connections and the entire exchange, including request reads, authorization and response writes. Host grant callbacks must honor their contexts for handler shutdown to remain bounded.

type Controller

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

Controller owns launch admission and recovery for one daemon lifetime. Use Launch through this controller exclusively after constructing it. The host must not call its underlying launcher or scanner concurrently from elsewhere. WorkerControl and Runtime share this lifetime. They do not qualify Linux.

func NewController

func NewController(launcher *Launcher, scanner *RecoveryScanner, interval time.Duration, policies ...CapturePolicy) (*Controller, error)

NewController joins a launcher and scanner that share the exact journal and reaper. The interval is between 10ms and one second; slow cleanup can still delay a scan, so independent worker and service deadline limits are required. An optional capture policy enables artifact persistence; omission denies it. Enabling capture requires recovery bound to the same journal.

func (*Controller) AuthorizeWorker

func (c *Controller) AuthorizeWorker(ctx context.Context, peer *workerpeer.Peer, claim WorkerClaim) (workerstore.Record, error)

AuthorizeWorker verifies a live local peer, effective service configuration, current grants and durable ownership. It issues no new claim and persists no completion. The worker must repeat this check before guest execution after staging; successful authorization does not extend its acceptance deadline. The caller owns peer and must close it when its socket connection ends.

func (*Controller) CaptureWorker

func (c *Controller) CaptureWorker(ctx context.Context, peer *workerpeer.Peer, claim WorkerClaim, ref evidence.Ref, confirm bool) (WorkerCaptureReceipt, error)

CaptureWorker authenticates a declared capture and commits its intent or readback confirmation. A confirmation records worker testimony, not grading.

func (*Controller) Launch

func (c *Controller) Launch(ctx context.Context, receipt sandbox.Receipt) error

Launch requires a recovered, running controller and binds the submission to both its caller and daemon lifetime. A stopped or unready controller returns ErrPending without enrolling or starting the receipt.

func (*Controller) ProposeWorkerResult

func (c *Controller) ProposeWorkerResult(ctx context.Context, peer *workerpeer.Peer, claim WorkerClaim, result sandbox.Result) (WorkerReportReceipt, error)

ProposeWorkerResult authenticates a worker report and retains it for cleanup. The controller's scanner independently finalizes or discards the report.

func (*Controller) Run

func (c *Controller) Run(ctx context.Context) (err error)

Run recovers every old acceptance before admitting launches, then scans on a bounded timer. Any scan error closes admission and stops the controller. A stopped controller cannot be restarted; resolve its error and create another. Cancellation closes admission, cancels and joins in-flight operations, then recovers outstanding claims with an independent 30-second cleanup context. Host callbacks must honor their contexts for shutdown to remain bounded.

func (*Controller) Status

func (c *Controller) Status() ControllerStatus

Status reports readiness without granting admission; Launch checks it again.

type ControllerStatus

type ControllerStatus struct {
	Running, Ready bool
	Err            error
}

ControllerStatus is a detached lifecycle snapshot. Err reports a recovery or shutdown error to the trusted daemon; it is not a public job-result endpoint.

type Credential

type Credential struct {
	SchemaVersion int                `json:"schema_version"`
	ProfileDigest string             `json:"profile_digest"`
	Record        workerstore.Record `json:"record"`
	Token         string             `json:"token"`
}

Credential is a private worker capability. Never log its body or token, copy it into guest mounts, or use it to authorize a second service start. The worker must confirm current journal ownership through authenticated daemon control.

func ReadCredential

func ReadCredential(ctx context.Context, directory string, key id.ID, profileDigest, brokerName string, publicKey ed25519.PublicKey) (Credential, error)

ReadCredential verifies the systemd credential copy in the exact worker subgroup. This verifies its signed acceptance and deployment binding, not current journal ownership or fresh user authorization. Those checks remain mandatory immediately before guest execution.

type CredentialScanner

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

CredentialScanner removes detached launch credentials after service fencing. Its gate also guards the controller's credential publisher, preventing a late writer from recreating a file after cleanup has returned.

func NewCredentialScanner

func NewCredentialScanner(cfg OrphanConfig, root string) (*CredentialScanner, error)

NewCredentialScanner pins the installed launch directory and shares the existing journal eligibility and bounded paging rules with other cleanup.

func (CredentialScanner) Recover

func (s CredentialScanner) Recover(ctx context.Context) (CleanupReport, error)

Recover visits a complete bounded discovery pass before admission or after shutdown. It preserves the first failure while attempting remaining pages.

func (CredentialScanner) Sweep

func (s CredentialScanner) Sweep(ctx context.Context, after string) (CleanupPage, error)

Sweep processes one page from a fresh discovery snapshot. Known nonterminal jobs remain with normal execution recovery. Each page has a 30-second budget.

type Daemon

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

Daemon owns one broker lifetime, private socket and child-service join. The host retains ownership of the prepared worker journal, reaper and providers; close them only after Run returns. Construction does not qualify the worker.

func AssembleDaemon

func AssembleDaemon(ctx context.Context, cfg HostConfig) (*Daemon, error)

AssembleDaemon binds one verified installation to launch, recovery, content and private transport. It neither starts services nor invokes qualification. Public TLS serving is supplied to Run. Production requires root on Linux.

func NewDaemon

func NewDaemon(cfg DaemonConfig) (*Daemon, error)

NewDaemon binds public admission to successful worker recovery and private transport startup. The reconciliation interval is between 10ms and one second.

func (*Daemon) Run

func (d *Daemon) Run(ctx context.Context, serve PublicServer) (err error)

Run acquires the broker journal and private endpoint, recovers workers, starts private control, reconciles broker state, then admits the public server. Any child exit or reconciliation error cancels and joins every child. Socket and broker ownership are released only after that join; cleanup errors survive. A daemon is single-use. The host must restart with newly prepared services.

type DaemonConfig

type DaemonConfig struct {
	Controller *Controller
	Control    *WorkerControl
	Broker     broker.Config
	Attest     DeploymentAttestation
	Socket     string
	Interval   time.Duration
}

DaemonConfig joins prepared worker services with a broker journal. Controller and Control must be unused and share one journal. Broker.Runtime must be nil; the daemon supplies the runtime adapter. Host configuration owns signing keys, current authorization, providers, qualification evidence and private paths.

type DaemonCredentialFiles

type DaemonCredentialFiles struct {
	SigningKey  hostfs.Pin `json:"signing_key"`
	Certificate hostfs.Pin `json:"certificate"`
	TLSKey      hostfs.Pin `json:"tls_key"`
	ClientCAs   hostfs.Pin `json:"client_cas"`
}

DaemonCredentialFiles pins PEM files from protected daemon configuration. All four files must have mode 0600 and one link. Private keys use unencrypted PKCS8 PRIVATE KEY blocks; certificates use CERTIFICATE blocks. These pins and private material must never be included in worker configuration or credentials.

type DaemonCredentials

type DaemonCredentials struct {
	SigningKey ed25519.PrivateKey
	Server     *broker.Server
}

DaemonCredentials binds a receipt-signing identity to an installed public server. The caller owns SigningKey. Server copies its TLS credentials and requires verified client certificates followed by current host authentication.

func ReadDaemonCredentials

func ReadDaemonCredentials(ctx context.Context, files DaemonCredentialFiles, expected ed25519.PublicKey, authenticate broker.Authenticator, limits broker.ServerLimits) (*DaemonCredentials, error)

ReadDaemonCredentials loads root-owned pinned credentials and constructs a bounded mTLS server without opening a listener. expected must come from the verified worker configuration. Identity mapping and current grants still belong to authenticate and the broker authorizer. Rotations require a new lifetime.

type DeploymentAttestation

type DeploymentAttestation func(context.Context) (sandbox.Capabilities, error)

DeploymentAttestation checks the installed deployment against host-owned live qualification evidence. It must verify the current worker, configuration and runtime pins, honor cancellation, and never qualify a deployment from fixtures. Missing qualification may be returned as unqualified capabilities; Start then refuses execution. This callback is trusted host code, not worker input.

func NewDeploymentAttestation

func NewDeploymentAttestation(ctx context.Context, name string, verify QualificationVerifier) (DeploymentAttestation, error)

NewDeploymentAttestation pins the installed Linux configuration for one host lifetime. Each observation verifies installation before and after consulting current qualification evidence. Construction does not invoke the verifier or qualify a worker. Installation changes require new assembly and qualification.

type DeploymentIdentity

type DeploymentIdentity struct {
	Broker        string
	ProfileDigest string
	RuntimeDigest string
}

DeploymentIdentity binds qualification to one installed worker configuration. ProfileDigest includes the exact configuration bytes, worker pin, service template and outer limits. RuntimeDigest covers the complete runtime inventory.

type DeploymentQualification

type DeploymentQualification struct {
	Deployment   DeploymentIdentity
	Capabilities sandbox.Capabilities
}

DeploymentQualification is a trusted host verifier's observation, not a worker assertion. Both its deployment identity and capabilities must match.

type EvidenceCleanupGrant

type EvidenceCleanupGrant struct {
	Principal string       `json:"principal"`
	Scope     cortex.Scope `json:"scope"`
	Actor     string       `json:"actor"`
	NotBefore time.Time    `json:"not_before"`
	NotAfter  time.Time    `json:"not_after"`
}

EvidenceCleanupGrant permits deletion and tombstone audit by Actor for a signed job's original principal and exact scope. It remains independent of subject execution, input and capture grants. Recovery checks terminal state.

type EvidencePolicy

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

EvidencePolicy rereads installed grants on each operation. It retains no authorization snapshot. Missing, malformed or expired documents deny access.

func NewEvidencePolicy

func NewEvidencePolicy(ctx context.Context, name string) (*EvidencePolicy, error)

NewEvidencePolicy requires a root-owned, single-link mode-0600 canonical JSON file of at most one MiB. Keep its parent protected; publish updates by atomic replacement. File reads require responsive local storage. Construction checks the initial policy but grants no execution or publication authority.

func (*EvidencePolicy) AuthorizeCapture

func (p *EvidencePolicy) AuthorizeCapture(ctx context.Context, job sandbox.Job, action evidence.Action, ref evidence.Ref) error

AuthorizeCapture permits put/read for declared outputs under current byte and retention ceilings. Use it for controller capture and repository policies.

func (*EvidencePolicy) AuthorizeCleanup

func (p *EvidencePolicy) AuthorizeCleanup(ctx context.Context, job sandbox.Job, ref evidence.Ref) error

AuthorizeCleanup permits only the configured cleanup actor and declared job outputs, including expired evidence or jobs whose subject grant was revoked. It is suitable for CaptureRecovery.Authorize and EvidenceRepository.Cleanup.

func (*EvidencePolicy) AuthorizeInput

func (p *EvidencePolicy) AuthorizeInput(ctx context.Context, job sandbox.Job, action evidence.Action, ref evidence.Ref) error

AuthorizeInput permits reads of exact signed input bindings under a current subject grant. Use it for both WorkerEvidence and EvidenceRepository inputs.

type EvidencePolicyDocument

type EvidencePolicyDocument struct {
	SchemaVersion int                    `json:"schema_version"`
	NotBefore     time.Time              `json:"not_before"`
	NotAfter      time.Time              `json:"not_after"`
	Subjects      []EvidenceSubjectGrant `json:"subjects"`
	Cleanup       []EvidenceCleanupGrant `json:"cleanup"`
}

EvidencePolicyDocument is canonical JSON in a protected host file. Subject access and cleanup are separate grants, each bounded by the document lifetime. Each list permits at most 512 entries. Empty lists revoke their access.

type EvidenceRepository

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

EvidenceRepository requires the service's validated job context in addition to exact scope and current host policy. WorkerEvidence still owns live worker, claim and capture-intent checks. This adapter cannot authorize execution.

func NewEvidenceRepository

func NewEvidenceRepository(cfg EvidenceRepositoryConfig) (*EvidenceRepository, error)

NewEvidenceRepository wraps existing storage without opening a database or granting ambient callers access. Its storage dependency must fence late uploads.

func (*EvidenceRepository) AuthorizeEvidence

func (r *EvidenceRepository) AuthorizeEvidence(ctx context.Context, action evidence.Action, ref evidence.Ref) error

AuthorizeEvidence validates service authority before invoking host policy. Callback arguments are detached from the context's original signed job.

func (*EvidenceRepository) Delete

func (r *EvidenceRepository) Delete(ctx context.Context, ref evidence.Ref, reason string) error

Delete accepts only the independent cleanup context for a declared capture.

func (*EvidenceRepository) GetEvidenceTombstone

func (r *EvidenceRepository) GetEvidenceTombstone(ctx context.Context, ref evidence.Ref) (evidence.Tombstone, error)

GetEvidenceTombstone checks cleanup authority before and after reading raw audit metadata. It returns no proof when binding or authorization fails.

func (*EvidenceRepository) Open

Open reads a declared input or capture after current policy checks.

func (*EvidenceRepository) Put

Put stores a declared capture through the bounded immutable repository.

type EvidenceRepositoryConfig

type EvidenceRepositoryConfig struct {
	Storage  evidence.Storage
	Audit    evidence.TombstoneReader
	Inputs   CapturePolicy
	Captures CapturePolicy
	Cleanup  func(context.Context, sandbox.Job, evidence.Ref) error
	MaxBytes int64
}

EvidenceRepositoryConfig reuses host storage with independent current input, capture and cleanup policies. Cleanup authorizes deletion and tombstone audit for the context's cleanup actor under the job's original subject. It must work after execution authority expires. Nil Captures disables output reads/writes. Storage and Audit must refer to the same durable repository. Callbacks must honor cancellation; MaxBytes must also fit the backend's storage ceiling.

type EvidenceSubjectGrant

type EvidenceSubjectGrant struct {
	Principal     string        `json:"principal"`
	Scope         cortex.Scope  `json:"scope"`
	NotBefore     time.Time     `json:"not_before"`
	NotAfter      time.Time     `json:"not_after"`
	InputBindings []string      `json:"input_bindings"`
	Captures      *CaptureGrant `json:"captures,omitempty"`
}

EvidenceSubjectGrant permits exact input bindings and bounded captures for one principal and scope. InputBindings holds up to 256 Ref.BindingDigest values, including provenance and retention. Nil Captures disables captures.

type HostConfig

type HostConfig struct {
	WorkerConfig    string
	Store           *workerstore.Store
	Reaper          *Reaper
	Broker          broker.Config
	Qualification   QualificationVerifier
	AuthorizeLaunch func(context.Context, sandbox.Job) error
	Revalidate      func(context.Context, sandbox.Job) error
	Inputs          staging.Source
	InputPolicy     CapturePolicy
	Images          image.Source
	ImagePolicy     ImagePolicy
	// Captures is required even when new capture is disabled, so old evidence
	// remains recoverable. Its Store is filled by assembly or must match Store.
	Captures CaptureRecoveryConfig
	// CapturePolicy must be present exactly when installed retention is nonzero.
	CapturePolicy  CapturePolicy
	Control        ControlLimits
	Interval       time.Duration
	PageSize       int
	DiscoveryLimit int
}

HostConfig supplies installed daemon services. Store, Reaper and content providers remain caller-owned and must stay open until Daemon.Run returns. AuthorizeLaunch checks the authenticated caller's current execution grants; Revalidate checks the signed job subject independently of that caller's connection. Broker.Authorize separately governs every public operation. All callbacks must honor cancellation and support concurrent calls.

type HostPolicy

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

HostPolicy rereads a bounded file on every check. Unreadable, invalid or expired policy denies access; no previous grant snapshot is retained.

func NewHostPolicy

func NewHostPolicy(ctx context.Context, name string) (*HostPolicy, error)

NewHostPolicy requires a root-owned, single-link mode-0600 policy file. Keep its parent protected and publish updates by atomic replacement. Reads require responsive local storage, as kernel file calls cannot be interrupted forcibly by context cancellation. Construction validates the initial policy.

func (*HostPolicy) Authenticate

func (p *HostPolicy) Authenticate(request *http.Request) (broker.Identity, error)

Authenticate accepts only a completed TLS 1.3 connection with a verified, currently valid client chain and an explicit leaf fingerprint mapping. Subject names, request headers and payload fields cannot select another scope.

func (*HostPolicy) Authorize

func (p *HostPolicy) Authorize(ctx context.Context, who broker.Identity, job sandbox.Job) error

Authorize binds a public operation's authenticated identity to its sealed job and current execution grant. Use it as the broker's Authorize callback.

func (*HostPolicy) AuthorizeImage

func (p *HostPolicy) AuthorizeImage(ctx context.Context, job sandbox.Job, pin string) error

AuthorizeImage checks the job's current manifest access. WorkerImages still validates membership and hashes for individual config and layer blobs.

func (*HostPolicy) Revalidate

func (p *HostPolicy) Revalidate(ctx context.Context, job sandbox.Job) error

Revalidate checks the signed job subject without a live client connection. Use it for AuthorizeLaunch and Revalidate in HostConfig. The controller remains responsible for receipt verification, runtime qualification and worker fencing.

type HostPolicyDocument

type HostPolicyDocument struct {
	SchemaVersion int                `json:"schema_version"`
	NotBefore     time.Time          `json:"not_before"`
	NotAfter      time.Time          `json:"not_after"`
	Subjects      []HostSubjectGrant `json:"subjects"`
}

HostPolicyDocument is canonical JSON in a protected, replaceable host file. A document has at most 512 exact subjects and a finite validity interval. Empty Subjects revokes all access. Atomic replacement publishes an update.

type HostSubjectGrant

type HostSubjectGrant struct {
	Principal    string         `json:"principal"`
	Scope        cortex.Scope   `json:"scope"`
	NotBefore    time.Time      `json:"not_before"`
	NotAfter     time.Time      `json:"not_after"`
	Certificates []string       `json:"certificates"`
	Images       []string       `json:"images"`
	Limits       sandbox.Limits `json:"limits"`
}

HostSubjectGrant separately grants transport and bounded sandbox execution. Certificates contains up to 16 lowercase SHA256 leaf-certificate fingerprints. Empty Certificates revokes transport access while retaining the execution grant for recovery. Remove the subject to revoke execution as well. Images contains 1..256 immutable manifest pins. This grants no evidence access, artifact publication or cleanup authority and does not qualify the runtime.

type ImagePolicy

type ImagePolicy func(context.Context, sandbox.Job, string) error

ImagePolicy checks current source access for the signed job's manifest pin. The job and context scope are detached from retained controller state.

type InputInstallation

type InputInstallation struct {
	SchemaVersion int    `json:"schema_version"`
	JobID         id.ID  `json:"job_id"`
	JobDigest     string `json:"job_digest"`
	BindingDigest string `json:"binding_digest"`
	SHA256        string `json:"sha256"`
	Bytes         int64  `json:"bytes"`
}

InputInstallation identifies a verified installed input without disclosing its content, principal or source URI. It grants no execution or qualification.

func ProvisionInput

func ProvisionInput(ctx context.Context, request InputProvisionRequest) (InputInstallation, error)

ProvisionInput installs one authorized input on a Linux host as root. It opens no database, listener or worker service. Identical retries verify the existing file; conflicts leave it untouched. An error after publication can leave complete bytes installed, so retry the same request to resolve ambiguity.

type InputProvisionRequest

type InputProvisionRequest struct {
	Config string
	Job    string
	Input  string
	File   string
}

InputProvisionRequest selects an exact declared guest input from a protected canonical job file. Config and Job are mode-0600 files; File is the mode-0600 source whose bytes must match that declaration. No path is fetched remotely.

type LaunchProfile

type LaunchProfile struct {
	SchemaVersion                int
	Worker, Config               hostfs.Pin
	TemplatePath, StateDirectory string
	CPUMillis, MemoryBytes       uint64
	Tasks                        uint64
	WallTime                     time.Duration
}

LaunchProfile pins host deployment and outer service ceilings. These limits include worker/runtime overhead and are separate from each guest's limits. WallTime is an outer ceiling, not the receipt's absolute acceptance deadline.

func (LaunchProfile) Digest

func (p LaunchProfile) Digest() (string, error)

Digest binds the approved host paths, file pins and outer service ceilings.

func (LaunchProfile) Template

func (p LaunchProfile) Template() ([]byte, error)

Template renders the one supported installed service template. Paths cannot inject directives, substitutions or shell syntax. Installation is a separate host operation; this function neither writes unit files nor starts workers.

type Launcher

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

Launcher consumes durable ownership before publishing a credential and issuing one StartUnit call. A retry never reconstructs a lost claim token. The owning daemon must recover outstanding claims on startup and monitor accepted deadlines independently of request contexts.

func NewLauncher

func NewLauncher(store *workerstore.Store, reaper *Reaper, profile LaunchProfile, authorize func(context.Context, sandbox.Job) error) (*Launcher, error)

NewLauncher requires current host authorization. The callback must bind the authenticated host caller to the exact job scope/principal and current grants. This internal component does not expose an unauthenticated submission API.

func (*Launcher) Launch

func (l *Launcher) Launch(ctx context.Context, receipt sandbox.Receipt) error

Launch acknowledges an already claimed or completed receipt without another start attempt. Reaping work remains pending. Failures after claim acquisition trigger independent bounded recovery and preserve both errors when it fails.

type LocalInputs

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

LocalInputs serves root-owned input files named by the full Ref.BindingDigest. Bytes are verified against the job's exact reference and current source policy. This read-only source cannot upload captures or erase evidence tombstones.

func NewLocalInputs

func NewLocalInputs(root string, maximum int64, readers int, policy CapturePolicy) (*LocalInputs, error)

NewLocalInputs requires a private mode-0700 directory and a current input policy. Files are mode-0400 single-link regular files. maximum is at most one MiB and readers is 1..16; each open reader retains a slot until Close. Provision exact reference bindings through the trusted host before submission. Use a responsive local filesystem and prevent directory/file changes during Open.

func (*LocalInputs) Open

func (s *LocalInputs) Open(ctx context.Context, ref evidence.Ref) (io.ReadCloser, error)

Open permits only a declared input in the service's private validated job context. It checks current policy before and after file access and returns no reader on failure. WorkerEvidence additionally rechecks live worker authority and source grants around the complete transfer before acknowledging its bytes.

type OrphanConfig

type OrphanConfig struct {
	Store              *workerstore.Store
	Reaper             *Reaper
	MaxUnits, PageSize int
}

OrphanConfig binds bounded independent discovery to one worker journal. The host must reserve the complete discovered namespace for this journal.

type OrphanScanner

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

OrphanScanner fences services absent from the journal or already terminal. It never creates claims, reconstructs receipts, or changes recorded results. Journal read errors still trigger cleanup and remain unresolved afterward.

func NewOrphanScanner

func NewOrphanScanner(cfg OrphanConfig) (*OrphanScanner, error)

NewOrphanScanner requires independent enumeration and explicit size bounds.

func (OrphanScanner) Recover

func (s OrphanScanner) Recover(ctx context.Context) (CleanupReport, error)

Recover visits a complete bounded discovery pass before admission or after shutdown. It preserves the first failure while attempting remaining pages.

func (OrphanScanner) Sweep

func (s OrphanScanner) Sweep(ctx context.Context, after string) (CleanupPage, error)

Sweep processes one page from a fresh discovery snapshot. Known nonterminal jobs remain with normal execution recovery. Each page has a 30-second budget.

type PublicServer

type PublicServer func(context.Context, *broker.Broker) error

PublicServer serves the authenticated broker until cancellation, then closes its listener and joins every request before returning. Configure TLS, transport deadlines and authentication through Broker.Handler. Never retain the broker beyond this call. All host callbacks must honor cancellation.

type QualificationAuthority

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

QualificationAuthority verifies retained evidence on every challenge. It has no success cache, probe execution route, or way to mint a producer signature.

func (*QualificationAuthority) ServeHTTP

ServeHTTP accepts only canonical challenges from verified TLS client certificates. Errors disclose neither retained paths nor evidence contents.

type QualificationAuthorityConfig

type QualificationAuthorityConfig struct {
	SchemaVersion  int           `json:"schema_version"`
	Source         string        `json:"source"`
	Policy         string        `json:"policy"`
	MaxEvidenceAge time.Duration `json:"max_evidence_age_ns"`
	DecisionTTL    time.Duration `json:"decision_ttl_ns"`
	Timeout        time.Duration `json:"timeout_ns"`
	Readers        int           `json:"readers"`
}

QualificationAuthorityConfig bounds one authority lifetime. Policy is reread on every request; changing the other settings requires restarting the service.

type QualificationAuthorityGrant

type QualificationAuthorityGrant struct {
	ClientSHA256 string             `json:"client_sha256"`
	Host         QualificationHost  `json:"host"`
	Deployment   DeploymentIdentity `json:"deployment"`
	ProducerKey  []byte             `json:"producer_key"`
	Record       hostfs.Pin         `json:"record"`
}

QualificationAuthorityGrant authorizes one client certificate digest for an exact host, deployment and retained record signed by an approved producer.

type QualificationAuthorityPolicy

type QualificationAuthorityPolicy struct {
	SchemaVersion int                           `json:"schema_version"`
	Source        string                        `json:"source"`
	ValidUntil    time.Time                     `json:"valid_until"`
	Grants        []QualificationAuthorityGrant `json:"grants"`
}

QualificationAuthorityPolicy is protected current authorization. Removing a grant or producer key revokes it. ValidUntil bounds even an unchanged policy.

type QualificationAuthorityServerConfig

type QualificationAuthorityServerConfig struct {
	SchemaVersion int                          `json:"schema_version"`
	Authority     QualificationAuthorityConfig `json:"authority"`
	Listen        string                       `json:"listen"`
	Certificate   hostfs.Pin                   `json:"certificate"`
	TLSKey        hostfs.Pin                   `json:"tls_key"`
	ClientCAs     hostfs.Pin                   `json:"client_cas"`
	Limits        broker.ServerLimits          `json:"limits"`
}

QualificationAuthorityServerConfig pins the authority's listener and mTLS material. Policy changes take effect online; changing this file requires restart.

type QualificationClient

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

QualificationClient consults one pinned authority without caching decisions. Verify supports concurrent callers up to the configured bound. Close releases idle connections after the owning daemon has joined its active operations.

func OpenQualificationClient

func OpenQualificationClient(ctx context.Context, name string) (*QualificationClient, error)

OpenQualificationClient loads protected trust settings on a Linux root host. It makes no network request and cannot qualify an installation by itself.

func (*QualificationClient) Close

func (client *QualificationClient) Close()

Close releases idle authority connections. The owner must first join Verify.

func (*QualificationClient) Verify

Verify returns capabilities only after an authenticated, fresh authority decision and a second local host/trust check. It never falls back to fixtures.

type QualificationClientConfig

type QualificationClientConfig struct {
	SchemaVersion  int           `json:"schema_version"`
	Endpoint       string        `json:"endpoint"`
	Source         string        `json:"source"`
	ServerSPKI     string        `json:"server_spki"`
	Certificate    hostfs.Pin    `json:"certificate"`
	TLSKey         hostfs.Pin    `json:"tls_key"`
	ServerCAs      hostfs.Pin    `json:"server_cas"`
	Timeout        time.Duration `json:"timeout_ns"`
	MaxEvidenceAge time.Duration `json:"max_evidence_age_ns"`
	Readers        int           `json:"readers"`
}

QualificationClientConfig pins a separately provisioned authority and its mTLS credentials. You must install its canonical JSON as root with mode 0600. The authority owns live evidence verification; these settings grant no result.

type QualificationEvidence

type QualificationEvidence struct {
	Kind           string    `json:"kind"`
	Reference      string    `json:"reference"`
	SHA256         string    `json:"sha256"`
	ObservedAt     time.Time `json:"observed_at"`
	ControlsDigest string    `json:"controls_digest"`
	Checks         []string  `json:"checks"`
}

QualificationEvidence references the authority's retained live probe record. Checks names every required passing probe group. ControlsDigest binds the effective controls checked by those probes to the installed profile.

type QualificationHost

type QualificationHost struct {
	MachineID     string `json:"machine_id"`
	BootID        string `json:"boot_id"`
	KernelRelease string `json:"kernel_release"`
	KernelVersion string `json:"kernel_version"`
	Architecture  string `json:"architecture"`
}

QualificationHost identifies the current Linux installation and boot. MachineID is the SHA256 of /etc/machine-id; the kernel fields come from uname.

type QualificationProbe

type QualificationProbe struct {
	Name    string     `json:"name"`
	Package string     `json:"package"`
	Test    string     `json:"test"`
	Output  hostfs.Pin `json:"output"`
}

QualificationProbe binds a required check to retained go test -json output. The trusted producer must execute the named live test against this deployment. stdout text that merely says PASS is not an executable test result.

type QualificationRecord

type QualificationRecord struct {
	SchemaVersion int                     `json:"schema_version"`
	Kind          string                  `json:"kind"`
	Source        string                  `json:"source"`
	Reference     string                  `json:"reference"`
	Host          QualificationHost       `json:"host"`
	Qualification DeploymentQualification `json:"qualification"`
	ObservedAt    time.Time               `json:"observed_at"`
	Probes        []QualificationProbe    `json:"probes"`
	Signature     []byte                  `json:"signature"`
}

QualificationRecord is signed by an independent approved probe producer. Signature covers qualificationRecordDomain plus canonical JSON with a nil Signature. Paths and hashes bind retained output; no request can create it.

type QualificationRequest

type QualificationRequest struct {
	SchemaVersion int                `json:"schema_version"`
	Source        string             `json:"source"`
	Nonce         string             `json:"nonce"`
	Host          QualificationHost  `json:"host"`
	Deployment    DeploymentIdentity `json:"deployment"`
}

QualificationRequest asks the authority to revalidate retained live evidence and current revocation for one deployment. Nonce is fresh for every request.

type QualificationResponse

type QualificationResponse struct {
	SchemaVersion int                     `json:"schema_version"`
	Source        string                  `json:"source"`
	Nonce         string                  `json:"nonce"`
	Host          QualificationHost       `json:"host"`
	Status        string                  `json:"status"`
	CheckedAt     time.Time               `json:"checked_at"`
	ValidUntil    time.Time               `json:"valid_until"`
	Qualification DeploymentQualification `json:"qualification"`
	Evidence      QualificationEvidence   `json:"evidence"`
}

QualificationResponse is an online authority decision. CheckedAt records a fresh evidence and revocation check after receiving Nonce. Only qualified decisions with complete live evidence may contain usable capabilities.

type QualificationVerifier

type QualificationVerifier func(context.Context, DeploymentIdentity) (DeploymentQualification, error)

QualificationVerifier verifies retained live probe evidence for this exact deployment and the current host, kernel and effective isolation controls. It must reject revoked, stale, incomplete or fixture-only evidence and honor cancellation. File digests alone never establish qualification. This callback may run concurrently and must not derive authority from the request's payload.

type Reaper

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

Reaper permanently fences job service identities and stops their whole tree. It never starts or unmasks a service, deletes state, or grants a new claim. The host must reserve these identities and prevent other managers from removing masks or migrating payloads out of their fixed service hierarchy.

func Open

func Open(ctx context.Context) (*Reaper, error)

Open connects directly to the root systemd manager on Linux. ctx bounds connection establishment; Close releases the connection after use.

func (*Reaper) CheckLaunch

func (r *Reaper) CheckLaunch(ctx context.Context, p LaunchProfile, key id.ID) error

CheckLaunch verifies approved host bytes and systemd's effective configuration without granting a claim or starting execution. Recheck immediately before dispatch. Only the host may supply profiles; callers must also authenticate the receipt, enforce current grants and retain one-time launch ownership.

func (*Reaper) CheckWorker

func (r *Reaper) CheckWorker(ctx context.Context, p LaunchProfile, key id.ID, pid uint32) error

CheckWorker verifies that a live peer is the current main worker of the approved service. Obtain pid from a live workerpeer.Peer and check that handle again after this call; a request-supplied PID is not authenticated identity.

func (*Reaper) Close

func (r *Reaper) Close() error

Close releases the connection. In-flight operations fail without cleanup proof.

func (*Reaper) FenceAndStop

func (r *Reaper) FenceAndStop(ctx context.Context, key id.ID) error

FenceAndStop masks the exact instance persistently, reloads the manager, replaces queued starts with a stop job, and kills every cgroup descendant. Success additionally requires no queued job and an inactive or absent service. Use an independent recovery context; the total operation is capped at 30s. A failed attempt retains its mask and can be retried. This is a trusted host operation, not an authorization endpoint or a sandbox qualification claim.

func (*Reaper) Reap

func (r *Reaper) Reap(ctx context.Context, store *workerstore.Store, key id.ID) (workerstore.Record, error)

Reap fences worker completion durably before stopping the service. It commits the terminal failure or cancellation only at the revision that was fenced. Concurrent cancellation, journal failures and uncertain service observations leave work unresolved for retry. Cancel the journal first for a user-requested cancellation; Reap alone records recovery of a lost worker as failed.

func (*Reaper) Workers

func (r *Reaper) Workers(ctx context.Context, maximum int) ([]id.ID, error)

Workers snapshots loaded worker services, including inactive units and units with queued jobs. The trusted manager reply must fit maximum (1..10000); an oversized response fails instead of silently hiding later workers. systemd's method is not paginated, so this bounds accepted rows after D-Bus decoding.

type RecoveryConfig

type RecoveryConfig struct {
	Credentials *CredentialScanner
	Workspaces  *WorkspaceScanner
	Orphans     *OrphanScanner
	Captures    *CaptureRecovery
	Store       *workerstore.Store
	Reaper      *Reaper
	Revalidate  func(context.Context, sandbox.Job) error
	Now         func() time.Time
	PageSize    int
}

RecoveryConfig supplies trusted host services, independent of a user request. Revalidate must check current grants for the signed job scope and principal. Its context carries the verified job scope, not an inherited caller scope. It must honor context cancellation and must not require the original caller to remain connected. A non-nil error stops the job, including provider outages.

type RecoveryPage

type RecoveryPage struct {
	RecoveryReport
	Next string
	Done bool
}

RecoveryPage advances even when an individual entry fails. Continue with Next until Done, then start the next pass with an empty cursor to retry failures. Done means the index page ended; only a nil error establishes a healthy page.

type RecoveryReport

type RecoveryReport struct {
	Credentials                             CleanupReport
	Workspaces                              CleanupReport
	Orphans                                 CleanupReport
	Captures                                CaptureRecoveryReport
	Examined, Cancelled, Reaped, Unresolved int
}

RecoveryReport counts observations in one scan, not unique lifetime events. Unresolved counts entries whose checks or cleanup returned an error.

type RecoveryScanner

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

RecoveryScanner reconciles bounded pages without starting or reclaiming jobs. The daemon must stop admission while Recover runs, keep admission closed on any recovery error, and call Sweep continuously during operation. Sweeps are a recovery fallback, not a substitute for worker and external deadline limits.

func NewRecoveryScanner

func NewRecoveryScanner(cfg RecoveryConfig) (*RecoveryScanner, error)

NewRecoveryScanner requires explicit grant revalidation and a bounded page.

func (*RecoveryScanner) Recover

func (s *RecoveryScanner) Recover(ctx context.Context) (RecoveryReport, error)

Recover reconciles every outstanding acceptance before the daemon admits work. Unclaimed jobs are cancelled. Claims without reports are fenced and reaped as failed unless cancellation was requested. Reports require independent cleanup and current authorization before finalization. One failure does not stop later pages; the report retains counts and the first error without unbounded accumulation.

func (*RecoveryScanner) Sweep

func (s *RecoveryScanner) Sweep(ctx context.Context, after string) (RecoveryPage, error)

Sweep checks one index page using fresh records. It retries reaping, cancels expired or unauthorized work and leaves currently authorized live work alone. Jobs inserted before the cursor are visited on the next complete pass.

type Runtime

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

Runtime connects the trusted broker to a controller's durable worker journal. Only the broker and its supervisor may call it. The broker owns caller scope and grant checks; Inspect and Cancel deliberately permit trusted recovery after grants expire. Never expose these methods directly as transport handlers.

func NewRuntime

func NewRuntime(controller *Controller, attest DeploymentAttestation) (*Runtime, error)

NewRuntime requires a controller and an independent deployment attestation. Construction neither starts the controller nor qualifies the Linux worker.

func (*Runtime) Cancel

func (r *Runtime) Cancel(ctx context.Context, key id.ID) error

Cancel persists intent before stopping containment. An unknown identity is persistently masked and stopped before ErrNotFound permits the broker to mark a never-started acceptance cancelled. Failed cleanup must not report absence.

func (*Runtime) Capabilities

func (r *Runtime) Capabilities(ctx context.Context) (sandbox.Capabilities, error)

Capabilities checks the deployment while enrolled in the controller lifetime.

func (*Runtime) Inspect

func (r *Runtime) Inspect(ctx context.Context, key id.ID) (sandbox.Result, error)

Inspect returns detached terminal output only after independent finalization. A claim or pending cleanup reports running without exposing proposal bytes. An enrolled but unclaimed acceptance remains pending, not started.

func (*Runtime) Start

func (r *Runtime) Start(ctx context.Context, receipt sandbox.Receipt) error

Start rechecks current controls before the launcher verifies and enrolls the signed acceptance. Retries retain the original claim and acceptance deadline.

type WorkerCaptureReceipt

type WorkerCaptureReceipt struct {
	SchemaVersion int                      `json:"schema_version"`
	JobID         id.ID                    `json:"job_id"`
	ClaimRevision uint64                   `json:"claim_revision"`
	ArtifactID    id.ID                    `json:"artifact_id"`
	BindingDigest string                   `json:"binding_digest"`
	State         workerstore.CaptureState `json:"state"`
	Revision      uint64                   `json:"revision"`
}

WorkerCaptureReceipt acknowledges a committed capture binding. It grants no upload, execution, grading or release authority and contains no claim token.

func CaptureAt

func CaptureAt(ctx context.Context, path string, claim WorkerClaim, ref evidence.Ref, confirm bool) (WorkerCaptureReceipt, error)

CaptureAt sends one capture intent or readback confirmation through a verified private endpoint. It authenticates before sending the bounded reference and never retries an uncertain response, including explicit capacity refusal.

type WorkerClaim

type WorkerClaim struct {
	SchemaVersion int    `json:"schema_version"`
	JobID         id.ID  `json:"job_id"`
	Token         string `json:"token"`
	Revision      uint64 `json:"revision"`
	ProfileDigest string `json:"profile_digest"`
}

WorkerClaim carries a private credential reference. Never log its token.

type WorkerConfig

type WorkerConfig struct {
	SchemaVersion    int               `json:"schema_version"`
	Broker           string            `json:"broker"`
	BrokerPublicKey  ed25519.PublicKey `json:"broker_public_key"`
	ControlSocket    string            `json:"control_socket"`
	Service          WorkerService     `json:"service"`
	Runtime          WorkerRuntime     `json:"runtime"`
	Workspace        workspace.Policy  `json:"workspace"`
	ImageStaging     image.Limits      `json:"image_staging"`
	InputStaging     staging.Limits    `json:"input_staging"`
	CaptureRetention time.Duration     `json:"capture_retention_ns,omitempty"`
}

WorkerConfig is installed by the host as canonical JSON with mode 0600. It contains no broker signing key, guest commands or source credentials.

type WorkerConfiguration

type WorkerConfiguration struct {
	Settings      WorkerConfig
	Profile       LaunchProfile
	ProfileDigest string
	RuntimeDigest string
}

WorkerConfiguration binds a parsed configuration to its installed profile. This snapshot proves file identity only, not current execution authority.

func ReadWorkerConfig

func ReadWorkerConfig(ctx context.Context, name string) (WorkerConfiguration, error)

ReadWorkerConfig loads protected configuration and verifies the installed worker, template, private state directory and complete runtime inventory.

type WorkerContent

type WorkerContent struct {
	Evidence *WorkerEvidence
	Images   *WorkerImages
}

WorkerContent binds optional content services to the controller. An omitted configuration leaves both capabilities unavailable on the private endpoint.

type WorkerControl

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

WorkerControl serves authorization, capture, content transfer and report receipt. It cannot launch, cancel or complete jobs. JSON frames are canonical; JSON and binary content chunks have explicit byte bounds.

func NewWorkerControl

func NewWorkerControl(controller *Controller, limits ControlLimits, services ...WorkerContent) (*WorkerControl, error)

NewWorkerControl binds the transport to kernel peer authentication and the controller's current grants, service configuration and durable claim checks. Optional content services must share the same controller. All transfer operations share the Reports capacity limit.

func (*WorkerControl) Serve

func (s *WorkerControl) Serve(ctx context.Context, listener *net.UnixListener) error

Serve takes ownership of a host-created listener in a root-owned 0700 directory, with a root-owned 0600 socket. It never removes or replaces a socket path. The host owns installation and fenced removal. Start after controller recovery; shutdown closes the listener, cancels and joins every exchange. The trusted directory owner must prevent replacement while serving.

func (*WorkerControl) ServeAt

func (s *WorkerControl) ServeAt(ctx context.Context, path string) (err error)

ServeAt creates and owns the private worker socket for this daemon lifetime. The host must precreate its root-owned 0700 directory and prevent owner mutation. A stale socket is reclaimed only with matching durable identity and an explicit kernel connection refusal. Shutdown joins handlers before removing its inode. The persistent lock file must not be removed while any daemon may be running.

type WorkerEvidence

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

WorkerEvidence binds repository access to a live worker and its signed job. Repository credentials stay in the daemon. Output access uses the controller's capture policy and the same repository configured for independent recovery.

func NewWorkerEvidence

func NewWorkerEvidence(c *Controller, inputs staging.Source, policy CapturePolicy, maxInput int64) (*WorkerEvidence, error)

NewWorkerEvidence requires an input provider, current source policy and byte ceiling. Inputs must already be declared in the signed job. Output operations additionally require configured capture recovery and a durable capture intent.

func (*WorkerEvidence) PutArtifact

func (s *WorkerEvidence) PutArtifact(ctx context.Context, peer *workerpeer.Peer, claim WorkerClaim, a evidence.Artifact) (evidence.Ref, error)

PutArtifact performs one immutable repository upload after durable intent. No repository error is retried. A lost acknowledgement requires recovery.

func (*WorkerEvidence) ReadArtifact

func (s *WorkerEvidence) ReadArtifact(ctx context.Context, peer *workerpeer.Peer, claim WorkerClaim, ref evidence.Ref, destination io.Writer) error

ReadArtifact verifies readback for an exact retained output binding. It does not confirm capture, finalize the job, or release the artifact for publication.

func (*WorkerEvidence) ReadInput

func (s *WorkerEvidence) ReadInput(ctx context.Context, peer *workerpeer.Peer, claim WorkerClaim, ref evidence.Ref, destination io.Writer) error

ReadInput copies a declared input with bounded memory and exact size/digest checks. Bytes are provisional until the method returns nil. A transport must withhold its completion acknowledgement on any read, close or authority error. The caller must unblock destination writes on cancellation, for example by closing its socket. This method owns the source reader, not the destination.

type WorkerImages

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

WorkerImages serves only the signed manifest and its directly declared blobs. Registry credentials stay in the daemon; workers cannot supply URLs or tags.

func NewWorkerImages

func NewWorkerImages(controller *Controller, source image.Source, policy ImagePolicy, maximum int64) (*WorkerImages, error)

NewWorkerImages requires an approved content source, current source policy and aggregate compressed-image ceiling. It does not qualify or execute the image.

func (*WorkerImages) Read

func (s *WorkerImages) Read(ctx context.Context, peer *workerpeer.Peer, claim WorkerClaim, pin string, destination io.Writer) (int64, error)

Read copies one approved blob and returns its exact size only on success. Bytes remain provisional until all content, close and authority checks pass. The caller must unblock destination writes on cancellation.

type WorkerReportReceipt

type WorkerReportReceipt struct {
	SchemaVersion  int    `json:"schema_version"`
	JobID          id.ID  `json:"job_id"`
	ClaimRevision  uint64 `json:"claim_revision"`
	ProposalDigest string `json:"proposal_digest"`
}

WorkerReportReceipt acknowledges durable receipt of a report. It establishes neither completed cleanup nor a collectible result, and grants no execution.

func ReportAt

func ReportAt(ctx context.Context, path string, claim WorkerClaim, result sandbox.Result) (WorkerReportReceipt, error)

ReportAt sends one bounded report through the verified private endpoint. The returned receipt acknowledges persistence only. A lost reply must be resolved through broker inspection, never by rerunning the job. ErrPending means upload capacity was refused before payload transfer; only that report may be retried with the same claim and original deadline. No retry occurs here.

type WorkerRuntime

type WorkerRuntime struct {
	Directory string              `json:"directory"`
	Manifest  deployment.Manifest `json:"manifest"`
}

WorkerRuntime inventories the complete host-approved runtime installation.

type WorkerService

type WorkerService struct {
	Worker         hostfs.Pin    `json:"worker"`
	TemplatePath   string        `json:"template_path"`
	StateDirectory string        `json:"state_directory"`
	CPUMillis      uint64        `json:"cpu_millis"`
	MemoryBytes    uint64        `json:"memory_bytes"`
	Tasks          uint64        `json:"tasks"`
	WallTime       time.Duration `json:"wall_time_ns"`
}

WorkerService configures the installed service without a self-referential configuration hash. The loader supplies that pin from the exact file bytes.

type WorkerSession

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

WorkerSession holds the private launch capability after startup validation. It does not stage files or execute a workload. Reauthorize after staging and immediately before execution; the original signed deadline never moves.

func BootstrapWorker

func BootstrapWorker(ctx context.Context, configPath, credentialDirectory string, key id.ID) (*WorkerSession, error)

BootstrapWorker verifies the current Linux worker, protected configuration, signed credential and current broker authority. Only a bound pending response permits waiting for activation. Startup never launches or claims another job.

func (*WorkerSession) ArtifactRepository

func (w *WorkerSession) ArtifactRepository() capture.Repository

ArtifactRepository returns this session's capture upload/readback capability. Each artifact gets one upload attempt after intent acknowledgement. An uncertain upload, including capacity refusal, requires broker recovery instead of replay.

func (*WorkerSession) Authorize

func (w *WorkerSession) Authorize(ctx context.Context) error

Authorize repeats current authority and local deployment checks. It grants no new deadline and performs no activation retry after startup.

func (*WorkerSession) BeginExecution

func (w *WorkerSession) BeginExecution(ctx context.Context) error

BeginExecution consumes this session's one execution attempt before checking current deployment and authority. A failed entry cannot be retried by the same session. Authorize remains available to recheck grants during that attempt.

func (*WorkerSession) CaptureJournal

func (w *WorkerSession) CaptureJournal() capture.Journal

CaptureJournal returns this session's authenticated capture capability, or nil when unavailable. Each declared output gets one intent and one confirmation attempt. An uncertain response requires daemon recovery, never worker replay.

func (*WorkerSession) Configuration

func (w *WorkerSession) Configuration() WorkerConfiguration

Configuration returns a detached deployment snapshot without the launch token.

func (*WorkerSession) Deadline

func (w *WorkerSession) Deadline() time.Time

Deadline is the earlier signed execution or qualification deadline.

func (*WorkerSession) ImageSource

func (w *WorkerSession) ImageSource() image.Source

ImageSource returns this session's private image read capability. The daemon permits only the signed manifest and its direct members. Readers retain the session until a verified receipt or Close cancels and joins the transfer.

func (*WorkerSession) InputSource

func (w *WorkerSession) InputSource() staging.Source

InputSource returns the signed-input read capability of this session. Readers hold the session until transfer completes or Close cancels and joins it. EOF means the broker receipt and final current-authority check both succeeded.

func (*WorkerSession) Job

func (w *WorkerSession) Job() (sandbox.Job, error)

Job returns a detached copy of the signed job without the launch token.

func (*WorkerSession) Report

Report submits at most one report, permitting only identical retries after explicit upload backpressure. Any uncertain outcome requires broker inspection.

type WorkspaceScanner

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

WorkspaceScanner reclaims detached workspace mountpoints after fencing their services. Known nonterminal jobs remain with normal execution recovery.

func NewWorkspaceScanner

func NewWorkspaceScanner(cfg OrphanConfig, root string) (*WorkspaceScanner, error)

NewWorkspaceScanner pins the installed workspace directory. It shares the bounded journal eligibility rules with independent service orphan recovery.

func (WorkspaceScanner) Recover

func (s WorkspaceScanner) Recover(ctx context.Context) (CleanupReport, error)

Recover visits a complete bounded discovery pass before admission or after shutdown. It preserves the first failure while attempting remaining pages.

func (WorkspaceScanner) Sweep

func (s WorkspaceScanner) Sweep(ctx context.Context, after string) (CleanupPage, error)

Sweep processes one page from a fresh discovery snapshot. Known nonterminal jobs remain with normal execution recovery. Each page has a 30-second budget.

Jump to

Keyboard shortcuts

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