console: save settings and say where they land
Save on the app settings Environments form makes one config write through writeConfig, conditional on the bundle version the page showed, and requests no restart. It then renders "After you save" from classifyConfigWrite, the same WriteReach the CLI notice is built from. op=check (Retry) re-classifies and writes nothing. A conflict keeps staged ordinary changes over the fresh bundle and drops sealed ones. Other refusals keep the draft minus what was refused. Save spends the write budget, and its audit row carries counts and the bundle only, "(console)".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/console/appsettings.go+3 −0internal/console/envcopy.go+61 −5internal/console/envform.go+16 −15internal/console/envform_test.go+46 −22internal/console/envsave.go+294 −0internal/console/envsave_test.go+571 −0internal/console/templates/app_settings.html+60 −0
Intent
<task-notification> <task-id>a500c517b888e4b83</task-id> <tool-use-id>toolu_01BBfxPuk5FogG5RGFFk3bzV</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/abe35d56-e4c2-40df-9005-6e66b76b1f50/tasks/a500c517b888e4b83.output</output-file> <status>completed</status> <summary>Agent "Implement Task 7 settings page" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Done; commit 901a40b6. The "Change" buttons are gone and Enter still stages. The save bar is now always in the form: hidden until something is staged, shown by a few lines of script on the first edit in a panel, and always shown with scripts off. Discard hides it again. Each row's summary carries both Edit and Close, and CSS on `.envvar[open]` picks one. Styleguide updated, mockup kit regenerated. Tests: the targeted set is green and both Chromium tests ran (not skipped). The browser driver can now fire input events and check a condition before clicking. A new scene checks the bar is hidden at first, appears after a panel edit, and Discard posts once and comes back with the bar hidden. Fix note appended to `.superpowers/sdd/2026-11-08-console-secrets/task-7-report.md`.</result> <usage><subagent_tokens>265751</subagent_tokens><tool_uses>82</tool_uses><duration_ms>2673997</duration_ms></usage> </task-notification>
Attributed to this commit: 4.86 g CO₂e (591,624 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-console-secrets, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go| index b33dfe17d..2ed4c2fc1 100644 |
| --- a/internal/console/appsettings.go |
| +++ b/internal/console/appsettings.go |
| @@ -139,6 +139,9 @@ type SettingsView struct { |
| EnvDraft *envDraft |
| EnvSummary string |
| EnvError string |
| + // EnvOutcome is "After you save" (envsave.go): set after a Save that |
| + // wrote, or a Retry; nil otherwise. |
| + EnvOutcome *envOutcome |
| // EnvCopy is the section's words; ConfigSealJS the sealing script the |
| // page inlines. |
| EnvCopy envPageCopy |
diff --git a/internal/console/envcopy.go b/internal/console/envcopy.go| index 6cf28491b..cc706c540 100644 |
| --- a/internal/console/envcopy.go |
| +++ b/internal/console/envcopy.go |
| @@ -63,7 +63,6 @@ type envPageCopy struct { |
| AddNoName string |
| AddNameTaken string // {name} {env} |
| AddEmptySec string |
| - SaveSoon string // save and check are Task 8's |
| CouldNotRead string |
| EnvelopeStale string // {name} |
| @@ -103,9 +102,30 @@ type envPageCopy struct { |
| OutcomeAsleep string |
| OutcomeAsleepHlp string |
| OutcomeCantSee string |
| - OutcomeCantHelp string // {host} |
| + OutcomeCantHelp string |
| + OutcomeCantCmd string // {host}, a command, shown as code |
| OutcomePartial string |
| OutcomeSeeRun string |
| + // The Restart it yourself rows' How sentences. A sidecar's links to |
| + // Running between OutcomeYouSidecar and OutcomeSidecarAfter. |
| + OutcomeYouAddr string // {host} |
| + OutcomeYouSidecar string // {host} |
| + OutcomeCheckRun string |
| + OutcomeSidecarAfter string |
| + OutcomeNotRunning string |
| + OutcomeNotRunHlp string |
| + OutcomeBlocked string |
| + OutcomeBlockedHlp string |
| + OutcomeUnresolved string |
| + OutcomeUnresHlp string |
| + OutcomeUndeliv string |
| + OutcomeUndelivHlp string // {app} |
| + OutcomeNone string |
| + OutcomeUnknown string |
| + OutcomeRetry string |
| + OutcomeCheckBad string |
| + RateLimited string |
| + NothingToSave string |
| } |
| // envCopyDraft is the section's copy before {console} is filled. |
| @@ -158,7 +178,6 @@ var envCopyDraft = envPageCopy{ |
| AddNoName: "Give the setting a name.", |
| AddNameTaken: "{name} is already set in {env}. Use Edit to change it.", |
| AddEmptySec: "A secret can't be empty.", |
| - SaveSoon: "Saving from this page isn't switched on yet. Your changes are still here.", |
| CouldNotRead: "Couldn't read this app's settings just now. Try again in a moment.", |
| EnvelopeStale: "The sealed value for {name} couldn't be read, so it was dropped. Enter it again.", |
| @@ -195,9 +214,29 @@ var envCopyDraft = envPageCopy{ |
| OutcomeAsleep: "Asleep", |
| OutcomeAsleepHlp: "it picks up the change when it next wakes.", |
| OutcomeCantSee: "Can't see", |
| - OutcomeCantHelp: "it runs on a box {console} can't check from here. It picks up the change when it next restarts, or run carlos restart --host {host}.", |
| + OutcomeCantHelp: "it runs on a box {console} can't check from here. It picks up the change when it next restarts, or you can restart it now:", |
| + OutcomeCantCmd: "carlos restart --host {host}", |
| OutcomePartial: "Copies on other boxes may not all be listed here.", |
| OutcomeSeeRun: "See what's running", |
| + |
| + OutcomeYouAddr: "{host}: your app runs this one itself. Restart it the way you started it.", |
| + OutcomeYouSidecar: "{host}: a background worker.", |
| + OutcomeCheckRun: "Check Running", |
| + OutcomeSidecarAfter: "and restart the app if it hasn't picked this up.", |
| + OutcomeNotRunning: "Not running", |
| + OutcomeNotRunHlp: "it picks up the change when it starts.", |
| + OutcomeBlocked: "Blocked", |
| + OutcomeBlockedHlp: "its box won't apply settings to it as it is set up now.", |
| + OutcomeUnresolved: "Couldn't check", |
| + OutcomeUnresHlp: "{console} couldn't read the settings it would get, so it can't say whether it picks this up.", |
| + OutcomeUndeliv: "Doesn't get these", |
| + OutcomeUndelivHlp: "nothing delivers settings to it. If your app reads a settings file, turn on file delivery with carlos env exec-delivery --app {app} file.", |
| + OutcomeNone: "Nothing on this box uses these settings.", |
| + OutcomeUnknown: "Saved, but {console} couldn't check what uses these settings just now.", |
| + OutcomeRetry: "Retry", |
| + OutcomeCheckBad: "Couldn't check that save again. Reload the page.", |
| + RateLimited: "Too many changes at once. Nothing was saved. Try again in a minute.", |
| + NothingToSave: "There's nothing to save.", |
| } |
| // envCopyFor is the section's copy for a console called consoleName. |
| @@ -279,7 +318,6 @@ func (c envPageCopy) staging(ref *envFormRefusal) string { |
| envRefuseEmptySec: c.AddEmptySec, |
| envRefuseVarValue: c.RefVarValue, |
| envRefuseEnvelope: c.EnvelopeStale, |
| - envRefuseSaveSoon: c.SaveSoon, |
| envRefuseUnread: c.CouldNotRead, |
| }[ref.Code] |
| return envFill(line, "name", ref.Var, "env", ref.Env) |
| @@ -312,3 +350,21 @@ func (c envPageCopy) refusal(ref *configRefusal, fleet string) string { |
| } |
| return envFill(line, "name", ref.Var, "fleet", fleet) |
| } |
| + |
| +// SavedLine is the outcome's banner: how many changes landed where. |
| +func (c envPageCopy) SavedLine(o *envOutcome) string { |
| + if o.Count == 1 { |
| + return envFill(c.SavedOne, "env", o.Title) |
| + } |
| + return envFill(c.SavedMany, "n", strconv.Itoa(o.Count), "env", o.Title) |
| +} |
| + |
| +// UndelivLine explains Doesn't get these for app. |
| +func (c envPageCopy) UndelivLine(app string) string { |
| + return envFill(c.OutcomeUndelivHlp, "app", app) |
| +} |
| + |
| +// CantCmdLine is the command that restarts host from anywhere. |
| +func (c envPageCopy) CantCmdLine(host string) string { |
| + return envFill(c.OutcomeCantCmd, "host", host) |
| +} |
diff --git a/internal/console/envform.go b/internal/console/envform.go| index f87d1ba38..c954e9d62 100644 |
| --- a/internal/console/envform.go |
| +++ b/internal/console/envform.go |
| @@ -21,6 +21,8 @@ |
| // addenv.<b> carries the sealed value and .value must be gone |
| // op add:<b> | remove:<b>.<NAME> | undo:<b>.<NAME> | |
| // discard | stage | save | check |
| +// check_bundle Retry's own small form (op=check): the bundle a |
| +// check_key save wrote, and each key it touched (repeated) |
| // |
| // <b> is "default" for the default bundle or the environment's name. |
| // Anything else posted, and any secret plaintext, is refused with the |
| @@ -217,7 +219,6 @@ const ( |
| envRefuseEmptySec = "empty-secret" |
| envRefuseVarValue = "var-value" |
| envRefuseEnvelope = "envelope" |
| - envRefuseSaveSoon = "save-soon" |
| envRefuseUnread = "unread" |
| ) |
| @@ -246,7 +247,7 @@ func parseEnvOp(raw string) (envFormOp, bool) { |
| // ok is false for a name the protocol does not have. |
| func envField(key string) (kind, bundle, name string, ok bool) { |
| switch key { |
| - case "csrf", "bundle", "sealed_to", "op": |
| + case "csrf", "bundle", "sealed_to", "op", "check_bundle", "check_key": |
| return key, "", "", true |
| } |
| kind, rest, found := strings.Cut(key, ".") |
| @@ -554,9 +555,10 @@ func applyEnvDraft(sv *SettingsView, d *envDraft, ref *envFormRefusal) { |
| // handleEnvForm is the Environments section's one form: member-gated like |
| // every app page (accountApp: a non-member's 404 is an unknown app's), |
| // CSRF before anything is read from the form, then the draft re-rendered. |
| -// Nothing here writes; save and check go to envFormSave. |
| +// Nothing here writes: Save goes to envFormSave (envsave.go), the one |
| +// write, and Retry to envFormCheck, which only reads. |
| func (s *Server) handleEnvForm(w http.ResponseWriter, r *http.Request) { |
| - _, raw, _, _, _, ok := s.accountApp(w, r) |
| + addr, raw, _, _, _, ok := s.accountApp(w, r) |
| if !ok { |
| return |
| } |
| @@ -580,8 +582,17 @@ func (s *Server) handleEnvForm(w http.ResponseWriter, r *http.Request) { |
| } |
| d, ref := parseEnvForm(r, sv.Envs) |
| op, _ := parseEnvOp(r.PostFormValue("op")) |
| + if op.verb == "save" && ref != nil && ref.Code == envRefuseOneBundle { |
| + // Save writes the one staged bundle (parseEnvForm's keep) and |
| + // ignores the other cards' fields; staging still refuses them. |
| + ref = nil |
| + } |
| if ref == nil && (op.verb == "save" || op.verb == "check") { |
| - s.envFormSave(w, r, p, d, op.verb) |
| + if op.verb == "save" { |
| + s.envFormSave(w, r, p, acct, addr, d) |
| + } else { |
| + s.envFormCheck(w, r, p, acct) |
| + } |
| return |
| } |
| applyEnvDraft(sv, d, ref) |
| @@ -591,13 +602,3 @@ func (s *Server) handleEnvForm(w http.ResponseWriter, r *http.Request) { |
| } |
| s.render(w, status, "app_settings", p) |
| } |
| - |
| -// envFormSave is where Save and Check land. Task 8 builds them (the write |
| -// through writeConfig at the draft's version, and the outcome); until then |
| -// the page is drawn again with the draft and a line saying so. |
| -func (s *Server) envFormSave(w http.ResponseWriter, r *http.Request, p page, d *envDraft, verb string) { |
| - _ = verb |
| - sv := p.Settings |
| - applyEnvDraft(sv, d, &envFormRefusal{Code: envRefuseSaveSoon}) |
| - s.render(w, http.StatusOK, "app_settings", p) |
| -} |
diff --git a/internal/console/envform_test.go b/internal/console/envform_test.go| index b6ca0927f..4bcf8e6df 100644 |
| --- a/internal/console/envform_test.go |
| +++ b/internal/console/envform_test.go |
| @@ -2,9 +2,9 @@ package console |
| // The editable Environments section (console secrets, Task 7): the cards, |
| // the one form's staging round trip, and the rules that keep a secret's |
| -// plaintext off the server and out of the page. Saving is Task 8; nothing |
| -// here may write a bundle, and the store wrapper fails the test if anything |
| -// tries. |
| +// plaintext off the server and out of the page. Saving is envsave_test.go's; |
| +// nothing here may write a bundle, and the store wrapper fails the test if |
| +// anything tries. |
| import ( |
| "context" |
| @@ -27,11 +27,14 @@ import ( |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| -// envWriteSpy refuses and records every write under one app's prefix: the |
| -// staging doors write nothing, so any recorded key is a failure. |
| +// envWriteSpy records every write under one app's prefix and refuses it: |
| +// the staging doors write nothing, so any recorded key is a failure. With |
| +// allow set (Save's tests, envsave_test.go) it records and lets the write |
| +// through. |
| type envWriteSpy struct { |
| release.Store |
| prefix string |
| + allow bool |
| mu sync.Mutex |
| writes []string |
| } |
| @@ -40,8 +43,11 @@ func (s *envWriteSpy) Put(ctx context.Context, key string, body []byte, ifMatch |
| if s.prefix != "" && strings.HasPrefix(key, s.prefix) { |
| s.mu.Lock() |
| s.writes = append(s.writes, key) |
| + allow := s.allow |
| s.mu.Unlock() |
| - return "", os.ErrPermission |
| + if !allow { |
| + return "", os.ErrPermission |
| + } |
| } |
| return s.Store.Put(ctx, key, body, ifMatch) |
| } |
| @@ -50,8 +56,11 @@ func (s *envWriteSpy) Delete(ctx context.Context, key string) error { |
| if s.prefix != "" && strings.HasPrefix(key, s.prefix) { |
| s.mu.Lock() |
| s.writes = append(s.writes, "delete "+key) |
| + allow := s.allow |
| s.mu.Unlock() |
| - return os.ErrPermission |
| + if !allow { |
| + return os.ErrPermission |
| + } |
| } |
| return s.Store.Delete(ctx, key) |
| } |
| @@ -367,15 +376,7 @@ func TestEnvFormStageAddRemoveUndoDiscard(t *testing.T) { |
| mustNotContain(t, body, `<div class="savebar">`, "newenv.", `name="new.`, `name="bundle" value="default"`) |
| mustContain(t, body, `<div class="savebar" hidden>`, "<noscript><style>.savebar[hidden]") |
| - // Save is Task 8's: for now it draws the draft again and writes nothing. |
| - f = envFields(t, body) |
| - f.Set("val.default.LOG_LEVEL", "warn") |
| - status, body = e.post(t, f, "save") |
| - if status != http.StatusOK { |
| - t.Fatalf("save stub = %d", status) |
| - } |
| - mustContain(t, body, "1 change: LOG_LEVEL changed in All environments.") |
| - |
| + // Save is envsave_test.go's. |
| e.spy.none(t) |
| m, err := appconfig.Get(context.Background(), e.fx.rel, e.fx.sqid, "shop") |
| if err != nil || m.Vars["LOG_LEVEL"].Value != "info" || m.Vars["STRIPE_KEY"].Envelope != e.envelope || len(m.Vars) != 2 { |
| @@ -615,8 +616,9 @@ func TestEnvDraftWriteInput(t *testing.T) { |
| // it in a real browser: a secret Add posts only an envelope (no plaintext, |
| // no value field, the empty Replace field neither blocks nor posts), a |
| // Replace posts only its envelope, and the console stages what the browser |
| -// sent. With ENV_FORM_SHOTS set to a directory it also writes 390 px and |
| -// 1280 px screenshots there. |
| +// sent; a Save with a replaced secret and an edit posts once, envelope |
| +// only, and saves on the console. With ENV_FORM_SHOTS set to a directory it |
| +// also writes 390 px and 1280 px screenshots there. |
| func TestEnvFormChromium(t *testing.T) { |
| chromium, err := exec.LookPath("chromium") |
| if err != nil { |
| @@ -653,7 +655,7 @@ func TestEnvFormChromium(t *testing.T) { |
| ts := httptest.NewServer(mux) // 127.0.0.1 |
| defer ts.Close() |
| - const secret, replaced = "whsec_0123456789abcdef", "sk_live_replaced" |
| + const secret, replaced, saved = "whsec_0123456789abcdef", "sk_live_replaced", "sk_live_saved" |
| type scene struct { |
| URL string `json:"url"` |
| Fill map[string]string `json:"fill"` |
| @@ -669,6 +671,9 @@ func TestEnvFormChromium(t *testing.T) { |
| // An edit in a panel shows the hidden save bar; its Discard posts. |
| {ts.URL + "/page", map[string]string{"val.default.LOG_LEVEL": "warn"}, nil, "discard", true, |
| `document.querySelector(".savebar").hidden === false && getComputedStyle(document.querySelector(".savebar")).display !== "none"`}, |
| + // Save with a replaced secret and an ordinary edit: one post, the |
| + // secret as its envelope only. |
| + {ts.URL + "/page", map[string]string{"val.default.LOG_LEVEL": "warn", "sec.default.STRIPE_KEY": saved}, nil, "save", true, ""}, |
| } |
| payload, _ := json.Marshal(scenes) |
| ctx, cancel := context.WithTimeout(t.Context(), 90*time.Second) |
| @@ -680,8 +685,8 @@ func TestEnvFormChromium(t *testing.T) { |
| mu.Lock() |
| defer mu.Unlock() |
| - if len(posts) != 3 { |
| - t.Fatalf("%d posts, want 3: %v", len(posts), posts) |
| + if len(posts) != 4 { |
| + t.Fatalf("%d posts, want 4: %v", len(posts), posts) |
| } |
| if d := posts[2]; d.Get("op") != "discard" || d.Get("val.default.LOG_LEVEL") != "warn" { |
| t.Errorf("discard posted %v", d) |
| @@ -692,7 +697,7 @@ func TestEnvFormChromium(t *testing.T) { |
| t.Errorf("post %d: a Replace field was posted: %s", i, k) |
| } |
| for _, v := range vs { |
| - if strings.Contains(v, secret) || strings.Contains(v, replaced) { |
| + if strings.Contains(v, secret) || strings.Contains(v, replaced) || strings.Contains(v, saved) { |
| t.Errorf("post %d: field %s carries plaintext", i, k) |
| } |
| } |
| @@ -710,6 +715,11 @@ func TestEnvFormChromium(t *testing.T) { |
| } |
| checkBrowserEnvelope(t, e.priv, sealVector{Version: "2", Account: "bab", App: "shop", Plaintext: secret, Envelope: add.Get("addenv.default")}) |
| checkBrowserEnvelope(t, e.priv, sealVector{Version: "2", Account: "bab", App: "shop", Plaintext: replaced, Envelope: rep.Get("env.default.STRIPE_KEY")}) |
| + sv := posts[3] |
| + if sv.Get("op") != "save" || sv.Get("val.default.LOG_LEVEL") != "warn" || sv.Get("addenv.default") != "" { |
| + t.Errorf("save posted %v", sv) |
| + } |
| + checkBrowserEnvelope(t, e.priv, sealVector{Version: "2", Account: "bab", App: "shop", Plaintext: saved, Envelope: sv.Get("env.default.STRIPE_KEY")}) |
| // What the browser sent stages on the real console. |
| status, _, body := postForm(t, e.c, e.fx.u("/apps/shop/settings/environments"), add) |
| @@ -725,6 +735,20 @@ func TestEnvFormChromium(t *testing.T) { |
| mustContain(t, dbody, `<div class="savebar" hidden>`, `name="val.default.LOG_LEVEL" value="info"`) |
| e.spy.none(t) |
| + // The browser's Save, on the real console: one write, and the outcome. |
| + e.spy.mu.Lock() |
| + e.spy.allow = true |
| + e.spy.mu.Unlock() |
| + status, _, sbody := postForm(t, e.c, e.fx.u("/apps/shop/settings/environments"), sv) |
| + if status != http.StatusOK { |
| + t.Fatalf("console saving the browser's post = %d:\n%s", status, sbody) |
| + } |
| + mustContain(t, sbody, `<section class="env-outcome"`, "Saved 2 changes to All environments.") |
| + mustNotContain(t, sbody, saved) |
| + if m, err := appconfig.Get(context.Background(), e.fx.rel, e.fx.sqid, "shop"); err != nil || m.Vars["LOG_LEVEL"].Value != "warn" || m.Vars["STRIPE_KEY"].Envelope != sv.Get("env.default.STRIPE_KEY") { |
| + t.Fatalf("stored after the browser's save: %+v %v", m, err) |
| + } |
| + |
| if dir := os.Getenv("ENV_FORM_SHOTS"); dir != "" { |
| // The staged page, so the save bar shows too. |
| page = body |
diff --git a/internal/console/envsave.go b/internal/console/envsave.go| new file mode 100644 |
| index 000000000..0ee590dd5 |
| --- /dev/null |
| +++ b/internal/console/envsave.go |
| @@ -0,0 +1,294 @@ |
| +// Save on the app settings page's Environments form (console secrets, |
| +// Task 8): one conditional config write per Save through the shared write |
| +// boundary (writeConfig), no restart requested, then "After you save" from |
| +// the shared classifier (classifyConfigWrite), the same WriteReach the CLI's |
| +// restart notice is built from. Retry (op=check) re-runs that classification |
| +// and writes nothing. |
| +// |
| +// What Save never does: request a restart (no restart-scope or |
| +// restart-generation write; spec "How Save applies"), write more than the |
| +// one staged bundle, or put a value or an envelope into a log line, an audit |
| +// row or a refusal. |
| +package console |
| + |
| +import ( |
| + "fmt" |
| + "net/http" |
| + "sort" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| +) |
| + |
| +// envOutcome is "After you save": where one write lands, bucket by bucket, |
| +// in the page's words. Every host comes from one appconfig.WriteReach |
| +// (envOutcomeOf), so the page and the CLI notice (reachWire) cannot |
| +// disagree about a route. |
| +type envOutcome struct { |
| + Bundle string // the bundle written: "default" or the environment |
| + Title string // its card's title |
| + Count int // changes saved; 0 for a Retry, which saved nothing |
| + |
| + Self, Yours, Starting []envOutcomeRow |
| + Unseen []string |
| + Blocked []appconfig.BlockedHost |
| + Undelivered []string |
| + Unresolved []string |
| + // Unknown: this console did not look (no registry, or one that would not |
| + // open or list). Never drawn as an empty answer. |
| + Unknown bool |
| + |
| + // The Retry form's fields: the bundle and the keys the save touched. |
| + CheckBundle string |
| + CheckKeys []string |
| +} |
| + |
| +// envOutcomeRow is one route in a bucket: its chip, and for Yours the How |
| +// sentence (Line, then for a sidecar a link to Running and the rest). |
| +type envOutcomeRow struct { |
| + Host, Chip, Line, Link, After string |
| + |
| + why appconfig.ReachWhy |
| +} |
| + |
| +// Empty reports whether the write reached nothing this box can name. |
| +func (o *envOutcome) Empty() bool { |
| + return len(o.Self)+len(o.Yours)+len(o.Starting)+len(o.Unseen)+len(o.Blocked)+len(o.Undelivered)+len(o.Unresolved) == 0 |
| +} |
| + |
| +// Asleep and NotRunning say which Starting lines the page explains. |
| +func (o *envOutcome) Asleep() bool { return o.startingWhy(appconfig.ReachWhyAsleep) } |
| +func (o *envOutcome) NotRunning() bool { return o.startingWhy(appconfig.ReachWhyNotRunning) } |
| + |
| +func (o *envOutcome) startingWhy(why appconfig.ReachWhy) bool { |
| + for _, r := range o.Starting { |
| + if r.why == why { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// envOutcomeOf words one classification. ok false is "this console did not |
| +// look": Unknown, with Retry. |
| +func envOutcomeOf(c envPageCopy, bundle, title string, count int, keys []string, reach appconfig.WriteReach, ok bool) *envOutcome { |
| + o := &envOutcome{Bundle: bundle, Title: title, Count: count, CheckBundle: bundle, CheckKeys: keys} |
| + if !ok { |
| + o.Unknown = true |
| + return o |
| + } |
| + for _, h := range reach.Self { |
| + o.Self = append(o.Self, envOutcomeRow{Host: h.Host, Chip: c.OutcomeSelf}) |
| + } |
| + for _, h := range reach.Yours { |
| + row := envOutcomeRow{Host: h.Host, Chip: c.OutcomeYou} |
| + switch h.How { |
| + case appconfig.ReachHowSidecar: |
| + row.Line, row.Link, row.After = envFill(c.OutcomeYouSidecar, "host", h.Host), c.OutcomeCheckRun, c.OutcomeSidecarAfter |
| + default: |
| + // addr, and any How a later classifier adds: restart it the way |
| + // you started it is true of every route CARLOS does not restart. |
| + row.Line = envFill(c.OutcomeYouAddr, "host", h.Host) |
| + } |
| + o.Yours = append(o.Yours, row) |
| + } |
| + for _, h := range reach.Starting { |
| + chip := c.OutcomeAsleep |
| + if h.Why != appconfig.ReachWhyAsleep { |
| + chip = c.OutcomeNotRunning |
| + } |
| + o.Starting = append(o.Starting, envOutcomeRow{Host: h.Host, Chip: chip, why: h.Why}) |
| + } |
| + o.Unseen = append(o.Unseen, reach.Unseen...) |
| + o.Blocked = append(o.Blocked, reach.Blocked...) |
| + o.Undelivered = append(o.Undelivered, reach.Undelivered...) |
| + for _, h := range reach.Unresolved { |
| + o.Unresolved = append(o.Unresolved, h.Host) |
| + } |
| + return o |
| +} |
| + |
| +// envFormSave is Save: the staged bundle's one write at the version the |
| +// page showed, then the outcome. The gates before it (membership, CSRF, the |
| +// form's own refusals) are handleEnvForm's; the write boundary's rules |
| +// (environment, var names and values, the seal check under the account |
| +// lock) are writeConfig's, the same function the JSON door's checks are. |
| +func (s *Server) envFormSave(w http.ResponseWriter, r *http.Request, p page, acct *Account, addr string, d *envDraft) { |
| + sv := p.Settings |
| + c := sv.EnvCopy |
| + if d.Empty() { |
| + sv.EnvError = c.NothingToSave |
| + s.render(w, http.StatusOK, "app_settings", p) |
| + return |
| + } |
| + if !s.allowWrite(Principal{Kind: PrincipalUser, Address: addr}, time.Now()) { |
| + applyEnvDraft(sv, d, nil) |
| + sv.EnvError = c.RateLimited |
| + s.render(w, http.StatusTooManyRequests, "app_settings", p) |
| + return |
| + } |
| + ctx := r.Context() |
| + card := envCardFor(sv.Envs, d.Bundle) |
| + // The version the page showed the staged bundle at, as posted. A form |
| + // without one cannot say what it was looking at, so it is not written: |
| + // the conflict path re-reads it, as for a bundle that moved. |
| + want, verOK := appconfig.ParseBundleVersion(r.PostFormValue("ver." + d.Bundle)) |
| + var removed int |
| + var ref *configRefusal |
| + if !verOK || card == nil { |
| + ref = &configRefusal{Code: configRefusalConflict, Status: http.StatusConflict} |
| + } else { |
| + in, unset := d.writeInput(r.PostFormValue("sealed_to")) |
| + removed, ref = s.writeConfig(ctx, acct, p.AppName, d.envName(), &want, in, unset) |
| + if ref == nil { |
| + bundle := configBundleName(d.envName()) |
| + // Counts and the bundle, never keys or values: the JSON door's |
| + // row, naming this door. |
| + s.auditActivity(acct, p.AppName, addr, Activity{ |
| + Action: "config", TargetType: "environment", Target: bundle, |
| + Detail: fmt.Sprintf("config: %d set, %d unset (%s) (console)", len(in), removed, bundle), |
| + }) |
| + s.bumpSerial(ctx) |
| + keys := envWrittenKeys(in, unset) |
| + reach, ok := s.classifyConfigWrite(ctx, acct.Sqid, p.AppName, d.envName(), keys) |
| + sv.EnvOutcome = envOutcomeOf(c, d.Bundle, card.Title, len(d.changes()), keys, reach, ok) |
| + // Drawn fresh: the new versions, nothing staged. |
| + sv.Envs, sv.EnvsUnavailable = s.envCards(ctx, acct, p.AppName, p.Detail.Routes) |
| + s.render(w, http.StatusOK, "app_settings", p) |
| + return |
| + } |
| + } |
| + if ref.Code == configRefusalConflict { |
| + // Nothing was written. Drawn from the bundles as they are now, the |
| + // ordinary changes put back on top, the sealed ones dropped: they |
| + // were sealed against a page that is gone, and are entered again. |
| + sv.Envs, sv.EnvsUnavailable = s.envCards(ctx, acct, p.AppName, p.Detail.Routes) |
| + var nd *envDraft |
| + if fresh := envCardFor(sv.Envs, d.Bundle); fresh != nil { |
| + nd = d.rebase(fresh) |
| + } |
| + applyEnvDraft(sv, nd, nil) |
| + sv.EnvError = c.refusal(ref, sv.EnvSealFleet) |
| + s.render(w, http.StatusConflict, "app_settings", p) |
| + return |
| + } |
| + // Any other refusal: nothing was written, the draft stays, less what |
| + // the refusal is about (never drawn back), and the row it names opens. |
| + switch ref.Code { |
| + case configRefusalKeylessFleet, configRefusalSealedWrongKey, configRefusalSealedUnchecked, configRefusalSealedOld: |
| + // Every secret on the page was sealed by the same page to the same |
| + // key: if one is refused for its key, all of them would be. |
| + d.Secrets = map[string]string{} |
| + default: |
| + if ref.Var != "" { |
| + d.drop(ref.Var) |
| + } |
| + } |
| + applyEnvDraft(sv, d, nil) |
| + envOpenRow(sv, d.Bundle, ref.Var) |
| + sv.EnvError = c.refusal(ref, sv.EnvSealFleet) |
| + status := ref.Status |
| + if status == 0 { |
| + status = http.StatusBadRequest |
| + } |
| + s.render(w, status, "app_settings", p) |
| +} |
| + |
| +// envFormCheck is Retry: the classification for the bundle and keys the |
| +// Retry form carries, and no write. Only names are read from it, each |
| +// checked; anything else is refused rather than classified as something |
| +// it is not (fewer keys would hide a route the shadowing test should show). |
| +func (s *Server) envFormCheck(w http.ResponseWriter, r *http.Request, p page, acct *Account) { |
| + sv := p.Settings |
| + c := sv.EnvCopy |
| + bundle := r.PostFormValue("check_bundle") |
| + card := envCardFor(sv.Envs, bundle) |
| + keys := r.PostForm["check_key"] |
| + valid := card != nil && len(keys) <= envCheckMaxKeys |
| + for _, k := range keys { |
| + valid = valid && appconfig.ValidVarName(k) |
| + } |
| + if !valid { |
| + sv.EnvError = c.OutcomeCheckBad |
| + s.render(w, http.StatusBadRequest, "app_settings", p) |
| + return |
| + } |
| + keys = append([]string(nil), keys...) |
| + sort.Strings(keys) |
| + envName := "" |
| + if bundle != appconfig.DefaultBundle { |
| + envName = bundle |
| + } |
| + reach, ok := s.classifyConfigWrite(r.Context(), acct.Sqid, p.AppName, envName, keys) |
| + sv.EnvOutcome = envOutcomeOf(c, bundle, card.Title, 0, keys, reach, ok) |
| + s.render(w, http.StatusOK, "app_settings", p) |
| +} |
| + |
| +// envCheckMaxKeys bounds one Retry: far more keys than one page's save can |
| +// touch, few enough that a forged form cannot make one check expensive. |
| +const envCheckMaxKeys = 512 |
| + |
| +// envWrittenKeys is writtenKeys over the form's input, sorted (the Retry |
| +// form carries them in this order). |
| +func envWrittenKeys(in map[string]configVarIn, unset []string) []string { |
| + sets := make(map[string]appconfig.Var, len(in)) |
| + for k := range in { |
| + sets[k] = appconfig.Var{} |
| + } |
| + keys := writtenKeys(sets, unset) |
| + sort.Strings(keys) |
| + return keys |
| +} |
| + |
| +func envCardFor(cards []*EnvCard, bundle string) *EnvCard { |
| + for _, c := range cards { |
| + if c.Bundle == bundle { |
| + return c |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// envOpenRow opens name's row on bundle's card, so a refusal about it is |
| +// next to it. |
| +func envOpenRow(sv *SettingsView, bundle, name string) { |
| + if name == "" { |
| + return |
| + } |
| + if card := envCardFor(sv.Envs, bundle); card != nil { |
| + for i := range card.Vars { |
| + if card.Vars[i].Name == name { |
| + card.Vars[i].Open = true |
| + } |
| + } |
| + } |
| +} |
| + |
| +// rebase is d's ordinary changes over card as it is now, at its version: |
| +// changed values and new settings kept where they still differ (a setting |
| +// someone else made secret is theirs now), removals of what is still |
| +// there. Secrets are dropped. |
| +func (d *envDraft) rebase(card *EnvCard) *envDraft { |
| + nd := newEnvDraft(card) |
| + put := func(k, v string) { |
| + stored, ok := card.stored[k] |
| + switch { |
| + case !ok: |
| + nd.New[k] = v |
| + case stored.Kind != "secret" && stored.Value != v: |
| + nd.Values[k] = v |
| + } |
| + } |
| + for k, v := range d.Values { |
| + put(k, v) |
| + } |
| + for k, v := range d.New { |
| + put(k, v) |
| + } |
| + for _, k := range d.Unset { |
| + if _, ok := card.stored[k]; ok { |
| + nd.Unset = append(nd.Unset, k) |
| + } |
| + } |
| + return nd |
| +} |
diff --git a/internal/console/envsave_test.go b/internal/console/envsave_test.go| new file mode 100644 |
| index 000000000..fd02fe920 |
| --- /dev/null |
| +++ b/internal/console/envsave_test.go |
| @@ -0,0 +1,571 @@ |
| +package console |
| + |
| +// Save on the Environments form (console secrets, Task 8): one conditional |
| +// config write, no restart requested, then "After you save" from the |
| +// shared classifier; Retry re-classifies and writes nothing. |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "net/url" |
| + "reflect" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// saving lets the fixture's writes through, still recording them, and |
| +// forgets what setup wrote. |
| +func (e *envFx) saving() { |
| + e.spy.mu.Lock() |
| + e.spy.allow, e.spy.writes = true, nil |
| + e.spy.mu.Unlock() |
| +} |
| + |
| +func (e *envFx) written() []string { |
| + e.spy.mu.Lock() |
| + defer e.spy.mu.Unlock() |
| + return append([]string(nil), e.spy.writes...) |
| +} |
| + |
| +func (e *envFx) stored(t *testing.T) *appconfig.Manifest { |
| + t.Helper() |
| + m, err := appconfig.Get(context.Background(), e.fx.rel, e.fx.sqid, "shop") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return m |
| +} |
| + |
| +// envOutcomeRe is the "After you save" section. |
| +var envOutcomeRe = regexp.MustCompile(`(?s)<section class="env-outcome".*?</section>`) |
| + |
| +func envOutcomeHTML(t *testing.T, body string) string { |
| + t.Helper() |
| + m := envOutcomeRe.FindString(body) |
| + if m == "" { |
| + t.Fatalf("no outcome section:\n%s", body) |
| + } |
| + return m |
| +} |
| + |
| +// envBanner is the refusal banner's text, "" when none. |
| +func envBanner(body string) string { |
| + m := regexp.MustCompile(`<p class="banner error" role="alert">([^<]*)</p>`).FindStringSubmatch(body) |
| + if m == nil { |
| + return "" |
| + } |
| + return m[1] |
| +} |
| + |
| +func TestEnvSaveWritesOnceNoRestart(t *testing.T) { |
| + e := newEnvFx(t) |
| + e.saving() |
| + if _, err := appconfig.ApplyEnvironment(context.Background(), e.fx.rel, e.fx.sqid, "shop", "staging", |
| + map[string]appconfig.Var{"LOG_LEVEL": {Kind: "env", Value: "debug"}}, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + e.saving() |
| + f := envFields(t, e.page(t)) |
| + replaced := e.seal(t, "new-stripe") |
| + f.Set("val.default.LOG_LEVEL", "warn") |
| + f.Set("env.default.STRIPE_KEY", replaced) |
| + f.Set("bundle", "default") |
| + // An edit in another card is not this Save's: ignored, never written. |
| + f.Set("val.staging.LOG_LEVEL", "trace") |
| + status, body := e.post(t, f, "save") |
| + if status != http.StatusOK { |
| + t.Fatalf("save = %d:\n%s", status, body) |
| + } |
| + |
| + // Exactly one manifest write and the generation touch; never a restart. |
| + cfgKey, genKey := appconfig.Key(e.fx.sqid, "shop"), appconfig.GenKey(e.fx.sqid, "shop") |
| + var manifests, gens int |
| + for _, k := range e.written() { |
| + switch { |
| + case strings.HasSuffix(k, "restart-gen.json"), strings.HasSuffix(k, "restart-scope.json"), |
| + k == release.RestartGenKey(e.fx.sqid, "shop"), k == release.RestartScopeKey(e.fx.sqid, "shop"): |
| + t.Fatalf("Save requested a restart: wrote %s", k) |
| + case k == cfgKey: |
| + manifests++ |
| + case k == genKey: |
| + gens++ |
| + default: |
| + t.Errorf("Save wrote %s", k) |
| + } |
| + } |
| + if manifests != 1 || gens != 1 { |
| + t.Fatalf("writes = %v, want one manifest and one generation touch", e.written()) |
| + } |
| + m := e.stored(t) |
| + if m.Vars["LOG_LEVEL"].Value != "warn" || m.Vars["STRIPE_KEY"].Envelope != replaced || len(m.Vars) != 2 { |
| + t.Fatalf("stored = %+v", m.Vars) |
| + } |
| + if sm, _, err := appconfig.GetBundle(context.Background(), e.fx.rel, e.fx.sqid, "shop", "staging"); err != nil || sm.Vars["LOG_LEVEL"].Value != "debug" { |
| + t.Fatalf("staging moved: %+v %v", sm, err) |
| + } |
| + |
| + // The page is drawn fresh: the new version, nothing staged, the outcome. |
| + _, ver, _ := appconfig.GetBundle(context.Background(), e.fx.rel, e.fx.sqid, "shop", "") |
| + mustContain(t, body, `name="ver.default" value="`+ver.String()+`"`, `<div class="savebar" hidden>`, |
| + `name="val.default.LOG_LEVEL" value="warn"`) |
| + mustNotContain(t, body, replaced, "newenv.", `name="bundle" value="default"`) |
| + out := envOutcomeHTML(t, body) |
| + mustContain(t, out, "After you save", "Saved 2 changes to All environments.", |
| + "Nothing on this box uses these settings.", "Copies on other boxes may not all be listed here.", |
| + `href="/a/`+e.fx.srv.mustAccountName(t)+`/apps/shop/instances">See what's running</a>`) |
| + mustNotContain(t, out, "unused", "Unused", "<button") |
| + |
| + // The audit row: counts and the bundle, naming this door; no content. |
| + events, err := e.fx.st.Events(OpsAccountID, "shop", 20) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + found := false |
| + for _, ev := range events { |
| + if strings.Contains(ev.Detail, replaced) || strings.Contains(ev.Detail, "warn") || strings.Contains(ev.Detail, "LOG_LEVEL") { |
| + t.Fatalf("audit row carries content: %q", ev.Detail) |
| + } |
| + if ev.Action == "config" && ev.Detail == "config: 2 set, 0 unset (default) (console)" && ev.TargetType == "environment" && ev.Target == "default" { |
| + found = true |
| + } |
| + } |
| + if !found { |
| + t.Fatalf("no console config audit row in %+v", events) |
| + } |
| +} |
| + |
| +// mustAccountName is the Nav segment the fixture's pages use. |
| +func (s *Server) mustAccountName(t *testing.T) string { |
| + t.Helper() |
| + a, err := s.store.AccountBySqid(release.OpsAccount) |
| + if err != nil || a == nil { |
| + t.Fatalf("ops account: %v", err) |
| + } |
| + return a.Name |
| +} |
| + |
| +func TestEnvSaveConflictKeepsOrdinaryDropsSecrets(t *testing.T) { |
| + e := newEnvFx(t) |
| + e.saving() |
| + f := envFields(t, e.page(t)) |
| + replaced := e.seal(t, "new-stripe") |
| + f.Set("val.default.LOG_LEVEL", "warn") |
| + f.Set("new.default.MODE", "fast") |
| + f.Set("env.default.STRIPE_KEY", replaced) |
| + f.Set("bundle", "default") |
| + // Someone else saves first. |
| + if err := appconfig.SetEnv(context.Background(), e.fx.rel, e.fx.sqid, "shop", map[string]string{"OTHER": "1"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := e.stored(t) |
| + e.saving() |
| + status, body := e.post(t, f, "save") |
| + if status != http.StatusConflict { |
| + t.Fatalf("save over a moved bundle = %d:\n%s", status, body) |
| + } |
| + if w := e.written(); len(w) != 0 { |
| + t.Fatalf("a conflicted save wrote %v", w) |
| + } |
| + if after := e.stored(t); !reflect.DeepEqual(after, before) { |
| + t.Fatalf("stored moved: %+v, was %+v", after, before) |
| + } |
| + _, ver, _ := appconfig.GetBundle(context.Background(), e.fx.rel, e.fx.sqid, "shop", "") |
| + mustContain(t, body, "Someone else saved these settings first. Your other changes are still here; enter your secrets again.", |
| + `name="val.default.LOG_LEVEL" value="warn"`, `name="new.default.MODE" value="fast"`, |
| + `name="ver.default" value="`+ver.String()+`"`, `name="val.default.OTHER" value="1"`, |
| + "2 changes in All environments: LOG_LEVEL changed, new setting MODE.") |
| + mustNotContain(t, body, replaced, "newenv.", `class="env-outcome"`) |
| + |
| + // What the page drew saves at the fresh version. |
| + status, body = e.post(t, envFields(t, body), "save") |
| + if status != http.StatusOK { |
| + t.Fatalf("re-save = %d:\n%s", status, body) |
| + } |
| + m := e.stored(t) |
| + if m.Vars["LOG_LEVEL"].Value != "warn" || m.Vars["MODE"].Value != "fast" || m.Vars["OTHER"].Value != "1" || m.Vars["STRIPE_KEY"].Envelope != e.envelope { |
| + t.Fatalf("stored after re-save = %+v", m.Vars) |
| + } |
| + mustContain(t, body, "Saved 2 changes to All environments.") |
| +} |
| + |
| +func TestEnvSaveRefusalsPersonCopy(t *testing.T) { |
| + const marker = `x\bad-value-marker` |
| + t.Run("var-value", func(t *testing.T) { |
| + e := newEnvFx(t) |
| + e.saving() |
| + f := envFields(t, e.page(t)) |
| + f.Set("val.default.LOG_LEVEL", marker) |
| + f.Set("new.default.MODE", "fast") |
| + status, body := e.post(t, f, "save") |
| + if status != http.StatusBadRequest { |
| + t.Fatalf("status = %d", status) |
| + } |
| + mustContain(t, body, "The value of LOG_LEVEL can't contain a backslash, a quote, a newline or a NUL character.", |
| + `name="new.default.MODE" value="fast"`, `<details class="envvar" open><summary><code class="envvar-name">LOG_LEVEL</code>`) |
| + mustNotContain(t, body, "bad-value-marker") |
| + if w := e.written(); len(w) != 0 { |
| + t.Fatalf("wrote %v", w) |
| + } |
| + }) |
| + t.Run("sealed-wrong-key", func(t *testing.T) { |
| + e := newEnvFx(t) |
| + e.saving() |
| + f := envFields(t, e.page(t)) |
| + env := e.seal(t, "replacement") |
| + f.Set("env.default.STRIPE_KEY", env) |
| + f.Set("sealed_to", strings.Repeat("0", 64)) |
| + status, body := e.post(t, f, "save") |
| + if status != http.StatusBadRequest { |
| + t.Fatalf("status = %d", status) |
| + } |
| + mustContain(t, body, "STRIPE_KEY was sealed to a key this app's boxes don't hold. Reload the page and enter it again.") |
| + mustNotContain(t, body, env) |
| + if w := e.written(); len(w) != 0 { |
| + t.Fatalf("wrote %v", w) |
| + } |
| + }) |
| + t.Run("store", func(t *testing.T) { |
| + e := newEnvFx(t) // writes under shop refused: the store fails |
| + env := e.seal(t, "replacement") |
| + f := envFields(t, e.page(t)) |
| + f.Set("env.default.STRIPE_KEY", env) |
| + f.Set("new.default.MODE", "fast") |
| + status, body := e.post(t, f, "save") |
| + if status != http.StatusBadGateway { |
| + t.Fatalf("status = %d:\n%s", status, body) |
| + } |
| + banner := envBanner(body) |
| + if banner != "Couldn't save just now. Nothing changed. Try again." { |
| + t.Fatalf("banner = %q", banner) |
| + } |
| + // The draft stays, to try again; the refusal itself carries nothing. |
| + mustContain(t, body, `name="new.default.MODE" value="fast"`, "2 changes in All environments") |
| + if strings.Contains(banner, env) || strings.Contains(banner, "fast") { |
| + t.Fatalf("banner carries content: %q", banner) |
| + } |
| + mustNotContain(t, body, `class="env-outcome"`) |
| + if m := e.stored(t); m.Vars["LOG_LEVEL"].Value != "info" || m.Vars["STRIPE_KEY"].Envelope != e.envelope || len(m.Vars) != 2 { |
| + t.Fatalf("stored moved: %+v", m.Vars) |
| + } |
| + }) |
| + |
| + // The fleet rules: a fleet app's secret must name the fleet's key and be |
| + // sealed bound; a keyless fleet takes none. |
| + fleet := func(t *testing.T, code string, withKey bool, edit func(url.Values, skFleetKey, *consoleFixture)) (int, string, *consoleFixture) { |
| + t.Helper() |
| + appconfig.SetBoundSealing(false) |
| + fx, _, k := skFleetShop(t, code, withKey) |
| + c := signInPaul(t, fx) |
| + _, _, page := get(t, c, fx.u("/apps/shop/settings/environments")) |
| + f := envFields(t, page) |
| + edit(f, k, fx) |
| + f.Set("op", "save") |
| + status, _, body := postForm(t, c, fx.u("/apps/shop/settings/environments"), f) |
| + if m := skStored(t, fx); m != nil { |
| + if _, ok := m.Vars["API_KEY"]; ok { |
| + t.Fatalf("a refused save stored API_KEY") |
| + } |
| + } |
| + return status, body, fx |
| + } |
| + for _, c := range []struct { |
| + name, want string |
| + withKey bool |
| + edit func(url.Values, skFleetKey, *consoleFixture) string |
| + }{ |
| + {"sealed-unchecked", "Example Cloud couldn't check which key sealed API_KEY.", true, func(f url.Values, k skFleetKey, fx *consoleFixture) string { |
| + env := skSeal(t, fx, k.pub, true) |
| + f.Set("newenv.default.API_KEY", env) |
| + f.Del("sealed_to") |
| + return env |
| + }}, |
| + {"sealed-old", "API_KEY was sealed in an older format this app's boxes don't accept.", true, func(f url.Values, k skFleetKey, fx *consoleFixture) string { |
| + env := skSeal(t, fx, k.pub, false) |
| + f.Set("newenv.default.API_KEY", env) |
| + return env |
| + }}, |
| + {"keyless-fleet", "home has no secrets key yet, so secrets can't be set for this app.", false, func(f url.Values, k skFleetKey, fx *consoleFixture) string { |
| + env := skSeal(t, fx, k.pub, true) |
| + f.Set("newenv.default.API_KEY", env) |
| + return env |
| + }}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + var env string |
| + status, body, fx := fleet(t, "code-envsave-"+c.name, c.withKey, func(f url.Values, k skFleetKey, fx *consoleFixture) { env = c.edit(f, k, fx) }) |
| + if status < 400 { |
| + t.Fatalf("status = %d", status) |
| + } |
| + want := strings.ReplaceAll(c.want, "Example Cloud", fx.srv.consoleName()) |
| + mustContain(t, envBanner(body), want) |
| + mustNotContain(t, body, env, `class="env-outcome"`) |
| + }) |
| + } |
| +} |
| + |
| +func TestEnvSaveSealedToChecked(t *testing.T) { |
| + appconfig.SetBoundSealing(false) |
| + fx, _, k := skFleetShop(t, "code-envsave-sealedto", true) |
| + c := signInPaul(t, fx) |
| + _, _, page := get(t, c, fx.u("/apps/shop/settings/environments")) |
| + f := envFields(t, page) |
| + if f.Get("sealed_to") != k.fp { |
| + t.Fatalf("page sealed_to = %q, want the fleet key %s", f.Get("sealed_to"), k.fp) |
| + } |
| + other := skNewKey(t) |
| + env := skSeal(t, fx, k.pub, true) |
| + f.Set("newenv.default.API_KEY", env) |
| + f.Set("sealed_to", other.fp) |
| + f.Set("op", "save") |
| + status, _, body := postForm(t, c, fx.u("/apps/shop/settings/environments"), f) |
| + if status != http.StatusBadRequest { |
| + t.Fatalf("wrong sealed_to = %d:\n%s", status, body) |
| + } |
| + mustContain(t, envBanner(body), "API_KEY was sealed to a key this app's boxes don't hold.") |
| + mustNotContain(t, body, env, "newenv.") |
| + if m := skStored(t, fx); m != nil { |
| + if _, ok := m.Vars["API_KEY"]; ok { |
| + t.Fatal("stored API_KEY") |
| + } |
| + } |
| + // The right key lands. |
| + f.Set("sealed_to", k.fp) |
| + if status, _, body = postForm(t, c, fx.u("/apps/shop/settings/environments"), f); status != http.StatusOK { |
| + t.Fatalf("right sealed_to = %d:\n%s", status, envBanner(body)) |
| + } |
| + if m := skStored(t, fx); m == nil || m.Vars["API_KEY"].Envelope != env || m.Vars["API_KEY"].SealedTo != k.fp { |
| + t.Fatalf("stored = %+v", m) |
| + } |
| +} |
| + |
| +// envBucketsFx is shop with, on this box, a socket route, an opted-in addr |
| +// route and a sidecar no report says is managed, plus a provision record |
| +// for a host on another box. |
| +func envBucketsFx(t *testing.T) *envFx { |
| + t.Helper() |
| + e := newEnvFx(t) |
| + e.saving() |
| + ctx := context.Background() |
| + reg, err := registry.Open(e.fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, rt := range []registry.Route{ |
| + {Host: "sock.shop.example.com", Kind: "instance", Status: "ready", App: "shop", Account: e.fx.sqid, Socket: "/run/carlos/sock.sock"}, |
| + {Host: "addr.shop.example.com", Kind: "instance", Status: "ready", App: "shop", Account: e.fx.sqid, Addr: "127.0.0.1:9001"}, |
| + {Host: "worker.shop.example.com", Kind: "sidecar", Status: "ready", App: "shop", Account: e.fx.sqid}, |
| + } { |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := provision.CreateRecord(ctx, e.fx.rel, provision.Record{Schema: 1, Host: "remote.shop.example.com", Slug: "remote", |
| + App: "shop", Account: e.fx.sqid, Channel: "stable", CreatedAt: time.Now().UTC(), CreatedBy: "paul@keymail.dev"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + optIn(t, e.fx, "shop") |
| + e.saving() |
| + return e |
| +} |
| + |
| +func TestEnvSaveOutcomeBuckets(t *testing.T) { |
| + e := envBucketsFx(t) |
| + f := envFields(t, e.page(t)) |
| + f.Set("val.default.LOG_LEVEL", "warn") |
| + status, body := e.post(t, f, "save") |
| + if status != http.StatusOK { |
| + t.Fatalf("save = %d:\n%s", status, envBanner(body)) |
| + } |
| + out := envOutcomeHTML(t, body) |
| + row := func(host, chip string) string { |
| + return `<span class="envvar-name">` + host + `</span><span class="envvar-value"><span class="chip ` + chip |
| + } |
| + mustContain(t, out, "Saved 1 change to All environments.", |
| + row("sock.shop.example.com", "chip-health-ok\">Updates itself"), |
| + row("addr.shop.example.com", "chip-canary\">Restart it yourself"), |
| + row("worker.shop.example.com", "chip-canary\">Restart it yourself"), |
| + row("remote.shop.example.com", "chip-health-unknown\">Can't see"), |
| + "addr.shop.example.com: your app runs this one itself. Restart it the way you started it.", |
| + `worker.shop.example.com: a background worker. <a href="/a/`+e.fx.srv.mustAccountName(t)+`/apps/shop/instances">Check Running</a> and restart the app if it hasn't picked this up.`, |
| + "<code>carlos restart --host remote.shop.example.com</code>", |
| + "Copies on other boxes may not all be listed here.") |
| + mustNotContain(t, out, "Nothing on this box uses", "unused", `name="op" value="check"`) |
| + // Restart it yourself: each row its How sentence, and no control. |
| + yours := regexp.MustCompile(`(?s)<li data-outcome="yours">.*?</li>`).FindAllString(out, -1) |
| + if len(yours) != 4 { // two chip rows, two How sentences |
| + t.Fatalf("yours rows = %d:\n%s", len(yours), out) |
| + } |
| + for _, y := range yours { |
| + if strings.Contains(y, "<button") || strings.Contains(y, "<form") { |
| + t.Fatalf("a Restart it yourself row has a control: %s", y) |
| + } |
| + } |
| + if strings.Contains(out, "<button") && !strings.Contains(out, `value="check"`) { |
| + t.Fatalf("the outcome has a button:\n%s", out) |
| + } |
| + for _, k := range e.written() { |
| + if strings.Contains(k, "restart-") { |
| + t.Fatalf("Save requested a restart: %s", k) |
| + } |
| + } |
| +} |
| + |
| +func TestEnvSaveNoRegistryUnknown(t *testing.T) { |
| + e := newEnvFx(t) |
| + e.saving() |
| + // The page itself reads the registry, so it goes away only once the |
| + // write is under way: from there on this console has not looked. |
| + reg := e.fx.srv.cfg.Registry |
| + configPutBeforeApply = func() { e.fx.srv.cfg.Registry = "" } |
| + t.Cleanup(func() { configPutBeforeApply, e.fx.srv.cfg.Registry = nil, reg }) |
| + f := envFields(t, e.page(t)) |
| + f.Set("val.default.LOG_LEVEL", "warn") |
| + f.Set("new.default.MODE", "fast") |
| + status, body := e.post(t, f, "save") |
| + if status != http.StatusOK { |
| + t.Fatalf("save = %d:\n%s", status, envBanner(body)) |
| + } |
| + out := envOutcomeHTML(t, body) |
| + mustContain(t, out, "Saved 2 changes to All environments.", |
| + "Saved, but "+e.fx.srv.consoleName()+" couldn't check what uses these settings just now.", |
| + `name="check_bundle" value="default"`, `name="check_key" value="LOG_LEVEL"`, `name="check_key" value="MODE"`, |
| + `<button type="submit" class="btn-sm btn-secondary" name="op" value="check">Retry</button>`, |
| + "Copies on other boxes may not all be listed here.") |
| + mustNotContain(t, out, "Nothing on this box uses") |
| +} |
| + |
| +func TestEnvSaveCheckRerunsWithoutWrite(t *testing.T) { |
| + e := envBucketsFx(t) |
| + e.spy.mu.Lock() |
| + e.spy.allow, e.spy.writes = false, nil // any write now fails and is recorded |
| + e.spy.mu.Unlock() |
| + csrf := envFields(t, e.page(t)).Get("csrf") |
| + check := func(fields url.Values) (int, string) { |
| + t.Helper() |
| + fields.Set("csrf", csrf) |
| + status, _, body := postForm(t, e.c, e.fx.u("/apps/shop/settings/environments"), fields) |
| + return status, body |
| + } |
| + status, body := check(url.Values{"op": {"check"}, "check_bundle": {"default"}, "check_key": {"LOG_LEVEL"}}) |
| + if status != http.StatusOK { |
| + t.Fatalf("check = %d:\n%s", status, envBanner(body)) |
| + } |
| + out := envOutcomeHTML(t, body) |
| + mustContain(t, out, "Updates itself", "Restart it yourself", "Can't see", "Copies on other boxes may not all be listed here.") |
| + mustNotContain(t, out, "Saved ") |
| + e.spy.none(t) |
| + |
| + for name, fields := range map[string]url.Values{ |
| + "unknown bundle": {"op": {"check"}, "check_bundle": {"nope"}, "check_key": {"LOG_LEVEL"}}, |
| + "bad key": {"op": {"check"}, "check_bundle": {"default"}, "check_key": {"not a name"}}, |
| + } { |
| + status, body := check(fields) |
| + if status != http.StatusBadRequest { |
| + t.Fatalf("%s: check = %d", name, status) |
| + } |
| + mustContain(t, envBanner(body), "Couldn't check that save again. Reload the page.") |
| + mustNotContain(t, body, `class="env-outcome"`) |
| + } |
| + e.spy.none(t) |
| +} |
| + |
| +// TestEnvOutcomeMatchesCLIWire: one WriteReach, through the CLI's wire |
| +// (reachWire, over restartWire) and through the page's builder, names the |
| +// same hosts in each bucket. |
| +func TestEnvOutcomeMatchesCLIWire(t *testing.T) { |
| + hostsOf := func(l []apiConfigReachHost) []string { |
| + var out []string |
| + for _, h := range l { |
| + out = append(out, h.Host) |
| + } |
| + return out |
| + } |
| + rowHosts := func(l []envOutcomeRow) []string { |
| + var out []string |
| + for _, r := range l { |
| + out = append(out, r.Host) |
| + } |
| + return out |
| + } |
| + compare := func(t *testing.T, reach appconfig.WriteReach) { |
| + t.Helper() |
| + wire := reachWire(reach) |
| + o := envOutcomeOf(envCopyFor("Example Cloud"), "default", "All environments", 1, []string{"LOG_LEVEL"}, reach, true) |
| + for name, pair := range map[string][2][]string{ |
| + "self": {hostsOf(wire.Self), rowHosts(o.Self)}, |
| + "yours": {hostsOf(wire.Yours), rowHosts(o.Yours)}, |
| + "starting": {hostsOf(wire.Starting), rowHosts(o.Starting)}, |
| + "unseen": {wire.Unseen, o.Unseen}, |
| + } { |
| + if !reflect.DeepEqual(pair[0], pair[1]) { |
| + t.Errorf("%s: CLI %v, page %v", name, pair[0], pair[1]) |
| + } |
| + } |
| + // The how agrees too: the wire's sidecar is the page's Running link. |
| + for i, h := range wire.Yours { |
| + if (h.How == string(appconfig.ReachHowSidecar)) != (o.Yours[i].Link != "") { |
| + t.Errorf("yours %s: CLI how %q, page link %q", h.Host, h.How, o.Yours[i].Link) |
| + } |
| + } |
| + for i, h := range wire.Starting { |
| + if (h.Why == string(appconfig.ReachWhyAsleep)) != o.Starting[i].Asleep() { |
| + t.Errorf("starting %s: CLI why %q, page chip %q", h.Host, h.Why, o.Starting[i].Chip) |
| + } |
| + } |
| + } |
| + t.Run("classified", func(t *testing.T) { |
| + e := envBucketsFx(t) |
| + reach, ok := e.fx.srv.classifyConfigWrite(context.Background(), e.fx.sqid, "shop", "", []string{"LOG_LEVEL"}) |
| + if !ok || len(reach.Self) == 0 || len(reach.Yours) != 2 || len(reach.Unseen) != 1 { |
| + t.Fatalf("classification = %+v %v, want every bucket the fixture builds", reach, ok) |
| + } |
| + compare(t, reach) |
| + }) |
| + t.Run("every bucket", func(t *testing.T) { |
| + compare(t, appconfig.WriteReach{ |
| + Self: []appconfig.ReachHost{{Host: "a.example.com", Shape: appconfig.ReachShapeUnit}}, |
| + Yours: []appconfig.ReachHost{{Host: "b.example.com", How: appconfig.ReachHowAddr}, {Host: "c.example.com", How: appconfig.ReachHowSidecar}}, |
| + Starting: []appconfig.ReachHost{{Host: "d.example.com", Why: appconfig.ReachWhyAsleep}, {Host: "e.example.com", Why: appconfig.ReachWhyNotRunning}}, |
| + Unseen: []string{"f.example.com"}, |
| + }) |
| + }) |
| +} |
| + |
| +// Asleep reports whether the row is an asleep one (TestEnvOutcomeMatchesCLIWire). |
| +func (r envOutcomeRow) Asleep() bool { return r.why == appconfig.ReachWhyAsleep } |
| + |
| +func TestEnvSaveRateLimited(t *testing.T) { |
| + e := newEnvFx(t) |
| + e.saving() |
| + body := e.page(t) |
| + for i := 0; i < cliWriteBurst+3; i++ { |
| + f := envFields(t, body) |
| + f.Set("val.default.LOG_LEVEL", fmt.Sprintf("v%d", i)) |
| + var status int |
| + status, body = e.post(t, f, "save") |
| + if status == http.StatusOK { |
| + continue |
| + } |
| + if status != http.StatusTooManyRequests { |
| + t.Fatalf("save %d = %d:\n%s", i, status, envBanner(body)) |
| + } |
| + if i == 0 { |
| + t.Fatal("the first save was refused") |
| + } |
| + mustContain(t, envBanner(body), "Too many changes at once. Nothing was saved. Try again in a minute.") |
| + mustContain(t, body, fmt.Sprintf(`name="val.default.LOG_LEVEL" value="v%d"`, i)) |
| + if got := e.stored(t).Vars["LOG_LEVEL"].Value; got != fmt.Sprintf("v%d", i-1) { |
| + t.Fatalf("stored LOG_LEVEL = %q after a refused save, want v%d", got, i-1) |
| + } |
| + return |
| + } |
| + t.Fatalf("Save was never rate-limited in %d attempts", cliWriteBurst+3) |
| +} |
diff --git a/internal/console/templates/app_settings.html b/internal/console/templates/app_settings.html| index 0dbc9ce9d..2da9130e2 100644 |
| --- a/internal/console/templates/app_settings.html |
| +++ b/internal/console/templates/app_settings.html |
| @@ -635,6 +635,7 @@ blocks deletion. Turn the safety delay off on the <a href="{{.Nav}}/apps/{{.AppN |
| <h2>Environments</h2> |
| <p class="small">{{$c.Intro}}</p> |
| {{if $s.EnvError}}<p class="banner error" role="alert">{{$s.EnvError}}</p>{{end}} |
| +{{with $s.EnvOutcome}}{{template "app_settings_env_outcome" $}}{{end}} |
| <form method="post" action="{{.Nav}}/apps/{{.Detail.App}}/settings/environments" data-env-form{{with $seal}} data-seal-pub="{{.Pub}}" data-seal-version="{{.Version}}"{{if .Account}} data-account="{{.Account}}" data-app="{{.App}}"{{end}} data-msg-chars="{{$c.MsgChars}}" data-msg-empty="{{$c.MsgEmpty}}" data-msg-seal="{{$c.MsgSeal}}" data-msg-changed="{{$c.MsgChanged}}"{{end}}> |
| <input type="hidden" name="csrf" value="{{.CSRF}}"> |
| {{/* The form's default button: Enter in any field stages (an add row with a name adds). */}} |
| @@ -728,3 +729,62 @@ blocks deletion. Turn the safety delay off on the <a href="{{.Nav}}/apps/{{.AppN |
| </script> |
| {{if $seal}}<script>{{$s.ConfigSealJS}}</script>{{end}} |
| {{end}} |
| + |
| +{{/* "After you save" (envsave.go): where one write lands, from the shared |
| + classifier. Expectations only; observed state is the Running page's, |
| + linked. No restart control anywhere in it: Save requests none. */}} |
| +{{define "app_settings_env_outcome"}}{{$c := .Settings.EnvCopy}}{{$o := .Settings.EnvOutcome}}{{$run := printf "%s/apps/%s/instances" .Nav .Detail.App}} |
| +<section class="env-outcome" role="status" aria-labelledby="env-outcome-head"> |
| +<h3 id="env-outcome-head">{{$c.OutcomeHead}}</h3> |
| +{{if $o.Count}}<p class="banner">{{$c.SavedLine $o}}</p>{{end}} |
| +{{if $o.Unknown}}<p class="small">{{$c.OutcomeUnknown}}</p> |
| +{{else if $o.Empty}}<p class="small">{{$c.OutcomeNone}}</p> |
| +{{else}}<div class="tablewrap"> |
| +<ul class="envvars outcomes"> |
| +{{range $o.Self}} <li><div class="envvar-row"><span class="envvar-name">{{.Host}}</span><span class="envvar-value"><span class="chip chip-health-ok">{{.Chip}}</span></span></div></li> |
| +{{end}}{{range $o.Yours}} <li data-outcome="yours"><div class="envvar-row"><span class="envvar-name">{{.Host}}</span><span class="envvar-value"><span class="chip chip-canary">{{.Chip}}</span></span></div></li> |
| +{{end}}{{range $o.Starting}} <li><div class="envvar-row"><span class="envvar-name">{{.Host}}</span><span class="envvar-value"><span class="chip chip-env">{{.Chip}}</span></span></div></li> |
| +{{end}}{{range $o.Unseen}} <li><div class="envvar-row"><span class="envvar-name">{{.}}</span><span class="envvar-value"><span class="chip chip-health-unknown">{{$c.OutcomeCantSee}}</span></span></div></li> |
| +{{end}}{{range $o.Blocked}} <li><div class="envvar-row"><span class="envvar-name">{{.Host}}</span><span class="envvar-value"><span class="chip chip-health-attention">{{$c.OutcomeBlocked}}</span></span></div></li> |
| +{{end}}{{range $o.Unresolved}} <li><div class="envvar-row"><span class="envvar-name">{{.}}</span><span class="envvar-value"><span class="chip chip-health-unknown">{{$c.OutcomeUnresolved}}</span></span></div></li> |
| +{{end}}{{range $o.Undelivered}} <li><div class="envvar-row"><span class="envvar-name">{{.}}</span><span class="envvar-value"><span class="chip chip-health-notdeployed">{{$c.OutcomeUndeliv}}</span></span></div></li> |
| +{{end}}</ul> |
| +</div> |
| +<ul class="small"> |
| + {{- if $o.Self}} |
| + <li><strong>{{$c.OutcomeSelf}}:</strong> {{$c.OutcomeSelfHelp}}</li>{{end}} |
| + {{- if $o.Yours}} |
| + <li><strong>{{$c.OutcomeYou}}:</strong> {{$c.OutcomeYouHelp}} |
| + <ul>{{range $o.Yours}} |
| + <li data-outcome="yours">{{.Line}}{{if .Link}} <a href="{{$run}}">{{.Link}}</a> {{.After}}{{end}}</li>{{end}} |
| + </ul></li>{{end}} |
| + {{- if $o.Asleep}} |
| + <li><strong>{{$c.OutcomeAsleep}}:</strong> {{$c.OutcomeAsleepHlp}}</li>{{end}} |
| + {{- if $o.NotRunning}} |
| + <li><strong>{{$c.OutcomeNotRunning}}:</strong> {{$c.OutcomeNotRunHlp}}</li>{{end}} |
| + {{- if $o.Unseen}} |
| + <li><strong>{{$c.OutcomeCantSee}}:</strong> {{$c.OutcomeCantHelp}} |
| + <ul>{{range $o.Unseen}} |
| + <li><code>{{$c.CantCmdLine .}}</code></li>{{end}} |
| + </ul></li>{{end}} |
| + {{- if $o.Blocked}} |
| + <li><strong>{{$c.OutcomeBlocked}}:</strong> {{$c.OutcomeBlockedHlp}} |
| + <ul>{{range $o.Blocked}} |
| + <li>{{.Host}}: {{.Reason}}</li>{{end}} |
| + </ul></li>{{end}} |
| + {{- if $o.Unresolved}} |
| + <li><strong>{{$c.OutcomeUnresolved}}:</strong> {{$c.OutcomeUnresHlp}}</li>{{end}} |
| + {{- if $o.Undelivered}} |
| + <li><strong>{{$c.OutcomeUndeliv}}:</strong> {{$c.UndelivLine $.Detail.App}}</li>{{end}} |
| +</ul> |
| +{{end}} |
| +{{if or $o.Unknown $o.Unresolved}}<form method="post" action="{{.Nav}}/apps/{{.Detail.App}}/settings/environments" class="inline"> |
| + <input type="hidden" name="csrf" value="{{.CSRF}}"> |
| + <input type="hidden" name="check_bundle" value="{{$o.CheckBundle}}"> |
| + {{- range $o.CheckKeys}} |
| + <input type="hidden" name="check_key" value="{{.}}">{{end}} |
| + <button type="submit" class="btn-sm btn-secondary" name="op" value="check">{{$c.OutcomeRetry}}</button> |
| +</form>{{end}} |
| +<p class="small">{{$c.OutcomePartial}} <a href="{{$run}}">{{$c.OutcomeSeeRun}}</a></p> |
| +</section> |
| +{{end}} |