fix(apply,shaterd): a downgraded build may not RUN a config it can only half-read

model.WriteUCI already refuses to write a config whose schema is newer than the
build, so a downgrade can no longer eat the file. What was still open was
RUNNING one. ParseUCIExport ignores options it does not recognise — silently —
so a v3 config read by a v2 build yields a Model with the v3 settings simply
absent. The engine starts perfectly happily and routes traffic by a policy
nobody wrote. Nothing said so: cmdRun never called Migrate(), /etc/init.d/shater
calls it, logs one daemon.err line on failure and starts us anyway, and that log
defaults to a tmpfs file globals.log_syslog='0' can switch off entirely.

REFUSE OR START — and why refuse. Both sides, weighed by "the default falls to
the recoverable side":

  * REFUSE. With kill_switch=closed the fail-closed plane goes up and LAN->WAN
    forwarding stops. Loud, immediate, impossible to miss. SSH, LuCI and the
    panel stay reachable, nothing on disk changes, and reinstalling the build
    the router ran ten minutes ago puts everything back exactly as it was. The
    damage is an outage the operator caused themselves and can undo.
  * START ANYWAY. Traffic the missing rules were meant to tunnel leaves through
    the plain WAN with the router's real address on it, and nothing announces
    it. That is not recoverable in the sense that matters — the disclosure has
    already happened. It is the same choice `sub update` made when it was given
    FAIL over a silent direct fetch.

So: refuse. But the daemon does NOT exit and does not crash-loop — a refusal
nobody can see would be the third bad option. It stays up, keeps serving the
panel and the control socket, and says why in three places:

  1. apply.schemaDowngradeGate refuses every apply (step 0 of applyLocked), with
     the engine-swap failure policy of step 2: a previous engine that IS running
     a config this build understood is left alone; with no engine, holdLocked
     installs the fail-closed plane — and honours kill_switch=open, which is the
     operator's documented fail-open choice and may not be quietly overridden.
     This is in applyLocked and not only in cmdRun on purpose: cron reconciles
     once a minute, so a gate that only ran at startup would be bypassed sixty
     seconds later.
  2. Status carries the PAIR: schema_version (disk) and schema_supported
     (model.CurrentSchemaVersion). Either alone is unreadable — the panel
     already showed the disk version, and "v3" next to a build that understands
     v2 looks entirely normal. The difference IS the fault. schema_supported is
     a compile-time constant and is therefore set even on the offline stub, i.e.
     on the daemon most likely not to be answering. A critical warning naming
     the downgrade is computed at READ time, because in this state no apply can
     succeed and "the warnings of the last successful apply" would be empty.
  3. cmdRun consults model.Migrate() before reading the config (so a bare
     `shaterd run` gets the gate too) and classifies the outcome with
     CheckConfigWritable: ErrSchemaTooNew is the downgrade, anything else is an
     ordinary migration failure and is NOT reported as one.

Only ErrSchemaTooNew blocks. ErrUnmigratedConfig — schema-v1 dst_domain/dst_ip
leftovers — must not: the init script documents starting anyway with those rules
disabled, and turning that into a blackout would be a regression.

Also in this pass, reported by the coordinator: standing_state_test.go's
noGatewayFinding claimed to be quoted from netplane "so the test breaks if that
warning is ever reworded". It cannot — the string never leaves this package and
netplane.noGatewayWarning is never called — and the claim was already false when
it was read: netplane's text has since gained "over IPv4" and an IPv6 clause
while every test here stayed green. A fixture that advertises a guarantee it
does not provide is worse than one that advertises nothing. The comment now says
what it is, and netplanechannel_test.go pins the two couplings that are real:
the severity comes from the CHANNEL (warningFromText(t, "interface",
SeverityCritical), no classify pass), so no rewording can demote it — with the
control that the same texts on the generate channel are NOT critical — while
Section/Name DO come from the `kind "name": ` prefix, asserted in both
directions. A genuine text link is one exported helper in netplane away and is
left to whoever owns that file.

Verified: 13 seeded mutations. Twelve killed by named assertions; the
thirteenth SURVIVED — the guard in schemaWriteVerdict could not be seen, because
on a build host model.CheckConfigWritable answers nil for everything, so the
test reported success whether the guard was there or not. The checker is now
injected and both directions of that guard are killed. Every schema assertion is
walked over all three relations (disk newer / equal / older), so nothing here
passes by always answering the same way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BHw89tdWddzhjUc4bAH4tS
This commit is contained in:
omarandClaude Opus 5 committed 2026-07-27 11:05:10 +03:00
1 parent da7411e29a
commit b43f673ad2
7 files changed
+791 -8

No files matched your search

