package releaseupdate import ( "context" "encoding/json" "errors" "fmt" "os" "path/filepath" "regexp" "strings" "sync" "time" "golang.org/x/mod/semver" "github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/domain/distribution" "github.com/samcharles93/archie-core/internal/infrastructure/signedoci" ) // Annotation carries the source key's signature over a release statement. const Annotation = "dev.archie.release.signature.v1" // ArtifactType marks a release manifest. const ArtifactType = "application/vnd.archie.release.v1" // StatementMediaType is the release statement layer's media type. const StatementMediaType = "application/vnd.archie.release.statement.v1+json" // Platform is the only platform releases are built for. const Platform = "linux-amd64" const maxStatementBytes = 64 << 10 // buildSuffix is the git-describe tail of an untagged build (1.7.0-4-g0736708). var buildSuffix = regexp.MustCompile(`-[0-9]+-g[0-9a-f]+$`) // Statement is what a release's signature covers: the version, when it was // issued, the zip that installs it and the agent image it runs. Everything an // install trusts comes from here, never from the registry tag or the zip. type Statement struct { Version string `json:"version"` Prerelease bool `json:"prerelease"` IssuedAt time.Time `json:"issued_at"` Platform string `json:"platform"` Zip Blob `json:"zip"` AgentImage string `json:"agent_image"` Changelog string `json:"changelog,omitempty"` } // Blob names a release layer by its content digest. type Blob struct { Name string `json:"name"` Digest string `json:"digest"` Size int64 `json:"size"` } // Validate refuses a statement an install could not act on safely. func (s Statement) Validate() error { switch { case !releaseVersion.MatchString(s.Version): return fmt.Errorf("release statement version %q is not a release version", s.Version) case s.IssuedAt.IsZero(): return errors.New("release statement has no issue time") case s.Platform != Platform: return fmt.Errorf("release statement is for %q, not %s", s.Platform, Platform) case s.Zip.Name != ZipName(s.Version) || !strings.HasPrefix(s.Zip.Digest, "sha256:") || s.Zip.Size <= 0: return errors.New("release statement does not name its zip by name, digest and size") case !pinnedImage.MatchString(s.AgentImage): return fmt.Errorf("release statement agent image %q is not pinned by digest", s.AgentImage) } return nil } // ZipName is the distribution zip a version is published as. func ZipName(version string) string { return fmt.Sprintf("archie-core-archied-v%s-%s.zip", version, Platform) } // Tag is the registry tag a channel resolves through: stable and next are // moving tags, an exact pin is the version's own. func Tag(channel, pin string) string { if channel == "exact-pin" { return "v" + strings.TrimPrefix(pin, "v") } return channel } // Release is a verified release and the artifact its zip is read from. type Release struct { Statement Statement Artifact signedoci.Artifact } // Fetch resolves tag at source and verifies its statement. A statement on a // moving channel tag issued before the newest one accepted from that tag is a // replay and is refused; an exact pin may name an older release on purpose. func Fetch(ctx context.Context, source distribution.Source, tag string) (Release, error) { artifact, err := signedoci.Fetch(ctx, source, tag, Annotation, maxStatementBytes) if err != nil { return Release{}, fmt.Errorf("release: %w", err) } decoder := json.NewDecoder(strings.NewReader(string(artifact.Statement))) decoder.DisallowUnknownFields() var statement Statement if err := decoder.Decode(&statement); err != nil { return Release{}, fmt.Errorf("release statement: %w", err) } if err := statement.Validate(); err != nil { return Release{}, err } if strings.HasPrefix(tag, "v") { if "v"+statement.Version != tag { return Release{}, fmt.Errorf("tag %s carries the statement for %s", tag, statement.Version) } return Release{Statement: statement, Artifact: artifact}, nil } mark := &signedoci.FileFreshness{Path: signedoci.MarkPath("releases", source.Reference+":"+tag)} newest, err := mark.Newest(ctx) if err != nil { return Release{}, err } if !newest.IsZero() && statement.IssuedAt.Before(newest) { return Release{}, fmt.Errorf("release on %s was issued %s, before the newest accepted %s", tag, statement.IssuedAt.Format(time.RFC3339), newest.Format(time.RFC3339)) } if err := mark.Accept(ctx, statement.IssuedAt); err != nil { return Release{}, fmt.Errorf("record release freshness: %w", err) } return Release{Statement: statement, Artifact: artifact}, nil } // RegistryCatalog reports the release on the selected channel against this build. // Only one version covers every component, so the daemon and agent are // offered the same release. type RegistryCatalog struct { // Settings returns the source, channel and pin in force. Settings func(context.Context) (source distribution.Source, channel, pin string, err error) // A found release is reused for checkTTL so a dashboard that polls does // not hit the registry on every view. mu sync.Mutex key string at time.Time statement Statement } const checkTTL = 10 * time.Minute func (c *RegistryCatalog) Check(ctx context.Context) (Snapshot, error) { source, channel, pin, err := c.Settings(ctx) if err != nil { return Snapshot{}, err } if channel == "" { channel = "stable" } if err := ValidateChannel(channel, pin); err != nil { return Snapshot{}, err } statement, err := c.detect(ctx, source, Tag(channel, pin)) if err != nil { return Snapshot{}, err } component := func(id, label, installed string) Component { return Component{ ID: id, Label: label, Installed: installed, Available: statement.Version, Reference: statement.Zip.Name, Changelog: statement.Changelog, } } return Snapshot{Components: []Component{ component("daemon", "Services", ReleaseVersion(buildinfo.Version)), component("agent", "Runtime", installedAgent(executableDir())), }}, nil } func (c *RegistryCatalog) detect(ctx context.Context, source distribution.Source, tag string) (Statement, error) { c.mu.Lock() defer c.mu.Unlock() key := source.Reference + "\x00" + distribution.EncodeKey(source.Key) + "\x00" + tag if c.key == key && time.Since(c.at) < checkTTL { return c.statement, nil } release, err := Fetch(ctx, source, tag) if err != nil { return Statement{}, err } c.key, c.at, c.statement = key, time.Now(), release.Statement return release.Statement, nil } // ReleaseVersion is the release a build was cut from: a git-describe build // ("1.55.0-218-gabc123") is the same release as its tag. A build that names no // release ("dev") has none, so nothing can be judged newer than it. func ReleaseVersion(version string) string { version = buildSuffix.ReplaceAllString(version, "") if !semver.IsValid("v" + strings.TrimPrefix(version, "v")) { return "" } return version } // installedAgent is the image the installer last switched to, recorded in a // sidecar beside the binaries; without one it is the runtime this release was // cut with. A malformed sidecar is unknown, not guessed. func installedAgent(binDir string) string { data, err := os.ReadFile(filepath.Join(binDir, agentVersionFile)) if binDir == "" || errors.Is(err, os.ErrNotExist) { return ReleaseVersion(buildinfo.Runtime) } version := strings.TrimSpace(string(data)) if err != nil || strings.ContainsAny(version, " \n") || ValidateChannel("exact-pin", version) != nil { return "" } return ReleaseVersion(version) } func executableDir() string { exe, err := os.Executable() if err != nil { return "" } return filepath.Dir(exe) }