Probe burst limit: the per-app record-only switch (Task 5)
An app's owner can turn its protection to record only: every edge serving
the app records what hard, probe and burst rules would have refused and
refuses nothing. The setting lives in the app's own telemetry.json
(protection.mode "record", app level only) and rides the analytics
switch pass to a second edge map, so it lands within seconds of the
console's serial bump. A failed read keeps the app's last known value.
Edges that serve an app only through the far asset catch learn its switch
through Edge.AssetOwners: the pass resolves those apps too, one gated
app-level read each. newGuardState takes the route and sets recordOnly on
both guard sites.
Owners set it from the Protection tab (POST .../protection/setting, the
analytics setting's gate), through the telemetry PUT's new protection half
(which audits and bumps the serial), and with `carlos protection`, which
reads through the new GET /api/cli/apps/{account}/{app}/telemetry. Copy is
the approved deck's PB-C03..PB-C12; both new console routes join the claim
route census, and the Protection tab's perf budget counts its one extra read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
27 files changed,
+1,402
−78
apimode.go+18 −0docs/site/cli.md+10 −0internal/console/apierrors.go+68 −22internal/console/approved_burst_copy_test.go+12 −0internal/console/authcli.go+3 −0internal/console/claim_invariant_fixtures_test.go+7 −0internal/console/claim_invariant_probes_read_test.go+9 −0internal/console/protectionsetting.go+115 −0internal/console/protectionsetting_test.go+279 −0internal/console/protectionview.go+5 −0internal/console/server.go+1 −0internal/console/templates/app_protection.html+20 −0internal/console/testdata/claim-routes.txt+2 −0internal/console/testdata/perf-budgets.txt+1 −1internal/edge/assetcatch.go+46 −1internal/edge/burst_edge_test.go+113 −2internal/edge/edge.go+5 −1internal/edge/guard.go+36 −6internal/edge/guard_test.go+7 −1internal/host/agent.go+5 −0internal/host/telemetry_pass.go+179 −40internal/host/telemetry_pass_test.go+172 −0internal/telemetry/telemetry.go+28 −4internal/telemetry/telemetry_test.go+43 −0main.go+3 −0protection_cmd.go+81 −0protection_cmd_test.go+134 −0
diff --git a/apimode.go b/apimode.go| index 0f0d248bf..3f8171010 100644 |
| --- a/apimode.go |
| +++ b/apimode.go |
| @@ -44,6 +44,7 @@ import ( |
| "github.com/carlosframework/platform/internal/ratelimit" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/schedule" |
| + "github.com/carlosframework/platform/internal/telemetry" |
| "github.com/carlosframework/platform/internal/updatewords" |
| ) |
| @@ -4140,6 +4141,23 @@ func (s *apiSession) telemetryPut(ctx context.Context, a apiAcct, app string, bo |
| return nil |
| } |
| +// telemetryGet reads an app's stored telemetry settings, as set on the app |
| +// itself (nothing inherited) — GET /api/cli/apps/{account}/{app}/telemetry. |
| +func (s *apiSession) telemetryGet(ctx context.Context, a apiAcct, app string) (telemetry.Settings, error) { |
| + var st telemetry.Settings |
| + status, body, err := s.getJSON(ctx, apiPath(a, app, "/telemetry")) |
| + if err != nil { |
| + return st, err |
| + } |
| + if status != http.StatusOK { |
| + return st, apiErrorFromBody(status, body) |
| + } |
| + if err := json.Unmarshal(body, &st); err != nil { |
| + return st, fmt.Errorf("telemetry: unreadable response: %w", err) |
| + } |
| + return st, nil |
| +} |
| + |
| // instanceDelete retires one instance record. Idempotent server-side (the |
| // caller's goal is "not there"), so a 200 is the only success shape. |
| func (s *apiSession) instanceDelete(ctx context.Context, a apiAcct, app, host string, messages ...string) error { |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index eaa4d1df4..118e60bec 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -1510,6 +1510,16 @@ narrows to one instance. |
| `carlos explain <code> --app <a>` reads a reference code from a page the platform's edge protection answered. It says which rule fired and when, and shows the request while a record of it is kept, for 7 days. |
| +### carlos protection |
| + |
| +```sh |
| +carlos protection [--account a] [--app x] [--record-only on|off] |
| +``` |
| + |
| +Show or set whether protection only records on this app. When this is on, |
| +protection records what it would have blocked on this app and blocks nothing. |
| +Use it if protection is stopping something real while you fix it. |
| + |
| ### carlos errors |
| One row per distinct error, newest first, with how many times it happened |
diff --git a/internal/console/apierrors.go b/internal/console/apierrors.go| index 38aa45814..f8d6b759f 100644 |
| --- a/internal/console/apierrors.go |
| +++ b/internal/console/apierrors.go |
| @@ -98,20 +98,49 @@ func (s *Server) handleAPIAvailability(w http.ResponseWriter, r *http.Request) { |
| writeJSON(w, http.StatusOK, resp) |
| } |
| -// handleAPITelemetryPut sets the app-level telemetry object: the errors log |
| -// level, the analytics keys, or both in one call. Operate only — an app's |
| -// own token must not widen what its owner sees. |
| -func (s *Server) handleAPITelemetryPut(w http.ResponseWriter, r *http.Request) { |
| +// telemetryGate is the instance gate plus the owner rule both telemetry |
| +// doors keep: the browser forms for these settings are owner-only, so the |
| +// person path here is too. A SERVICE holds no account role (AccountByID does |
| +// not populate Role), which is why this reads the kind first. |
| +func (s *Server) telemetryGate(w http.ResponseWriter, r *http.Request) (string, *Account, string, bool) { |
| principal, acct, app, ok := s.instanceGate(w, r) |
| if !ok { |
| - return |
| + return "", nil, "", false |
| } |
| - // The browser form for this setting is owner-only, so the person path |
| - // here is too. A SERVICE holds no account role (AccountByID does not |
| - // populate Role), which is why this reads the kind first. |
| p, _ := principalFrom(r.Context()) |
| if p.Kind == PrincipalUser && acct.Role != RoleOwner { |
| - jsonError(w, http.StatusForbidden, "only an account owner can change an app's telemetry settings") |
| + jsonError(w, http.StatusForbidden, "only an account owner can read or change an app's telemetry settings") |
| + return "", nil, "", false |
| + } |
| + return principal, acct, app, true |
| +} |
| + |
| +// handleAPITelemetryGet answers the app-level telemetry object as stored |
| +// (absent halves absent, so the caller sees what is set on the app itself, |
| +// not what it inherits). The PUT's gate: it is that door's read. |
| +func (s *Server) handleAPITelemetryGet(w http.ResponseWriter, r *http.Request) { |
| + _, acct, app, ok := s.telemetryGate(w, r) |
| + if !ok { |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| + defer cancel() |
| + st, _, err := telemetry.Read(ctx, s.cfg.Releases, telemetry.AppKey(acct.Sqid, app)) |
| + if err != nil { |
| + log.Printf("console: api telemetry read %s/%s: %v", acct.Sqid, app, err) |
| + jsonError(w, http.StatusBadGateway, "could not read the settings") |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, st) |
| +} |
| + |
| +// handleAPITelemetryPut sets the app-level telemetry object: the errors log |
| +// level, the analytics keys, the protection mode, or any of them in one |
| +// call. Operate only — an app's own token must not widen what its owner |
| +// sees. |
| +func (s *Server) handleAPITelemetryPut(w http.ResponseWriter, r *http.Request) { |
| + principal, acct, app, ok := s.telemetryGate(w, r) |
| + if !ok { |
| return |
| } |
| var body telemetry.Settings |
| @@ -122,8 +151,12 @@ func (s *Server) handleAPITelemetryPut(w http.ResponseWriter, r *http.Request) { |
| // Either half may be absent — a caller setting the log level must not |
| // have to restate the analytics keys, and vice versa — but a body that |
| // sets nothing is a mistake worth naming rather than a silent no-op. |
| - if body.Errors == nil && body.Analytics == nil { |
| - jsonError(w, http.StatusBadRequest, "nothing to set: want errors, analytics or both") |
| + if body.Errors == nil && body.Analytics == nil && body.Protection == nil { |
| + jsonError(w, http.StatusBadRequest, "nothing to set: want errors, analytics, protection or more than one") |
| + return |
| + } |
| + if body.Protection != nil && !validProtectionMode(body.Protection.Mode) { |
| + jsonError(w, http.StatusBadRequest, "protection.mode: want record or empty") |
| return |
| } |
| if body.Errors != nil && !telemetry.ValidLogLevel(body.Errors.LogLevel) { |
| @@ -156,6 +189,9 @@ func (s *Server) handleAPITelemetryPut(w http.ResponseWriter, r *http.Request) { |
| if body.Analytics != nil { |
| mergeAnalytics(st, body.Analytics.Count, body.Analytics.Door) |
| } |
| + if body.Protection != nil { |
| + setProtectionMode(st, body.Protection.Mode) |
| + } |
| }); err != nil { |
| log.Printf("console: api telemetry %s/%s: %v", acct.Sqid, app, err) |
| jsonError(w, http.StatusBadGateway, "could not write the setting") |
| @@ -164,18 +200,14 @@ func (s *Server) handleAPITelemetryPut(w http.ResponseWriter, r *http.Request) { |
| // The audit row names what THIS call changed: a PUT that moved the log |
| // level and a PUT that turned counting on must not read alike in the |
| // activity feed, and a half nobody sent must not be claimed as set. |
| - resp, action, changed := map[string]string{}, "", []string(nil) |
| + resp, actions, changed := map[string]string{}, []string(nil), []string(nil) |
| if body.Errors != nil { |
| - action = "errors-level" |
| + actions = append(actions, "errors-level") |
| resp["log_level"] = body.Errors.LogLevel |
| changed = append(changed, "the Errors log level to "+body.Errors.LogLevel) |
| } |
| if body.Analytics != nil { |
| - if action == "" { |
| - action = "analytics-setting" |
| - } else { |
| - action = "telemetry" // both halves in one call |
| - } |
| + actions = append(actions, "analytics-setting") |
| if c := body.Analytics.Count; c != "" { |
| resp["count"] = c |
| changed = append(changed, "analytics counting to "+c) |
| @@ -185,11 +217,25 @@ func (s *Server) handleAPITelemetryPut(w http.ResponseWriter, r *http.Request) { |
| changed = append(changed, "the analytics browser door to "+d) |
| } |
| } |
| + if body.Protection != nil { |
| + actions = append(actions, "protection-setting") |
| + resp["protection_mode"] = body.Protection.Mode |
| + if body.Protection.Mode == telemetry.ProtectRecordOnly { |
| + changed = append(changed, "protection to record only") |
| + } else { |
| + changed = append(changed, "protection to block again") |
| + } |
| + } |
| + action := actions[0] |
| + if len(actions) > 1 { |
| + action = "telemetry" // more than one half in one call |
| + } |
| s.audit(acct, app, principal, action, "set "+strings.Join(changed, " and ")) |
| - if body.Analytics != nil { |
| - // The analytics switch is BOX-consumed: the edge counts or does not, |
| - // so every box has to hear about the change rather than wait for the |
| - // hourly floor. The errors level is console-read and needs no bump. |
| + if body.Analytics != nil || body.Protection != nil { |
| + // The analytics and protection switches are BOX-consumed: the edge |
| + // counts or does not, refuses or only records, so every box has to |
| + // hear about the change rather than wait for the hourly floor. The |
| + // errors level is console-read and needs no bump. |
| s.bumpSerial(ctx) |
| } |
| writeJSON(w, http.StatusOK, resp) |
diff --git a/internal/console/approved_burst_copy_test.go b/internal/console/approved_burst_copy_test.go| index c2b89e51f..f3b7a6897 100644 |
| --- a/internal/console/approved_burst_copy_test.go |
| +++ b/internal/console/approved_burst_copy_test.go |
| @@ -25,6 +25,18 @@ const ( |
| var burstCopyBuilt = map[string]bool{ |
| // Task 1: the 429 body already lives in internal/edge/burst_refusal.go. |
| "PB-C01": true, |
| + // Task 5: the record-only switch, on the Protection tab, its flashes |
| + // and `carlos protection`. |
| + "PB-C03": true, |
| + "PB-C04": true, |
| + "PB-C05": true, |
| + "PB-C06": true, |
| + "PB-C07": true, |
| + "PB-C08": true, |
| + "PB-C09": true, |
| + "PB-C10": true, |
| + "PB-C11": true, |
| + "PB-C12": true, |
| } |
| func parseBurstCopyDeck(t *testing.T) []navCopyRow { |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index ea30fe561..be46b32cc 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -722,6 +722,9 @@ func (s *Server) registerCLIRoutes() { |
| // app's owner, and a credential the app itself holds must not be able to |
| // widen or narrow what its owner is shown. |
| s.cliRoute("PUT /api/cli/apps/{account}/{app}/telemetry", svcrole.Allow(svcrole.Operate), s.handleAPITelemetryPut) |
| + // Its read (`carlos protection` with no flag): the stored settings under |
| + // the PUT's own gate, since they are the settings that PUT writes. |
| + s.cliRoute("GET /api/cli/apps/{account}/{app}/telemetry", svcrole.Allow(svcrole.Operate), s.handleAPITelemetryGet) |
| s.cliScopedRoute("POST /api/cli/apps/{account}/{app}/instances", svcrole.Allow(svcrole.Instance), scopeCreateBody, s.handleAPIInstanceCreate) |
| s.cliScopedRoute("GET /api/cli/apps/{account}/{app}/instances/{host}", svcrole.Allow(svcrole.Instance), scopeHost, s.handleAPIInstanceGet) |
| // PATCH is the multi-upstream repoint (issue #152): the two fields of a |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 37be416a1..ed7c9f687 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -872,6 +872,7 @@ var claimFixtures = map[string]claimFixture{ |
| "reads one object's verdict from its tags or a fallback result; parks on an in-process channel, writes nothing"), |
| "route GET /api/cli/apps/{account}/{app}/tags": claimRead("lists release tags"), |
| "route GET /api/cli/apps/{account}/{app}/tags/{version}": claimRead("reads one tag"), |
| + "route GET /api/cli/apps/{account}/{app}/telemetry": claimRead("reads the app's stored telemetry settings from the bucket; writes nothing"), |
| "route GET /api/cli/apps/{account}/{app}/version-target": claimRead("reads the version target"), |
| "route GET /api/cli/fleets/{account}": claimRead("lists an account's fleets"), |
| "route GET /api/cli/services/{account}": claimRead("lists service credentials"), |
| @@ -1263,6 +1264,12 @@ var claimFixtures = map[string]claimFixture{ |
| }}, |
| // Rename is refused for every app on an enabled console |
| // (claimUnsupported), recordless titogo included. |
| + // The record-only switch writes the app's telemetry.json, as the |
| + // analytics setting does. |
| + "route POST /a/{sqid}/apps/{app}/protection/setting": {door: &claimDoor{ |
| + apps: claimRefs("bab/kass"), |
| + do: claimForm("/a/bab/apps/kass/protection/setting", "mode", "record"), |
| + }}, |
| "route POST /a/{sqid}/apps/{app}/ratelimit": {door: &claimDoor{ |
| apps: claimRefs("bab/titogo"), |
| setup: func(t *testing.T, cx *claimCase) { |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index 9ba677e4f..020b61308 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -18,6 +18,7 @@ import ( |
| "github.com/carlosframework/platform/internal/geoip" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/reqrec" |
| + "github.com/carlosframework/platform/internal/telemetry" |
| ) |
| // claimPageRead is a browser GET of a page, the owner signed in. |
| @@ -277,6 +278,14 @@ var claimReadProbes = map[string]claimProbe{ |
| }, "/api/cli/apps/bab/titogo/store/scan/object?key=claim-fixture.txt", `"state":"clean"`), |
| "route GET /api/cli/apps/{account}/{app}/tags": claimAPIRead(claimWorldTag, "/api/cli/apps/bab/kass/tags", `"version":"0.1.0"`), |
| "route GET /api/cli/apps/{account}/{app}/tags/{version}": claimAPIRead(claimWorldTag, "/api/cli/apps/bab/kass/tags/0.1.0", `"version":"0.1.0"`, `"changelog":"census"`), |
| + "route GET /api/cli/apps/{account}/{app}/telemetry": claimAPIRead(func(t *testing.T, cx *claimCase) { |
| + t.Helper() |
| + if err := telemetry.Update(context.Background(), cx.rel, telemetry.AppKey("bab", "kass"), func(st *telemetry.Settings) { |
| + st.Protection = &telemetry.Protection{Mode: telemetry.ProtectRecordOnly} |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, "/api/cli/apps/bab/kass/telemetry", `"protection":{"mode":"record"}`), |
| "route GET /api/cli/apps/{account}/{app}/version-target": claimAPIRead(nil, "/api/cli/apps/bab/titogo/version-target", `"target"`), |
| "route GET /api/cli/fleets/{account}": claimAPIRead(claimWorldFleet, "/api/cli/fleets/bab", `"pi"`, `"pi-fleet-data"`), |
| "route GET /api/cli/services/{account}": claimAPIRead(func(t *testing.T, cx *claimCase) { cx.service(t) }, |
diff --git a/internal/console/protectionsetting.go b/internal/console/protectionsetting.go| new file mode 100644 |
| index 000000000..f389c2c33 |
| --- /dev/null |
| +++ b/internal/console/protectionsetting.go |
| @@ -0,0 +1,115 @@ |
| +package console |
| + |
| +// The record-only switch (probe-burst spec §5a): one app's protection |
| +// records what it would have refused and refuses nothing. It lives in the |
| +// app's own telemetry.json beside the analytics switch, so it reaches every |
| +// edge serving the app on the same settings pass, and its form door is the |
| +// analytics setting's, gate for gate. The words are the approved burst copy |
| +// deck's (docs/superpowers/plans/2026-10-31-probe-burst-limit-copy.md). |
| + |
| +import ( |
| + "context" |
| + "crypto/subtle" |
| + "log" |
| + "net/http" |
| + "net/url" |
| + |
| + "github.com/carlosframework/platform/internal/telemetry" |
| +) |
| + |
| +// The flashes after a save (deck PB-C08 and PB-C09). |
| +const ( |
| + protectionRecordOnlyFlash = "Protection now records only for this app. It takes effect within seconds." |
| + protectionBlocksFlash = "Protection can block on this app again. It takes effect within seconds." |
| +) |
| + |
| +// validProtectionMode reports whether mode is a protection mode an owner may |
| +// store: record only, or "" for the default. |
| +func validProtectionMode(mode string) bool { |
| + return mode == "" || mode == telemetry.ProtectRecordOnly |
| +} |
| + |
| +// setProtectionMode writes mode into st. Off removes the block, so the |
| +// stored object holds only what someone set. |
| +func setProtectionMode(st *telemetry.Settings, mode string) { |
| + if mode == telemetry.ProtectRecordOnly { |
| + st.Protection = &telemetry.Protection{Mode: mode} |
| + return |
| + } |
| + st.Protection = nil |
| +} |
| + |
| +// protectionAudit is the audit row's detail for a save of mode. |
| +func protectionAudit(mode string) string { |
| + if mode == telemetry.ProtectRecordOnly { |
| + return "set protection to record only for this app" |
| + } |
| + return "set protection to block again for this app" |
| +} |
| + |
| +// handleAppProtectionSetting is the Protection tab's switch: the session, |
| +// then the constant-time CSRF compare, then the bare 404 a non-owner gets, |
| +// as handleAppAnalyticsSetting. The edge acts on it, so the serial moves. |
| +func (s *Server) handleAppProtectionSetting(w http.ResponseWriter, r *http.Request) { |
| + addr, raw, acct, role, app, ok := s.accountApp(w, r) |
| + if !ok { |
| + return |
| + } |
| + if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 { |
| + s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.") |
| + return |
| + } |
| + if role != RoleOwner { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + // The tab's two buttons send one of the two modes; anything else is no |
| + // form of ours. |
| + mode := r.FormValue("mode") |
| + if !validProtectionMode(mode) { |
| + http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) |
| + return |
| + } |
| + back := "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app) + "/protection" |
| + if s.cfg.Releases == nil { |
| + s.setFlash(w, "err", "No deployment bucket on this host, so this setting cannot be stored.") |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| + return |
| + } |
| + if err := s.updateAppTelemetry(r.Context(), acct, app, "protection-setting", func(st *telemetry.Settings) { |
| + setProtectionMode(st, mode) |
| + }); err != nil { |
| + log.Printf("console: protection setting %s/%s: %v", acct.Sqid, app, err) |
| + s.setFlash(w, "err", "The setting could not be saved — try again in a moment.") |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| + return |
| + } |
| + s.audit(acct, app, addr, "protection-setting", protectionAudit(mode)) |
| + // Box-consumed: every edge serving the app picks it up on the next |
| + // settings pass, so the serial moves rather than waiting for the floor. |
| + s.bumpSerial(r.Context()) |
| + flash := protectionBlocksFlash |
| + if mode == telemetry.ProtectRecordOnly { |
| + flash = protectionRecordOnlyFlash |
| + } |
| + s.setFlash(w, "ok", flash) |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| +} |
| + |
| +// readRecordOnly is whether app's own settings turn its protection to record |
| +// only, read under instanceStoreTimeout. ok is false when there is no bucket |
| +// or the read failed: the tab then shows neither the notice nor the control, |
| +// rather than a switch position it does not know. |
| +func (s *Server) readRecordOnly(ctx context.Context, sqid, app string) (on, ok bool) { |
| + if s.cfg.Releases == nil { |
| + return false, false |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, instanceStoreTimeout) |
| + defer cancel() |
| + st, _, err := telemetry.Read(ctx, s.cfg.Releases, telemetry.AppKey(sqid, app)) |
| + if err != nil { |
| + log.Printf("console: protection setting read %s/%s: %v", sqid, app, err) |
| + return false, false |
| + } |
| + return telemetry.RecordOnly(st), true |
| +} |
diff --git a/internal/console/protectionsetting_test.go b/internal/console/protectionsetting_test.go| new file mode 100644 |
| index 000000000..2e112b524 |
| --- /dev/null |
| +++ b/internal/console/protectionsetting_test.go |
| @@ -0,0 +1,279 @@ |
| +package console |
| + |
| +// The record-only switch (probe-burst plan Task 5, spec §5a): the Protection |
| +// tab's control and notice, its owner-only form door, and the CLI's telemetry |
| +// PUT and GET carrying the protection half. Every word checked here is the |
| +// approved burst copy deck's. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| + "github.com/carlosframework/platform/internal/telemetry" |
| +) |
| + |
| +// pbCopy is a burst deck row's approved text with its placeholders filled. |
| +func pbCopy(t *testing.T, id string) string { |
| + t.Helper() |
| + for _, r := range parseBurstCopyDeck(t) { |
| + if r.ID == id { |
| + return r.New |
| + } |
| + } |
| + t.Fatalf("no deck row %s", id) |
| + return "" |
| +} |
| + |
| +// psSerial is the deployment serial boxes converge on. |
| +func psSerial(t *testing.T, fx *consoleFixture) int64 { |
| + t.Helper() |
| + doc, _, err := release.ReadSerial(context.Background(), fx.rel) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return doc.Serial |
| +} |
| + |
| +// psStored is shop's stored app-level telemetry settings. |
| +func psStored(t *testing.T, fx *consoleFixture) telemetry.Settings { |
| + t.Helper() |
| + st, _, err := telemetry.Read(context.Background(), fx.rel, telemetry.AppKey(fx.sqid, "shop")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return st |
| +} |
| + |
| +// psAudits is the account's protection-setting audit rows, newest first. |
| +func psAudits(t *testing.T, fx *consoleFixture) []FeedRow { |
| + t.Helper() |
| + rows, err := fx.st.ActivityFeed(ActivityFilter{AccountID: OpsAccountID, Actions: []string{"protection-setting"}}, 0, 50) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return rows |
| +} |
| + |
| +// psPost sends the tab's form as c, with c's own CSRF token unless csrf is |
| +// given. |
| +func psPost(t *testing.T, fx *consoleFixture, c *http.Client, mode string, csrf ...string) (int, string) { |
| + t.Helper() |
| + tok := sessionToken(t, fx, c) |
| + if len(csrf) > 0 { |
| + tok = csrf[0] |
| + } |
| + status, loc, _ := postForm(t, c, fx.u("/apps/shop/protection/setting"), url.Values{"csrf": {tok}, "mode": {mode}}) |
| + return status, loc |
| +} |
| + |
| +// psMember adds kim to the ops account as a member and signs her in. |
| +func psMember(t *testing.T, fx *consoleFixture) *http.Client { |
| + t.Helper() |
| + if err := fx.st.AddMember(OpsAccountID, "kim@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + c, _ := signInAs(t, fx, "kim@keymail.dev", "code-ps-kim") |
| + return c |
| +} |
| + |
| +// The form door is the analytics setting's: CSRF first, then the bare 404 |
| +// for anyone who is not an owner, and nothing written either way. |
| +func TestProtectionSettingOwnerOnly(t *testing.T) { |
| + fx, paul := ptFixture(t) |
| + kim := psMember(t, fx) |
| + serial := psSerial(t, fx) |
| + |
| + if status, loc := psPost(t, fx, kim, telemetry.ProtectRecordOnly); status != http.StatusNotFound || loc != "" { |
| + t.Fatalf("member = %d -> %q, want the owner gate's 404", status, loc) |
| + } |
| + if status, _ := psPost(t, fx, paul, telemetry.ProtectRecordOnly, "not-the-token"); status != http.StatusForbidden { |
| + t.Fatalf("owner without the CSRF token = %d, want 403", status) |
| + } |
| + if st := psStored(t, fx); st.Protection != nil { |
| + t.Fatalf("a refused post wrote %+v", st.Protection) |
| + } |
| + if got := psSerial(t, fx); got != serial { |
| + t.Fatalf("a refused post moved the serial %d -> %d", serial, got) |
| + } |
| + if rows := psAudits(t, fx); len(rows) != 0 { |
| + t.Fatalf("a refused post was audited: %+v", rows) |
| + } |
| + // A non-member gets the 404 every app page gives. |
| + fx.setUser("bob@keymail.dev") |
| + bob := newBrowser(t) |
| + signUp(t, fx, bob, "code-ps-bob") |
| + if status, _ := psPost(t, fx, bob, telemetry.ProtectRecordOnly); status != http.StatusNotFound { |
| + t.Fatalf("non-member = %d, want 404", status) |
| + } |
| +} |
| + |
| +// On and off each write the app's own telemetry.json (leaving its other |
| +// halves alone), audit, move the serial so boxes converge within seconds, |
| +// and come back to the tab with the deck's flash. |
| +func TestProtectionSettingWritesAndBumps(t *testing.T) { |
| + fx, paul := ptFixture(t) |
| + ctx := context.Background() |
| + if err := telemetry.Update(ctx, fx.rel, telemetry.AppKey(fx.sqid, "shop"), func(st *telemetry.Settings) { |
| + st.Analytics = &telemetry.Analytics{Count: telemetry.CountEdge} |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + for i, c := range []struct { |
| + mode, flash string |
| + on bool |
| + }{ |
| + {telemetry.ProtectRecordOnly, "PB-C08", true}, |
| + {"", "PB-C09", false}, |
| + } { |
| + serial := psSerial(t, fx) |
| + status, loc := psPost(t, fx, paul, c.mode) |
| + if want := fx.path("/apps/shop/protection"); status != http.StatusSeeOther || loc != want { |
| + t.Fatalf("mode %q = %d -> %q, want 303 to %q", c.mode, status, loc, want) |
| + } |
| + st := psStored(t, fx) |
| + if telemetry.RecordOnly(st) != c.on || st.Analytics == nil || st.Analytics.Count != telemetry.CountEdge { |
| + t.Fatalf("mode %q stored %+v", c.mode, st) |
| + } |
| + if !c.on && st.Protection != nil { |
| + t.Fatalf("off left a protection block behind: %+v", st.Protection) |
| + } |
| + if got := psSerial(t, fx); got <= serial { |
| + t.Fatalf("mode %q did not move the serial (%d -> %d)", c.mode, serial, got) |
| + } |
| + rows := psAudits(t, fx) |
| + if len(rows) != i+1 || rows[0].App != "shop" || rows[0].Address != "paul@keymail.dev" { |
| + t.Fatalf("mode %q audit rows %+v", c.mode, rows) |
| + } |
| + if _, _, body := get(t, paul, fx.ts.URL+loc); !strings.Contains(body, pbCopy(t, c.flash)) { |
| + t.Fatalf("mode %q: the tab does not show %s", c.mode, c.flash) |
| + } |
| + } |
| + // A mode no box knows is refused and writes nothing. |
| + serial := psSerial(t, fx) |
| + if status, _ := psPost(t, fx, paul, "block"); status != http.StatusBadRequest { |
| + t.Fatalf("an unknown mode = %d, want 400", status) |
| + } |
| + if st := psStored(t, fx); st.Protection != nil || psSerial(t, fx) != serial { |
| + t.Fatalf("an unknown mode wrote %+v", st.Protection) |
| + } |
| +} |
| + |
| +// The tab says when the switch is on, to everyone who can see the tab, and |
| +// shows the control to owners only, its button naming what it will do. |
| +func TestProtectionTabShowsRecordOnly(t *testing.T) { |
| + fx, paul := ptFixture(t) |
| + kim := psMember(t, fx) |
| + heading, explain, on, off, notice := pbCopy(t, "PB-C03"), pbCopy(t, "PB-C04"), pbCopy(t, "PB-C05"), pbCopy(t, "PB-C06"), pbCopy(t, "PB-C07") |
| + |
| + page := ptPage(t, fx, paul, "") |
| + ptWant(t, page, heading, explain, on, `action="`+fx.path("/apps/shop/protection/setting")+`"`, `name="mode" value="record"`) |
| + ptRefuse(t, page, off, notice) |
| + ptRefuse(t, ptPage(t, fx, kim, ""), heading, explain, on, off, notice, "/protection/setting") |
| + |
| + if status, _ := psPost(t, fx, paul, telemetry.ProtectRecordOnly); status != http.StatusSeeOther { |
| + t.Fatalf("turn on = %d", status) |
| + } |
| + page = ptPage(t, fx, paul, "") |
| + ptWant(t, page, heading, explain, off, notice, `name="mode" value=""`) |
| + ptRefuse(t, page, on) |
| + page = ptPage(t, fx, kim, "") |
| + ptWant(t, page, notice) |
| + ptRefuse(t, page, heading, explain, on, off, "/protection/setting") |
| + |
| + // The notice stands above counts too. |
| + ptSeed(t, fx, 10, 2, 0, map[string]int64{"hard/secrets": 2}) |
| + ptWant(t, ptPage(t, fx, paul, ""), notice) |
| +} |
| + |
| +// The CLI's telemetry PUT takes the protection half on its own: an owner's |
| +// on and off each write, audit and move the serial exactly as an analytics |
| +// write does, and answer what was set. |
| +func TestAPITelemetryProtectionOnlyBumps(t *testing.T) { |
| + fx, _ := ptFixture(t) |
| + putURL := fx.ts.URL + "/api/cli/apps/" + fx.sqid + "/shop/telemetry" |
| + owner := cliToken(t, fx, "paul@keymail.dev", "code-ps-owner") |
| + for i, c := range []struct { |
| + body, mode string |
| + }{ |
| + {`{"protection":{"mode":"record"}}`, "record"}, |
| + {`{"protection":{"mode":""}}`, ""}, |
| + } { |
| + serial := psSerial(t, fx) |
| + status, _, body := rawReq(t, http.MethodPut, putURL, owner, c.body) |
| + if status != http.StatusOK { |
| + t.Fatalf("%s = %d %s", c.body, status, body) |
| + } |
| + var resp map[string]string |
| + if err := json.Unmarshal([]byte(body), &resp); err != nil || resp["protection_mode"] != c.mode { |
| + t.Fatalf("%s answered %s (%v)", c.body, body, err) |
| + } |
| + if got := telemetry.RecordOnly(psStored(t, fx)); got != (c.mode == "record") { |
| + t.Fatalf("%s stored record-only %v", c.body, got) |
| + } |
| + if got := psSerial(t, fx); got <= serial { |
| + t.Fatalf("%s did not move the serial (%d -> %d)", c.body, serial, got) |
| + } |
| + if rows := psAudits(t, fx); len(rows) != i+1 || rows[0].App != "shop" { |
| + t.Fatalf("%s audit rows %+v", c.body, rows) |
| + } |
| + } |
| + if status, _, body := rawReq(t, http.MethodPut, putURL, owner, `{"protection":{"mode":"block"}}`); status != http.StatusBadRequest { |
| + t.Fatalf("an unknown mode = %d %s, want 400", status, body) |
| + } |
| + // A member may not, as for every half of this PUT. |
| + if err := fx.st.AddMember(OpsAccountID, "kim@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + member := cliToken(t, fx, "kim@keymail.dev", "code-ps-member") |
| + if status, _, body := rawReq(t, http.MethodPut, putURL, member, `{"protection":{"mode":"record"}}`); status != http.StatusForbidden { |
| + t.Fatalf("member PUT = %d %s, want 403", status, body) |
| + } |
| + if telemetry.RecordOnly(psStored(t, fx)) { |
| + t.Fatal("a refused PUT wrote") |
| + } |
| +} |
| + |
| +// The read beside the PUT: the app's stored settings as stored, under the |
| +// PUT's gate (Operate, and a person must own the account). |
| +func TestAPITelemetryGet(t *testing.T) { |
| + fx, _ := ptFixture(t) |
| + getURL := fx.ts.URL + "/api/cli/apps/" + fx.sqid + "/shop/telemetry" |
| + op := serviceToken(t, fx.st, OpsAccountID, "ops", "shop", svcrole.Operate) |
| + status, _, body := rawReq(t, http.MethodGet, getURL, op, "") |
| + if status != http.StatusOK || strings.TrimSpace(body) != "{}" { |
| + t.Fatalf("nothing stored = %d %s, want {}", status, body) |
| + } |
| + if err := telemetry.Update(context.Background(), fx.rel, telemetry.AppKey(fx.sqid, "shop"), func(st *telemetry.Settings) { |
| + st.Protection = &telemetry.Protection{Mode: telemetry.ProtectRecordOnly} |
| + st.Errors = &telemetry.Errors{LogLevel: telemetry.LogLevelWarn} |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + owner := cliToken(t, fx, "paul@keymail.dev", "code-ps-get-owner") |
| + for _, tok := range []string{op, owner} { |
| + status, _, body := rawReq(t, http.MethodGet, getURL, tok, "") |
| + var st telemetry.Settings |
| + if status != http.StatusOK || json.Unmarshal([]byte(body), &st) != nil || !telemetry.RecordOnly(st) || |
| + st.Errors == nil || st.Errors.LogLevel != telemetry.LogLevelWarn { |
| + t.Fatalf("GET = %d %s", status, body) |
| + } |
| + } |
| + inst := serviceToken(t, fx.st, OpsAccountID, "router", "shop", svcrole.Instance) |
| + if status, _, body := rawReq(t, http.MethodGet, getURL, inst, ""); status != http.StatusForbidden && status != http.StatusNotFound { |
| + t.Fatalf("instance token GET = %d %s", status, body) |
| + } |
| + if err := fx.st.AddMember(OpsAccountID, "kim@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + member := cliToken(t, fx, "kim@keymail.dev", "code-ps-get-member") |
| + if status, _, body := rawReq(t, http.MethodGet, getURL, member, ""); status != http.StatusForbidden { |
| + t.Fatalf("member GET = %d %s, want 403", status, body) |
| + } |
| +} |
diff --git a/internal/console/protectionview.go b/internal/console/protectionview.go| index 62092ff03..f69c8b60e 100644 |
| --- a/internal/console/protectionview.go |
| +++ b/internal/console/protectionview.go |
| @@ -45,6 +45,10 @@ type protectionView struct { |
| Groups []shareRow |
| // LogsURL opens Logs filtered to the same requests the counts cover. |
| LogsURL string |
| + // RecordOnly is the app's record-only switch (probe-burst spec §5a), |
| + // and RecordOnlyKnown whether it could be read: the notice and the |
| + // owner's control show only when it was. |
| + RecordOnly, RecordOnlyKnown bool |
| } |
| // protectionRange reads the tab's range: 30d, or 7d for anything else. A |
| @@ -82,6 +86,7 @@ func (s *Server) handleAppProtection(w http.ResponseWriter, r *http.Request) { |
| now := time.Now() |
| rng, days := protectionRange(r.URL.Query()) |
| v := &protectionView{Range: rng, Days: days} |
| + v.RecordOnly, v.RecordOnlyKnown = s.readRecordOnly(r.Context(), acct.Sqid, p.AppName) |
| dates := protectionDates(days, now) |
| sum, err := s.readProtection(r.Context(), acct.Sqid, p.AppName, dates, now) |
| if err != nil { |
diff --git a/internal/console/server.go b/internal/console/server.go| index 004be63f5..3ac627a1e 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1880,6 +1880,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| // like the Analytics tab, through the same gate. |
| s.registerRoute("GET /a/{sqid}/apps/{app}/protection", s.handleAppProtection) |
| s.registerRoute("GET /a/{sqid}/apps/{app}/protection/data", s.handleAppProtectionData) |
| + s.registerRoute("POST /a/{sqid}/apps/{app}/protection/setting", s.handleAppProtectionSetting) |
| s.registerRoute("GET /a/{sqid}/apps/{app}/activity", s.handleAppActivity) |
| s.registerRoute("GET /a/{sqid}/apps/{app}/settings", s.handleAppSettings) |
| s.registerRoute("GET /a/{sqid}/apps/{app}/settings/{section}", s.handleAppSettings) |
diff --git a/internal/console/templates/app_protection.html b/internal/console/templates/app_protection.html| index 09550d128..fda299f84 100644 |
| --- a/internal/console/templates/app_protection.html |
| +++ b/internal/console/templates/app_protection.html |
| @@ -5,6 +5,7 @@ |
| <h2 class="visually-hidden">Protection</h2> |
| {{with .Protection}} |
| +{{if and .RecordOnlyKnown .RecordOnly}}<p class="banner">Protection is recording only for this app. Nothing is blocked.</p>{{end}} |
| {{/* Two links rather than a select and a button, as the Analytics tab: |
| one click, and every view is a URL. */}} |
| <nav class="an-range" aria-label="Period"> |
| @@ -48,5 +49,24 @@ |
| {{template "analyticsscript"}} |
| {{end}} |
| {{end}} |
| +{{/* The record-only switch (probe-burst spec §5a), for owners, whatever |
| + the counts say: it is the way out when protection stops something |
| + real. One button, naming what it will do. */}} |
| +{{if and $.IsOwner .RecordOnlyKnown}} |
| +<section aria-labelledby="pt-record-only"> |
| + <h3 id="pt-record-only">Record only</h3> |
| + <p>When this is on, protection records what it would have blocked on this app and blocks nothing. Use it if protection is stopping something real while you fix it.</p> |
| + <form method="post" action="{{$.Base}}/apps/{{$.AppName}}/protection/setting"> |
| + <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| + {{- if .RecordOnly}} |
| + <input type="hidden" name="mode" value=""> |
| + <button type="submit">Let protection block again</button> |
| + {{- else}} |
| + <input type="hidden" name="mode" value="record"> |
| + <button type="submit">Record only for this app</button> |
| + {{- end}} |
| + </form> |
| +</section> |
| +{{end}} |
| {{end}} |
| {{template "bottom" .}}{{end}} |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index dd0b6c269..3c2a9111d 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -94,6 +94,7 @@ route GET /api/cli/apps/{account}/{app}/store/scan |
| route GET /api/cli/apps/{account}/{app}/store/scan/object |
| route GET /api/cli/apps/{account}/{app}/tags |
| route GET /api/cli/apps/{account}/{app}/tags/{version} |
| +route GET /api/cli/apps/{account}/{app}/telemetry |
| route GET /api/cli/apps/{account}/{app}/version-target |
| route GET /api/cli/billing/problems |
| route GET /api/cli/fleets/{account} |
| @@ -163,6 +164,7 @@ route POST /a/{sqid}/apps/{app}/pipeline |
| route POST /a/{sqid}/apps/{app}/place |
| route POST /a/{sqid}/apps/{app}/production |
| route POST /a/{sqid}/apps/{app}/promote |
| +route POST /a/{sqid}/apps/{app}/protection/setting |
| route POST /a/{sqid}/apps/{app}/ratelimit |
| route POST /a/{sqid}/apps/{app}/region |
| route POST /a/{sqid}/apps/{app}/rename |
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt| index ca38dcb2d..1c34f34b8 100644 |
| --- a/internal/console/testdata/perf-budgets.txt |
| +++ b/internal/console/testdata/perf-budgets.txt |
| @@ -66,7 +66,7 @@ GET /a/{sqid}/apps/{app}/logs/data deferred: deferred part (the Logs tab's data |
| /fleet/architecture calls 12: reads economics/active.json, infra/inventory.json and status/fleet.json, and lists and reads every box report (12 S3 calls warm and cold, about 390 ms) |
| GET /a/{sqid}/apps/{app}/analytics/live calls 2: the live door the Analytics tab and Overview card refresh from once a minute: both telemetry settings, read on every refresh so an owner turning analytics on sees it at once; the window's counts come from the traffic memo, read at most once a minute per app and view (about 50 ms) |
| GET /a/{sqid}/apps/{app}/analytics calls 4: both telemetry settings, the analytics day listing and one day read (about 105 ms); cold, also the app-tab frame and the account manifest (11 S3 calls, about 190 ms) |
| -GET /a/{sqid}/apps/{app}/protection calls 2: the Protection tab reads the edge days: one box listing at the root and one in each fleet the account owns (the walk's fixture: two listings and no edge days, about 55 ms); each box adds its today's and yesterday's day, which never settle, and the usage-day cache answers the rest; cold, also the app-tab frame and the account manifest (9 S3 calls, about 135 ms) |
| +GET /a/{sqid}/apps/{app}/protection calls 3: the Protection tab reads the edge days: one box listing at the root and one in each fleet the account owns (the walk's fixture: two listings and no edge days); each box adds its today's and yesterday's day, which never settle, and the usage-day cache answers the rest; and the app's telemetry.json for the record-only switch (3 S3 calls, about 85 ms); cold, also the app-tab frame and the account manifest (10 S3 calls, about 160 ms) |
| GET /a/{sqid}/apps/{app}/protection/data calls 2: the Protection tab's JSON door, the same edge-day read without the app-tab frame (about 55 ms) |
| GET /a/{sqid}/apps/{app}/availability calls 10: both telemetry settings and three listings and a read each for the log and error chunks (about 265 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 340 ms) |
| GET /a/{sqid}/apps/{app}/errors calls 10: both telemetry settings and three listings and a read each for the log and error chunks (about 265 ms); cold, also the app-tab frame and the account manifest (17 S3 calls, about 340 ms) |
diff --git a/internal/edge/assetcatch.go b/internal/edge/assetcatch.go| index 82bf114a9..871da1093 100644 |
| --- a/internal/edge/assetcatch.go |
| +++ b/internal/edge/assetcatch.go |
| @@ -12,6 +12,7 @@ import ( |
| "net/http/httputil" |
| "net/url" |
| "path" |
| + "slices" |
| "strconv" |
| "strings" |
| "sync" |
| @@ -1029,6 +1030,48 @@ func (e *Edge) farAssetCatch(r *http.Request, host string) (a HostAssets, eip, b |
| return a, eip, box, key, true |
| } |
| +// AssetOwners is the (account, app) of every host this edge's far asset |
| +// catch can serve: the published asset blocks in the home map, one route per |
| +// app (its first host), carrying Host, Account, App and Kind "instance" as |
| +// the catch's synthetic route does. The home map holds only other boxes' |
| +// hosts, so these are apps this edge serves without a local route. The |
| +// host's telemetry pass resolves their settings beside its routes', so an |
| +// edge serving only an app's declared assets knows its record-only switch. |
| +// Nil while the cache is not armed, when the catch serves nothing. |
| +// |
| +// Freshness is not checked: a block that is stale now may be fresh again |
| +// after the next publish, and the switch should already be there when it is. |
| +func (e *Edge) AssetOwners() []registry.Route { |
| + if st := e.assets.Load(); st == nil || st.store == nil { |
| + return nil |
| + } |
| + m := e.homes.Load() |
| + if m == nil || m.self == "" { |
| + return nil |
| + } |
| + snap := m.snapshot() |
| + hosts := make([]string, 0, len(snap.hosts)) |
| + for h := range snap.hosts { |
| + hosts = append(hosts, h) |
| + } |
| + slices.Sort(hosts) |
| + var out []registry.Route |
| + seen := map[string]bool{} |
| + for _, host := range hosts { |
| + h := snap.hosts[host] |
| + if !h.dial || h.account == "" || h.app == "" || h.assets == nil || h.assets.Gen == "" || len(h.assets.Paths) == 0 { |
| + continue |
| + } |
| + key := h.account + "/" + h.app |
| + if seen[key] { |
| + continue |
| + } |
| + seen[key] = true |
| + out = append(out, registry.Route{Host: host, Account: h.account, App: h.app, Kind: "instance"}) |
| + } |
| + return out |
| +} |
| + |
| // serveAssetFar is the far catch (§5.1, §5.3): called on both forwarding |
| // paths, the exact-remote precedence branch and the lookup-miss branch, just |
| // before the backhaul each would make. It reports whether it answered; false |
| @@ -1125,7 +1168,9 @@ func (e *Edge) serveAssetFar(w http.ResponseWriter, r *http.Request, host string |
| // block is billed and recorded like any answer. |
| if e.guard != guardOff && !fromTunnel(r.Context()) { |
| r, out = withOutcome(r) |
| - out.guard = e.newGuardState() |
| + // The owner's record-only switch reaches this edge through |
| + // AssetOwners, since it has no route for the app. |
| + out.guard = e.newGuardState(rt) |
| if hit, matched := edgeguard.Check(r.URL.Path, r.URL.RawQuery); matched && guardDecide(cw, r, hit) { |
| billed = true |
| return true |
diff --git a/internal/edge/burst_edge_test.go b/internal/edge/burst_edge_test.go| index 0095e7e27..a934ce340 100644 |
| --- a/internal/edge/burst_edge_test.go |
| +++ b/internal/edge/burst_edge_test.go |
| @@ -486,7 +486,13 @@ type burstFar struct { |
| func newBurstFar(t *testing.T, app http.HandlerFunc) *burstFar { |
| t.Helper() |
| - t.Setenv("CARLOS_EDGE_PROTECT", "") |
| + return newBurstFarIn(t, "", app) |
| +} |
| + |
| +// newBurstFarIn is newBurstFar with both edges in the protection mode protect. |
| +func newBurstFarIn(t *testing.T, protect string, app http.HandlerFunc) *burstFar { |
| + t.Helper() |
| + t.Setenv("CARLOS_EDGE_PROTECT", protect) |
| clock := newBurstClock() |
| x := &burstFar{served: new(atomic.Int32), farRec: &lockedRecorder{}, homeRec: &lockedRecorder{}} |
| x.s = newFarEdge(t, func(key []byte, m *homeMap) http.Handler { |
| @@ -706,7 +712,7 @@ func TestBurstRecordOnlyBlocksNothing(t *testing.T) { |
| }, edgeguard.BurstRule.ID}, |
| } { |
| r, out := withOutcome(httptest.NewRequest("GET", "http://"+burstHost+"/.env", nil)) |
| - out.guard = g.e.newGuardState() |
| + out.guard = g.e.newGuardState(registry.Route{Host: burstHost, Account: "bdk", App: "shop", Kind: "instance"}) |
| out.guard.recordOnly = true |
| w := httptest.NewRecorder() |
| if tc.decide(w, r) || w.Code != 200 || w.Body.Len() != 0 { |
| @@ -860,3 +866,108 @@ func TestBurstStaleBrowserFillCountedNowhere(t *testing.T) { |
| t.Fatalf("scanner misses through a stale far edge: far %d, home %d; want 0 and 3", far, home) |
| } |
| } |
| + |
| +// Review Focus 5 (probe-burst plan Task 5): the record-only switch flipped |
| +// while a client is cooling. In block mode the cooling scanner's next |
| +// catalogue request to that app reaches the app and is recorded, and so does |
| +// a hard-tier path from anyone; another app on the platform still refuses |
| +// the cooling client, since the switch is per app. |
| +func TestRecordOnlyNeverRefuses(t *testing.T) { |
| + g := newBurstRig(t, "block") |
| + until := g.trip(t, burstHost) |
| + g.e.SetProtectionRecordOnly(map[string]bool{"bdk/shop": true}) |
| + |
| + n := g.upstream.Load() |
| + w := g.get(burstHost, "/wp-login.php") |
| + if w.Code != 404 || w.Body.String() != "the app's own 404" || g.upstream.Load() != n+1 { |
| + t.Fatalf("record only: %d %q, upstream %d; want the app's answer", w.Code, w.Body.String(), g.upstream.Load()-n) |
| + } |
| + m := g.lastMatch(t, "/wp-login.php") |
| + wantBurstMatch(t, m, reqrec.KindWatch, reqrec.CooldownFromThisApp, until) |
| + if m.Ref != "" { |
| + t.Fatalf("record only: a code was minted for %+v", m) |
| + } |
| + |
| + // The hard tier, from the cooling scanner and from a client that is not |
| + // cooling: both reach the app, both are recorded. |
| + for _, from := range []string{"", "198.51.100.7:4000"} { |
| + r := httptest.NewRequest("GET", "http://"+burstHost+"/.env", nil) |
| + if from != "" { |
| + r.RemoteAddr = from |
| + } |
| + w := httptest.NewRecorder() |
| + n := g.upstream.Load() |
| + g.e.ServeHTTP(w, r) |
| + if w.Code != 404 || w.Body.String() != "the app's own 404" || g.upstream.Load() != n+1 { |
| + t.Fatalf("/.env from %q: %d %q; want the app's answer", from, w.Code, w.Body.String()) |
| + } |
| + m := g.lastMatch(t, "/.env") |
| + if m.Kind != reqrec.KindWatch || m.Ref != "" { |
| + t.Fatalf("/.env from %q: match %+v, want recorded", from, m) |
| + } |
| + if from != "" && m.RuleID != "hard.secrets.env" { |
| + t.Fatalf("/.env from a client not cooling: match %+v, want the hard rule", m) |
| + } |
| + } |
| + |
| + // Another app still refuses the cooling client. |
| + g.wantRefused(t, g.get(burstOther, "/wp-login.php"), until) |
| + |
| + // Off again: the same request is refused. |
| + g.e.SetProtectionRecordOnly(nil) |
| + g.wantRefused(t, g.get(burstHost, "/wp-login.php"), until) |
| +} |
| + |
| +// R1-2: an edge that serves an app only through the far asset catch has no |
| +// route for it, so the switch reaches it through AssetOwners: the owners the |
| +// telemetry pass resolves beside the edge's routes. With the switch on, the |
| +// far edge's own guard (block mode) lets a hard-tier asset path go on to the |
| +// home rather than answering the block page; with it off the far edge |
| +// refuses, as before. |
| +func TestRecordOnlyReachesFarAssetEdge(t *testing.T) { |
| + x := newBurstFarIn(t, "block", func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusNotFound) |
| + io.WriteString(w, "the app's own 404") |
| + }) |
| + // The home serves the app from its own route, as the pass resolves it |
| + // there; the far edge has no route for it, only the published asset |
| + // block. |
| + x.home.e.SetProtectionRecordOnly(map[string]bool{"abc/shop": true}) |
| + if _, ok := x.s.e.lookupUpstream(laHost); ok { |
| + t.Fatal("the far edge has a route for the app") |
| + } |
| + |
| + // Off on the far edge: its own block page, and the home never sees it. |
| + w := x.s.get(t, "/assets/.env") |
| + if w.Code != 404 || w.Header().Get("X-Carlos-Ref") == "" || x.served.Load() != 0 { |
| + t.Fatalf("switch off: %d ref %q, home served %d; want the far edge's block page", w.Code, w.Header().Get("X-Carlos-Ref"), x.served.Load()) |
| + } |
| + |
| + // What the pass does with the owners: the same key it builds for a route. |
| + owners := x.s.e.AssetOwners() |
| + on := map[string]bool{} |
| + for _, rt := range owners { |
| + on[release.RouteAccount(rt)+"/"+rt.App] = true |
| + } |
| + if len(owners) != 1 || !on["abc/shop"] || owners[0].Host != laHost { |
| + t.Fatalf("asset owners %+v, want abc/shop for %s", owners, laHost) |
| + } |
| + x.s.e.SetProtectionRecordOnly(on) |
| + |
| + w = x.s.get(t, "/assets/.env") |
| + x.waitHome(t, 1) |
| + if w.Code != 404 || w.Header().Get("X-Carlos-Ref") != "" || !strings.Contains(w.Body.String(), "the app's own 404") { |
| + t.Fatalf("switch on: %d ref %q body %q; want the app's answer", w.Code, w.Header().Get("X-Carlos-Ref"), w.Body.String()) |
| + } |
| + x.homeRec.mu.Lock() |
| + defer x.homeRec.mu.Unlock() |
| + var got []reqrec.Match |
| + for _, m := range x.homeRec.match { |
| + if m.Path == "/assets/.env" { |
| + got = append(got, m) |
| + } |
| + } |
| + if len(got) != 1 || got[0].Kind != reqrec.KindWatch || got[0].RuleID != "hard.secrets.env" || got[0].Ref != "" { |
| + t.Fatalf("home matches %+v, want one recorded hard.secrets.env", got) |
| + } |
| +} |
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index b05283a7c..f910336e7 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -193,6 +193,10 @@ type Edge struct { |
| // every app nobody has switched on. |
| analyticsMeter atomic.Pointer[analyticsMeterRef] |
| analyticsOn atomic.Pointer[map[string]bool] |
| + // protectRecordOnly is the record-only switch map (guard.go), keyed as |
| + // analyticsOn is and replaced by the same pass. Nil = no app is record |
| + // only, which is every box until the pass first runs. |
| + protectRecordOnly atomic.Pointer[map[string]bool] |
| // requestRecords, when set, receives every response the observer defer |
| // sees and every protection-rule match (reqrecords.go). Atomic like |
| // analyticsMeter, so it can be wired after construction while serving |
| @@ -2190,7 +2194,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // checked, and is recorded, by the hub that forwarded it, so |
| // checking it again here would answer or count it twice. |
| if e.guard != guardOff && !isDoor && !hopDoorFrom(r.Context()) && !fromTunnel(r.Context()) { |
| - out.guard = e.newGuardState() |
| + out.guard = e.newGuardState(up.route) |
| out.guard.acct, out.guard.app = release.RouteAccount(up.route), up.route.App |
| } |
| defer func() { |
diff --git a/internal/edge/guard.go b/internal/edge/guard.go| index 8ad974637..b3089abad 100644 |
| --- a/internal/edge/guard.go |
| +++ b/internal/edge/guard.go |
| @@ -102,16 +102,46 @@ type guardState struct { |
| acct, app string |
| } |
| -// newGuardState is the guard's state for one request. It costs the struct |
| -// and nothing else: the mint function was bound in New. An Edge built |
| -// without New has none bound and pays for the method value instead, so a |
| -// block never calls a nil func. |
| -func (e *Edge) newGuardState() *guardState { |
| +// newGuardState is the guard's state for one request to rt's app. It costs |
| +// the struct and nothing else: the mint function was bound in New, and the |
| +// switch lookup's key is built on the stack. An Edge built without New has |
| +// none bound and pays for the method value instead, so a block never calls a |
| +// nil func. |
| +func (e *Edge) newGuardState(rt registry.Route) *guardState { |
| mint := e.guardMint |
| if mint == nil { |
| mint = e.mintRef |
| } |
| - return &guardState{mode: e.guard, mint: mint, burst: e.burst} |
| + return &guardState{mode: e.guard, mint: mint, burst: e.burst, recordOnly: e.protectionRecordOnly(rt)} |
| +} |
| + |
| +// SetProtectionRecordOnly replaces the record-only switch map: sqid+"/"+app |
| +// → protection records and refuses nothing for that app (probe-burst spec |
| +// §5a). The host's telemetry pass pushes it with the analytics switches. The |
| +// map is copied before it is stored, as SetAnalyticsOn's is, for the same |
| +// reason: every serving goroutine reads the stored copy without a lock. |
| +func (e *Edge) SetProtectionRecordOnly(m map[string]bool) { |
| + if len(m) == 0 { |
| + e.protectRecordOnly.Store(nil) |
| + return |
| + } |
| + cp := make(map[string]bool, len(m)) |
| + for k, v := range m { |
| + if v { |
| + cp[k] = true |
| + } |
| + } |
| + e.protectRecordOnly.Store(&cp) |
| +} |
| + |
| +// protectionRecordOnly reports whether rt's app has the record-only switch |
| +// on. |
| +func (e *Edge) protectionRecordOnly(rt registry.Route) bool { |
| + m := e.protectRecordOnly.Load() |
| + if m == nil { |
| + return false |
| + } |
| + return (*m)[release.RouteAccount(rt)+"/"+rt.App] |
| } |
| // blocks reports whether a match on rule is answered here rather than |
diff --git a/internal/edge/guard_test.go b/internal/edge/guard_test.go| index bbe424cb9..4888b5c2c 100644 |
| --- a/internal/edge/guard_test.go |
| +++ b/internal/edge/guard_test.go |
| @@ -423,10 +423,16 @@ func TestGuardSkipsDoorCalls(t *testing.T) { |
| func TestGuardStateAllocs(t *testing.T) { |
| g := guardEdge(t, false, false, http.StatusOK, "app") |
| var keep *guardState |
| - if n := testing.AllocsPerRun(100, func() { keep = g.e.newGuardState() }); n != 1 { |
| + // A switch map is set and the route is in it, so the lookup is paid for. |
| + rt := registry.Route{Host: "shop.example.com", Account: "bdk", App: "shop", Kind: "instance"} |
| + g.e.SetProtectionRecordOnly(map[string]bool{"bdk/shop": true}) |
| + if n := testing.AllocsPerRun(100, func() { keep = g.e.newGuardState(rt) }); n != 1 { |
| t.Fatalf("newGuardState allocates %v times, want 1 (the struct)", n) |
| } |
| if keep.mint == nil { |
| t.Fatal("no mint function bound") |
| } |
| + if !keep.recordOnly { |
| + t.Fatal("the app's record-only switch did not reach its guard state") |
| + } |
| } |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 8d2a63fb4..5ec9a93ed 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -1071,6 +1071,11 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| am := analytics.NewMeter(dataDir(), status.Label(readMachineID()), time.Now) |
| e.EnableAnalytics(am) |
| setAnalyticsSink(e.SetAnalyticsOn) |
| + // The record-only switch rides the same pass (probe-burst spec §5a): |
| + // the apps this box routes, and the apps its far asset catch serves |
| + // without a route. |
| + setProtectionSink(e.SetProtectionRecordOnly) |
| + setAssetOwnersSource(e.AssetOwners) |
| go usageLoop(m.Drain, am) |
| // Edge request records (spec 2026-10-24-edge-request-protection-design): |
| // sampled 404 and rule-match records plus per-minute counts, filed |
diff --git a/internal/host/telemetry_pass.go b/internal/host/telemetry_pass.go| index c4a598e9d..e5fc1c8d3 100644 |
| --- a/internal/host/telemetry_pass.go |
| +++ b/internal/host/telemetry_pass.go |
| @@ -1,12 +1,15 @@ |
| // The analytics switch pass (spec 2026-09-07 §3.3): resolve |
| // telemetry.json app → account → default for every (account, app) this |
| -// box serves and hand the edge a fresh switch map. Rides the serial- |
| -// triggered full pass and the five-minute instances loop, so a console |
| -// write lands within seconds and the hourly floor stands underneath. |
| +// box serves and hand the edge a fresh switch map. The same reads give the |
| +// edge the record-only switch map (probe-burst spec §5a), app level only. |
| +// Rides the serial-triggered full pass and the five-minute instances loop, |
| +// so a console write lands within seconds and the hourly floor stands |
| +// underneath. |
| package host |
| import ( |
| "context" |
| + "errors" |
| "log" |
| "sync" |
| "sync/atomic" |
| @@ -23,6 +26,72 @@ var analyticsSink atomic.Pointer[func(map[string]bool)] |
| // SetAnalyticsOn), the way setUpstreamSource publishes the prober table. |
| func setAnalyticsSink(fn func(map[string]bool)) { analyticsSink.Store(&fn) } |
| +// protectionSink is where the record-only switch map goes (the edge's |
| +// SetProtectionRecordOnly, probe-burst spec §5a): the same pass, the same |
| +// keys, its own map. |
| +var protectionSink atomic.Pointer[func(map[string]bool)] |
| + |
| +func setProtectionSink(fn func(map[string]bool)) { protectionSink.Store(&fn) } |
| + |
| +// assetOwnersSource lists the apps the edge's far asset catch serves without |
| +// a local route (the edge's AssetOwners). The pass resolves their |
| +// record-only switch too, so an edge serving only an app's declared assets |
| +// never refuses for an app whose owner turned refusals off. |
| +var assetOwnersSource atomic.Pointer[func() []registry.Route] |
| + |
| +func setAssetOwnersSource(fn func() []registry.Route) { assetOwnersSource.Store(&fn) } |
| + |
| +// recordOnlyLast is the last known record-only value per app, across |
| +// passes, armed or not: an app whose settings cannot be read keeps it, so a |
| +// failed read never turns refusals on or off. The armed gate's last good |
| +// object covers most of this; this covers the disarmed pass and an app the |
| +// gate has no good object for yet. |
| +var recordOnlyLast = &recordOnlyMemory{} |
| + |
| +type recordOnlyMemory struct { |
| + mu sync.Mutex |
| + m map[string]bool |
| +} |
| + |
| +// settle is the switch map to push: read's values, and the last known value |
| +// (off when there is none) for each key in unread. Keys in neither are |
| +// forgotten, so an app that returns starts from what is read for it. |
| +func (rm *recordOnlyMemory) settle(read map[string]bool, unread []string) map[string]bool { |
| + rm.mu.Lock() |
| + defer rm.mu.Unlock() |
| + next := make(map[string]bool, len(read)+len(unread)) |
| + for k, v := range read { |
| + next[k] = v |
| + } |
| + for _, k := range unread { |
| + next[k] = rm.m[k] |
| + } |
| + rm.m = next |
| + on := map[string]bool{} |
| + for k, v := range next { |
| + if v { |
| + on[k] = true |
| + } |
| + } |
| + return on |
| +} |
| + |
| +func (rm *recordOnlyMemory) reset() { |
| + rm.mu.Lock() |
| + rm.m = nil |
| + rm.mu.Unlock() |
| +} |
| + |
| +// telemetrySwitchSet is one pass's answer: the analytics switch map, the |
| +// record-only value of every app whose app-level settings were read (or |
| +// stood in for by the gate's last good object), and the apps whose settings |
| +// could not be had at all. |
| +type telemetrySwitchSet struct { |
| + analytics map[string]bool |
| + recordOnly map[string]bool |
| + unread []string |
| +} |
| + |
| // telemetryReads is what the switch pass remembers between passes while the |
| // change index is armed (S3 change-index design §5): a gate over the app and |
| // account scopes, and the last good settings object per key, so a read the |
| @@ -77,24 +146,42 @@ func telemetrySwitches(ctx context.Context, s release.Store, reg *registry.Regis |
| return telemetrySwitchesWith(ctx, s, reg, currentTelemetryReads(), time.Now()) |
| } |
| -// telemetrySwitchesWith is telemetrySwitches over r at now. Over a watch, |
| -// each account's telemetry.json is read at most once per pass, however many |
| -// of its apps the box serves, and each app's at most once; a read is skipped |
| -// when r's gate says its scope has not moved and r holds a last good value. |
| -// A pair with no good value at either level is left OFF and logged: off is |
| -// the safe side of this switch. Without one (disarmed), it is main's pass. |
| +// telemetrySwitchesWith is the analytics half of telemetrySettle over the |
| +// box's routes alone. |
| func telemetrySwitchesWith(ctx context.Context, s release.Store, reg *registry.Registry, r *telemetryReads, now time.Time) (map[string]bool, error) { |
| + set, err := telemetrySettle(ctx, s, reg, r, now, nil) |
| + return set.analytics, err |
| +} |
| + |
| +// telemetrySettle is the pass over r at now: the analytics switch and the |
| +// record-only switch for each distinct (account, app) among the box's |
| +// routes, and the record-only switch for each of owners (the far asset |
| +// catch's apps) that no route already names. |
| +// |
| +// Over a watch, each account's telemetry.json is read at most once per pass, |
| +// however many of its apps the box serves, and each app's at most once; a |
| +// read is skipped when r's gate says its scope has not moved and r holds a |
| +// last good value. A pair with no good value at either level is left OFF for |
| +// analytics and logged: off is the safe side of that switch. The record-only |
| +// switch reads the app level only, so an app's own read decides it, and an |
| +// app with no good value is reported unread for the caller's last known |
| +// value. Without a watch (disarmed), it is main's pass. |
| +// |
| +// Request budget: the owners add one app-level read per far asset app per |
| +// pass, behind the same gate (none while the app's scope is quiet), and |
| +// never an account read. |
| +func telemetrySettle(ctx context.Context, s release.Store, reg *registry.Registry, r *telemetryReads, now time.Time, owners []registry.Route) (telemetrySwitchSet, error) { |
| if r == nil || r.w == nil { |
| - return telemetrySwitchesResolve(ctx, s, reg) |
| + return telemetrySettleResolve(ctx, s, reg, owners) |
| } |
| routes, err := reg.List() |
| if err != nil { |
| - return nil, err |
| + return telemetrySwitchSet{}, err |
| } |
| r.mu.Lock() |
| defer r.mu.Unlock() |
| pass := map[string]error{} // keys this pass has settled, and the error when there is no good value |
| - on := map[string]bool{} |
| + set := telemetrySwitchSet{analytics: map[string]bool{}, recordOnly: map[string]bool{}} |
| seen := map[string]bool{} |
| for _, rt := range routes { |
| if rt.Kind == "status" || rt.App == "" { |
| @@ -106,39 +193,65 @@ func telemetrySwitchesWith(ctx context.Context, s release.Store, reg *registry.R |
| continue |
| } |
| seen[key] = true |
| - acct, err := r.read(ctx, s, telemetry.AccountKey(sqid), now, pass) |
| - if err != nil { |
| - log.Printf("agent: telemetry resolve %s: %v (analytics stays off)", key, err) |
| + acct, errAcct := r.read(ctx, s, telemetry.AccountKey(sqid), now, pass) |
| + app, errApp := r.read(ctx, s, telemetry.AppKey(sqid, rt.App), now, pass) |
| + set.noteRecordOnly(key, app, errApp) |
| + if err := errors.Join(errAcct, errApp); err != nil { |
| + log.Printf("agent: telemetry resolve %s: %v (analytics stays off; record only keeps its last known value if the app level failed)", key, err) |
| continue |
| } |
| - app, err := r.read(ctx, s, telemetry.AppKey(sqid, rt.App), now, pass) |
| - if err != nil { |
| - log.Printf("agent: telemetry resolve %s: %v (analytics stays off)", key, err) |
| + if telemetry.Fold(acct, app).Count == telemetry.CountEdge { |
| + set.analytics[key] = true |
| + } |
| + } |
| + for _, rt := range owners { |
| + sqid := release.RouteAccount(rt) |
| + key := sqid + "/" + rt.App |
| + if rt.App == "" || seen[key] { |
| continue |
| } |
| - if telemetry.Fold(acct, app).Count == telemetry.CountEdge { |
| - on[key] = true |
| + seen[key] = true |
| + app, err := r.read(ctx, s, telemetry.AppKey(sqid, rt.App), now, pass) |
| + if err != nil { |
| + log.Printf("agent: telemetry resolve %s (assets): %v (record only keeps its last known value)", key, err) |
| } |
| + set.noteRecordOnly(key, app, err) |
| } |
| - // Objects no route needs any more are forgotten, so a returning app is |
| - // read afresh. |
| + // Objects no route or owner needs any more are forgotten, so a returning |
| + // app is read afresh. |
| for k := range r.last { |
| if _, used := pass[k]; !used { |
| delete(r.last, k) |
| } |
| } |
| - return on, nil |
| + return set, nil |
| } |
| -// telemetrySwitchesResolve is the pass with no change index armed, exactly |
| -// as before the index: one Resolve (two Gets) per (account, app); a pair |
| -// that fails to resolve is left OFF and logged, and no other pair is. |
| -func telemetrySwitchesResolve(ctx context.Context, s release.Store, reg *registry.Registry) (map[string]bool, error) { |
| +// noteRecordOnly files key's record-only value from its app-level settings, |
| +// or marks it unread when there are none to be had. |
| +func (set *telemetrySwitchSet) noteRecordOnly(key string, app telemetry.Settings, err error) { |
| + if err != nil { |
| + set.unread = append(set.unread, key) |
| + return |
| + } |
| + set.recordOnly[key] = telemetry.RecordOnly(app) |
| +} |
| + |
| +// telemetrySettleResolve is the pass with no change index armed, as before |
| +// the index: each (account, app) reads both of its levels on its own, and a |
| +// pair that fails to resolve is left OFF for analytics and logged, and no |
| +// other pair is. Each owner reads its app level alone. |
| +func telemetrySettleResolve(ctx context.Context, s release.Store, reg *registry.Registry, owners []registry.Route) (telemetrySwitchSet, error) { |
| routes, err := reg.List() |
| if err != nil { |
| - return nil, err |
| + return telemetrySwitchSet{}, err |
| + } |
| + set := telemetrySwitchSet{analytics: map[string]bool{}, recordOnly: map[string]bool{}} |
| + // No store is every default, as telemetry.Resolve answers it: nothing |
| + // counted, nothing record only. |
| + if s == nil { |
| + return set, nil |
| } |
| - on := map[string]bool{} |
| seen := map[string]bool{} |
| for _, rt := range routes { |
| if rt.Kind == "status" || rt.App == "" { |
| @@ -150,16 +263,31 @@ func telemetrySwitchesResolve(ctx context.Context, s release.Store, reg *registr |
| continue |
| } |
| seen[key] = true |
| - res, err := telemetry.Resolve(ctx, s, sqid, rt.App) |
| - if err != nil { |
| - log.Printf("agent: telemetry resolve %s: %v (analytics stays off)", key, err) |
| + acct, _, errAcct := telemetry.Read(ctx, s, telemetry.AccountKey(sqid)) |
| + app, _, errApp := telemetry.Read(ctx, s, telemetry.AppKey(sqid, rt.App)) |
| + set.noteRecordOnly(key, app, errApp) |
| + if err := errors.Join(errAcct, errApp); err != nil { |
| + log.Printf("agent: telemetry resolve %s: %v (analytics stays off; record only keeps its last known value if the app level failed)", key, err) |
| + continue |
| + } |
| + if telemetry.Fold(acct, app).Count == telemetry.CountEdge { |
| + set.analytics[key] = true |
| + } |
| + } |
| + for _, rt := range owners { |
| + sqid := release.RouteAccount(rt) |
| + key := sqid + "/" + rt.App |
| + if rt.App == "" || seen[key] { |
| continue |
| } |
| - if res.Count == telemetry.CountEdge { |
| - on[key] = true |
| + seen[key] = true |
| + app, _, err := telemetry.Read(ctx, s, telemetry.AppKey(sqid, rt.App)) |
| + if err != nil { |
| + log.Printf("agent: telemetry resolve %s (assets): %v (record only keeps its last known value)", key, err) |
| } |
| + set.noteRecordOnly(key, app, err) |
| } |
| - return on, nil |
| + return set, nil |
| } |
| // read is key's settings for this pass: settled once per pass in pass. The |
| @@ -195,16 +323,27 @@ func (r *telemetryReads) read(ctx context.Context, s release.Store, key string, |
| return telemetry.Settings{}, err |
| } |
| -// telemetryPass resolves and pushes; errors are one log line each. |
| +// telemetryPass resolves and pushes both switch maps; errors are one log |
| +// line each. A pass that cannot list the routes pushes nothing, so the edge |
| +// keeps the maps it has. |
| func telemetryPass(ctx context.Context, s release.Store, reg *registry.Registry) { |
| - sink := analyticsSink.Load() |
| - if sink == nil { |
| + aSink, pSink := analyticsSink.Load(), protectionSink.Load() |
| + if aSink == nil && pSink == nil { |
| return |
| } |
| - on, err := telemetrySwitches(ctx, s, reg) |
| + var owners []registry.Route |
| + if src := assetOwnersSource.Load(); src != nil && pSink != nil { |
| + owners = (*src)() |
| + } |
| + set, err := telemetrySettle(ctx, s, reg, currentTelemetryReads(), time.Now(), owners) |
| if err != nil { |
| log.Printf("agent: telemetry pass: %v", err) |
| return |
| } |
| - (*sink)(on) |
| + if aSink != nil { |
| + (*aSink)(set.analytics) |
| + } |
| + if pSink != nil { |
| + (*pSink)(recordOnlyLast.settle(set.recordOnly, set.unread)) |
| + } |
| } |
diff --git a/internal/host/telemetry_pass_test.go b/internal/host/telemetry_pass_test.go| index 04b43afda..08543cbfd 100644 |
| --- a/internal/host/telemetry_pass_test.go |
| +++ b/internal/host/telemetry_pass_test.go |
| @@ -2,7 +2,12 @@ package host |
| import ( |
| "context" |
| + "errors" |
| + "maps" |
| + "slices" |
| + "sync" |
| "testing" |
| + "time" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -36,3 +41,170 @@ func TestTelemetrySwitchesResolvePerRoute(t *testing.T) { |
| t.Fatal("status routes have no app and must not appear") |
| } |
| } |
| + |
| +// keysFailingStore fails every Get of the keys in fail while it is set. |
| +type keysFailingStore struct { |
| + *ciCountingStore |
| + mu sync.Mutex |
| + fail map[string]bool |
| +} |
| + |
| +func (s *keysFailingStore) failing(keys ...string) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + s.fail = map[string]bool{} |
| + for _, k := range keys { |
| + s.fail[k] = true |
| + } |
| +} |
| + |
| +func (s *keysFailingStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + s.mu.Lock() |
| + failed := s.fail[key] |
| + s.mu.Unlock() |
| + if failed { |
| + s.note("Get", key) |
| + return nil, "", errors.New("503 slow down") |
| + } |
| + return s.ciCountingStore.Get(ctx, key) |
| +} |
| + |
| +// The record-only switch map (probe-burst plan Task 5) rides the analytics |
| +// pass to its own sink: every app the box routes, plus every app its far |
| +// asset catch serves without a route (one app-level read each, the account |
| +// never read for them). A failed read keeps the app's last known value, on |
| +// or off, rather than flipping it by error; disarmed, too, where nothing |
| +// else is remembered between passes. |
| +func TestTelemetryPassRecordOnlyMap(t *testing.T) { |
| + ctx := context.Background() |
| + cs := newCICountingStore(t) |
| + fs := &keysFailingStore{ciCountingStore: cs} |
| + reg := telemetryRoutes(t, "bab", "shop", "blog") |
| + setRecordOnly := func(acct, app string, on bool) { |
| + t.Helper() |
| + if err := telemetry.Update(ctx, cs, telemetry.AppKey(acct, app), func(st *telemetry.Settings) { |
| + st.Protection = nil |
| + if on { |
| + st.Protection = &telemetry.Protection{Mode: telemetry.ProtectRecordOnly} |
| + } |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + setRecordOnly("bab", "shop", true) |
| + setRecordOnly("bdk", "cart", true) |
| + |
| + var pushed []map[string]bool |
| + prevA, prevP, prevO := analyticsSink.Load(), protectionSink.Load(), assetOwnersSource.Load() |
| + t.Cleanup(func() { |
| + analyticsSink.Store(prevA) |
| + protectionSink.Store(prevP) |
| + assetOwnersSource.Store(prevO) |
| + recordOnlyLast.reset() |
| + }) |
| + recordOnlyLast.reset() |
| + setAnalyticsSink(func(map[string]bool) {}) |
| + setProtectionSink(func(m map[string]bool) { pushed = append(pushed, maps.Clone(m)) }) |
| + // bdk/cart is served here only as declared assets homed on another box. |
| + setAssetOwnersSource(func() []registry.Route { |
| + return []registry.Route{{Host: "cart.example.com", Account: "bdk", App: "cart", Kind: "instance"}} |
| + }) |
| + pass := func() map[string]bool { |
| + t.Helper() |
| + n := len(pushed) |
| + telemetryPass(ctx, fs, reg) |
| + if len(pushed) != n+1 { |
| + t.Fatalf("the pass pushed %d maps, want 1", len(pushed)-n) |
| + } |
| + return pushed[len(pushed)-1] |
| + } |
| + want := func(got map[string]bool, keys ...string) { |
| + t.Helper() |
| + w := map[string]bool{} |
| + for _, k := range keys { |
| + w[k] = true |
| + } |
| + if !maps.Equal(got, w) { |
| + t.Fatalf("record-only map %v, want %v", got, w) |
| + } |
| + } |
| + |
| + cs.reset() |
| + want(pass(), "bab/shop", "bdk/cart") |
| + if a, b := cs.count("Get", telemetry.AppKey("bdk", "cart")), cs.count("Get", telemetry.AccountKey("bdk")); a != 1 || b != 0 { |
| + t.Fatalf("the far app's reads: app %d account %d, want 1 and 0: %v", a, b, cs.got()) |
| + } |
| + |
| + // Its reads fail: both switches stay on, and blog stays off. |
| + fs.failing(telemetry.AppKey("bab", "shop"), telemetry.AppKey("bdk", "cart"), telemetry.AppKey("bab", "blog")) |
| + want(pass(), "bab/shop", "bdk/cart") |
| + |
| + // shop is switched off and blog on while the reads still fail: nothing |
| + // moves until they succeed. |
| + setRecordOnly("bab", "shop", false) |
| + setRecordOnly("bab", "blog", true) |
| + want(pass(), "bab/shop", "bdk/cart") |
| + fs.failing() |
| + want(pass(), "bab/blog", "bdk/cart") |
| + |
| + // An app the box no longer serves is forgotten: a failed read for it |
| + // when it returns starts from off. |
| + setAssetOwnersSource(func() []registry.Route { return nil }) |
| + want(pass(), "bab/blog") |
| + setAssetOwnersSource(func() []registry.Route { |
| + return []registry.Route{{Host: "cart.example.com", Account: "bdk", App: "cart", Kind: "instance"}} |
| + }) |
| + fs.failing(telemetry.AppKey("bdk", "cart")) |
| + want(pass(), "bab/blog") |
| +} |
| + |
| +// Armed, a far asset app's settings ride the same change-index gate as a |
| +// routed app's: read on the first pass, not on a quiet one, and read again |
| +// when its own file moves. The request budget is one gated read per app. |
| +func TestTelemetryPassRecordOnlyGatedForAssetOwners(t *testing.T) { |
| + t.Parallel() |
| + ctx := context.Background() |
| + cs := newCICountingStore(t) |
| + reg := telemetryRoutes(t, "bab", "shop") |
| + owners := []registry.Route{{Host: "cart.example.com", Account: "bdk", App: "cart", Kind: "instance"}} |
| + w := release.NewChangeWatch(cs) |
| + pollWatch(t, w) |
| + r := newTelemetryReads(w) |
| + clock := newGateClock() |
| + pass := func() telemetrySwitchSet { |
| + t.Helper() |
| + set, err := telemetrySettle(ctx, cs, reg, r, clock.now(), owners) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return set |
| + } |
| + cs.reset() |
| + if set := pass(); set.recordOnly["bdk/cart"] || len(set.unread) != 0 { |
| + t.Fatalf("first pass %+v", set) |
| + } |
| + if n := cs.count("Get", telemetry.AppKey("bdk", "cart")); n != 1 { |
| + t.Fatalf("the first pass read the far app %d time(s), want 1", n) |
| + } |
| + clock.add(time.Minute) |
| + pollWatch(t, w) |
| + cs.reset() |
| + pass() |
| + if n := cs.count("Get", ""); n != 0 { |
| + t.Fatalf("a quiet pass read %v", cs.got()) |
| + } |
| + if err := telemetry.Update(ctx, cs, telemetry.AppKey("bdk", "cart"), func(st *telemetry.Settings) { |
| + st.Protection = &telemetry.Protection{Mode: telemetry.ProtectRecordOnly} |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + clock.add(time.Minute) |
| + pollWatch(t, w) |
| + cs.reset() |
| + if set := pass(); !set.recordOnly["bdk/cart"] { |
| + t.Fatalf("after the far app's change %+v, want it on", set) |
| + } |
| + if got := cs.got(); !slices.Equal(got, []string{"Get " + telemetry.AppKey("bdk", "cart")}) { |
| + t.Fatalf("after the far app's change the pass read %v, want its telemetry.json only", got) |
| + } |
| +} |
diff --git a/internal/telemetry/telemetry.go b/internal/telemetry/telemetry.go| index c0c48e52a..21c4a07e2 100644 |
| --- a/internal/telemetry/telemetry.go |
| +++ b/internal/telemetry/telemetry.go |
| @@ -23,6 +23,9 @@ const ( |
| CountOff = "off" |
| DoorOn = "on" |
| DoorOff = "off" |
| + // ProtectRecordOnly is the protection mode in which the edge records |
| + // what it would have refused on the app and refuses nothing. |
| + ProtectRecordOnly = "record" |
| ) |
| // Analytics is the analytics half. Empty strings mean "not set here". |
| @@ -36,11 +39,19 @@ type Errors struct { |
| LogLevel string `json:"log_level,omitempty"` |
| } |
| +// Protection is the edge protection switch (probe-burst spec §5a). Mode |
| +// ProtectRecordOnly turns refusals off for the app; empty is the default, |
| +// protection refusing as its mode says. |
| +type Protection struct { |
| + Mode string `json:"mode,omitempty"` |
| +} |
| + |
| // Settings is the wire shape at either level. Additive: unknown keys are |
| -// ignored, absent halves inherit. |
| +// ignored, absent halves inherit. Protection is read at the app level only. |
| type Settings struct { |
| - Analytics *Analytics `json:"analytics,omitempty"` |
| - Errors *Errors `json:"errors,omitempty"` |
| + Analytics *Analytics `json:"analytics,omitempty"` |
| + Errors *Errors `json:"errors,omitempty"` |
| + Protection *Protection `json:"protection,omitempty"` |
| } |
| // AccountKey is the account-level object, beside account.json (which stays |
| @@ -97,11 +108,13 @@ func Update(ctx context.Context, s release.Store, key string, fn func(*Settings) |
| } |
| // Resolved is what a reader acts on, with each value's provenance so a |
| -// settings page can say "inherited from the account". |
| +// settings page can say "inherited from the account". RecordOnly has none: |
| +// it is the app's own switch, and an account cannot set it for every app. |
| type Resolved struct { |
| LogLevel, LogLevelFrom string |
| Count, CountFrom string |
| Door, DoorFrom string |
| + RecordOnly bool |
| } |
| // Resolve reads both levels and folds them over the defaults. A store |
| @@ -148,5 +161,16 @@ func Fold(acct, appSt Settings) Resolved { |
| } |
| } |
| } |
| + // The record-only switch is per app (the plan's call): an account-level |
| + // protection block is never read, so no one setting can stop protection |
| + // refusing on every app of an account. |
| + r.RecordOnly = RecordOnly(appSt) |
| return r |
| } |
| + |
| +// RecordOnly reports whether the app-level settings st turn the app's |
| +// protection to record only. Any mode other than ProtectRecordOnly is not: |
| +// a value no box knows never stops protection. |
| +func RecordOnly(st Settings) bool { |
| + return st.Protection != nil && st.Protection.Mode == ProtectRecordOnly |
| +} |
diff --git a/internal/telemetry/telemetry_test.go b/internal/telemetry/telemetry_test.go| index 6dd3ca170..da6714372 100644 |
| --- a/internal/telemetry/telemetry_test.go |
| +++ b/internal/telemetry/telemetry_test.go |
| @@ -51,3 +51,46 @@ func TestResolveAppThenAccountThenDefault(t *testing.T) { |
| t.Fatalf("read back = %+v", got) |
| } |
| } |
| + |
| +// The record-only switch is per app (probe-burst plan Task 5): the app's own |
| +// setting turns it on, and a protection block at the account level is never |
| +// read, so it can never turn every app of an account to record only. |
| +func TestResolveRecordOnly(t *testing.T) { |
| + ctx := context.Background() |
| + s := release.NewDirStore(t.TempDir()) |
| + if r, err := Resolve(ctx, s, "bab", "shop"); err != nil || r.RecordOnly { |
| + t.Fatalf("default = %+v %v, want record-only off", r, err) |
| + } |
| + if err := Update(ctx, s, AccountKey("bab"), func(st *Settings) { st.Protection = &Protection{Mode: ProtectRecordOnly} }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r, _ := Resolve(ctx, s, "bab", "shop"); r.RecordOnly { |
| + t.Fatal("an account-level protection mode turned an app to record only") |
| + } |
| + if err := Update(ctx, s, AppKey("bab", "shop"), func(st *Settings) { st.Protection = &Protection{Mode: ProtectRecordOnly} }); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r, _ := Resolve(ctx, s, "bab", "shop"); !r.RecordOnly { |
| + t.Fatal("the app's own record-only setting did not resolve") |
| + } |
| + if r, _ := Resolve(ctx, s, "bab", "blog"); r.RecordOnly { |
| + t.Fatal("one app's switch reached a sibling") |
| + } |
| + // Any other mode is not record only: a value no box knows never stops |
| + // protection. |
| + if r := Fold(Settings{}, Settings{Protection: &Protection{Mode: "nonsense"}}); r.RecordOnly { |
| + t.Fatal("an unknown mode resolved to record only") |
| + } |
| + // Turning it off leaves no protection block behind, and the other halves |
| + // stand. |
| + if err := Update(ctx, s, AppKey("bab", "shop"), func(st *Settings) { |
| + st.Analytics = &Analytics{Count: CountEdge} |
| + st.Protection = nil |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _, err := s.Get(ctx, AppKey("bab", "shop")) |
| + if err != nil || string(raw) != `{"analytics":{"count":"edge"}}` { |
| + t.Fatalf("stored %s %v", raw, err) |
| + } |
| +} |
diff --git a/main.go b/main.go| index 2fa35ec21..e03262842 100644 |
| --- a/main.go |
| +++ b/main.go |
| @@ -128,6 +128,8 @@ func main() { |
| runExplain(args) |
| case "analytics": |
| runAnalytics(args) |
| + case "protection": |
| + runProtection(args) |
| case "channels": |
| // Two sub-verbs, resign and digests (#253); bare `carlos channels` |
| // still lists, the `carlos releases retention` precedent. |
| @@ -303,6 +305,7 @@ Your apps — ship and run software on a CARLOS deployment |
| grouped by cause, plus failed wakes and exits |
| analytics an app's page views and visitors from a terminal, counted at |
| the edge as it serves your app |
| + protection show or set whether protection only records on this app |
| geo what the platform's GeoIP database says about an address |
| explain what a reference code from a page the edge answered says |
| ledger open ledgers: append | head | list | publish | blob | verify |
diff --git a/protection_cmd.go b/protection_cmd.go| new file mode 100644 |
| index 000000000..9372461bb |
| --- /dev/null |
| +++ b/protection_cmd.go |
| @@ -0,0 +1,81 @@ |
| +// `carlos protection` — an app's record-only switch from a terminal (the |
| +// probe-burst spec §5a): with it on, the edge records what protection would |
| +// have refused on the app and refuses nothing. API mode only; owners only, |
| +// as the Protection tab's control. The words are the approved burst copy |
| +// deck's (docs/superpowers/plans/2026-10-31-probe-burst-limit-copy.md). |
| +package main |
| + |
| +import ( |
| + "context" |
| + "flag" |
| + "fmt" |
| + "log" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/telemetry" |
| +) |
| + |
| +// protectionUsage is the deck's help line (PB-C10). |
| +const protectionUsage = `carlos protection [--account a] [--app x] [--record-only on|off]: show or set whether protection only records on this app |
| +` |
| + |
| +// The two answers (PB-C11, PB-C12), {app} filled by protectionResult. |
| +const ( |
| + protectionOnCopy = "Protection records only on {app}. Nothing is blocked." |
| + protectionOffCopy = "Protection can block on {app} again." |
| +) |
| + |
| +func runProtection(args []string) { |
| + fs := flag.NewFlagSet("protection", flag.ExitOnError) |
| + app := appFlag(fs, "") |
| + recordOnly := fs.String("record-only", "", "on | off") |
| + consoleFlag := consoleOption(fs, "console to read through (default: the only logged-in one)") |
| + acctRaw := fs.String("account", "", "account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one)") |
| + acctIDRaw := fs.String("account-id", "", "account sqid, matched as a sqid ONLY — supersedes --account") |
| + fs.Usage = flagUsage(fs, protectionUsage) |
| + fs.Parse(args) |
| + |
| + mode, set, err := protectionMode(*recordOnly) |
| + if err != nil { |
| + log.Fatalf("protection: %v", err) |
| + } |
| + sess := requireAPISession("protection", *consoleFlag) |
| + acct := resolvedAccount(sess, acctRaw, acctIDRaw) |
| + app2 := resolvedApp(sess, acct, *app, protectionUsage) |
| + ctx := context.Background() |
| + |
| + if set { |
| + if err := sess.telemetryPut(ctx, acct, app2, map[string]any{"protection": map[string]string{"mode": mode}}); err != nil { |
| + log.Fatalf("protection: %v", err) |
| + } |
| + fmt.Fprintln(stdout, protectionResult(app2, mode == telemetry.ProtectRecordOnly)) |
| + return |
| + } |
| + st, err := sess.telemetryGet(ctx, acct, app2) |
| + if err != nil { |
| + log.Fatalf("protection: %v", err) |
| + } |
| + fmt.Fprintln(stdout, protectionResult(app2, telemetry.RecordOnly(st))) |
| +} |
| + |
| +// protectionMode reads --record-only: on is the record-only mode, off the |
| +// default (""), and empty means show, not set. |
| +func protectionMode(flagVal string) (mode string, set bool, err error) { |
| + switch flagVal { |
| + case "": |
| + return "", false, nil |
| + case "on": |
| + return telemetry.ProtectRecordOnly, true, nil |
| + case "off": |
| + return "", true, nil |
| + } |
| + return "", false, fmt.Errorf("--record-only wants on or off") |
| +} |
| + |
| +// protectionResult is the deck's answer for app's switch. |
| +func protectionResult(app string, on bool) string { |
| + if on { |
| + return strings.ReplaceAll(protectionOnCopy, "{app}", app) |
| + } |
| + return strings.ReplaceAll(protectionOffCopy, "{app}", app) |
| +} |
diff --git a/protection_cmd_test.go b/protection_cmd_test.go| new file mode 100644 |
| index 000000000..69a0cc69b |
| --- /dev/null |
| +++ b/protection_cmd_test.go |
| @@ -0,0 +1,134 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "net/http/httptest" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/console" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/telemetry" |
| +) |
| + |
| +// protectionE2E is a real console whose ops account (bab) has the app shop, |
| +// with its owner signed in to the CLI, and the built carlos binary. |
| +type protectionE2E struct { |
| + bin, creds string |
| + rel release.Store |
| +} |
| + |
| +func newProtectionE2E(t *testing.T) *protectionE2E { |
| + t.Helper() |
| + bin := buildCarlos(t) // first: useTempCredentials chdirs out of the module |
| + creds := useTempCredentials(t) |
| + clearDeploymentEnv(t) |
| + const addr = "paul@keymail.dev" |
| + tmp := t.TempDir() |
| + rel := release.NewDirStore(filepath.Join(tmp, "store")) |
| + seed, pubB64, err := release.GenerateKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + priv, err := release.ParseSigningKey(seed, "e2e") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pub, err := release.ParsePublicKey(pubB64, "e2e") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cst, err := console.Open(filepath.Join(tmp, "console.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { cst.Close() }) |
| + var srv *console.Server |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv.ServeHTTP(w, r) })) |
| + t.Cleanup(ts.Close) |
| + srv, err = console.NewServer(console.Config{ |
| + Origin: ts.URL, Keymail: "http://keymail.invalid", |
| + Registry: filepath.Join(tmp, "registry.db"), Releases: rel, |
| + ReleasePub: pub, Key: priv, AppScheme: "http", AppsDomain: "oncarlos.test", |
| + }, cst) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := cst.AddMember(console.OpsAccountID, addr, console.RoleOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := cst.CreateAppIn(console.OpsAccountID, "shop", addr, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + token, expiresAt := e2eDeviceLogin(t, ts.URL, cst, addr, "e2e@laptop") |
| + credFile, err := loadCredentials() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + credFile.put(credential{Console: ts.URL, Address: addr, Token: token, ExpiresAt: expiresAt}) |
| + if err := credFile.save(); err != nil { |
| + t.Fatal(err) |
| + } |
| + return &protectionE2E{bin: bin, creds: creds, rel: rel} |
| +} |
| + |
| +func (e *protectionE2E) run(t *testing.T, args ...string) (string, error) { |
| + t.Helper() |
| + cmd := exec.Command(e.bin, append([]string{"protection"}, args...)...) |
| + cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+e.creds) |
| + cmd.Dir = t.TempDir() |
| + out, err := cmd.CombinedOutput() |
| + return string(out), err |
| +} |
| + |
| +// carlos protection through a real console: with no flag it shows the |
| +// switch, --record-only on and off set it in the app's own settings, and |
| +// each answer is the approved deck's (PB-C11, PB-C12). |
| +func TestProtectionCmdSetsAndShows(t *testing.T) { |
| + e := newProtectionE2E(t) |
| + const on, off = "Protection records only on shop. Nothing is blocked.\n", "Protection can block on shop again.\n" |
| + recordOnly := func() bool { |
| + t.Helper() |
| + st, _, err := telemetry.Read(context.Background(), e.rel, telemetry.AppKey(release.OpsAccount, "shop")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return telemetry.RecordOnly(st) |
| + } |
| + for _, c := range []struct { |
| + args []string |
| + want string |
| + on bool |
| + }{ |
| + {nil, off, false}, |
| + {[]string{"--record-only", "on"}, on, true}, |
| + {nil, on, true}, |
| + {[]string{"--record-only", "off"}, off, false}, |
| + {nil, off, false}, |
| + } { |
| + args := append([]string{"--app", "shop", "--account", "bab"}, c.args...) |
| + out, err := e.run(t, args...) |
| + if err != nil || out != c.want { |
| + t.Fatalf("carlos protection %v: %v\n%q, want %q", c.args, err, out, c.want) |
| + } |
| + if recordOnly() != c.on { |
| + t.Fatalf("after carlos protection %v the stored switch is %v, want %v", c.args, !c.on, c.on) |
| + } |
| + } |
| + // A value that is neither is refused before anything is sent. |
| + if out, err := e.run(t, "--app", "shop", "--account", "bab", "--record-only", "maybe"); err == nil || !strings.Contains(out, "--record-only") { |
| + t.Fatalf("--record-only maybe: %v\n%s", err, out) |
| + } |
| + if recordOnly() { |
| + t.Fatal("a refused value wrote") |
| + } |
| + // The help line is the deck's (PB-C10). |
| + out, _ := e.run(t, "-h") |
| + if !strings.Contains(out, "carlos protection [--account a] [--app x] [--record-only on|off]: show or set whether protection only records on this app") { |
| + t.Fatalf("help:\n%s", out) |
| + } |
| +} |