+124 -3
View File
@@ -718,6 +718,20 @@ func (a *Applier) applyLocked(m *model.Model) (bool, error) {
// boundary crossed mid-apply cannot yield an engine plan and an nft plan that
// disagree about which rules are in force.
now := time.Now()
// (0) SCHEMA GATE. Refuse to build anything at all from a configuration whose
// schema this build does not understand. See schemaDowngradeGate.
//
// The failure policy is the engine-swap policy of step (2), for the same
// reason: a previous engine that is still running a config this build DID
// understand is better than nothing, so it is left alone; with no engine at all
// there is nothing protecting the LAN, and holdLocked (which honours
// kill_switch=open) is what closes that.
if serr := schemaDowngradeGate(m); serr != nil {
if !a.eng.Running() {
a.holdLocked(m, serr)
}
return false, serr
}
// (1) generate.
opts, warnings, err := generate.GenerateWithWarningsAt(m, now)
if err != nil {
@@ -1898,9 +1912,9 @@ func ActiveFlagPresent() bool {
// predecessor config. When false the panel hides the rollback control
// (there is nothing to roll back to).
type Status struct {
Running bool `json:"running"`
Enabled bool `json:"enabled"`
Active bool `json:"active"`
Running bool `json:"running"`
Enabled bool `json:"enabled"`
Active bool `json:"active"`
Table bool `json:"table"`
Hash string `json:"hash"`
KillSwitch string `json:"kill_switch"`
@@ -1931,6 +1945,23 @@ type Status struct {
// only render the warning list still show it.
ConfigError string `json:"config_error"`
// SchemaVersion is the schema version of the configuration ON DISK, and
// SchemaSupported is the highest this BUILD understands
// (model.CurrentSchemaVersion).
//
// They exist as a PAIR because either one alone is unreadable. The panel already
// showed the disk version, which on a downgraded router reads "v3" and looks
// entirely normal next to a build that understands v2 — and a v3 config parsed
// by a v2 build loses every option v2 does not know, silently, because
// ParseUCIExport ignores what it does not recognise. The difference between the
// two numbers IS the fault; neither number shows it on its own.
//
// SchemaSupported is a compile-time constant and is therefore ALWAYS set, on
// every status including the offline stub. SchemaVersion is read from the
// config and is only meaningful with config_readable=true; 0 means "not read".
SchemaVersion int `json:"schema_version"`
SchemaSupported int `json:"schema_supported"`
// EngineRunning is whether a sing-box instance is actually started.
//
// It was added as the honest field to stand beside a `running` that was hard-wired
@@ -2056,6 +2087,9 @@ func (a *Applier) Status() Status {
EngineRunning: engineUp,
Traffic: a.Traffic(),
Warnings: a.warningsWith(engineUp),
// A compile-time constant: it is known whether or not anything else could be
// read, and it is the half of the pair that makes the other half legible.
SchemaSupported: model.CurrentSchemaVersion,
}
s.StartedUnix, s.UptimeSeconds = processUptime(time.Now())
switch {
@@ -2092,6 +2126,34 @@ func (a *Applier) Status() Status {
s.Enabled = m.Globals.Enabled
s.KillSwitch = m.Globals.KillSwitch
s.PanelPort = effectivePanelPort(m.Globals.PanelPort)
s.SchemaVersion = m.Globals.SchemaVersion
// The DOWNGRADE, said in the one place every consumer already renders.
//
// It is computed at READ time, like the unreadable-config warning below and
// for the same reason — but here the reason is sharper: in this state no
// apply can succeed (schemaDowngradeGate refuses them all), so the warning
// set published by "the last successful apply" is empty or belongs to a
// previous build, and a fault that blocks every apply would be the one fault
// with no way to reach the panel at all.
//
// Strictly greater: an OLDER schema on disk is the ordinary
// upgrade case that `shaterd migrate` exists for, and an equal one is
// healthy. Neither may raise this.
if s.SchemaVersion > s.SchemaSupported {
s.Warnings = append([]Warning{{
Severity: SeverityCritical,
Section: "config",
Name: "schema",
Message: fmt.Sprintf("/etc/config/shater is schema v%d and this build understands only v%d — "+
"the shater package was DOWNGRADED under a configuration a newer build wrote. Nothing is "+
"being applied and nothing on disk has been changed: a v%d config read by a v%d build "+
"silently loses every setting v%d added, so running it would route your traffic by a "+
"policy you never wrote. Saves are refused for the same reason. Install the build this "+
"router ran before the downgrade (see docs-shater/INSTALL.md) and the configuration is "+
"exactly as you left it.",
s.SchemaVersion, s.SchemaSupported, s.SchemaVersion, s.SchemaSupported, s.SchemaVersion),
}}, s.Warnings...)
}
} else {
s.ConfigError = err.Error()
// Say it in the warning list too, and not only in a new field. The warning
@@ -2130,6 +2192,65 @@ func effectivePanelPort(configured int) int {
// MarshalJSON is a convenience so callers can json.Marshal a Status directly.
func (s Status) JSON() ([]byte, error) { return json.MarshalIndent(s, "", " ") }
// --- the schema gate ----------------------------------------------------------
// checkConfigWritable is model.CheckConfigWritable behind a seam. Production
// reads /etc/config/shater through the model's own uci runner; a test cannot
// stage that from here, and what this gate DOES with each verdict is the part
// worth pinning.
var checkConfigWritable = model.CheckConfigWritable
// schemaDowngradeGate refuses an apply when /etc/config/shater carries a schema
// version this build does not understand — i.e. the package was DOWNGRADED under
// a config a newer build wrote.
//
// WHY REFUSING IS THE RECOVERABLE SIDE. model.WriteUCI already refuses to WRITE
// in this state, so the file is safe. What was left open is RUNNING: ParseUCIExport
// ignores options it does not know, silently, so a v3 config read by a v2 build
// yields a Model with the v3 settings simply missing. The engine then starts
// perfectly happily and routes traffic by a policy the operator never wrote —
// and nothing anywhere says so. Weigh the two outcomes:
//
// - REFUSE. With kill_switch=closed the fail-closed plane goes up and LAN->WAN
// forwarding stops: loud, immediate, impossible to miss. SSH, LuCI and the
// panel stay reachable, nothing on disk changes, and reinstalling the build
// the router ran before the downgrade puts everything back exactly as it was.
// The damage is an outage the operator caused ten seconds earlier and can
// undo.
// - START ANYWAY. Traffic that the missing rules were meant to tunnel leaves
// through the plain WAN with the router's real address on it. That is not
// recoverable in the sense that matters: the disclosure has already happened,
// and nothing announces it — the very definition of the failure this project
// keeps paying for. (This is the same reasoning that made `sub update` FAIL
// rather than fall back to a direct fetch.)
//
// So the default falls to the recoverable side and the apply is refused. The
// daemon does NOT exit: it stays up, keeps serving the panel and the control
// socket, and publishes the reason (Status.SchemaVersion vs SchemaSupported plus
// a critical warning computed at READ time, so it is visible even though no apply
// ever succeeded to publish a warning set).
//
// ONLY ErrSchemaTooNew blocks. ErrUnmigratedConfig — a config still carrying the
// schema-v1 dst_domain/dst_ip on some rules — must NOT: /etc/init.d/shater starts
// anyway in that case by documented design, with those rules disabled, and
// turning it into a blackout would be a regression.
//
// An unreadable or unparseable export produces no verdict at all (the model
// treats it as "nothing to protect", because it cannot be told apart from a fresh
// install). That case is not silently ignored here — it is the ReadUCI failure
// that cmd/shaterd's armOnUnreadableConfig already covers, loudly.
func schemaDowngradeGate(m *model.Model) error {
err := checkConfigWritable(m)
if err == nil || !errors.Is(err, model.ErrSchemaTooNew) {
return nil
}
return fmt.Errorf("REFUSING to apply this configuration: %w. Applying it would be worse than "+
"not running: options this build does not know are dropped SILENTLY when the config is parsed, "+
"so the engine would start and route your traffic by a policy you never wrote, with no sign "+
"anywhere that anything was missing. Nothing on disk has been changed. Install the shater build "+
"this router ran before the downgrade and everything is exactly as you left it", err)
}
// --- configuration history --------------------------------------------------
//
// WHAT IT IS. Every successful apply that CHANGES the configuration files a copy
+98
View File
@@ -0,0 +1,98 @@
package apply
// What this package actually depends on in netplane's WORDING.
//
// standing_state_test.go's noGatewayFinding used to claim it was quoted from
// netplane so that a rewording would break a test here. It was not, and it did
// not: netplane's text has since gained "over IPv4" and an IPv6 clause while
// every test in this package stayed green. Rather than leave the promise
// unbacked or fake a link that does not exist, the two real couplings are named
// and pinned here — one that a rewording CANNOT break (by design, and that is
// worth knowing) and one that it CAN.
//
// Every case is walked in both directions, so neither result can be an artifact
// of an instrument that only ever answers one way.
import (
"testing"
"github.com/sagernet/sing-box/shater/model"
)
// TestNetplaneChannelSeverityIsIndependentOfWording pins the fact that makes the
// old promise unnecessary: a finding that arrives on the netplane channel is
// graded critical because of WHERE IT CAME FROM, not because of any word in it
// (gatherWarnings: warningFromText(t, "interface", SeverityCritical), with no
// classify() pass — unlike the generate channel). netplane may therefore reword
// freely and the panel will still highlight it.
func TestNetplaneChannelSeverityIsIndependentOfWording(t *testing.T) {
m := &model.Model{Globals: model.DefaultGlobals()}
texts := []string{
noGatewayFinding,
// Deliberately shares no vocabulary with the sample above, and carries none
// of the free-text markers classify() looks for.
`egress "wan2": zzz qqq`,
// No entity prefix at all.
`something entirely different happened`,
}
for _, text := range texts {
ws := gatherWarnings(m, nil, []string{text}, nil)
w, ok := findFinding(ws, text[len(text)-4:])
if !ok {
t.Fatalf("a netplane finding was dropped on the floor: %q", text)
}
if w.Severity != SeverityCritical {
t.Fatalf("netplane finding %q came out %q, want critical — the grade must come from the "+
"channel, so no rewording can quietly demote it", text, w.Severity)
}
}
// CONTROL: the very same texts on the GENERATE channel are NOT critical. Without
// this, an implementation that graded everything critical would pass above.
for _, text := range []string{`egress "wan2": zzz qqq`, `something entirely different happened`} {
ws := gatherWarnings(m, []string{text}, nil, nil)
w, ok := findFinding(ws, text[len(text)-4:])
if !ok {
t.Fatalf("a generate finding was dropped on the floor: %q", text)
}
if w.Severity == SeverityCritical {
t.Fatalf("control failed: %q is critical on the generate channel too, so the check above "+
"proves nothing about the netplane channel", text)
}
}
}
// TestNetplaneFindingAttributionComesFromTheEntityPrefix pins the coupling that a
// rewording CAN break: the panel groups and deep-links a finding by Section/Name,
// and those are recovered from the `kind "name": ` prefix by entityRe. A netplane
// warning that dropped the prefix would still be critical and still be shown — it
// would simply stop being attributable to the egress it is about.
func TestNetplaneFindingAttributionComesFromTheEntityPrefix(t *testing.T) {
m := &model.Model{Globals: model.DefaultGlobals()}
with := gatherWarnings(m, nil, []string{`egress "wan2": no IPv4 gateway`}, nil)
w, ok := findFinding(with, "no IPv4 gateway")
if !ok {
t.Fatal("the prefixed finding vanished")
}
if w.Section != "egress" || w.Name != "wan2" {
t.Fatalf("section/name = %q/%q, want egress/wan2 — the panel deep-links on these", w.Section, w.Name)
}
if w.Message != "no IPv4 gateway" {
t.Fatalf("the prefix must be consumed, not repeated: %q", w.Message)
}
// The other direction: no prefix, so the finding falls back to the channel's
// default section and carries no name. Stating it here is what makes the
// dependency visible to whoever next rewords a netplane warning.
without := gatherWarnings(m, nil, []string{`no IPv4 gateway for wan2`}, nil)
w, ok = findFinding(without, "no IPv4 gateway")
if !ok {
t.Fatal("the unprefixed finding vanished")
}
if w.Section != "interface" || w.Name != "" {
t.Fatalf("section/name = %q/%q, want interface/\"\" — a netplane warning without the "+
"`kind \"name\": ` prefix cannot be attributed to an entity", w.Section, w.Name)
}
}
+232
View File
@@ -0,0 +1,232 @@
package apply
// Tests for the schema gate (apply.go, "the schema gate") and for the pair of
// numbers Status publishes so the state is visible without an apply.
//
// The instrument is proved to DISCRIMINATE, not merely to fire: every case is
// walked against all three schema relations — the config on disk NEWER than this
// build, EQUAL to it, and OLDER (which is the ordinary upgrade path and must
// behave exactly as before). A gate that refused everything, or a warning that
// always appeared, would pass a one-sided test.
import (
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-box/shater/engine"
"github.com/sagernet/sing-box/shater/model"
)
// stubWritable points the gate's seam at a fixed verdict for one test.
func stubWritable(t *testing.T, verdict error) {
t.Helper()
prev := checkConfigWritable
checkConfigWritable = func(*model.Model) error { return verdict }
t.Cleanup(func() { checkConfigWritable = prev })
}
func TestSchemaGateRefusesOnlyTheDowngrade(t *testing.T) {
tooNew := fmt.Errorf("%w: /etc/config/shater is schema v3 and this build understands only v2",
model.ErrSchemaTooNew)
for _, tc := range []struct {
name string
verdict error
refuse bool
}{
{"disk newer than this build", tooNew, true},
{"disk equal to this build", nil, false},
// The schema-v1 leftovers case. /etc/init.d/shater documents that the daemon
// starts anyway with those rules disabled; turning it into a blackout would
// be a regression, so it must NOT be caught by this gate.
{"disk older, not fully migrated", fmt.Errorf("%w: rules still carry dst_domain",
model.ErrUnmigratedConfig), false},
// A real I/O failure is not a schema verdict either.
{"the check itself failed", errors.New("uci: no such file"), false},
} {
t.Run(tc.name, func(t *testing.T) {
stubWritable(t, tc.verdict)
err := schemaDowngradeGate(&model.Model{})
if tc.refuse && err == nil {
t.Fatal("the gate let a downgraded configuration through")
}
if !tc.refuse && err != nil {
t.Fatalf("the gate refused a configuration it must accept: %v", err)
}
if tc.refuse && !errors.Is(err, model.ErrSchemaTooNew) {
t.Fatalf("the refusal does not carry ErrSchemaTooNew, so no caller can classify it: %v", err)
}
if tc.refuse && !strings.Contains(err.Error(), "Nothing on disk has been changed") {
t.Fatalf("the refusal does not tell the operator the config is safe: %v", err)
}
})
}
}
func TestApplyRefusesADowngradedConfigAndHoldsTheLAN(t *testing.T) {
applied := 0
restore := stubApplyStages(t,
func(*Applier, option.Options) (bool, error) { applied++; return true, nil },
func(*Applier, *model.Model, option.Options, time.Time) (planeOutcome, error) {
return planeOutcome{}, nil
})
defer restore()
// The holding plane must be INSTALLED, not merely intended: intercept the
// loader so what would reach the kernel is observable without one.
held := 0
origHold := applyHoldNft
applyHoldNft = func(string) error { held++; return nil }
t.Cleanup(func() { applyHoldNft = origHold })
// holdModel: RenderHoldNft needs a real inbound to have anything to hold.
m := holdModel("closed")
// (1) Downgraded: no engine is built, and the LAN is held shut.
stubWritable(t, fmt.Errorf("%w: schema v3 vs v2", model.ErrSchemaTooNew))
a := New(engine.New(), nil)
a.mu.Lock()
_, err := a.applyLocked(m)
a.mu.Unlock()
if err == nil {
t.Fatal("applyLocked accepted a configuration this build cannot read")
}
if !errors.Is(err, model.ErrSchemaTooNew) {
t.Fatalf("the apply error is not classifiable: %v", err)
}
if applied != 0 {
t.Fatalf("the engine was handed a configuration parsed with settings missing (%d applies)", applied)
}
if held == 0 {
t.Fatal("nothing was applied AND the LAN was left forwarding in the clear: no holding plane")
}
if !a.Holding() {
t.Fatal("the daemon does not report that it is holding the LAN")
}
// (2) CONTROL: the very same applier, the same model, the same stubs — with the
// schema verdict clear the apply goes through and the engine IS built. Without
// this, a gate that refused unconditionally would pass every check above.
stubWritable(t, nil)
a2 := New(engine.New(), nil)
a2.mu.Lock()
_, err = a2.applyLocked(m)
a2.mu.Unlock()
if err != nil {
t.Fatalf("control failed: an ordinary configuration was also refused: %v", err)
}
if applied != 1 {
t.Fatalf("control failed: the engine was not built for a healthy config (%d applies)", applied)
}
if a2.Holding() {
t.Fatal("control failed: a successful apply still reports the LAN held")
}
}
func TestApplyDowngradeRefusalHonoursAnOpenKillSwitch(t *testing.T) {
restore := stubApplyStages(t,
func(*Applier, option.Options) (bool, error) { return true, nil },
func(*Applier, *model.Model, option.Options, time.Time) (planeOutcome, error) {
return planeOutcome{}, nil
})
defer restore()
held := 0
origHold := applyHoldNft
applyHoldNft = func(string) error { held++; return nil }
t.Cleanup(func() { applyHoldNft = origHold })
stubWritable(t, fmt.Errorf("%w: schema v3 vs v2", model.ErrSchemaTooNew))
a := New(engine.New(), nil)
a.mu.Lock()
_, err := a.applyLocked(holdModel("open"))
a.mu.Unlock()
if err == nil {
t.Fatal("the refusal did not happen at all")
}
if held != 0 {
t.Fatal("kill_switch=open is the operator's documented fail-open choice; " +
"the refusal must not quietly override it")
}
// Control: with the switch CLOSED the same refusal DOES install the plane, so
// "nothing installed" above is the open switch and not a broken instrument.
a2 := New(engine.New(), nil)
a2.mu.Lock()
_, _ = a2.applyLocked(holdModel("closed"))
a2.mu.Unlock()
if held == 0 {
t.Fatal("control failed: the refusal installs no plane even with the kill switch closed")
}
}
func TestStatusPublishesTheSchemaPairAndNamesADowngrade(t *testing.T) {
origRead := readConfig
t.Cleanup(func() { readConfig = origRead })
for _, tc := range []struct {
name string
onDisk int
wantWarn bool
}{
{"newer than this build", model.CurrentSchemaVersion + 1, true},
{"equal to this build", model.CurrentSchemaVersion, false},
{"older than this build", model.CurrentSchemaVersion - 1, false},
} {
t.Run(tc.name, func(t *testing.T) {
readConfig = func() (*model.Model, error) {
return &model.Model{Globals: model.Globals{
Enabled: true, KillSwitch: "closed", SchemaVersion: tc.onDisk,
}}, nil
}
s := New(engine.New(), nil).Status()
if s.SchemaSupported != model.CurrentSchemaVersion {
t.Fatalf("schema_supported = %d, want %d — without it schema_version is unreadable",
s.SchemaSupported, model.CurrentSchemaVersion)
}
if s.SchemaVersion != tc.onDisk {
t.Fatalf("schema_version = %d, want the %d that is on disk", s.SchemaVersion, tc.onDisk)
}
w, found := findFinding(s.Warnings, "DOWNGRADED")
if tc.wantWarn && !found {
t.Fatalf("a config newer than the build raised no warning; warnings: %+v", s.Warnings)
}
if !tc.wantWarn && found {
t.Fatalf("an ordinary schema raised a downgrade warning: %+v", w)
}
if tc.wantWarn && w.Severity != SeverityCritical {
t.Fatalf("severity %q: silently mis-routing every packet is not a note", w.Severity)
}
if tc.wantWarn && s.Warnings[0].Name != "schema" {
t.Fatalf("the downgrade must be first (critical-first ordering), got %q", s.Warnings[0].Name)
}
})
}
}
func TestStatusSchemaSupportedSurvivesAnUnreadableConfig(t *testing.T) {
origRead := readConfig
readConfig = func() (*model.Model, error) { return nil, errors.New("uci: no such file") }
t.Cleanup(func() { readConfig = origRead })
s := New(engine.New(), nil).Status()
if s.SchemaSupported != model.CurrentSchemaVersion {
t.Fatalf("schema_supported = %d: it is a compile-time constant and must not depend on a read",
s.SchemaSupported)
}
if s.SchemaVersion != 0 {
t.Fatalf("schema_version = %d after a failed read: it must stay 0 (\"not read\"), never a guess",
s.SchemaVersion)
}
// Control: the same field IS populated when the read succeeds, so the 0 above
// is the failure and not a field nobody ever sets.
readConfig = func() (*model.Model, error) {
return &model.Model{Globals: model.Globals{SchemaVersion: model.CurrentSchemaVersion}}, nil
}
if got := New(engine.New(), nil).Status().SchemaVersion; got != model.CurrentSchemaVersion {
t.Fatalf("control failed: schema_version = %d on a good read", got)
}
}
+19 -5
View File
@@ -41,11 +41,25 @@ func init() {
readConfig = func() (*model.Model, error) { return &model.Model{Globals: model.DefaultGlobals()}, nil }
}
// noGatewayFinding is netplane/apply.go's real text for the fault this is all
// about, shortened to its load-bearing clause: an egress that was BUILT, reports as
// applied everywhere in the UI, and cannot carry a packet off its own subnet.
// Quoted rather than invented so the test breaks if that warning is ever reworded
// out of the critical class.
// noGatewayFinding is a SAMPLE of the kind of text netplane puts on the routing
// channel: an egress that was BUILT, reports as applied everywhere in the UI, and
// cannot carry a packet off its own subnet. The tests below inject it and then
// look for it again, which is all it is for.
//
// IT IS NOT A LINK TO NETPLANE, and this comment used to say it was — "quoted so
// the test breaks if that warning is ever reworded". It cannot: the string never
// leaves this package, and netplane.noGatewayWarning is never called. The claim
// was already false when it was read: netplane's real text has since gained
// "over IPv4" and a whole IPv6 clause, and every test in this package stayed
// green. A fixture that advertises a guarantee it does not provide is worse than
// one that advertises nothing, because the guarantee gets relied on.
//
// The two properties that DO couple this package to netplane's wording are
// pinned, for real, in netplanechannel_test.go: the severity comes from the
// CHANNEL and no rewording can drop it out of critical, while the Section/Name a
// finding is filed under DOES come from its `kind "name": ` prefix. Restoring a
// genuine text link would take one exported helper in netplane
// (noGatewayWarning); until that exists, nothing here may claim to have one.
const noGatewayFinding = `egress "wan2": no IPv4 gateway could be found for interface "wan2" (device eth1) ` +
`by any means, so its routing table sends traffic straight onto the local segment. The device is not ` +
`point-to-point, so this egress CANNOT REACH ANYTHING outside its own subnet — every node, group and ` +
+41
View File
@@ -253,7 +253,27 @@ func cmdRun() int {
// listen address (globals.panel_port), and the stats-retention knobs. On a read
// error we stay up with zero-value globals (panel falls back to the env gate below,
// and the aggregator's Config{} uses its built-in defaults).
// THE SCHEMA GATE, before the config is read — because a migration that runs
// would change what a read returns.
//
// /etc/init.d/shater runs `shaterd migrate` and, on failure, logs one
// daemon.err line and starts us anyway. The daemon itself never asked, so the
// one state that machinery exists to catch — the package DOWNGRADED under a
// config a newer build wrote — reached a running daemon as nothing but a syslog
// line, in a log globals.log_syslog='0' switches off. Migrate() already refuses
// a newer schema; this consults that same refusal rather than deriving a second
// one, and CheckConfigWritable classifies it (ErrSchemaTooNew is the downgrade;
// anything else is an ordinary migration failure and must NOT be treated as
// one). A bare `shaterd run` with no init script gets the same gate.
migrateErr := model.Migrate()
m, readErr := model.ReadUCI()
if level, msg := schemaGateReport(migrateErr, schemaWriteVerdict(m, readErr)); msg != "" {
if level == schemaGateRefusing {
logger.Error(msg)
} else {
logger.Warn(msg)
}
}
if readErr == nil {
// Apply the operator's log settings as early as possible; later changes
// arrive through the Applier's Reconcile hook. On a read error the sink
@@ -1156,17 +1176,38 @@ func offlineStatusStub(read func() (*model.Model, error), active, table bool) ap
Running: false,
Active: active,
Table: table,
// A compile-time constant, so the stub knows it as well as the daemon does.
// It is the half that makes schema_version legible: on a DOWNGRADED router
// the disk says v3 and looks perfectly normal until it is read next to the
// v2 this build understands — and a downgraded daemon is exactly the one
// that may not be answering.
SchemaSupported: model.CurrentSchemaVersion,
}
m, err := read()
if err == nil {
s.ConfigReadable = true
s.Enabled = m.Globals.Enabled
s.KillSwitch = m.Globals.KillSwitch
s.SchemaVersion = m.Globals.SchemaVersion
// The configured panel port, or the built-in default when unset —
// the same mapping as the live path's effectivePanelPort.
if s.PanelPort = m.Globals.PanelPort; s.PanelPort == 0 {
s.PanelPort = 8088
}
if s.SchemaVersion > s.SchemaSupported {
s.Warnings = append(s.Warnings, apply.Warning{
Severity: apply.SeverityCritical,
Section: "config",
Name: "schema",
Message: fmt.Sprintf("no daemon answered, and /etc/config/shater is schema v%d while this "+
"build understands only v%d — the shater package was DOWNGRADED under a configuration a "+
"newer build wrote. That is very likely WHY nothing is running: this build refuses to "+
"apply a configuration it would have to read with settings missing. Nothing on disk has "+
"been changed. Install the build this router ran before the downgrade (see "+
"docs-shater/INSTALL.md) and the configuration is exactly as you left it.",
s.SchemaVersion, s.SchemaSupported),
})
}
return s
}
s.ConfigError = err.Error()
+91
View File
@@ -0,0 +1,91 @@
//go:build linux
package main
// The daemon's own reading of the UCI schema state at startup.
//
// WHAT WAS MISSING. model.Migrate() has refused a config newer than the build
// since it was written, and model.WriteUCI now refuses to write one — so a
// DOWNGRADE (a v2 package installed under a config a v3 build wrote) can no
// longer eat the configuration. What it could still do is RUN: /etc/init.d/shater
// calls `shaterd migrate`, logs one daemon.err line if it fails, and starts the
// daemon anyway; cmdRun never asked. ParseUCIExport ignores options it does not
// recognise, silently, so the daemon would come up on a config with the newer
// build's settings simply absent and route traffic by a policy nobody wrote.
//
// apply.schemaDowngradeGate is what actually refuses to apply in that state, and
// apply.Status carries the pair of numbers that makes it visible. This file is
// the third piece: the daemon says it, by name, at the moment it starts, with the
// two failures kept apart — a downgrade is not the same event as a migration that
// could not write.
import (
"errors"
"fmt"
"github.com/sagernet/sing-box/shater/model"
)
// The two levels schemaGateReport can return. Positive and closed: there is no
// third, and "" is the fourth state ("nothing to report"), which is why the
// caller keys on the MESSAGE being empty rather than on the level.
const (
schemaGateRefusing = "refusing" // the config is newer than this build
schemaGateDegraded = "degraded" // the migration did not complete, for another reason
)
// schemaWriteVerdict is model.CheckConfigWritable applied to the config as read,
// or nil when there was nothing to ask about. Kept separate from
// schemaGateReport so the classification below is a pure function of two errors
// and can be exercised for all four combinations.
func schemaWriteVerdict(m *model.Model, readErr error) error {
return schemaWriteVerdictWith(model.CheckConfigWritable, m, readErr)
}
// schemaWriteVerdictWith is the same with the checker injected.
//
// The seam is not decoration. Without it the guard below can only be tested on a
// host that HAS a working `uci` and a config to disagree with — and on a build
// host, where there is neither, model.CheckConfigWritable answers nil for
// everything, so a test would report "the guard works" whether the guard was
// there or not. That is the instrument-with-no-control this project keeps
// finding, and it was found here: the first seeded mutation of this function
// SURVIVED against the un-seamed version.
func schemaWriteVerdictWith(check func(*model.Model) error, m *model.Model, readErr error) error {
if readErr != nil || m == nil {
// An unreadable config is a different fault with its own loud path
// (armOnUnreadableConfig). Reporting a schema verdict derived from a config
// nobody could read would be an invention.
return nil
}
return check(m)
}
// schemaGateReport turns the two verdicts into one operator-facing line.
//
// migrateErr is model.Migrate()'s result; writeErr is model.CheckConfigWritable's.
// The DOWNGRADE is identified by ErrSchemaTooNew on the write verdict, not by the
// text of the migration error — Migrate returns a plain fmt.Errorf, and matching
// its wording would be exactly the kind of fixture that claims a link it does not
// have.
//
// Returns ("", "") when there is nothing to say: schema equal to this build, or
// OLDER and migrated successfully, which is the ordinary upgrade path.
func schemaGateReport(migrateErr, writeErr error) (level, message string) {
if errors.Is(writeErr, model.ErrSchemaTooNew) {
return schemaGateRefusing, fmt.Sprintf("SCHEMA DOWNGRADE — this daemon will NOT apply any "+
"configuration: %v. Nothing on disk has been changed and nothing is being routed by this "+
"build's reading of a config it cannot fully understand. The panel and the control socket "+
"stay up and report the state (schema_version vs schema_supported); with kill_switch=closed "+
"the fail-closed plane is holding LAN->WAN forwarding shut, which is deliberate. Install the "+
"shater build this router ran before the downgrade to get everything back.", writeErr)
}
if migrateErr != nil {
return schemaGateDegraded, fmt.Sprintf("UCI schema migration did not complete: %v. The daemon is "+
"starting anyway — this is NOT a downgrade, so the config is readable and applying it costs "+
"nothing that was not already lost — but routing rules that still carry the removed "+
"dst_domain/dst_ip options stay DISABLED until it succeeds. Free space on /overlay and re-run "+
"`shaterd migrate`, or restart the service.", migrateErr)
}
return "", ""
}
+186
View File
@@ -0,0 +1,186 @@
//go:build linux
package main
// Tests for schemagate.go and for the schema half of the offline status stub.
//
// Both are walked over all three schema relations — disk NEWER than this build,
// EQUAL, and OLDER — so the instrument is shown to DISCRIMINATE. A gate that
// reported a downgrade for every migration failure, or a stub that always
// attached the warning, would pass a one-sided test.
import (
"errors"
"fmt"
"strings"
"testing"
"github.com/sagernet/sing-box/shater/apply"
"github.com/sagernet/sing-box/shater/model"
)
func TestSchemaGateReportSeparatesADowngradeFromAFailedMigration(t *testing.T) {
tooNew := fmt.Errorf("%w: /etc/config/shater is schema v3 and this build understands only v2",
model.ErrSchemaTooNew)
ioFail := errors.New("uci commit shater: No space left on device")
for _, tc := range []struct {
name string
migrateErr, writeErr error
wantLevel string
wantIn string
}{
{
name: "downgrade: migrate refused and the config is unwritable",
// This is the real pairing: migrateWith returns its own refusal AND
// CheckConfigWritable reports ErrSchemaTooNew.
migrateErr: errors.New("config schema v3 newer than this build (v2); upgrade the package"),
writeErr: tooNew,
wantLevel: schemaGateRefusing,
wantIn: "SCHEMA DOWNGRADE",
},
{
name: "downgrade classified from the WRITE verdict, not the migration text",
migrateErr: nil,
writeErr: tooNew,
wantLevel: schemaGateRefusing,
wantIn: "SCHEMA DOWNGRADE",
},
{
name: "an ordinary migration failure is NOT a downgrade",
migrateErr: ioFail,
writeErr: nil,
wantLevel: schemaGateDegraded,
wantIn: "starting anyway",
},
{
name: "an unmigrated config is not a downgrade either",
migrateErr: ioFail,
writeErr: fmt.Errorf("%w: rules still carry dst_domain", model.ErrUnmigratedConfig),
wantLevel: schemaGateDegraded,
wantIn: "dst_domain",
},
{
name: "healthy: nothing to say",
migrateErr: nil,
writeErr: nil,
wantLevel: "",
wantIn: "",
},
} {
t.Run(tc.name, func(t *testing.T) {
level, msg := schemaGateReport(tc.migrateErr, tc.writeErr)
if level != tc.wantLevel {
t.Fatalf("level = %q, want %q (message: %s)", level, tc.wantLevel, msg)
}
if tc.wantLevel == "" {
if msg != "" {
t.Fatalf("a healthy router was told something: %s", msg)
}
return
}
if !strings.Contains(msg, tc.wantIn) {
t.Fatalf("the message does not carry %q: %s", tc.wantIn, msg)
}
if tc.wantLevel == schemaGateRefusing && !strings.Contains(msg, "Nothing on disk has been changed") {
t.Fatalf("the refusal does not reassure the operator about the file: %s", msg)
}
if tc.wantLevel == schemaGateDegraded && strings.Contains(msg, "DOWNGRADE") {
t.Fatalf("an ordinary migration failure was reported as a downgrade: %s", msg)
}
})
}
}
// TestSchemaWriteVerdictInventsNothingForAnUnreadableConfig uses the injected
// checker deliberately. The production checker answers nil for everything on a
// host with no `uci`, so a test that called it would report success whether the
// guard existed or not — and it did: the first seeded mutation of the guard
// SURVIVED until this seam was added.
func TestSchemaWriteVerdictInventsNothingForAnUnreadableConfig(t *testing.T) {
sentinel := fmt.Errorf("%w: v3 vs v2", model.ErrSchemaTooNew)
calls := 0
check := func(*model.Model) error { calls++; return sentinel }
if err := schemaWriteVerdictWith(check, nil, errors.New("uci: no such file")); err != nil {
t.Fatalf("an unreadable config produced a schema verdict: %v", err)
}
if err := schemaWriteVerdictWith(check, &model.Model{}, errors.New("boom")); err != nil {
t.Fatalf("a failed read produced a schema verdict from the model anyway: %v", err)
}
if err := schemaWriteVerdictWith(check, nil, nil); err != nil {
t.Fatalf("a nil model produced a schema verdict: %v", err)
}
if calls != 0 {
t.Fatalf("the checker was consulted %d times about a config nobody could read", calls)
}
// CONTROL: with a good read the checker IS consulted and its verdict is passed
// through unchanged. Without this, a function that always returned nil would
// pass every check above.
got := schemaWriteVerdictWith(check, &model.Model{}, nil)
if calls != 1 {
t.Fatalf("control failed: the checker was consulted %d times for a readable config", calls)
}
if !errors.Is(got, model.ErrSchemaTooNew) {
t.Fatalf("control failed: the verdict was not passed through: %v", got)
}
// And the production wiring reaches the model package at all — a nil here is
// the build host having no `uci` (the model's documented "nothing to protect"),
// not a short circuit, which is why the assertions above use the seam.
if v := schemaWriteVerdict(&model.Model{}, nil); v != nil &&
!errors.Is(v, model.ErrUnmigratedConfig) && !errors.Is(v, model.ErrSchemaTooNew) {
t.Fatalf("unexpected verdict shape from the model package: %v", v)
}
}
func TestOfflineStatusStubCarriesTheSchemaPair(t *testing.T) {
for _, tc := range []struct {
name string
onDisk int
wantWarn bool
}{
{"newer than this build", model.CurrentSchemaVersion + 1, true},
{"equal to this build", model.CurrentSchemaVersion, false},
{"older than this build", model.CurrentSchemaVersion - 1, false},
} {
t.Run(tc.name, func(t *testing.T) {
read := func() (*model.Model, error) {
return &model.Model{Globals: model.Globals{
Enabled: true, KillSwitch: "closed", SchemaVersion: tc.onDisk,
}}, nil
}
s := offlineStatusStub(read, false, true)
if s.SchemaSupported != model.CurrentSchemaVersion {
t.Fatalf("schema_supported = %d, want %d", s.SchemaSupported, model.CurrentSchemaVersion)
}
if s.SchemaVersion != tc.onDisk {
t.Fatalf("schema_version = %d, want %d", s.SchemaVersion, tc.onDisk)
}
found := false
for _, w := range s.Warnings {
if strings.Contains(w.Message, "DOWNGRADED") {
found = true
if w.Severity != apply.SeverityCritical {
t.Fatalf("severity %q for a downgrade", w.Severity)
}
}
}
if found != tc.wantWarn {
t.Fatalf("downgrade warning present=%v, want %v; warnings: %+v", found, tc.wantWarn, s.Warnings)
}
})
}
}
func TestOfflineStatusStubSchemaSupportedSurvivesAnUnreadableConfig(t *testing.T) {
s := offlineStatusStub(func() (*model.Model, error) { return nil, errors.New("uci: no such file") },
false, true)
if s.SchemaSupported != model.CurrentSchemaVersion {
t.Fatalf("schema_supported = %d: a compile-time constant must not depend on a read", s.SchemaSupported)
}
if s.SchemaVersion != 0 {
t.Fatalf("schema_version = %d after a failed read: it must stay 0, never a guess", s.SchemaVersion)
}
}