package release import ( "bytes" "context" "encoding/json" "errors" "io" "os" "path/filepath" "time" "github.com/carlosframework/platform/internal/rootstate" ) // Public history is separate from the private claim journals. Agents may read // these records, but only root can create or replace them. const RootHealthyDir = "/var/lib/carlos-release" func rootHealthyStore(acct, app string, create bool) (rootstate.Store, error) { if acct == "" { acct = OpsAccount } if !ValidAccount(acct) || !ValidApp(app) { return nil, os.ErrPermission } return rootstate.Open(filepath.Join(RootHealthyDir, "healthy", acct), create, true) } func decodeRootHealthy(raw []byte) ([]HealthyBuild, error) { var f healthyFile d := json.NewDecoder(bytes.NewReader(raw)) d.DisallowUnknownFields() if err := d.Decode(&f); err != nil { return nil, err } if d.Decode(new(any)) != io.EOF || f.Schema != 1 || len(f.Builds) > healthyMax { return nil, os.ErrPermission } for _, b := range f.Builds { if !sha256Re.MatchString(b.SHA256) || b.At.IsZero() || (b.How != "live" && b.How != "settle") { return nil, os.ErrPermission } } return f.Builds, nil } func readRootHealthy(acct, app string) []HealthyBuild { d, err := rootHealthyStore(acct, app, false) if err != nil { return nil } defer d.Close() raw, err := d.Read(app + ".json") if err != nil { return nil } b, err := decodeRootHealthy(raw) if err != nil { return nil } return b } func recordRootHealthy(acct, app string, b HealthyBuild) error { if !sha256Re.MatchString(b.SHA256) || b.At.IsZero() || (b.How != "live" && b.How != "settle") { return os.ErrPermission } d, err := rootHealthyStore(acct, app, true) if err != nil { return err } defer d.Close() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() unlock, err := d.Lock(ctx, app+".lock") if err != nil { return err } defer unlock() return addRootHealthy(d, app, b) } func addRootHealthy(d rootstate.Store, app string, b HealthyBuild) error { var have []HealthyBuild raw, err := d.Read(app + ".json") if err == nil { have, err = decodeRootHealthy(raw) } if err != nil && !errors.Is(err, os.ErrNotExist) { return err } for _, h := range have { if h.SHA256 == b.SHA256 { // A prior rename may be visible despite a failed parent fsync. // Rewrite the exact original evidence through the durable store. return d.Write(app+".json", raw) } } have = append([]HealthyBuild{b}, have...) if len(have) > healthyMax { have = have[:healthyMax] } body, err := json.Marshal(healthyFile{Schema: 1, Builds: have}) if err != nil { return err } return d.Write(app+".json", append(body, '\n')) }