package release import ( "context" "crypto/ed25519" "encoding/base64" "encoding/json" "errors" "fmt" "os" "regexp" "time" ) // SystemPointer is the platform's own channel pointer: what a ChannelPointer // is for an app, for the thing that does the adopting. It lives under // control/, not apps/, because the substrate is not an app (the // console-as-an-app spec's dividing line), and it is ROOT-KEY-ONLY: a scoped // grant's rungs name app channels, and a key that can roll the platform is a // bigger key than any app promoter should hold. Spec §3. type SystemPointer struct { ActivationID string `json:"activation_id,omitempty"` CancellationID string `json:"cancellation_id,omitempty"` Schema int `json:"schema"` Component string `json:"component"` Channel string `json:"channel"` Current SystemRelease `json:"current"` History []SystemRelease `json:"history,omitempty"` Spread string `json:"spread"` PromotedAt time.Time `json:"promoted_at"` // of THIS write; the box's replay guard reads only this Audit []Promotion `json:"audit,omitempty"` } // SystemRelease is everything a box needs to install one version. It travels // whole into History so a rollback re-installs what was there, not a version // string with someone else's artifacts. type SystemRelease struct { ConsoleArtifacts map[string]SystemArtifact `json:"console_artifacts,omitempty"` ReleaseTag string `json:"release_tag,omitempty"` SeedsProtocol int `json:"seeds_protocol,omitempty"` MovesProtocol int `json:"moves_protocol,omitempty"` Version string `json:"version"` Artifacts map[string]SystemArtifact `json:"artifacts"` // keyed by "-" Source string `json:"source,omitempty"` ReleasedAt time.Time `json:"released_at"` // audit only; never compared } // SystemArtifact is one mirrored binary. Its sha in the signed pointer IS // the artifact's signature: boxes need no .sig object. type SystemArtifact struct { Key string `json:"key"` SHA256 string `json:"sha256"` } // SystemComponentRouter is the one component today: the substrate binary // (edge + activator + adoption, one process). A split adds a name here. const SystemComponentRouter = "router" // ErrNoSystemHistory is RollbackSystem's answer when the pointer has never // moved: there is nothing older to go back to. var ErrNoSystemHistory = errors.New("system pointer: nothing to roll back to") // ErrBadSystemPointer marks every way an object on the wire can fail to be // this component and channel's signed pointer: a torn wrapper, a grant, a // signature that does not verify, a payload that does not validate. Callers // that must tell "this is not authority" from "the bucket is unreachable" — // the box's self-update refuses on the first and defers on the second — test // with errors.Is instead of reading the message. var ErrBadSystemPointer = errors.New("system pointer does not verify") const ( systemSpreadMax = 24 * time.Hour systemSpreadDefault = 5 * time.Minute ) var ( systemComponentRe = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`) systemPlatformRe = regexp.MustCompile(`^[a-z0-9]+-[a-z0-9]+$`) systemSHA256Re = regexp.MustCompile(`^[0-9a-f]{64}$`) ) // SystemPointerKey is control/system//.json. func SystemPointerKey(component, channel string) string { return "control/system/" + component + "/" + channel + ".json" } // SystemArtifactKey is bootstrap/router//carlos-: under // bootstrap/ because the store door already means "the platform's own // binary" by that name, per-version because canary and stable boxes must be // able to run different binaries at once. func SystemArtifactKey(version, platform string) string { return "bootstrap/router/" + version + "/carlos-" + platform } // SpreadDuration is Spread parsed, or the default when it is unparseable — // validation refuses the unparseable case on the way in, so this only // defaults for a hand-edited or pre-field pointer. func (p *SystemPointer) SpreadDuration() time.Duration { d, err := time.ParseDuration(p.Spread) if err != nil || d < 0 || d > systemSpreadMax { return systemSpreadDefault } return d } func validateSystemRelease(r SystemRelease) error { if !ValidVersion(r.Version) || r.Version == "dev" { return fmt.Errorf("version %q is not a valid platform version", r.Version) } for platform, artifact := range r.ConsoleArtifacts { if !systemPlatformRe.MatchString(platform) || artifact.Key != "bootstrap/console/"+r.Version+"/carlos-"+platform || !systemSHA256Re.MatchString(artifact.SHA256) { return ErrBadSystemPointer } } if len(r.Artifacts) == 0 { return fmt.Errorf("version %s names no artifacts", r.Version) } for plat, a := range r.Artifacts { if !systemPlatformRe.MatchString(plat) { return fmt.Errorf("platform %q is not -", plat) } if a.Key != SystemArtifactKey(r.Version, plat) { return fmt.Errorf("artifact key %q is not %s", a.Key, SystemArtifactKey(r.Version, plat)) } if !systemSHA256Re.MatchString(a.SHA256) { return fmt.Errorf("artifact %s: sha256 %q is not 64 hex characters", a.Key, a.SHA256) } } return nil } func validateSystemPointer(p *SystemPointer, wantComponent, wantChannel string) error { if p.Schema != 1 { return fmt.Errorf("system pointer schema %d unsupported", p.Schema) } if p.Component != wantComponent || p.Channel != wantChannel { return fmt.Errorf("system pointer is for %s/%s, not %s/%s", p.Component, p.Channel, wantComponent, wantChannel) } if !systemComponentRe.MatchString(p.Component) || !ValidChannel(p.Channel) { return fmt.Errorf("system pointer %s/%s: bad component or channel", p.Component, p.Channel) } if p.CancellationID != "" && p.Current.Version == "" { return nil } if err := validateSystemRelease(p.Current); err != nil { return fmt.Errorf("system pointer %s/%s: %w", p.Component, p.Channel, err) } if d, err := time.ParseDuration(p.Spread); err != nil || d < 0 || d > systemSpreadMax { return fmt.Errorf("system pointer %s/%s: spread %q must be a duration between 0 and %s", p.Component, p.Channel, p.Spread, systemSpreadMax) } if p.PromotedAt.IsZero() { return fmt.Errorf("system pointer %s/%s: promoted_at unset", p.Component, p.Channel) } if len(p.History) > historyMax { return fmt.Errorf("system pointer %s/%s: history longer than %d", p.Component, p.Channel, historyMax) } for _, h := range p.History { if err := validateSystemRelease(h); err != nil { return fmt.Errorf("system pointer %s/%s: history: %w", p.Component, p.Channel, err) } } if len(p.Audit) > auditMax { return fmt.Errorf("system pointer %s/%s: audit longer than %d", p.Component, p.Channel, auditMax) } return nil } // signSystemPointer mirrors signPointer with two differences: the signer // must be the root key, and the wrapper never carries a grant. func signSystemPointer(sg Signer, p *SystemPointer) ([]byte, error) { if err := sg.usable(); err != nil { return nil, err } if sg.scope != nil { return nil, errors.New("system pointer: signed by a scoped key — the platform takes the root key only") } p.Schema = 1 p.PromotedAt = time.Now().UTC().Truncate(time.Second) if err := validateSystemPointer(p, p.Component, p.Channel); err != nil { return nil, err } payload, err := json.MarshalIndent(p, "", " ") if err != nil { return nil, err } return signRootPayload(sg, payload) } // verifySystemPointer is the single parse site for system pointers, and so // the one place ErrBadSystemPointer is attached: every refusal below reaches // the caller wrapped, whatever its own wording. func verifySystemPointer(pub ed25519.PublicKey, wrapper []byte, wantComponent, wantChannel string) (*SystemPointer, error) { p, err := parseSystemPointer(pub, wrapper, wantComponent, wantChannel) if err != nil { return nil, fmt.Errorf("%w: %v", ErrBadSystemPointer, err) } return p, nil } // parseSystemPointer does the work. A grant on the wire is refused before // the signature is looked at (the production flag's rule, production.go). func parseSystemPointer(pub ed25519.PublicKey, wrapper []byte, wantComponent, wantChannel string) (*SystemPointer, error) { var sw signedWrapper if err := json.Unmarshal(wrapper, &sw); err != nil { return nil, fmt.Errorf("system pointer %s/%s: %w", wantComponent, wantChannel, err) } if sw.Grant != nil { return nil, fmt.Errorf("system pointer %s/%s: signed by a scoped key — the platform takes the root key only", wantComponent, wantChannel) } sig, err := base64.StdEncoding.DecodeString(sw.Sig) if err != nil { return nil, fmt.Errorf("system pointer %s/%s: bad signature encoding", wantComponent, wantChannel) } if len(pub) != ed25519.PublicKeySize || !ed25519.Verify(pub, []byte(sw.Payload), sig) { return nil, fmt.Errorf("system pointer %s/%s: signature does not verify", wantComponent, wantChannel) } payload, err := base64.StdEncoding.DecodeString(sw.Payload) if err != nil { return nil, fmt.Errorf("system pointer %s/%s: bad payload encoding", wantComponent, wantChannel) } var p SystemPointer if err := json.Unmarshal(payload, &p); err != nil { return nil, fmt.Errorf("system pointer %s/%s: %w", wantComponent, wantChannel, err) } if err := validateSystemPointer(&p, wantComponent, wantChannel); err != nil { return nil, err } return &p, nil } // GetSystemPointer reads and verifies one channel's pointer. A missing key // is os.ErrNotExist, which is the normal state of every deployment before // its first `carlos system update`. func GetSystemPointer(ctx context.Context, s Store, pub ed25519.PublicKey, component, channel string) (*SystemPointer, string, error) { body, etag, err := s.Get(ctx, SystemPointerKey(component, channel)) if err != nil { return nil, "", err } p, err := verifySystemPointer(pub, body, component, channel) if err != nil { return nil, "", err } if p.CancellationID != "" && p.Current.Version == "" { return nil, etag, os.ErrNotExist } return p, etag, nil } // SystemPromoteOptions: who did it, and how long boxes spread their starts. type SystemPromoteOptions struct { Actor string Spread time.Duration // 0 = hotfix, every box at once; unset in the CLI means the default } // PromoteSystem writes the pointer for one channel, CAS-guarded. The // outgoing release goes whole into History unless it is the same version // (a re-promote of the running version is a no-op for boxes and must not // push that version into its own history). func PromoteSystem(ctx context.Context, s Store, sg Signer, component, channel string, rel SystemRelease, o SystemPromoteOptions) (*SystemPointer, error) { prepared, err := PrepareSystemPromotion(ctx, s, sg, component, channel, rel, o, "") if err != nil { return nil, err } return PublishSystemPublication(ctx, s, sg.verifyPub(), prepared) } func PrepareSystemPromotion(ctx context.Context, s Store, sg Signer, component, channel string, rel SystemRelease, o SystemPromoteOptions, id string) (SystemPublication, error) { key := SystemPointerKey(component, channel) var old *SystemPointer body, etag, err := s.Get(ctx, key) switch { case err == nil: if old, err = verifySystemPointer(sg.verifyPub(), body, component, channel); err != nil { return SystemPublication{}, err } case errors.Is(err, os.ErrNotExist): etag = "" default: return SystemPublication{}, err } if old != nil && old.CancellationID != "" && old.Current.Version == "" { old = nil } next := &SystemPointer{ActivationID: id, Component: component, Channel: channel, Current: rel, Spread: o.Spread.String()} if rel.ReleasedAt.IsZero() { next.Current.ReleasedAt = time.Now().UTC().Truncate(time.Second) } from := "" if old != nil { next.History, next.Audit = old.History, old.Audit from = old.Current.Version if old.Current.Version != rel.Version { next.History = prependCapped(old.Current, old.History, historyMax) } } next.Audit = prependCapped(Promotion{Version: rel.Version, From: from, To: channel, Actor: o.Actor, At: time.Now().UTC()}, next.Audit, auditMax) wrapper, err := signSystemPointer(sg, next) if err != nil { return SystemPublication{}, err } return SystemPublication{Component: component, Channel: channel, ID: id, ExpectedETag: etag, Before: body, After: wrapper}, nil } // RollbackSystem POPS History[0] rather than swapping with it: History[0] // becomes Current and is removed from History, and the release that was // Current is not pushed back on. So a second rollback goes one release // further back, not forward again to where it started — the verb means "go // back another one", and repeating it walks the history down. // // It writes a NEW pointer — new PromotedAt — so every box's replay guard // sees a promote, not a replay. func RollbackSystem(ctx context.Context, s Store, sg Signer, component, channel, actor string, expectedETag ...string) (*SystemPointer, error) { prepared, err := PrepareSystemRollback(ctx, s, sg, component, channel, actor, "", expectedETag...) if err != nil { return nil, err } return PublishSystemPublication(ctx, s, sg.verifyPub(), prepared) } func PrepareSystemRollback(ctx context.Context, s Store, sg Signer, component, channel, actor, id string, expectedETag ...string) (SystemPublication, error) { key := SystemPointerKey(component, channel) body, etag, err := s.Get(ctx, key) if err != nil { return SystemPublication{}, err } if len(expectedETag) > 1 || (len(expectedETag) == 1 && etag != expectedETag[0]) { return SystemPublication{}, ErrCASConflict } old, err := verifySystemPointer(sg.verifyPub(), body, component, channel) if err != nil { return SystemPublication{}, err } if len(old.History) == 0 { return SystemPublication{}, ErrNoSystemHistory } next := &SystemPointer{ActivationID: id, Component: component, Channel: channel, Current: old.History[0], History: old.History[1:], Spread: old.Spread, Audit: prependCapped(Promotion{Version: old.History[0].Version, From: old.Current.Version, To: channel, Actor: actor, At: time.Now().UTC()}, old.Audit, auditMax), } wrapper, err := signSystemPointer(sg, next) if err != nil { return SystemPublication{}, err } return SystemPublication{Component: component, Channel: channel, ID: id, ExpectedETag: etag, Before: body, After: wrapper}, nil }