diff --git a/cmd/archied/telegram_setup.go b/cmd/archied/telegram_setup.go index e69cf0696..bbc6df0aa 100644 --- a/cmd/archied/telegram_setup.go +++ b/cmd/archied/telegram_setup.go @@ -96,6 +96,7 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o }, } tg.UpdateReportPath = updateReportPath(cfg.WorkDir, cfg.BotUser) + tg.RunningVersions = daemonRunningVersions tg.Reload = makeTelegramReload(s) sessionStore := s.SessionStore @@ -120,6 +121,22 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o }, true } +// daemonRunningVersions reports the component versions this process can +// vouch for from its own build, for checking a pending update report against +// (see releaseupdate.Report.Verify). +// +// Only the daemon is listed, and that is the whole point: gatewayVersion is +// compiled into this binary, so if an installer claims it put a version into +// service and this value disagrees, the installer is wrong. runtimeVersion +// is deliberately NOT reported for the agent -- it records the agent version +// archied's own release pipeline stamped, not the version the agent +// container is actually running, and the two diverge in exactly the +// situation this check exists to detect. An unverifiable component is left +// out so it is reported as unchecked rather than as confirmed. +func daemonRunningVersions() map[string]string { + return map[string]string{releaseupdate.ComponentDaemon: gatewayVersion} +} + func configureTelegramUpdates(tg *telegram.Gateway, s telegramSetup) { if updates := makeUpdateService(s); updates != nil { tg.Updates = updates diff --git a/cmd/archied/telegram_setup_test.go b/cmd/archied/telegram_setup_test.go index 525ce97d0..d39a48f42 100644 --- a/cmd/archied/telegram_setup_test.go +++ b/cmd/archied/telegram_setup_test.go @@ -5,6 +5,7 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/installtype" + "github.com/samcharles93/archie-core/internal/releaseupdate" ) // TestMakeUpdateServiceWiresInstallType is the regression test for @@ -26,3 +27,22 @@ func TestMakeUpdateServiceWiresInstallType(t *testing.T) { t.Errorf("Service.InstallType = %q, want installtype.Type() = %q", service.InstallType, installtype.Type()) } } + +// TestDaemonRunningVersionsVouchesOnlyForItself: the point of checking a +// pending update report against running versions is that the value checked +// against is ground truth. This process's own compiled-in version is; the +// agent's is not, because runtimeVersion records what archied's release +// pipeline stamped, not what the agent container is actually running. +// Including a guess here would recreate the false success the check exists +// to catch, so its absence is the assertion. +func TestDaemonRunningVersionsVouchesOnlyForItself(t *testing.T) { + running := daemonRunningVersions() + + if got := running[releaseupdate.ComponentDaemon]; got != gatewayVersion { + t.Errorf("running[%q] = %q, want gatewayVersion = %q", releaseupdate.ComponentDaemon, got, gatewayVersion) + } + if _, ok := running[releaseupdate.ComponentAgent]; ok { + t.Errorf("running vouches for %q, which this process cannot verify: %#v", + releaseupdate.ComponentAgent, running) + } +} diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index bbe1dcc53..a8d5e2a8a 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -61,6 +61,17 @@ type Gateway struct { // /restart alike), same as ReleaseAnnouncements. Empty disables it. UpdateReportPath string + // RunningVersions reports, per component ID (see + // releaseupdate.ComponentDaemon), the version that component reports for + // itself rather than the version an installer claimed to install. It is + // what turns a pending update report from a self-reported claim into a + // checked one: the daemon's own compiled-in build version cannot be + // talked out of being what is actually running. Only components that can + // genuinely self-report belong here -- a guess would re-introduce + // exactly the false success this check exists to catch. Nil leaves every + // claim unverified. + RunningVersions func() map[string]string + // Dangerous is the sandbox/process authority for /rollback and /stop. // When nil, those commands return "not configured". The composition // root supplies this; Telegram only renders approval UX. diff --git a/internal/channels/telegram/update.go b/internal/channels/telegram/update.go index 59bb35b33..f8a9776be 100644 --- a/internal/channels/telegram/update.go +++ b/internal/channels/telegram/update.go @@ -252,26 +252,64 @@ func formatVersionChanges(result releaseupdate.Result) string { if previous == "" || previous == installed { continue } + // A placeholder is not a release: rendering "1.0.0 → unknown" reads + // as a downgrade to a version by that name rather than as the + // missing bookkeeping it actually is. + if !releaseupdate.IsRecordedVersion(installed) { + continue + } parts = append(parts, fmt.Sprintf("%s %s → %s", id, previous, installed)) } return strings.Join(parts, ", ") } -// formatPendingReport describes the phase-2 outcome. There are three -// distinct cases, not two: the daemon came back up healthy; it didn't, and -// was rolled back to its previous version; or it didn't, and there was no -// backup to roll back to. That third case must never be worded like the -// second -- claiming a rollback that didn't happen tells the operator to -// stand down while the daemon may still be running the broken version, or -// not running at all. -func formatPendingReport(report releaseupdate.Report) string { - changes := formatVersionChanges(releaseupdate.Result{Previous: report.Previous, Installed: report.Installed}) +// formatPendingReport describes the phase-2 outcome. There are five distinct +// cases, not two: the daemon came back up and confirms it is running what was +// installed; it came back up but reports running something else; it came back +// up and nothing could be checked either way; it didn't come up, and was +// rolled back; or it didn't, and there was no backup to roll back to. +// +// Two of those are easy to collapse into a neighbour and must not be. A +// no-backup failure worded like a rollback tells the operator to stand down +// while the daemon may still be running the broken version, or not running +// at all. An unverified success worded like a confirmed one re-asserts +// exactly the claim that went unchecked in the incident this verification +// was added for. +// +// running maps component ID to the version that component reports for +// itself; see Report.Verify for why a passed health check is not on its own +// evidence that the install took effect. +func formatPendingReport(report releaseupdate.Report, running map[string]string) string { if !report.RolledBack && report.HealthCheck == "passed" { + verification := report.Verify(running) + if len(verification.Drift) > 0 { + return formatVersionDrift(verification.Drift) + } + changes := formatVersionChanges(releaseupdate.Result{Previous: report.Previous, Installed: report.Installed}) text := "Update complete" if changes != "" { text += ": " + changes } - return text + ". Health check passed — archie-core is healthy on the new version." + if len(verification.Confirmed) == 0 { + // Nothing self-reported a version we could check the claim + // against, so a passed health probe is all we have -- and it + // only ever proved that *something* answered. Saying "healthy + // on the new version" here would assert the exact thing that + // went unverified in the incident this check was added for. + return text + ". Health check passed, but I could not confirm which version is actually running." + } + text += ". Health check passed — archie-core is healthy on the new version." + if len(verification.Unverified) > 0 { + // Something WAS confirmed, so the headline is earned -- but the + // version change printed above covers every component the + // installer claimed, including ones nothing checked. Naming them + // keeps the confirmed part from silently vouching for the rest. + // This is the ordinary case, not an edge one: only the daemon + // can self-report today, so the agent lands here on every + // successful update. + text += " Not independently checked: " + strings.Join(verification.Unverified, ", ") + "." + } + return text } ids := make([]string, 0, len(report.Previous)) @@ -291,6 +329,34 @@ func formatPendingReport(report releaseupdate.Report) string { return fmt.Sprintf("Update failed health check after restarting and could NOT be rolled back automatically (no backup was found). archie-core may still be running the broken version, or may not be running at all — manual intervention is required. Previous version was %s.", previousVersions) } +// formatVersionDrift words the case where the installer reported success and +// the health check passed, but a component reports it is running something +// other than what was installed. +// +// "still the version this update meant to replace" is attached PER COMPONENT +// rather than stated once for the whole message, because a single sentence +// cannot be true of a mixed set: one component can be sitting on the version +// the update meant to replace while another is on some third version the +// report never mentions. Asserting one cause for both would invent a fact +// about at least one of them -- the same defect as the false success this +// whole check exists to catch. The trailing sentence is therefore worded to +// hold either way, and says only what a passed probe actually establishes. +func formatVersionDrift(drift []releaseupdate.VersionDrift) string { + parts := make([]string, 0, len(drift)) + for _, d := range drift { + part := fmt.Sprintf("%s reports %s, not the installed %s", + d.ID, strings.TrimSpace(d.Running), strings.TrimSpace(d.Claimed)) + if d.RunningIsPrevious { + part += " (still the version this update meant to replace)" + } + parts = append(parts, part) + } + return "Update did NOT take effect: " + strings.Join(parts, "; ") + ". " + + "The health check passed because something was there to answer it, not because the new version " + + "is in service, so nothing was rolled back. " + + "Investigate before retrying — otherwise /update will report success again." +} + // reportPendingUpdate checks for a phase-2 outcome left by the update // watchdog and relays it, exactly like announceRelease -- called on every // gateway launch so it fires whether this is a fresh process boot (the @@ -327,7 +393,22 @@ func (g *Gateway) reportPendingUpdate(ctx context.Context, b *bot.Bot) { // process finds a pending report left by the previous boot's install; see // releaseupdate.ReadPendingReport. func (g *Gateway) SendPendingReport(ctx context.Context, b *bot.Bot, report releaseupdate.Report) { - g.sendMessage(ctx, b, report.ChatID, report.ThreadID, formatPendingReport(report)) + g.sendMessage(ctx, b, report.ChatID, report.ThreadID, formatPendingReport(report, g.runningVersions())) +} + +// runningVersions returns the versions components report for themselves, or +// nil when the composition root wired none. +// +// Nil is not a no-op: with nothing to check against, every claim is +// Unverified, so the relayed message says the versions could not be +// confirmed rather than repeating the pre-verification "healthy on the new +// version". That is deliberate -- an unwired gateway should read as +// unchecked, not as verified. +func (g *Gateway) runningVersions() map[string]string { + if g.RunningVersions == nil { + return nil + } + return g.RunningVersions() } func sameUpdateSnapshot(left, right releaseupdate.Snapshot) bool { diff --git a/internal/channels/telegram/update_test.go b/internal/channels/telegram/update_test.go index 8ed4f1694..56dd16653 100644 --- a/internal/channels/telegram/update_test.go +++ b/internal/channels/telegram/update_test.go @@ -51,8 +51,8 @@ func TestInstallUpdateStreamsProgressAndReportsSuccess(t *testing.T) { stub := &updateStub{ progressText: []string{"==> fetching", "==> building"}, result: releaseupdate.Result{ - Previous: map[string]string{"daemon": "1.0.0", "agent": "1.0.0"}, - Installed: map[string]string{"daemon": "1.1.0", "agent": "1.0.0"}, + Previous: map[string]string{releaseupdate.ComponentDaemon: "1.0.0", releaseupdate.ComponentAgent: "1.0.0"}, + Installed: map[string]string{releaseupdate.ComponentDaemon: "1.1.0", releaseupdate.ComponentAgent: "1.0.0"}, RestartRequested: true, }, } @@ -117,7 +117,7 @@ func TestReportPendingUpdateSendsAndClearsReport(t *testing.T) { path := filepath.Join(t.TempDir(), "update-report.json") report := releaseupdate.Report{ Channel: "telegram", ChatID: 7, ThreadID: 3, - Previous: map[string]string{"daemon": "1.0.0"}, Installed: map[string]string{"daemon": "1.1.0"}, + Previous: map[string]string{releaseupdate.ComponentDaemon: "1.0.0"}, Installed: map[string]string{releaseupdate.ComponentDaemon: "1.1.0"}, HealthCheck: "passed", } if err := releaseupdate.WritePendingReport(path, report); err != nil { @@ -184,14 +184,149 @@ func TestReportPendingUpdateDisabledWhenPathEmpty(t *testing.T) { } } +// TestFormatPendingReportVerifiesAgainstRunningVersions is the regression +// suite for the false-success bug: the watchdog's health probe passes +// whenever *a* daemon answers it, so a report can claim an install that never +// took effect. A claim the running system contradicts must not be worded as +// success; a claim it cannot check must still be, since failing closed on +// components that simply cannot self-report would call every update a +// failure. +func TestFormatPendingReportVerifiesAgainstRunningVersions(t *testing.T) { + const ( + daemon = releaseupdate.ComponentDaemon + agent = releaseupdate.ComponentAgent + previousVer = "1.0.0" + installedVer = "1.1.0" + ) + tests := []struct { + name string + previous map[string]string + installed map[string]string + running map[string]string + wantText []string + denyText []string + }{ + { + name: "running the version the update replaced", + previous: map[string]string{daemon: previousVer}, + installed: map[string]string{daemon: installedVer}, + running: map[string]string{daemon: previousVer}, + wantText: []string{daemon, previousVer, installedVer, "still the version this update meant to replace"}, + denyText: []string{"update complete", "healthy on the new version"}, + }, + { + name: "running a version the report never mentions", + previous: map[string]string{daemon: previousVer}, + installed: map[string]string{daemon: installedVer}, + running: map[string]string{daemon: "9.9.9"}, + wantText: []string{daemon, "9.9.9", installedVer}, + denyText: []string{"update complete", "still the version this update meant to replace"}, + }, + { + // A single sentence covering all components cannot be true of a + // mixed set: the daemon here IS on the version the update meant + // to replace and the agent is on neither, so the explanation has + // to attach per component or it states a falsehood about one of + // them. The trailing semicolon in the agent assertion is what + // proves the annotation did not leak onto it. + name: "mixed drift annotates each component separately", + previous: map[string]string{daemon: previousVer, agent: previousVer}, + installed: map[string]string{daemon: installedVer, agent: installedVer}, + running: map[string]string{daemon: previousVer, agent: "9.9.9"}, + wantText: []string{ + "agent reports 9.9.9, not the installed " + installedVer + ";", + "daemon reports " + previousVer + ", not the installed " + installedVer + + " (still the version this update meant to replace)", + }, + denyText: []string{"update complete"}, + }, + { + name: "claim confirmed by the running version", + previous: map[string]string{daemon: previousVer}, + installed: map[string]string{daemon: installedVer}, + running: map[string]string{daemon: installedVer}, + wantText: []string{"update complete"}, + denyText: []string{"did not take effect"}, + }, + { + // The ordinary production shape: only the daemon can self-report, + // so a successful update always confirms the daemon and leaves + // the agent unchecked. The headline is earned, but the version + // line above it covers the agent too, so the message has to say + // which components nothing actually verified -- otherwise the + // confirmed daemon silently vouches for the agent. + name: "component that cannot self-report is named, not treated as drift", + previous: map[string]string{daemon: previousVer, agent: previousVer}, + installed: map[string]string{daemon: installedVer, agent: installedVer}, + running: map[string]string{daemon: installedVer}, + wantText: []string{"update complete", "not independently checked: " + agent}, + denyText: []string{"did not take effect"}, + }, + { + name: "nothing is left unchecked when every component confirms", + previous: map[string]string{daemon: previousVer}, + installed: map[string]string{daemon: installedVer}, + running: map[string]string{daemon: installedVer}, + wantText: []string{"healthy on the new version"}, + denyText: []string{"not independently checked"}, + }, + { + name: "nothing self-reports, so success is reported unconfirmed", + previous: map[string]string{daemon: previousVer}, + installed: map[string]string{daemon: installedVer}, + running: nil, + wantText: []string{"could not confirm which version"}, + denyText: []string{"did not take effect", "healthy on the new version"}, + }, + { + name: "an unrecorded claim is not a contradiction, but is not confirmed either", + previous: map[string]string{daemon: previousVer}, + installed: map[string]string{daemon: releaseupdate.VersionUnknown}, + running: map[string]string{daemon: installedVer}, + wantText: []string{"could not confirm which version"}, + denyText: []string{"did not take effect", "healthy on the new version", releaseupdate.VersionUnknown}, + }, + { + name: "an unstamped running build cannot confirm or contradict", + previous: map[string]string{daemon: previousVer}, + installed: map[string]string{daemon: installedVer}, + running: map[string]string{daemon: releaseupdate.VersionDev}, + wantText: []string{"could not confirm which version"}, + denyText: []string{"did not take effect", "healthy on the new version"}, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + report := releaseupdate.Report{ + Previous: test.previous, + Installed: test.installed, + HealthCheck: "passed", + } + text := formatPendingReport(report, test.running) + lower := strings.ToLower(text) + for _, want := range test.wantText { + if !strings.Contains(lower, strings.ToLower(want)) { + t.Errorf("report does not mention %q: %q", want, text) + } + } + for _, deny := range test.denyText { + if strings.Contains(lower, strings.ToLower(deny)) { + t.Errorf("report wrongly claims %q: %q", deny, text) + } + } + }) + } +} + func TestFormatPendingReportDescribesSuccessAndRollback(t *testing.T) { success := releaseupdate.Report{ - Previous: map[string]string{"daemon": "1.0.0"}, - Installed: map[string]string{"daemon": "1.1.0"}, + Previous: map[string]string{releaseupdate.ComponentDaemon: "1.0.0"}, + Installed: map[string]string{releaseupdate.ComponentDaemon: "1.1.0"}, HealthCheck: "passed", RolledBack: false, } - text := formatPendingReport(success) + text := formatPendingReport(success, map[string]string{releaseupdate.ComponentDaemon: "1.1.0"}) for _, want := range []string{"1.0.0 → 1.1.0", "healthy"} { if !strings.Contains(strings.ToLower(text), strings.ToLower(want)) { t.Errorf("success report missing %q: %q", want, text) @@ -199,12 +334,12 @@ func TestFormatPendingReportDescribesSuccessAndRollback(t *testing.T) { } failure := releaseupdate.Report{ - Previous: map[string]string{"daemon": "1.0.0"}, - Installed: map[string]string{"daemon": "1.1.0"}, + Previous: map[string]string{releaseupdate.ComponentDaemon: "1.0.0"}, + Installed: map[string]string{releaseupdate.ComponentDaemon: "1.1.0"}, HealthCheck: "failed", RolledBack: true, } - text = formatPendingReport(failure) + text = formatPendingReport(failure, map[string]string{releaseupdate.ComponentDaemon: "1.0.0"}) for _, want := range []string{"rolled back", "1.0.0"} { if !strings.Contains(strings.ToLower(text), strings.ToLower(want)) { t.Errorf("rollback report missing %q: %q", want, text) @@ -220,12 +355,12 @@ func TestFormatPendingReportDescribesSuccessAndRollback(t *testing.T) { // than reporting nothing, because it tells the operator to stand down. func TestFormatPendingReportDistinguishesUnrolledBackFailure(t *testing.T) { notRolledBack := releaseupdate.Report{ - Previous: map[string]string{"daemon": "1.0.0"}, - Installed: map[string]string{"daemon": "1.1.0"}, + Previous: map[string]string{releaseupdate.ComponentDaemon: "1.0.0"}, + Installed: map[string]string{releaseupdate.ComponentDaemon: "1.1.0"}, HealthCheck: "failed", RolledBack: false, } - text := strings.ToLower(formatPendingReport(notRolledBack)) + text := strings.ToLower(formatPendingReport(notRolledBack, map[string]string{releaseupdate.ComponentDaemon: "1.1.0"})) if strings.Contains(text, "was automatically rolled back") { t.Errorf("report falsely claims a rollback happened: %q", text) } diff --git a/internal/releaseupdate/verify.go b/internal/releaseupdate/verify.go new file mode 100644 index 000000000..3df2ad6fb --- /dev/null +++ b/internal/releaseupdate/verify.go @@ -0,0 +1,153 @@ +package releaseupdate + +import ( + "sort" + "strings" +) + +// Component IDs used by the reference install script and watchdog in the +// Result and Report JSON documents (scripts/archie-update-install, +// scripts/archie-update-watchdog). They are named here because the +// composition root has to key its running-version map by exactly these +// strings for verification to match anything -- a typo would otherwise +// silently downgrade every component to "unverifiable" and restore the +// false-success behaviour this file exists to prevent. +const ( + ComponentDaemon = "daemon" + ComponentAgent = "agent" +) + +// Version placeholders that carry no release information. Both mean "nobody +// recorded a real version here", and neither may be compared as though it +// were one: doing so turns a healthy update whose bookkeeping went missing +// into a reported failure. +// +// - VersionUnknown is what the reference watchdog substitutes when it +// cannot tell what was installed ("${ARCHIE_UPDATE_INSTALLED_GATEWAY:-unknown}"). +// - VersionDev is what an unstamped build reports for itself: it is the +// default of gatewayVersion/runtimeVersion in cmd/archied, of +// GATEWAY_VERSION in Dockerfile.archied, and of the version Taskfile.yml +// falls back to when git describes no tag. A plain `go build` or an +// untagged image is therefore "dev", not a release. +const ( + VersionUnknown = "unknown" + VersionDev = "dev" +) + +// VersionDrift is one component whose reported install the running system +// contradicts: the installer said it put Claimed into service, but the +// component itself reports it is running Running. Both are the versions as +// recorded rather than normalized, so an operator sees the strings the two +// sides actually wrote; renderers should trim them for display. +type VersionDrift struct { + ID string + Claimed string + Running string + + // RunningIsPrevious reports whether the version actually running is the + // one this update set out to replace. True is the ordinary case -- the + // install silently did nothing and the pre-update process is still there + // answering the health probe. False means what is running is neither the + // installed version nor the replaced one, and a caller must NOT describe + // that as "still on the old release": it does not know what happened, + // and asserting a cause it cannot support is the same defect as the + // false success this type exists to catch. + RunningIsPrevious bool +} + +// Verification is the outcome of checking a Report's claims against the +// versions actually running. Every component the Report claims to have +// installed lands in exactly one of the three sets. +// +// Unverified is not a lesser Drift: a caller that cannot tell the two apart +// will either cry wolf over components that simply cannot self-report, or +// keep asserting success it never checked. Both have shipped here. +type Verification struct { + // Confirmed lists component IDs whose claimed version matches what the + // component reports for itself, in ID order. + Confirmed []string + // Drift lists claims the running system actively contradicts, in ID + // order. Non-empty means the update did not take effect. + Drift []VersionDrift + // Unverified lists component IDs that could not be checked either way, + // in ID order -- nothing recorded what was installed, or the component + // does not report a real version for itself. + Unverified []string +} + +// Verify compares what r claims was installed against the versions actually +// running now. +// +// This exists because a Report is entirely self-reported. The reference +// watchdog decides "passed" from an HTTP health probe, which proves only +// that *a* daemon is answering -- if the new binary never actually made it +// into service, the previous one answers the probe just as happily, and the +// watchdog then copies the version the installer *intended* into Installed. +// The result reads as a successful upgrade to a version that is not running. +// That is not hypothetical: it shipped, and a task run immediately after a +// reported-successful update hit the exact bug the update was supposed to +// fix. +// +// running maps a component ID (see ComponentDaemon and ComponentAgent) to +// the version that component reports for itself -- archied's own compiled-in +// build version, for instance, which no installer can talk it out of. A +// component absent from running is Unverified, not drifting. +func (r Report) Verify(running map[string]string) Verification { + var result Verification + for id, claimed := range r.Installed { + claimedVersion, claimable := comparableVersion(claimed) + actualVersion, actualKnown := comparableVersion(running[id]) + switch { + case !claimable || !actualKnown: + result.Unverified = append(result.Unverified, id) + case claimedVersion == actualVersion: + result.Confirmed = append(result.Confirmed, id) + default: + previousVersion, previousKnown := comparableVersion(r.Previous[id]) + result.Drift = append(result.Drift, VersionDrift{ + ID: id, + Claimed: claimed, + Running: running[id], + RunningIsPrevious: previousKnown && actualVersion == previousVersion, + }) + } + } + sort.Strings(result.Confirmed) + sort.Strings(result.Unverified) + sort.Slice(result.Drift, func(i, j int) bool { return result.Drift[i].ID < result.Drift[j].ID }) + return result +} + +// IsRecordedVersion reports whether version names an actual release rather +// than a placeholder standing in for one. Renderers use it to avoid printing +// a version change like "1.0.0 -> unknown", which reads as a downgrade to a +// release by that name. +func IsRecordedVersion(version string) bool { + _, ok := comparableVersion(version) + return ok +} + +// comparableVersion reduces a recorded version to the form both sides of a +// comparison can be expected to agree on, and reports whether it carries any +// usable information at all. +// +// Normalization is deliberately minimal: surrounding whitespace, and a +// single leading "v" or "V" so an installer that records the git tag +// "v1.9.11" matches a binary stamped "1.9.11" (the reference installer +// strips that prefix itself, but nothing forces another deployment shape +// to). Everything else is compared exactly -- an installer is expected to +// record the version it stamped, not a differently formatted description of +// it, and guessing at looser equivalences here would start hiding the very +// mismatches this check is for. +func comparableVersion(version string) (string, bool) { + normalized := strings.TrimSpace(version) + if len(normalized) > 0 && (normalized[0] == 'v' || normalized[0] == 'V') { + normalized = normalized[1:] + } + if normalized == "" || + strings.EqualFold(normalized, VersionUnknown) || + strings.EqualFold(normalized, VersionDev) { + return "", false + } + return normalized, true +} diff --git a/internal/releaseupdate/verify_test.go b/internal/releaseupdate/verify_test.go new file mode 100644 index 000000000..e1747b9c6 --- /dev/null +++ b/internal/releaseupdate/verify_test.go @@ -0,0 +1,237 @@ +package releaseupdate_test + +import ( + "fmt" + "sort" + "testing" + + "github.com/samcharles93/archie-core/internal/releaseupdate" +) + +const ( + daemon = releaseupdate.ComponentDaemon + agent = releaseupdate.ComponentAgent +) + +// TestVerifyDetectsDrift covers the false-success bug this +// verification exists for: an installer reports a version it never actually +// managed to put into service, and nothing contradicts it because the health +// check only proves *a* daemon is answering -- possibly the old one. +func TestVerifyDetectsDrift(t *testing.T) { + tests := []struct { + name string + previous map[string]string + installed map[string]string + running map[string]string + want []releaseupdate.VersionDrift + }{ + { + name: "claim matches running", + installed: map[string]string{daemon: "1.9.0"}, + running: map[string]string{daemon: "1.9.0"}, + want: nil, + }, + { + name: "claim contradicted by the version it replaced", + previous: map[string]string{daemon: "1.9.8"}, + installed: map[string]string{daemon: "1.9.0"}, + running: map[string]string{daemon: "1.9.8"}, + want: []releaseupdate.VersionDrift{ + {ID: daemon, Claimed: "1.9.0", Running: "1.9.8", RunningIsPrevious: true}, + }, + }, + { + name: "running is neither installed nor previous", + previous: map[string]string{daemon: "1.9.8"}, + installed: map[string]string{daemon: "1.9.0"}, + running: map[string]string{daemon: "1.2.3"}, + want: []releaseupdate.VersionDrift{ + {ID: daemon, Claimed: "1.9.0", Running: "1.2.3", RunningIsPrevious: false}, + }, + }, + { + name: "unknown previous cannot make running the previous version", + previous: map[string]string{daemon: releaseupdate.VersionUnknown}, + installed: map[string]string{daemon: "1.9.0"}, + running: map[string]string{daemon: "1.9.8"}, + want: []releaseupdate.VersionDrift{ + {ID: daemon, Claimed: "1.9.0", Running: "1.9.8", RunningIsPrevious: false}, + }, + }, + { + name: "component with no running version is unverifiable, not wrong", + installed: map[string]string{daemon: "1.9.0", agent: "1.9.0"}, + running: map[string]string{daemon: "1.9.0"}, + want: nil, + }, + { + name: "empty running version is unverifiable, not wrong", + installed: map[string]string{daemon: "1.9.0"}, + running: map[string]string{daemon: ""}, + want: nil, + }, + { + name: "unknown running version is unverifiable, not wrong", + installed: map[string]string{daemon: "1.9.0"}, + running: map[string]string{daemon: releaseupdate.VersionUnknown}, + want: nil, + }, + { + name: "unknown claim asserts nothing to contradict", + installed: map[string]string{daemon: releaseupdate.VersionUnknown}, + running: map[string]string{daemon: "1.9.8"}, + want: nil, + }, + { + name: "empty claim asserts nothing to contradict", + installed: map[string]string{daemon: ""}, + running: map[string]string{daemon: "1.9.8"}, + want: nil, + }, + { + name: "nothing running verifies nothing", + installed: map[string]string{daemon: "1.9.0"}, + running: nil, + want: nil, + }, + { + name: "an unstamped running build is unverifiable, not wrong", + installed: map[string]string{daemon: "1.9.0"}, + running: map[string]string{daemon: releaseupdate.VersionDev}, + want: nil, + }, + { + name: "an unstamped claim asserts nothing to contradict", + installed: map[string]string{daemon: releaseupdate.VersionDev}, + running: map[string]string{daemon: "1.9.0"}, + want: nil, + }, + { + name: "an upper-case tag prefix does not manufacture drift", + installed: map[string]string{daemon: "V1.9.0"}, + running: map[string]string{daemon: "1.9.0"}, + want: nil, + }, + { + name: "a tag-shaped claim matches the stamped version it names", + installed: map[string]string{daemon: "v1.9.0"}, + running: map[string]string{daemon: "1.9.0"}, + want: nil, + }, + { + name: "surrounding whitespace does not manufacture drift", + installed: map[string]string{daemon: " 1.9.0\n"}, + running: map[string]string{daemon: "1.9.0"}, + want: nil, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + report := releaseupdate.Report{Previous: test.previous, Installed: test.installed} + got := report.Verify(test.running).Drift + if len(got) != len(test.want) { + t.Fatalf("Verify().Drift = %#v, want %#v", got, test.want) + } + for i := range test.want { + if got[i] != test.want[i] { + t.Errorf("Verify().Drift[%d] = %#v, want %#v", i, got[i], test.want[i]) + } + } + }) + } +} + +// TestVerifyPartitionsEveryClaim proves each claimed component lands in +// exactly one of Confirmed/Drift/Unverified. Callers word their message from +// which set is non-empty, so a component silently falling into none of them +// (or into two) is what would let an unchecked claim be reported as a +// checked one. +func TestVerifyPartitionsEveryClaim(t *testing.T) { + tests := []struct { + name string + claimed string + running string + wantConfirmed bool + wantDrift bool + wantUnverified bool + }{ + {name: "agreeing versions confirm", claimed: "1.9.0", running: "1.9.0", wantConfirmed: true}, + {name: "disagreeing versions drift", claimed: "1.9.0", running: "1.9.8", wantDrift: true}, + {name: "unrecorded claim is unverified", claimed: releaseupdate.VersionUnknown, running: "1.9.8", wantUnverified: true}, + {name: "unstamped runner is unverified", claimed: "1.9.0", running: releaseupdate.VersionDev, wantUnverified: true}, + {name: "absent runner is unverified", claimed: "1.9.0", running: "", wantUnverified: true}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + report := releaseupdate.Report{Installed: map[string]string{daemon: test.claimed}} + got := report.Verify(map[string]string{daemon: test.running}) + + total := len(got.Confirmed) + len(got.Drift) + len(got.Unverified) + if total != 1 { + t.Fatalf("claim landed in %d sets, want exactly 1: %#v", total, got) + } + if (len(got.Confirmed) == 1) != test.wantConfirmed { + t.Errorf("Confirmed = %v, want confirmed=%v", got.Confirmed, test.wantConfirmed) + } + if (len(got.Drift) == 1) != test.wantDrift { + t.Errorf("Drift = %#v, want drift=%v", got.Drift, test.wantDrift) + } + if (len(got.Unverified) == 1) != test.wantUnverified { + t.Errorf("Unverified = %v, want unverified=%v", got.Unverified, test.wantUnverified) + } + }) + } +} + +// TestVerifyIgnoresUnclaimedRunningComponents proves a component +// that is running but was never part of the update is not treated as drift: +// the claim set is what is under test, not the inventory. +func TestVerifyIgnoresUnclaimedRunningComponents(t *testing.T) { + report := releaseupdate.Report{Installed: map[string]string{daemon: "1.9.0"}} + running := map[string]string{daemon: "1.9.0", agent: "0.0.1"} + + if got := report.Verify(running).Drift; len(got) != 0 { + t.Fatalf("Verify().Drift = %#v, want no drift", got) + } +} + +// TestVerifyOrdersDriftStably guards the sort, which callers rely on +// to render a stable message. +// +// The component count is load-bearing and is NOT about permutations. Go +// randomizes a small map's iteration start offset rather than its order, so +// up to 8 keys in one bucket come out as a rotation -- an unsorted +// implementation still emits sorted output about 1/n of the time, not 1/n!. +// Measured against this code with the sort removed: 2 components pass 87% of +// the time and 8 pass 12%, while 9 crosses into bucket-order randomization +// and passes 0 times in 200,000. Nine is therefore the first count that +// fails an unsorted implementation on a single attempt; the repeats are +// belt-and-braces. Do not reduce either number. +func TestVerifyOrdersDriftStably(t *testing.T) { + const components = 9 + installed := make(map[string]string, components) + running := make(map[string]string, components) + want := make([]string, 0, components) + for i := range components { + id := fmt.Sprintf("component-%d", i) + installed[id] = "2.0.0" + running[id] = "1.0.0" + want = append(want, id) + } + sort.Strings(want) + report := releaseupdate.Report{Installed: installed} + + for attempt := range 25 { + drift := report.Verify(running).Drift + if len(drift) != components { + t.Fatalf("attempt %d: Verify().Drift returned %d drifts, want %d", attempt, len(drift), components) + } + for i, id := range want { + if drift[i].ID != id { + t.Fatalf("attempt %d: drift[%d].ID = %q, want %q (order is not stable)", attempt, i, drift[i].ID, id) + } + } + } +}