package host import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "log" "os" "path/filepath" "reflect" "time" "github.com/carlosframework/platform/internal/hostbox" "github.com/carlosframework/platform/internal/hostclaim" "github.com/carlosframework/platform/internal/hostguard" "github.com/carlosframework/platform/internal/registry" "github.com/carlosframework/platform/internal/release" ) func (h ClaimRootHTTP) commitRootInventory(ctx context.Context, q hostbox.JournalRequest) (hostbox.JournalResponse, error) { return h.withRootInventoryHistory(ctx, q, false) } func (h ClaimRootHTTP) withRootInventoryHistory(ctx context.Context, q hostbox.JournalRequest, pending bool) (hostbox.JournalResponse, error) { if h.history == nil { return h.commitRootInventoryPending(ctx, q, pending, nil) } var out hostbox.JournalResponse err := h.history(ctx, func(history *release.RootHistory) error { var err error out, err = h.commitRootInventoryPending(ctx, q, pending, history) return err }) return out, err } func (h ClaimRootHTTP) commitRootInventoryPending(ctx context.Context, q hostbox.JournalRequest, pending bool, history *release.RootHistory) (hostbox.JournalResponse, error) { var out hostbox.JournalResponse if !pending && (q.V == 2 || q.V == 3) { now := time.Now() if h.Journals != nil && h.Journals.Now != nil { now = h.Journals.Now() } age := now.Sub(time.Unix(0, q.IssuedAt)) if age > hostbox.JournalRequestWindow || age < -hostbox.JournalRequestWindow { return out, hostbox.ErrJournalUncertain } } guard := h.Stop.Coordinator.Guard if guard.Root == nil || h.Journals == nil || h.InventoryActor == nil || h.Reconcile.Registry == nil || h.Reconcile.Census == nil { return out, hostbox.ErrUnsupported } if h.RequireNewWork != nil { if err := h.RequireNewWork(ctx); err != nil { return out, err } } actor, err := h.InventoryActor(ctx) if err != nil { return out, err } in, t := q.Inventory, q.Target in.Entries = append([]hostbox.StopInventoryEntry(nil), in.Entries...) // The inventory's stamp is validated against the fresh binding; a target // stamp, when the agent sends one, must name that same binding before // any intent is persisted (fix round 1, finding 2). if q.Op != "inventory-write" || !in.Complete || in.Box != actor.Box || in.Enrollment != actor.Enrollment || in.DirectoryRevision != actor.Binding || (t.DirectoryRevision != "" && t.DirectoryRevision != in.DirectoryRevision) || t.Host != in.Host || t.Incarnation != in.Incarnation || t.Stamp != in.InstallationStamp || t.Box != actor.Box || t.Enrollment != actor.Enrollment || t.ClaimETag == "" || q.RecordKey == "" || q.RecordETag == "" { return out, hostbox.ErrChanged } observed, err := hostclaim.Read(ctx, h.Stop.Coordinator.Evidence, in.Host) if err != nil { return out, err } if observed.Absent || observed.Claim == nil || observed.Claim.Holder == nil { return out, hostbox.ErrChanged } applied := false if pending { saved, e := h.Journals.Inventory.SnapshotRequest(ctx, t) if e != nil { return out, e } applied = saved.Revision == q.Revision+1 && saved.LastRequest == q.ID } holder := observed.Claim.Holder if (!applied && observed.ETag != t.ClaimETag) || holder.Incarnation != t.Incarnation || holder.Stamp != t.Stamp || holder.Session != t.Session || holder.Key != q.RecordKey || observed.Claim.Op.ID != t.Op || observed.Claim.Op.Phase != t.Phase { return out, hostbox.ErrChanged } firstLanding := q.Revision == 0 && observed.Claim.Op.Kind == hostclaim.KindLanding if firstLanding { if err := rootFirstInstallation(observed.Claim, actor); err != nil { return out, err } entry := rootLandingEntry(q, observed.Claim, actor) if len(in.Entries) != 0 { return out, hostbox.ErrTypedInventory } in.Entries = []hostbox.StopInventoryEntry{entry} } var canonical registry.Route var currentRow *registry.Route installation := hostguard.RootInstallation{Empty: len(in.Entries) == 0, Host: in.Host, Incarnation: in.Incarnation, Stamp: in.InstallationStamp, Migration: 1, InventoryRevision: q.Revision + 1, Account: holder.Account, App: holder.App, Record: holder.Key, Box: actor.Box, Enrollment: actor.Enrollment} if q.Revision == 0 { installation.Registration = hostguard.InstallationRegistration{Op: observed.Claim.Op.ID, Kind: observed.Claim.Op.Kind, Phase: observed.Claim.Op.Phase, Session: holder.Session} if firstLanding { installation.Registration.RowID = in.Entries[0].RowIdentity } } raw, err := json.Marshal(q) if err != nil { return out, err } replayed := false err = guard.CommitRootInventoryArtifacts(ctx, installation, raw, func(c *hostclaim.Claim) error { if !reflect.DeepEqual(c, observed.Claim) { return hostbox.ErrChanged } fresh, err := hostclaim.Read(ctx, h.Stop.Coordinator.Evidence, in.Host) if err != nil { return err } if !applied && fresh.ETag != t.ClaimETag { return hostbox.ErrChanged } var etag string canonical, etag, err = rootClaimRecord(ctx, h.Stop.Coordinator.Evidence, c, h.Roots["data"]) if err != nil { return err } if etag != q.RecordETag { return hostbox.ErrChanged } if c.Op.Kind == hostclaim.KindRelocating && q.Revision == 0 { rec, e := relocationRecord(ctx, h.Roots["data"], h.Stop.Coordinator.Evidence, observed) if e != nil { return e } canonical = rec.Route } if c.Op.Kind == hostclaim.KindLanding { canonical, err = h.rootLandingRoute(ctx, c, actor) if err != nil { return err } } owner := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%d\x00%s", in.Host, in.Incarnation, in.InstallationStamp, actor.Box))) canonical.ClaimIncarnation, canonical.ClaimStamp, canonical.ClaimOwner = in.Incarnation, in.InstallationStamp, hex.EncodeToString(owner[:]) for _, entry := range in.Entries { if entry.Kind == "route" { if canonical.ClaimRowID != "" { return hostbox.ErrTypedInventory } canonical.ClaimRowID = entry.RowIdentity } } row, err := h.Reconcile.Registry.Get(in.Host) if err != nil { return err } currentRow = row if row != nil && (row.Host != canonical.Host || row.Account != canonical.Account || row.App != canonical.App || row.DBPath != canonical.DBPath || row.ClaimOwnership != canonical.ClaimOwnership) { return hostbox.ErrTypedInventory } if row == nil { for _, e := range in.Entries { if e.Kind != "route" || (e.Materialization != "intended" && !firstLanding) { return hostbox.ErrTypedInventory } } } else if err := hostbox.ValidateAgentInventory(in, &canonical, h.Roots["data"]); err != nil { return err } if err := h.verifyInventoryTimers(in); err != nil { return err } if err := h.bindInventoryPaths(ctx, &in); err != nil { return err } for _, e := range in.Entries { if e.Ownership != canonical.ClaimOwner { return hostbox.ErrTypedInventory } if e.Kind == "route" { if e.ManagedRoot != "registry" || e.RelativePath != in.Host || e.RowIdentity == "" { return hostbox.ErrTypedInventory } continue } if e.Kind == "timer" { if err := h.verifyTimerMutationRow(in.Host, canonical.ClaimOwnership, e, q.Timer); err != nil { return err } continue } if err := h.verifyInventoryPath(e); err != nil { return err } } return nil }, func(priorRoot hostguard.RootInstallation) error { if firstLanding && currentRow != nil && priorRoot.Registration != installation.Registration { return hostbox.ErrTypedInventory } if firstLanding && currentRow == nil && priorRoot.InventoryRevision != 0 { return hostbox.ErrTypedInventory } if observed.Claim.Op.Kind == hostclaim.KindLanding && !firstLanding && !landingRegistrationMatches(priorRoot, observed.Claim, currentRow) { return hostbox.ErrTypedInventory } snapshot, err := h.Journals.Inventory.SnapshotRequest(ctx, hostguard.FenceTarget{Host: in.Host, Incarnation: in.Incarnation, Stamp: in.InstallationStamp}) prior, revision := snapshot.Inventory, snapshot.Revision if err != nil { return err } replay, found, err := h.Journals.Replay(ctx, actor.Box+"/"+actor.Enrollment, q) if err != nil { return err } if found { if revision != q.Revision+1 || !reflect.DeepEqual(prior, in) { return hostbox.ErrChanged } out = replay replayed = true return nil } if revision == q.Revision+1 && reflect.DeepEqual(prior, in) && (priorRoot.InventoryRevision == revision || pending && snapshot.LastRequest == q.ID) { out = hostbox.JournalResponse{V: 1, ID: q.ID, Revision: revision} replayed = true return nil } if revision != q.Revision { return hostbox.ErrChanged } if err := h.verifyNewInventoryIdentities(prior, in); err != nil { return err } if err := h.verifyTimerMutation(prior, in, q.Timer); err != nil { return err } if revision == 0 { if (!firstLanding && len(in.Entries) != 0) || rootFirstInstallation(observed.Claim, actor) != nil { return hostbox.ErrChanged } census := h.rootEmptyCensus() selected := hostbox.RecordSelection{Host: in.Host, Key: holder.Key, ETag: q.RecordETag, Incarnation: in.Incarnation, Family: holder.Family} if firstLanding && currentRow != nil && priorRoot.Registration == installation.Registration { if err := census.CheckRootRegisteredRow(ctx, observed, selected, currentRow.ClaimOwnership); err != nil { return err } } else if err := census.CheckLocal(ctx, observed, selected); err != nil { return err } } else { if priorRoot.InventoryRevision != revision { return hostbox.ErrChanged } for _, old := range prior.Entries { found := false for _, next := range in.Entries { if old.ArtifactID == next.ArtifactID { if q.Timer != nil && old.Kind == "timer" && old.RelativePath == q.Timer.Timer.Host+"/"+q.Timer.Timer.Name { old.RowIdentity, old.Materialization, old.TimerRetired = next.RowIdentity, next.Materialization, next.TimerRetired } if old.Materialization == "intended" && next.Materialization == "materialized" { old.Materialization = next.Materialization old.Identity = next.Identity old.Device = next.Device old.Inode = next.Inode old.Type = next.Type } if old != next { return hostbox.ErrChanged } found = true } } if !found { return hostbox.ErrChanged } } } return nil }, func(prior hostguard.RootInstallation) error { if history != nil && q.Revision == 0 && prior.InventoryRevision == 0 && observed.Claim.Op.Kind == hostclaim.KindServing && holder.Session == 0 && holder.WriterBox == "" { if err := history.RecordCreation(release.HistoryBinding{Host: in.Host, Account: holder.Account, App: holder.App}, rootHistoryInstallation(installation)); err != nil { return err } } if firstLanding && currentRow == nil { if err := h.Reconcile.Registry.Upsert(canonical); err != nil { return err } } if replayed { return nil } if q.Timer != nil { if err := h.applyTimerMutation(*q.Timer); err != nil { return err } } if firstLanding || h.inventoryIdentity != nil { out, err = h.Journals.ExecuteRootInventory(ctx, actor.Box+"/"+actor.Enrollment, q, in, pending) } else if pending { out, err = h.Journals.CompletePendingInventory(ctx, actor.Box+"/"+actor.Enrollment, q) } else { out, err = h.Journals.Execute(ctx, actor.Box+"/"+actor.Enrollment, q) } return err }, func(prior hostguard.RootInstallation) (hostguard.InstallationArtifacts, error) { return rootInventoryArtifacts(prior, canonical, in, q.Revision) }) return out, err } func (h ClaimRootHTTP) verifyInventoryPath(e hostbox.StopInventoryEntry) error { if e.Kind != "path" || e.ManagedRoot != "data" || !filepath.IsLocal(e.RelativePath) { return hostbox.ErrTypedInventory } path := filepath.Join(h.Roots["data"], e.RelativePath) if e.Materialization == "intended" { if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { return hostbox.ErrChanged } return nil } if e.Materialization != "materialized" { return hostbox.ErrTypedInventory } return hostbox.VerifyInventoryIdentity(h.Roots["data"], e) } func (h ClaimRootHTTP) verifyNewInventoryIdentities(prior, next hostbox.StopInventory) error { for _, e := range next.Entries { if e.Kind != "path" || e.Materialization != "materialized" { continue } retained := false for _, old := range prior.Entries { if old.ArtifactID == e.ArtifactID && old.Materialization == "materialized" { retained = true } } if retained { continue } current, err := hostbox.CaptureInventoryIdentity(h.Roots[e.ManagedRoot], e.RelativePath) if err != nil { return err } if e.Identity.Boot != current.Boot { return hostbox.ErrChanged } if err := h.verifyInventoryPath(e); err != nil { return err } } return nil } // obsoleteIntent reports whether a pending intent was stamped under a binding // other than the startup binding. Its stamp is validated binding evidence // only: an inventory's own stamp (checked against the fresh binding before // the intent was persisted) or a rebind's successor stamp (likewise). An // agent-sent target stamp is never consulted (fix round 1, finding 2). // Replaying an obsolete intent would compare the old binding with today's // authority; it is settled instead (N3). func (h ClaimRootHTTP) obsoleteIntent(stamp string) bool { return h.startupBinding != "" && stamp != h.startupBinding } // settleObsoleteIntent settles an obsolete pending intent through the // guard's SettleObsoleteRootInventory (same host lock, exact intent bytes), // whatever the claim says now: the binding difference alone supersedes it. // The installation is quarantined and marked settled: it stays refused for // execution and new work, because every fresh comparison needs the new // binding, and the migration census at root's next start still inspects it, // so cleanup and migration startup are not blocked (fix round 1, finding 1). // applied says whether root's interrupted commit had already landed the // intent in the inventory; the guard then records the installation that // commit would have recorded, so guard and inventory agree. A settlement // failure is logged and leaves the intent pending, as any recovery failure // does. It never consults InventoryActor, so a quarantined box settles its // own leftovers. // // Cold-handover barriers (roster binding B3) are not pending installations // and are not settled here: RecoverPending's cold handover recovery settles // them (hostbox ColdHandover.Obsolete, hostguard // SettleObsoleteColdHandover) with the same startup binding. func (h ClaimRootHTTP) settleObsoleteIntent(ctx context.Context, host string, raw []byte, kind, stamped string, applied func(context.Context, hostguard.RootInstallation) (bool, error)) { err := h.Stop.Coordinator.Guard.SettleObsoleteRootInventory(ctx, host, raw, applied) log.Printf("instance-control: %s: obsolete pending %s intent: stamped %s current %s", host, kind, stamped, h.startupBinding) if err != nil { log.Printf("instance-control: %s: obsolete pending %s intent not settled: %v", host, kind, err) } } // inventoryIntentApplied reports whether q, an interrupted inventory write, // already landed in the inventory: the pending installation's inventory is // at q's revision and names q as its last request, the test the pending // replay makes (commitRootInventoryPending's applied). func (h ClaimRootHTTP) inventoryIntentApplied(q hostbox.JournalRequest) func(context.Context, hostguard.RootInstallation) (bool, error) { return func(ctx context.Context, pending hostguard.RootInstallation) (bool, error) { if h.Journals == nil || h.Journals.Inventory == nil { return false, hostbox.ErrUnsupported } saved, err := h.Journals.Inventory.SnapshotRequest(ctx, hostguard.FenceTarget{Host: pending.Host, Incarnation: pending.Incarnation, Stamp: pending.Stamp}) if err != nil { return false, err } return saved.Revision == q.Revision+1 && saved.LastRequest == q.ID && saved.Revision == pending.InventoryRevision, nil } } // rebindIntentUnapplied: a recovery rebind's commit writes only the // successor's inventory, so the predecessor the record keeps still agrees // with its own inventory; the record keeps it. func rebindIntentUnapplied(context.Context, hostguard.RootInstallation) (bool, error) { return false, nil } func (h ClaimRootHTTP) recoverRootInventory(ctx context.Context) error { authority := h.Stop.Coordinator.Guard.Root if authority == nil { return nil } pending, err := authority.PendingInstallations() if err != nil { return err } for _, raw := range pending { var recovery recoveryRebindIntent if err = json.Unmarshal(raw, &recovery); err != nil { return err } if recovery.Recovery != nil { if next := recovery.Recovery.Next; h.obsoleteIntent(next.DirectoryRevision) { h.settleObsoleteIntent(ctx, next.Host, raw, "rebind", next.DirectoryRevision, rebindIntentUnapplied) continue } if err = h.rebindRecoveryInventory(ctx, *recovery.Recovery); err != nil { n := recovery.Recovery.Next if errors.Is(err, hostbox.ErrChanged) { err = errors.Join(err, h.Stop.Coordinator.Guard.AbandonRootInventory(ctx, n.Host, raw, func(c *hostclaim.Claim) bool { fresh, e := hostclaim.Read(ctx, h.Stop.Coordinator.Evidence, n.Host) return e == nil && fresh.Claim != nil && reflect.DeepEqual(c, fresh.Claim) && fresh.ETag != n.ETag }, rebindIntentUnapplied)) } log.Printf("instance-control: %s: %v", n.Host, err) } continue } var q hostbox.JournalRequest if err = json.Unmarshal(raw, &q); err != nil { return err } if settled, settleErr := h.settleTimerInventory(ctx, q, raw); settled { continue } else if settleErr != nil { return settleErr } if h.obsoleteIntent(q.Inventory.DirectoryRevision) { h.settleObsoleteIntent(ctx, q.Target.Host, raw, "inventory", q.Inventory.DirectoryRevision, h.inventoryIntentApplied(q)) continue } if _, err = h.withRootInventoryHistory(ctx, q, true); err != nil { if errors.Is(err, hostbox.ErrChanged) || errors.Is(err, hostbox.ErrJournalUncertain) { err = errors.Join(err, h.Stop.Coordinator.Guard.AbandonRootInventory(ctx, q.Target.Host, raw, func(c *hostclaim.Claim) bool { fresh, readErr := hostclaim.Read(ctx, h.Stop.Coordinator.Evidence, q.Target.Host) if readErr != nil || fresh.Claim == nil || !reflect.DeepEqual(c, fresh.Claim) { return false } _, recordETag, recordErr := h.Stop.Coordinator.Evidence.Get(ctx, q.RecordKey) return recordErr == nil && recordETag != q.RecordETag || fresh.ETag != q.Target.ClaimETag || c.Holder == nil || c.Holder.Incarnation != q.Target.Incarnation || c.Holder.Stamp != q.Target.Stamp || c.Holder.Session != q.Target.Session || c.Op.ID != q.Target.Op || c.Op.Phase != q.Target.Phase || errors.Is(err, hostbox.ErrJournalUncertain) }, h.inventoryIntentApplied(q))) } log.Printf("instance-control: %s: %v", q.Target.Host, err) } } return nil }