carlos / platform Public

console: re-check egress allows on an edges change and the backstop, and alert (#328)

The fleet-address report: every egressReportTick an in-memory due check
(plus the console's own policy rows when a pass would be due) runs a pass
on the first tick, on a control/edges generation change read from the
record view's watch (RecordView.Watch; no new poll of control/changes.json),
or on the 30-33 minute backstop. A pass reads control/edges/ through the
cached ETag reader, records allowed addresses a box now holds
(egressConflicts) and alerts once per app and address per 24 h, giving
the slot back on a failed send. The allow stays in force (ruling 8).
Runs on every console, takes no lease (ruling C6).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 64b6f19efb973396bd6645d29012b3754396db15 parent 002fb34
10 files changed, +809 −0
  • cmd/console/main.go +5 −0
  • internal/console/claim_invariant_fixtures_test.go +1 −0
  • internal/console/claim_invariant_probes_worker_test.go +21 −0
  • internal/console/claim_invariant_world_test.go +7 −0
  • internal/console/claim_workers.go +1 −0
  • internal/console/egressfleet.go +294 −0
  • internal/console/egressfleet_test.go +449 −0
  • internal/console/server.go +4 −0
  • internal/provision/recordview.go +11 −0
  • internal/provision/recordview_test.go +16 −0
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 1c02fb51f..6ae2aa7e2 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -644,6 +644,11 @@ func serve() {
// expiry, once at startup and then every 12 hours. Inert without a
// signing key or a deployment bucket.
go srv.RunClaimWorker(context.Background(), "StartDoorKeyResign")
+ // The fleet-address report (internal/console/egressfleet.go, #328):
+ // re-checks every live egress allow against the boxes' published
+ // addresses on an edges change and the 30-minute backstop, and alerts.
+ // Read-only, on every console; idle with no allow.
+ go srv.RunClaimWorker(context.Background(), "StartEgressReport")
// Once, at boot: log any route already sitting at another app's platform
// apex (internal/console/apex.go). Reports; repairs nothing.
go srv.RunClaimWorker(context.Background(), "ReportApexSquats")
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 315672dd8..94a8a7127 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1974,6 +1974,7 @@ var claimFixtures = map[string]claimFixture{
"worker StartInfraPass": claimNonApp("the deployment's infrastructure inventory snapshot"),
"worker StartPlanLimitsPass": claimNonApp("account plan rows and their limits records under accounts/<sqid>/limits.json; names no app"),
"worker PublishPlansMarker": claimNonApp("the plans deployment marker (control/plans.json): whether boxes read limits; names no app"),
+ "worker StartEgressReport": claimNonApp("operator alert mail; writes no store object"),
"worker StartClaimRecoveryPass": {door: &claimDoor{
apps: claimRefs("bab/titogo"),
setup: func(t *testing.T, cx *claimCase) { cx.crashedRestore(t) },
diff --git a/internal/console/claim_invariant_probes_worker_test.go b/internal/console/claim_invariant_probes_worker_test.go
index a79737061..31706fb94 100644
--- a/internal/console/claim_invariant_probes_worker_test.go
+++ b/internal/console/claim_invariant_probes_worker_test.go
@@ -9,6 +9,7 @@ package console
import (
"context"
"encoding/json"
+ "net/http"
"strings"
"testing"
"time"
@@ -205,6 +206,26 @@ var claimWorkerProbes = map[string]claimProbe{
return ""
},
},
+ "worker StartEgressReport": {
+ setup: func(t *testing.T, cx *claimCase) {
+ // titogo allows 10.0.5.20, which box annie then publishes; the
+ // alert goes to the server's own sink, not process-wide state.
+ claimPolicyLease(cx)
+ if st, _, out := rawReqHeader(t, http.MethodPut, cx.ts.URL+"/api/cli/apps/bab/titogo/policy", cx.bearer,
+ `{"egress_allow":["10.0.5.20"]}`, map[string]string{"If-None-Match": "*"}); st != http.StatusOK {
+ t.Fatalf("stage the egress allow = %d %s", st, out)
+ }
+ putEdgesAddrs(t, cx.rel, "annie", []string{"10.0.5.20"})
+ cx.srv.egressReport.page = func(context.Context, string, string, string) error { return nil }
+ },
+ do: claimWorkerReply("StartEgressReport"),
+ effect: func(t *testing.T, cx *claimCase, r claimReply) string {
+ if got := cx.srv.egressConflicts()["10.0.5.20"]; got != "annie" {
+ return "the report did not find titogo's allowed 10.0.5.20 on box annie"
+ }
+ return ""
+ },
+ },
"worker StartPlanLimitsPass": {
setup: func(t *testing.T, cx *claimCase) { cx.srv.cfg.PlanCatalog = examplePlanCatalog(t) },
do: claimWorkerReply("StartPlanLimitsPass"),
diff --git a/internal/console/claim_invariant_world_test.go b/internal/console/claim_invariant_world_test.go
index 5032724f6..647549055 100644
--- a/internal/console/claim_invariant_world_test.go
+++ b/internal/console/claim_invariant_world_test.go
@@ -192,6 +192,7 @@ var (
_ release.ModLister = (*claimRawStore)(nil)
_ release.SizeLister = (*claimRawStore)(nil)
_ release.PageLister = (*claimRawStore)(nil)
+ _ release.ETagLister = (*claimRawStore)(nil)
)
func (s *claimRawStore) Get(ctx context.Context, key string) ([]byte, string, error) {
@@ -215,6 +216,12 @@ func (s *claimRawStore) ListSizes(ctx context.Context, prefix string) ([]release
func (s *claimRawStore) ListPage(ctx context.Context, prefix, startAfter string, limit int) ([]string, error) {
return s.dir.ListPage(ctx, prefix, startAfter, limit)
}
+
+// ListETags is the S3 store's ETag listing, which the egress report's
+// cached read of control/edges/ takes (edgesfile.ReadAddrsCached).
+func (s *claimRawStore) ListETags(ctx context.Context, prefix string) ([]release.KeyETag, error) {
+ return s.dir.ListETags(ctx, prefix)
+}
func (s *claimRawStore) Put(ctx context.Context, key string, body []byte, tag string) (string, error) {
e := s.rec.classifyBucket(ctx, "bucket", "Put", key, tag, body)
out, err := s.inner.Put(ctx, key, body, tag)
diff --git a/internal/console/claim_workers.go b/internal/console/claim_workers.go
index ed947d88c..70893d990 100644
--- a/internal/console/claim_workers.go
+++ b/internal/console/claim_workers.go
@@ -21,6 +21,7 @@ func (s *Server) registerClaimWorkers() {
"StartRelay": s.StartRelay,
"StartMailEventPush": s.StartMailEventPush,
"StartDoorKeyResign": s.StartDoorKeyResign,
+ "StartEgressReport": s.StartEgressReport,
"ReportApexSquats": s.ReportApexSquats,
"LogPlacementDiscrepancies": s.LogPlacementDiscrepancies,
"PublishMovesConsole": s.publishMovesConsoleWorker,
diff --git a/internal/console/egressfleet.go b/internal/console/egressfleet.go
index 554253006..55d475ae2 100644
--- a/internal/console/egressfleet.go
+++ b/internal/console/egressfleet.go
@@ -21,14 +21,20 @@ package console
import (
"context"
"fmt"
+ "maps"
+ "math/rand/v2"
"net/http"
"net/netip"
"slices"
"strings"
+ "sync"
"time"
+ "github.com/carlosframework/platform/internal/alerting"
+ "github.com/carlosframework/platform/internal/apppolicy"
"github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/egressaddr"
+ "github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/status"
)
@@ -126,3 +132,291 @@ func grantAdded(old, next []string) ([]netip.Addr, error) {
}
return added, nil
}
+
+// ---- the fleet-address report (spec §3a and §4.2, rulings 8 and 11) -------
+//
+// A grant is checked once, when it is made. A box can take an allowed
+// address later, so the report checks every live allow again, on an edges
+// change and on the backstop, and tells the operator. It changes nothing:
+// the allow stays in force (ruling 8) until an operator removes it or moves
+// the address.
+
+const (
+ // egressReportTick is how often StartEgressReport asks egressReportDue:
+ // an in-memory check, plus a read of the console's own database when a
+ // pass would otherwise be due. No store request.
+ egressReportTick = 30 * time.Second
+ // egressAlertEvery is how often one app's alert for one address may
+ // repeat, per console process.
+ egressAlertEvery = 24 * time.Hour
+ // egressAlertTimeout bounds one alert send.
+ egressAlertTimeout = 30 * time.Second
+ // egressEdgesScope is the change-index scope every write under
+ // control/edges/ bumps (release.ChangeScope).
+ egressEdgesScope = "control/edges"
+)
+
+// pageEgressConflict sends the report's alert; a server's
+// egressReport.page stands in for it in tests.
+var pageEgressConflict = alerting.Page
+
+// egressConflictAlert is the report's alert (drafts, collected for review
+// in plan 2 Task 17).
+func egressConflictAlert(sqid, app string, addr netip.Addr, box string) (subject, body string) {
+ return fmt.Sprintf("Egress allow %s is now a fleet box's address", addr),
+ fmt.Sprintf("App %s in account %s may reach %s, and box %s now holds that address. "+
+ "The allow is still in force. Remove it with carlos apps set %s --egress-allow, or move the address off the box.",
+ app, sqid, addr, box, app)
+}
+
+// egressReportState is the report's memory. Every field after mu is guarded
+// by it; now and page are set once, before the report starts.
+type egressReportState struct {
+ mu sync.Mutex
+ // ran is whether a pass has run in this process; next is when the
+ // backstop makes the next one due.
+ ran bool
+ next time.Time
+ // gen is the control/edges generation marked by the last pass, when
+ // genOK (the watch could vouch for it then).
+ gen uint64
+ genOK bool
+ // conflicts is the last pass's findings, address -> box; nil before
+ // the first pass.
+ conflicts map[string]string
+ // alerted is when each "<sqid>/<app> <addr>" alert was last sent.
+ alerted map[string]time.Time
+
+ now func() time.Time // nil: time.Now
+ page func(ctx context.Context, level, subject, body string) error // nil: pageEgressConflict
+}
+
+func (s *Server) egressClock() time.Time {
+ if f := s.egressReport.now; f != nil {
+ return f()
+ }
+ return time.Now()
+}
+
+// egressEdgesGen is control/edges's generation as the record view's watch
+// last observed it, or ok false with no view or a watch that cannot vouch.
+func (s *Server) egressEdgesGen() (uint64, bool) {
+ w := s.recordView.Watch()
+ if w == nil {
+ return 0, false
+ }
+ return w.Gen(egressEdgesScope)
+}
+
+// egressAllowed is one address of one app's allow.
+type egressAllowed struct {
+ sqid, app string
+ addr netip.Addr
+}
+
+// egressLiveAllows is every address of every live allow, read from the
+// console's own policy rows (AppPolicyRowsContext) and opened with the key
+// they were signed with. unopened names the rows that do not open (or hold
+// an entry that does not parse): their allows are not checked.
+func (s *Server) egressLiveAllows(ctx context.Context) (allows []egressAllowed, unopened []string, err error) {
+ rows, err := s.store.AppPolicyRowsContext(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ pub := s.policyPub()
+ for _, r := range rows {
+ p, err := apppolicy.OpenKey(pub, r.Wire, r.Sqid, r.App)
+ if err != nil {
+ unopened = append(unopened, r.Sqid+"/"+r.App)
+ continue
+ }
+ for _, e := range p.EgressAllow {
+ a, err := egressaddr.Parse(e)
+ if err != nil {
+ unopened = append(unopened, r.Sqid+"/"+r.App)
+ continue
+ }
+ allows = append(allows, egressAllowed{sqid: r.Sqid, app: r.App, addr: a})
+ }
+ }
+ return allows, unopened, nil
+}
+
+// StartEgressReport is the fleet-address report's loop (spec §4.2): every
+// egressReportTick it asks egressReportDue and runs egressReportPass when a
+// pass is due. It returns at once without a deployment bucket.
+//
+// Ruling 11: no timer here reads the store. The tick reads memory and, when
+// a pass would be due, the console's own database. A pass is due on a
+// control/edges generation change, which it reads from the record view's
+// watch (kept current by the run sweep's refresh with CARLOS_CHANGE_INDEX=read;
+// the report never polls control/changes.json itself), and on the backstop,
+// 30 to 33 minutes after the last pass: at most 48 a day, each one ETag
+// listing of control/edges/ and a Get only of a file that changed.
+//
+// Every console reports, not only the policy writer (ruling C6): the report
+// is read-only and takes no lease, and tying it to the writer lease, which
+// is taken lazily, would leave it dark for hours after a roll. A deployment
+// with two consoles may send each alert twice.
+//
+// The allows come from the console's own policy rows, not the bucket: the
+// rows are the signed records this console wrote or adopted, and reading
+// them costs no store request, where listing control/app-policy/ and
+// fetching each object would cost a LIST and a GET per policy every pass.
+func (s *Server) StartEgressReport(ctx context.Context) {
+ if s.cfg.Releases == nil {
+ return
+ }
+ t := time.NewTicker(egressReportTick)
+ defer t.Stop()
+ for {
+ if s.egressReportDue(s.egressClock()) {
+ if err := s.egressReportPass(ctx); err != nil {
+ s.policyLogf("console: egress report: %v", err)
+ }
+ }
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ }
+ }
+}
+
+// egressReportDue reports whether a pass should run at now. It makes no
+// store request: it reads the report's memory, the watch's last
+// observation, and (only when one of those makes a pass due) the console's
+// own policy rows. A pass is due when one of these holds and at least one
+// live allow exists, or the last pass left findings to clear:
+//
+// - no pass has run in this process;
+// - the backstop deadline has passed;
+// - the watch's control/edges generation differs from the one the last
+// pass marked.
+//
+// A nil or unusable watch leaves only the first pass and the backstop. When
+// the last pass marked no generation (the watch could not vouch then), the
+// first generation observed after it is adopted as the mark without a pass:
+// a change in between waits for the backstop, rather than every recovery
+// of a flapping index costing a listing.
+func (s *Server) egressReportDue(now time.Time) bool {
+ st := &s.egressReport
+ st.mu.Lock()
+ due := !st.ran || !now.Before(st.next)
+ if !due {
+ if gen, ok := s.egressEdgesGen(); ok {
+ if !st.genOK {
+ st.gen, st.genOK = gen, true
+ } else if gen != st.gen {
+ due = true
+ }
+ }
+ }
+ findings := len(st.conflicts) > 0
+ st.mu.Unlock()
+ if !due {
+ return false
+ }
+ if findings {
+ return true
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), egressReportTick)
+ defer cancel()
+ allows, _, err := s.egressLiveAllows(ctx)
+ // A failed read is due, so the pass says why (and marks the schedule).
+ return err != nil || len(allows) > 0
+}
+
+// egressReportPass checks every live allow against every box's published
+// addresses. It marks the schedule and the edges generation first, so a
+// write that lands during the read is caught by the next pass and a failed
+// pass is not retried before the next change or backstop. Each allowed
+// address a box holds goes into the findings, and raises an alert at most
+// once per egressAlertEvery per app and address, in this console process;
+// a send that fails gives its slot back. The findings replace the last
+// pass's at the end; a pass that fails leaves them as they were. With no
+// live allow it reads no store and clears the findings.
+func (s *Server) egressReportPass(ctx context.Context) error {
+ now := s.egressClock()
+ gen, genOK := s.egressEdgesGen()
+ b := release.ChangeIndexBackstop
+ st := &s.egressReport
+ st.mu.Lock()
+ st.ran, st.next = true, now.Add(b+rand.N(b/10))
+ st.gen, st.genOK = gen, genOK
+ st.mu.Unlock()
+
+ allows, unopened, err := s.egressLiveAllows(ctx)
+ if err != nil {
+ return fmt.Errorf("app policy rows: %w", err)
+ }
+ if len(unopened) > 0 {
+ slices.Sort(unopened)
+ s.policyLogf("console: egress report: not checked, the recorded policy does not open: %s",
+ strings.Join(slices.Compact(unopened), ", "))
+ }
+ conflicts := map[string]string{}
+ if len(allows) > 0 {
+ inv, err := edgesfile.ReadAddrsCached(ctx, s.cfg.Releases, &s.egressAddrs)
+ if err != nil {
+ return fmt.Errorf("list %s: %w", edgesfile.Prefix, err)
+ }
+ if len(inv.Unreadable) > 0 {
+ s.policyLogf("console: egress report: unreadable edges files, their addresses not checked: %s", strings.Join(inv.Unreadable, ", "))
+ }
+ for _, a := range allows {
+ box, ok := inv.Holder(a.addr)
+ if !ok {
+ continue
+ }
+ conflicts[a.addr.String()] = box
+ s.egressAlert(ctx, a, box, now)
+ }
+ }
+ st.mu.Lock()
+ st.conflicts = conflicts
+ st.mu.Unlock()
+ return nil
+}
+
+// egressAlert sends a's alert unless one went out for the same app and
+// address within egressAlertEvery. The slot is taken before the send and
+// given back if it fails, so the next pass tries again.
+func (s *Server) egressAlert(ctx context.Context, a egressAllowed, box string, now time.Time) {
+ key := a.sqid + "/" + a.app + " " + a.addr.String()
+ st := &s.egressReport
+ st.mu.Lock()
+ if at, ok := st.alerted[key]; ok && now.Sub(at) < egressAlertEvery {
+ st.mu.Unlock()
+ return
+ }
+ if st.alerted == nil {
+ st.alerted = map[string]time.Time{}
+ }
+ st.alerted[key] = now
+ page := st.page
+ st.mu.Unlock()
+ if page == nil {
+ page = pageEgressConflict
+ }
+ subject, body := egressConflictAlert(a.sqid, a.app, a.addr, box)
+ sctx, cancel := context.WithTimeout(ctx, egressAlertTimeout)
+ defer cancel()
+ if err := page(sctx, alerting.LevelWarning, subject, body); err != nil {
+ st.mu.Lock()
+ if at, ok := st.alerted[key]; ok && at.Equal(now) {
+ delete(st.alerted, key)
+ }
+ st.mu.Unlock()
+ s.policyLogf("console: egress report: alert for %s on box %s: %v", key, box, err)
+ }
+}
+
+// egressConflicts is the last pass's findings, allowed address -> the box
+// that holds it, or nil before the first pass. The map is a copy.
+func (s *Server) egressConflicts() map[string]string {
+ st := &s.egressReport
+ st.mu.Lock()
+ defer st.mu.Unlock()
+ return maps.Clone(st.conflicts)
+}
diff --git a/internal/console/egressfleet_test.go b/internal/console/egressfleet_test.go
index 57c470316..7b996d7d7 100644
--- a/internal/console/egressfleet_test.go
+++ b/internal/console/egressfleet_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "maps"
"net/http"
"net/netip"
"slices"
@@ -12,6 +13,8 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/alerting"
+ "github.com/carlosframework/platform/internal/apppolicy"
"github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -357,3 +360,449 @@ func TestPolicyDoorWritesNothingWhenTheCheckRefuses(t *testing.T) {
t.Fatalf("serial %d, want %d", got, before)
}
}
+
+// ---- the fleet-address report (Task 10) ----------------------------------
+
+// reportCountingStore is the fixture's bucket as a DirStore with the change
+// index on, counting every request by operation and key. Embedding the
+// concrete store forwards ETagLister and ConditionalGetter as the S3 store
+// answers them.
+type reportCountingStore struct {
+ *release.DirStore
+ mu sync.Mutex
+ calls map[string]int // "<op> <key or prefix>"
+}
+
+func (c *reportCountingStore) note(op, key string) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.calls == nil {
+ c.calls = map[string]int{}
+ }
+ c.calls[op+" "+key]++
+}
+
+func (c *reportCountingStore) List(ctx context.Context, prefix string) ([]string, error) {
+ c.note("List", prefix)
+ return c.DirStore.List(ctx, prefix)
+}
+
+func (c *reportCountingStore) ListPage(ctx context.Context, prefix, after string, limit int) ([]string, error) {
+ c.note("List", prefix)
+ return c.DirStore.ListPage(ctx, prefix, after, limit)
+}
+
+func (c *reportCountingStore) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) {
+ c.note("List", prefix)
+ return c.DirStore.ListMod(ctx, prefix)
+}
+
+func (c *reportCountingStore) ListDirs(ctx context.Context, prefix string) ([]string, error) {
+ c.note("List", prefix)
+ return c.DirStore.ListDirs(ctx, prefix)
+}
+
+func (c *reportCountingStore) ListETags(ctx context.Context, prefix string) ([]release.KeyETag, error) {
+ c.note("ListETags", prefix)
+ return c.DirStore.ListETags(ctx, prefix)
+}
+
+func (c *reportCountingStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ c.note("Get", key)
+ return c.DirStore.Get(ctx, key)
+}
+
+func (c *reportCountingStore) GetIfChanged(ctx context.Context, key, etag string) ([]byte, string, bool, error) {
+ c.note("Get", key)
+ return c.DirStore.GetIfChanged(ctx, key, etag)
+}
+
+// taken is the requests counted since the last call, then zeroed:
+// total, and op -> count under each of prefixes.
+func (c *reportCountingStore) taken(prefixes ...string) (total int, under map[string]int) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ under = map[string]int{}
+ for k, n := range c.calls {
+ total += n
+ op, key, _ := strings.Cut(k, " ")
+ for _, p := range prefixes {
+ if strings.HasPrefix(key, p) {
+ under[op+" "+p] += n
+ }
+ }
+ }
+ c.calls = map[string]int{}
+ return total, under
+}
+
+// reportFx is the policy fixture over a reportCountingStore, with the
+// report's clock and page sink in the test's hands.
+type reportFx struct {
+ *policyFx
+ cs *reportCountingStore
+
+ mu sync.Mutex
+ now time.Time
+ pages []string // subject + "\n" + body, of each send that succeeded
+ fail int // the next fail sends fail
+}
+
+func newReportFx(t *testing.T, code string) *reportFx {
+ t.Helper()
+ pfx := newPolicyFx(t, code)
+ d, ok := pfx.rel.(*deletableStore)
+ if !ok {
+ t.Fatalf("fixture store is %T", pfx.rel)
+ }
+ ds := release.NewDirStore(d.root)
+ ds.EnableChangeIndex()
+ fx := &reportFx{policyFx: pfx, cs: &reportCountingStore{DirStore: ds}, now: time.Now()}
+ fx.rel, fx.srv.cfg.Releases = fx.cs, fx.cs
+ fx.srv.egressReport.now = fx.clock
+ fx.srv.egressReport.page = func(ctx context.Context, level, subject, body string) error {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ if level != alerting.LevelWarning {
+ t.Errorf("page level %q, want %q", level, alerting.LevelWarning)
+ }
+ if fx.fail > 0 {
+ fx.fail--
+ return errors.New("sink down")
+ }
+ fx.pages = append(fx.pages, subject+"\n"+body)
+ return nil
+ }
+ return fx
+}
+
+func (fx *reportFx) clock() time.Time {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ return fx.now
+}
+
+// tick is one egressReportTick of StartEgressReport's loop on the fake
+// clock: the due check, then the pass when due. It reports whether a pass
+// ran.
+func (fx *reportFx) tick(t *testing.T) bool {
+ t.Helper()
+ fx.mu.Lock()
+ fx.now = fx.now.Add(egressReportTick)
+ now := fx.now
+ fx.mu.Unlock()
+ if !fx.srv.egressReportDue(now) {
+ return false
+ }
+ if err := fx.srv.egressReportPass(context.Background()); err != nil {
+ t.Fatalf("pass: %v", err)
+ }
+ return true
+}
+
+// ticks runs n ticks and counts the passes.
+func (fx *reportFx) ticks(t *testing.T, n int) int {
+ t.Helper()
+ passes := 0
+ for range n {
+ if fx.tick(t) {
+ passes++
+ }
+ }
+ return passes
+}
+
+func (fx *reportFx) sent() []string {
+ fx.mu.Lock()
+ defer fx.mu.Unlock()
+ return slices.Clone(fx.pages)
+}
+
+// policyObject is the bytes and ETag of app's policy object in the bucket.
+func (fx *reportFx) policyObject(t *testing.T, app string) (string, string) {
+ t.Helper()
+ body, etag, err := fx.cs.DirStore.Get(context.Background(), apppolicy.Key(fx.sqid, app))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(body), etag
+}
+
+const (
+ reportDay = int(24 * time.Hour / egressReportTick) // 2880 ticks
+ reportBackstopTo = int(33 * time.Minute / egressReportTick) // the backstop's latest
+)
+
+// An allowed address that a box later publishes is reported: one alert per
+// app and address however many passes find it (until egressAlertEvery has
+// passed), egressConflicts names its box, and the allow stays as it was:
+// the policy object and the console's row are untouched (ruling 8).
+func TestEgressReportAlertsOnceAndKeepsTheAllow(t *testing.T) {
+ t.Parallel()
+ fx := newReportFx(t, "code-egress-report-once")
+ fx.mustPut(t, "shop", `{"egress_allow":["10.0.5.20","10.0.5.21"]}`, policyCreate)
+ putEdgesAddrs(t, fx.cs, "annie", []string{"10.0.1.5"})
+ if got := fx.srv.egressConflicts(); got != nil {
+ t.Fatalf("conflicts before any pass = %v, want nil", got)
+ }
+ if !fx.tick(t) {
+ t.Fatal("the first tick with a live allow ran no pass")
+ }
+ if got := fx.srv.egressConflicts(); got == nil || len(got) != 0 || len(fx.sent()) != 0 {
+ t.Fatalf("a pass with no box holding an allowed address = %v, pages %q", got, fx.sent())
+ }
+
+ putEdgesAddrs(t, fx.cs, "betty", []string{"10.0.9.9", "10.0.5.20/32"})
+ body, etag := fx.policyObject(t, "shop")
+ before := fx.row(t, "shop")
+ if n := fx.ticks(t, reportBackstopTo); n != 1 {
+ t.Fatalf("the backstop ran %d passes in 33 minutes, want 1", n)
+ }
+ want := "Egress allow 10.0.5.20 is now a fleet box's address\n" +
+ "App shop in account " + fx.sqid + " may reach 10.0.5.20, and box betty now holds that address. " +
+ "The allow is still in force. Remove it with carlos apps set shop --egress-allow, or move the address off the box."
+ if got := fx.sent(); len(got) != 1 || got[0] != want {
+ t.Fatalf("pages = %q, want one: %q", got, want)
+ }
+ if got := fx.srv.egressConflicts(); !maps.Equal(got, map[string]string{"10.0.5.20": "betty"}) {
+ t.Fatalf("conflicts = %v, want 10.0.5.20 on betty", got)
+ }
+
+ if n := fx.ticks(t, reportBackstopTo); n != 1 {
+ t.Fatalf("the second backstop ran %d passes, want 1", n)
+ }
+ if got := fx.sent(); len(got) != 1 {
+ t.Fatalf("a second pass paged again: %q", got)
+ }
+ if got := fx.srv.egressConflicts(); !maps.Equal(got, map[string]string{"10.0.5.20": "betty"}) {
+ t.Fatalf("conflicts after the second pass = %v", got)
+ }
+ if b, e := fx.policyObject(t, "shop"); b != body || e != etag {
+ t.Fatal("the report changed the policy object")
+ }
+ if after := fx.row(t, "shop"); after.Revision != before.Revision || after.SyncedETag != before.SyncedETag {
+ t.Fatalf("the report changed the row: %+v -> %+v", before, after)
+ }
+ if g := fx.get(t, "shop"); !slices.Equal(g.Policy.EgressAllow, []string{"10.0.5.20", "10.0.5.21"}) {
+ t.Fatalf("the allow is now %v", g.Policy.EgressAllow)
+ }
+
+ // A day on, the same finding pages once more.
+ fx.ticks(t, reportDay)
+ if got := fx.sent(); len(got) != 2 || got[1] != want {
+ t.Fatalf("a day later, pages = %q, want the alert once more", got)
+ }
+
+ // The box gives the address up: the next pass clears the finding.
+ putEdgesAddrs(t, fx.cs, "betty", []string{"10.0.9.9"})
+ fx.ticks(t, reportBackstopTo)
+ if got := fx.srv.egressConflicts(); got == nil || len(got) != 0 {
+ t.Fatalf("conflicts after betty gave the address up = %v, want empty", got)
+ }
+}
+
+// A send that fails gives its slot back: the next pass sends it again, and
+// once one has gone through the next pass is quiet.
+func TestEgressReportRetriesAFailedSend(t *testing.T) {
+ t.Parallel()
+ fx := newReportFx(t, "code-egress-report-retry")
+ fx.mustPut(t, "shop", `{"egress_allow":["10.0.5.20"]}`, policyCreate)
+ putEdgesAddrs(t, fx.cs, "betty", []string{"10.0.5.20"})
+ fx.mu.Lock()
+ fx.fail = 1
+ fx.mu.Unlock()
+ if !fx.tick(t) {
+ t.Fatal("no first pass")
+ }
+ if got := fx.sent(); len(got) != 0 {
+ t.Fatalf("pages after a failed send = %q", got)
+ }
+ if got := fx.srv.egressConflicts(); got["10.0.5.20"] != "betty" {
+ t.Fatalf("a failed send hid the finding: %v", got)
+ }
+ fx.ticks(t, reportBackstopTo)
+ if got := fx.sent(); len(got) != 1 {
+ t.Fatalf("pages after the next pass = %q, want the alert sent", got)
+ }
+ fx.ticks(t, reportBackstopTo)
+ if got := fx.sent(); len(got) != 1 {
+ t.Fatalf("pages after a third pass = %q, want no repeat", got)
+ }
+}
+
+// With the record view armed, a write under control/edges/ runs a pass on
+// the first tick after the view's own refresh (the run sweep's) observes
+// it; the report never polls the index itself, and with the generation
+// unchanged a tick runs nothing.
+func TestEgressReportRunsOnEdgesGeneration(t *testing.T) {
+ t.Parallel()
+ fx := newReportFx(t, "code-egress-report-gen")
+ fx.mustPut(t, "shop", `{"egress_allow":["10.0.5.20"]}`, policyCreate)
+ putEdgesAddrs(t, fx.cs, "annie", []string{"10.0.1.5"})
+ v := armRecordView(t, fx.srv, fx.cs)
+ if !fx.tick(t) {
+ t.Fatal("no first pass")
+ }
+ if fx.tick(t) {
+ t.Fatal("a tick with the edges generation unchanged ran a pass")
+ }
+
+ putEdgesAddrs(t, fx.cs, "betty", []string{"10.0.5.20"})
+ fx.cs.taken()
+ if fx.tick(t) {
+ t.Fatal("a pass ran before anything polled the index")
+ }
+ if total, under := fx.cs.taken(release.ChangeIndexKey); total != 0 || under["Get "+release.ChangeIndexKey] != 0 {
+ t.Fatalf("the due check made %d requests (%v): the report polled the index itself", total, under)
+ }
+ if err := v.Refresh(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if !fx.tick(t) {
+ t.Fatal("the tick after the view observed an edges write ran no pass")
+ }
+ if got := fx.srv.egressConflicts(); got["10.0.5.20"] != "betty" || len(fx.sent()) != 1 {
+ t.Fatalf("the generation pass = %v, pages %q", got, fx.sent())
+ }
+ if fx.tick(t) {
+ t.Fatal("a second tick on the same generation ran a pass")
+ }
+}
+
+// The report is read-only and runs on every console (ruling C6): a console
+// that is not the policy writer, and whose writer lease would be refused,
+// still reports, and asks for no lease to do it.
+func TestEgressReportRunsWithoutTheWriterLease(t *testing.T) {
+ t.Parallel()
+ fx := newReportFx(t, "code-egress-report-lease")
+ fx.mustPut(t, "shop", `{"egress_allow":["10.0.5.20"]}`, policyCreate) // sole: no bucket yet
+ putEdgesAddrs(t, fx.cs, "betty", []string{"10.0.5.20"})
+ f := &fakePolicyLeaser{err: errors.New("acquire lease: held by another console")}
+ fx.srv.cfg.Bucket = "deploy"
+ fx.srv.cfg.PolicyLease = f.leaser
+ if fx.srv.policyHeld() {
+ t.Fatal("the console still holds the writer lease; the fixture tests nothing")
+ }
+ if !fx.tick(t) {
+ t.Fatal("a console that is not the writer ran no pass")
+ }
+ if got := fx.srv.egressConflicts(); got["10.0.5.20"] != "betty" || len(fx.sent()) != 1 {
+ t.Fatalf("the non-writer's pass = %v, pages %q", got, fx.sent())
+ }
+ if n := f.callCount(); n != 0 {
+ t.Fatalf("the report asked for the writer lease %d times, want none", n)
+ }
+}
+
+// With no allow in any row (no rows, then a policy that sets only a size)
+// no pass runs and nothing is requested, all day.
+func TestEgressReportIsQuietWithNoAllows(t *testing.T) {
+ t.Parallel()
+ fx := newReportFx(t, "code-egress-report-quiet")
+ putEdgesAddrs(t, fx.cs, "betty", []string{"10.0.5.20"})
+ fx.cs.taken()
+ if n := fx.ticks(t, 120); n != 0 {
+ t.Fatalf("with no policy rows, %d passes ran", n)
+ }
+ fx.mustPut(t, "shop", `{"default_size":"large"}`, policyCreate)
+ fx.cs.taken()
+ if n := fx.ticks(t, reportDay); n != 0 {
+ t.Fatalf("with no allow, %d passes ran in a day", n)
+ }
+ if total, under := fx.cs.taken(); total != 0 {
+ t.Fatalf("with no allow, the report made %d requests: %v", total, under)
+ }
+ if got := fx.srv.egressConflicts(); got != nil || len(fx.sent()) != 0 {
+ t.Fatalf("conflicts %v, pages %q", got, fx.sent())
+ }
+}
+
+// Revoking every allow clears the last pass's findings on the next pass,
+// which then requests nothing.
+func TestEgressReportClearsWhenTheAllowsGo(t *testing.T) {
+ t.Parallel()
+ fx := newReportFx(t, "code-egress-report-clear")
+ first := fx.mustPut(t, "shop", `{"egress_allow":["10.0.5.20"]}`, policyCreate)
+ putEdgesAddrs(t, fx.cs, "betty", []string{"10.0.5.20"})
+ fx.tick(t)
+ if got := fx.srv.egressConflicts(); got["10.0.5.20"] != "betty" {
+ t.Fatalf("conflicts = %v", got)
+ }
+ fx.mustPut(t, "shop", `{"egress_allow":[]}`, policyIfMatch(first.ETag))
+ fx.cs.taken()
+ if n := fx.ticks(t, reportBackstopTo); n != 1 {
+ t.Fatalf("%d passes after the allows went, want 1 to clear the findings", n)
+ }
+ if got := fx.srv.egressConflicts(); got == nil || len(got) != 0 {
+ t.Fatalf("conflicts after the allows went = %v, want empty", got)
+ }
+ if total, under := fx.cs.taken(); total != 0 {
+ t.Fatalf("the clearing pass made %d requests: %v", total, under)
+ }
+ if n := fx.ticks(t, reportDay); n != 0 {
+ t.Fatalf("%d passes ran with nothing to report", n)
+ }
+}
+
+// Without a deployment bucket the report does not start.
+func TestEgressReportNeedsABucket(t *testing.T) {
+ t.Parallel()
+ s := &Server{policyLog: func(string, ...any) {}}
+ done := make(chan struct{})
+ go func() { s.StartEgressReport(context.Background()); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("StartEgressReport with no bucket did not return")
+ }
+}
+
+// The §3a console budget for the report, pinned (ruling 11). Fails on any increase.
+func TestEgressReportKeepsTheRequestBudget(t *testing.T) {
+ t.Parallel()
+ fx := newReportFx(t, "code-egress-report-budget")
+ putEdgesAddrs(t, fx.cs, "annie", []string{"10.0.1.5"})
+ putEdgesAddrs(t, fx.cs, "betty", []string{"10.0.1.6"})
+ putEdgesAddrs(t, fx.cs, "cleo", []string{"10.0.1.7", "fd00:5::/64"})
+ fx.mustPut(t, "shop", `{"egress_allow":["10.0.5.20"]}`, policyCreate)
+ fx.mustPut(t, "shop-b", `{"egress_allow":["10.0.5.21"]}`, policyCreate)
+ v := armRecordView(t, fx.srv, fx.cs)
+ if !fx.tick(t) {
+ t.Fatal("no first pass")
+ }
+ fx.cs.taken()
+
+ // One day, 30 s ticks, nothing written.
+ passes := fx.ticks(t, reportDay)
+ total, under := fx.cs.taken(edgesfile.Prefix, apppolicy.Prefix)
+ if passes < 43 || passes > 48 {
+ t.Fatalf("%d passes in a day, want the backstop's 43 to 48", passes)
+ }
+ if n := under["ListETags "+edgesfile.Prefix]; n > 48 || n != passes {
+ t.Fatalf("%d ETag listings of %s in a day over %d passes, want one a pass and at most 48", n, edgesfile.Prefix, passes)
+ }
+ if n := under["Get "+edgesfile.Prefix]; n != 0 {
+ t.Fatalf("%d Gets of unchanged edges files in a day, want 0", n)
+ }
+ if n := under["List "+apppolicy.Prefix] + under["ListETags "+apppolicy.Prefix] + under["Get "+apppolicy.Prefix]; n != 0 {
+ t.Fatalf("%d requests under %s in a day, want 0", n, apppolicy.Prefix)
+ }
+ if extra := total - under["ListETags "+edgesfile.Prefix]; extra != 0 {
+ t.Fatalf("the report made %d requests in a day beyond its ETag listings (a List, an index poll, ...)", extra)
+ }
+
+ // One edges file rewritten: the view's refresh observes the bump, and
+ // the next tick runs a pass that reads just that file.
+ putEdgesAddrs(t, fx.cs, "betty", []string{"10.0.1.6", "10.0.1.8"})
+ if err := v.Refresh(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ fx.cs.taken()
+ if !fx.tick(t) {
+ t.Fatal("the tick after an edges write ran no pass")
+ }
+ total, under = fx.cs.taken(edgesfile.Prefix)
+ if under["ListETags "+edgesfile.Prefix] != 1 || under["Get "+edgesfile.Prefix] != 1 || total != 2 {
+ t.Fatalf("the pass after one edges write made %d requests (%v), want 1 ETag listing and 1 Get", total, under)
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 99424ec66..c446b2368 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1185,6 +1185,10 @@ type Server struct {
// (egressfleet.go) re-reads only a file that changed. Zero value is
// ready to use.
egressAddrs edgesfile.AddrCache
+ // egressReport is the fleet-address report's memory (egressfleet.go):
+ // its schedule, its last findings and its alert slots. Zero value is
+ // ready to use.
+ egressReport egressReportState
// edgeProof is the mesh-key cache and the seen latch behind clientIP's
// loopback check (edgeproof.go). Zero value is ready to use.
edgeProof edgeProofState
diff --git a/internal/provision/recordview.go b/internal/provision/recordview.go
index 7324b541a..63519be87 100644
--- a/internal/provision/recordview.go
+++ b/internal/provision/recordview.go
@@ -62,6 +62,17 @@ func NewRecordView(live release.Store, watch *release.ChangeWatch) *RecordView {
return &RecordView{live: live, watch: watch, pollTimeout: release.ChangeIndexPollTimeout, applied: map[string]uint64{}, pending: map[string]bool{}}
}
+// Watch is the watch the view was built over, kept current by the view's
+// refreshes, or nil for a nil view. A reader of a scope the view does not
+// keep (the console's egress report, control/edges) reads its generation
+// here instead of polling the index itself.
+func (v *RecordView) Watch() *release.ChangeWatch {
+ if v == nil {
+ return nil
+ }
+ return v.watch
+}
+
// Snapshot is the latest publication, or nil before the first. It never
// blocks on a refresh in progress.
func (v *RecordView) Snapshot() *ViewSnapshot { return v.snap.Load() }
diff --git a/internal/provision/recordview_test.go b/internal/provision/recordview_test.go
index f0dd76f71..d47bbd3f7 100644
--- a/internal/provision/recordview_test.go
+++ b/internal/provision/recordview_test.go
@@ -1350,3 +1350,19 @@ func TestRemovalOverTheBucketWalksOnce(t *testing.T) {
t.Fatalf("a walking pass listed accounts/ %d time(s), want 1: %v", n, w.live.got())
}
}
+
+// Watch is the watch the view was built over, so another reader can follow
+// the generations the view's refreshes observe without polling the index
+// itself; a nil view has none.
+func TestRecordViewWatch(t *testing.T) {
+ t.Parallel()
+ live := release.NewDirStore(t.TempDir())
+ w := release.NewChangeWatch(live)
+ if got := NewRecordView(live, w).Watch(); got != w {
+ t.Fatalf("Watch() = %p, want the view's own watch %p", got, w)
+ }
+ var v *RecordView
+ if got := v.Watch(); got != nil {
+ t.Fatalf("a nil view's Watch() = %p, want nil", got)
+ }
+}