console: edit an app's settings and secrets on the settings page
The Environments section becomes one form: a card per bundle, All environments first, ordinary values editable, secrets sealed in the browser. Staged changes round-trip in form fields, one bundle at a time, with a save bar while something is staged. Save and Check land in a stub for Task 8. Secret plaintext reaching the server is refused and dropped.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/console-mockup-kit/shell.html+31 −0docs/console-styleguide.md+63 −0internal/console/appsettings.go+112 −52internal/console/appsettings_env_test.go+15 −19internal/console/configseal.js+4 −2internal/console/envcopy.go+312 −0internal/console/envform.go+603 −0internal/console/envform_test.go+726 −0internal/console/gettingstarted.go+10 −3internal/console/server.go+3 −0internal/console/templates/app_settings.html+93 −9internal/console/templates/console_chrome.html+35 −0
Intent
<task-notification> <task-id>addaddeb7f77aa259</task-id> <tool-use-id>toolu_01Lstd8kdbGWRbcvZK8UBbUT</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/abe35d56-e4c2-40df-9005-6e66b76b1f50/tasks/addaddeb7f77aa259.output</output-file> <status>completed</status> <summary>Agent "Implement Task 4 shared validation" 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>Fixed in commit 066346db: `TestFleetSecretsCopyBuiltIsApplied` now passes. The copy deck in `docs/superpowers/plans` names `apiconfig.go` for FSK-C39..C42, and I can't edit plans. So the test file now maps those four rows to `configwrite.go`, keeps every assertion, and fails if the deck stops naming the old file. `go test . -run TestFleetSecretsCopyBuiltIsApplied -count=1`: ok. I committed only that test file; a note is appended to `task-4-report.md`. If the deck itself should say `configwrite.go`, someone allowed to edit plans needs to change it, and the mapping can then be removed.</result> <usage><subagent_tokens>154359</subagent_tokens><tool_uses>7</tool_uses><duration_ms>64245</duration_ms></usage> </task-notification>
<task-notification> <task-id>bu8gu4cxq</task-id> <tool-use-id>toolu_0199KZ9vg2HxbwNq4dG8tTid</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/abe35d56-e4c2-40df-9005-6e66b76b1f50/tasks/bu8gu4cxq.output</output-file> <status>completed</status> <summary>Background command "until [ -f .superpowers/sdd/2026-11-08-console-secrets/astra-t2t4-r2.done ]; do sleep 30; done; tail -2 .superpowers/sdd/2026-11-08-console-secrets/astra-t2t4-r2-findings.md" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 4.73 g CO₂e (575,623 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/docs/console-mockup-kit/shell.html b/docs/console-mockup-kit/shell.html| index a7dcccc92..cf3432ace 100644 |
| --- a/docs/console-mockup-kit/shell.html |
| +++ b/docs/console-mockup-kit/shell.html |
| @@ -394,6 +394,37 @@ |
| .settings-content :is(.tile, .tablewrap, .rung) { background-color: var(--rst-surface-2); box-shadow: none; } |
| .settings-content > h2:first-child { margin-top: 0; } |
| .danger-head { color: var(--bad); } |
| + |
| + .envvars { list-style: none; margin: 0; padding: 0; } |
| + .envvars > li { border-bottom: 1px solid var(--rule); } |
| + .envvars > li:last-child { border-bottom: 0; } |
| + .envvar > summary, .envvar-row { display: flex; align-items: baseline; gap: 0.75rem; padding: 0.55rem 0.9rem; list-style: none; } |
| + .envvar > summary { cursor: pointer; } |
| + .envvar > summary::-webkit-details-marker { display: none; } |
| + .envvar-name { flex: none; } |
| + .envvar-value { flex: 1; min-width: 0; text-align: right; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.9rem; } |
| + .outcomes .envvar-row { flex-wrap: wrap; justify-content: space-between; row-gap: 0.3rem; } |
| + .outcomes .envvar-value { flex: none; } |
| + .envvar-edit { flex: none; color: var(--accent); font-size: 0.9rem; } |
| + .envvar[open] .envvar-edit { color: var(--muted); } |
| + .envvar-panel { padding: 0 0.9rem 0.6rem; } |
| + .envvar-panel .settings-row { margin: 0; } |
| + .envvar-panel input[type=text], .envvar-panel input[type=password] { flex: 1; min-width: 8rem; } |
| + .envhead { margin: 1.75rem 0 0.15rem; } |
| + .envhead + .small { margin: 0 0 0.6rem; } |
| + .addvar { margin: 0.6rem 0 0.25rem; } |
| + .addvar input[name$=".name"] { flex: 0 1 9rem; min-width: 6rem; } |
| + .addvar input[name$=".value"] { flex: 1 1 8rem; min-width: 6rem; } |
| + .addvar + .small { margin: 0 0 0.5rem; } |
| + |
| + @media (max-width: 40rem) { .addvar input[name$=".name"] { flex-basis: 100%; } } |
| + .savebar { |
| + position: sticky; bottom: 0.75rem; display: flex; flex-wrap: wrap; gap: 0.5rem 0.9rem; align-items: center; |
| + margin: 1.5rem 0 1rem; padding: 0.6rem 0.9rem; background: var(--accent-soft); |
| + border: 1px solid var(--rule); border-radius: var(--rst-radius); |
| + } |
| + .savebar p { margin: 0; flex: 1 1 12rem; } |
| + .savebar .actions { display: flex; gap: 0.9rem; align-items: center; } |
| p { max-width: 40rem; margin: 0 0 1rem; } |
| .lede { font-size: 1.15rem; color: var(--muted); } |
| .small { font-size: 0.9rem; color: var(--muted); } |
diff --git a/docs/console-styleguide.md b/docs/console-styleguide.md| index 653a81997..475b512be 100644 |
| --- a/docs/console-styleguide.md |
| +++ b/docs/console-styleguide.md |
| @@ -297,6 +297,69 @@ is confirmed in place: the reader types the name, presses the red |
| button, then confirms with their passkey (the server checks |
| `confirm=<name>`). It does not go through a confirm card. |
| +### Variable rows and the save bar |
| + |
| +A list of named values edited in place: one compact row per variable, an |
| +Edit that opens the change controls under it, an add row, and a save bar |
| +that appears only while something is staged. The app settings page's |
| +Environments section is built from it. |
| + |
| +```html |
| +<form method="post" action="/a/shop/apps/shop/settings/environments"> |
| + <input type="hidden" name="csrf" value="mockup"> |
| + <h3 class="envhead">All environments</h3> |
| + <p class="small">Used by shop.example.com</p> |
| + <div class="tablewrap"> |
| + <ul class="envvars"> |
| + <li><details class="envvar"><summary><code class="envvar-name">LOG_LEVEL</code><span class="envvar-value">info</span><span class="envvar-edit">Edit</span></summary> |
| + <div class="envvar-panel settings-row"> |
| + <label class="visually-hidden" for="val.default.LOG_LEVEL">New value for LOG_LEVEL</label> |
| + <input type="text" id="val.default.LOG_LEVEL" name="val.default.LOG_LEVEL" value="info" autocomplete="off"> |
| + <button type="submit" class="btn-sm btn-secondary" name="op" value="stage">Change</button> |
| + <button type="submit" class="linkish danger" name="op" value="remove:default.LOG_LEVEL">Remove</button> |
| + </div> |
| + </details></li> |
| + <li><div class="envvar-row"><code class="envvar-name">WEBHOOK_SECRET</code><span class="envvar-value"><span class="chip chip-canary">New secret</span></span><button type="submit" class="linkish" name="op" value="undo:default.WEBHOOK_SECRET">Undo</button></div></li> |
| + </ul> |
| + </div> |
| + <div class="settings-row addvar"> |
| + <label class="visually-hidden" for="add.default.name">Name</label> |
| + <input type="text" id="add.default.name" name="add.default.name" placeholder="NAME" autocomplete="off"> |
| + <label class="visually-hidden" for="add.default.value">Value</label> |
| + <input type="text" id="add.default.value" name="add.default.value" placeholder="Value" autocomplete="off"> |
| + <label class="small"><input type="checkbox" name="add.default.secret" value="1"> Secret</label> |
| + <button type="submit" class="btn-sm btn-secondary" name="op" value="add:default">Add</button> |
| + </div> |
| + <p class="small">Secrets are sealed in your browser. Nobody can read them back, only replace them.</p> |
| + <div class="savebar"> |
| + <p class="small">1 change: new secret WEBHOOK_SECRET in All environments.</p> |
| + <div class="actions"> |
| + <button type="submit" class="linkish" name="op" value="discard">Discard</button> |
| + <button type="submit" class="btn-sm" name="op" value="save">Save</button> |
| + </div> |
| + </div> |
| +</form> |
| +<div class="tablewrap"> |
| +<ul class="envvars outcomes"> |
| + <li><div class="envvar-row"><span class="envvar-name">shop.example.com</span><span class="envvar-value"><span class="chip chip-health-ok">Updates itself</span></span></div></li> |
| +</ul> |
| +</div> |
| +``` |
| + |
| +- `.envhead` is a group's plain heading; the `.small` line after it is its |
| + muted subtitle. No table header. |
| +- A row is a `details.envvar` while it can be edited and a plain |
| + `.envvar-row` once it is staged (a chip says how, and Undo takes it |
| + back). `.envvar-value` is right-aligned and truncates; a secret shows a |
| + quiet `small` "Sealed", never a value. |
| +- `.addvar` is one line on a desktop and wraps to two at 390 px with the |
| + checkbox beside the value. Its inputs are matched by `name` ending in |
| + `.name` and `.value`. |
| +- `.savebar` sticks to the bottom of the screen and is drawn only while |
| + something is staged; Discard is a `linkish` beside the Save button. |
| +- `.outcomes` turns the same rows into a host list with a chip each, for |
| + what happened after a save. |
| + |
| ## Confirm card |
| The interstitial before a consequential change to what is serving |
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go| index 8984a5dbc..b33dfe17d 100644 |
| --- a/internal/console/appsettings.go |
| +++ b/internal/console/appsettings.go |
| @@ -32,6 +32,7 @@ import ( |
| "crypto/subtle" |
| "errors" |
| "fmt" |
| + "html/template" |
| "log" |
| "net/http" |
| "net/url" |
| @@ -113,16 +114,35 @@ type SettingsView struct { |
| // record, so the section remains present and does not claim there is no |
| // store during a transient failure. |
| StoreUnavailable bool |
| - // Envs is one card per named config environment — the bundles themselves, |
| - // which until now had no console surface at all: the ladder shows which |
| - // environment a route is wired to, and nothing showed what the |
| - // environments ARE. Read-only, and variable NAMES only: this page has |
| - // never shown a config value and does not start here. |
| + // Envs is the default bundle's card ("All environments", always first) |
| + // and one card per named config environment: the bundles themselves. |
| + // Editable by any account member (EnvCanEdit, envform.go); ordinary |
| + // values are shown, secrets by name only. |
| Envs []*EnvCard |
| // EnvsUnavailable distinguishes a failed listing from an app that |
| // genuinely has none, so the section does not claim "no environments" |
| // during a transient bucket failure — StoreUnavailable's rule. |
| EnvsUnavailable bool |
| + // EnvCanEdit: the section is a form (any account member, as with the |
| + // CLI doors for a person). False keeps the read-only text. |
| + EnvCanEdit bool |
| + // EnvSeal is what the browser seals secrets with; nil when there is no |
| + // usable key, EnvSealOff saying why ("keyless", "no-key", or |
| + // "unavailable" for a read that failed) and EnvSealFleet naming a |
| + // keyless fleet. |
| + EnvSeal *envSealView |
| + EnvSealOff string |
| + EnvSealFleet string |
| + // EnvDraft is the one bundle's staged changes the form carries (nil or |
| + // empty when none); EnvSummary is the save bar's line for it and |
| + // EnvError a refusal to show above the cards. |
| + EnvDraft *envDraft |
| + EnvSummary string |
| + EnvError string |
| + // EnvCopy is the section's words; ConfigSealJS the sealing script the |
| + // page inlines. |
| + EnvCopy envPageCopy |
| + ConfigSealJS template.JS |
| // StoreEnvs is one card per ENVIRONMENT store (2026-09-19), oldest name |
| // first, empty for the apps that have none — which is all of them until |
| @@ -235,37 +255,55 @@ type StoreCard struct { |
| CanDestroy bool |
| } |
| -// EnvCard is one named config environment as the Settings page sees it. |
| +// EnvCard is one config bundle as the Settings page's Environments section |
| +// sees it: the app's default bundle ("All environments", always first, |
| +// present even when the bundle does not exist yet) or one named |
| +// environment. |
| // |
| -// Variable NAMES only, never values. This page has never shown a config |
| -// value — `carlos env list` is where values live, behind a bearer token — |
| -// and an environment bundle is exactly where a per-tenant origin or a |
| -// delivered credential name sits, so starting here would be the wrong place |
| -// to start. |
| +// Ordinary values are shown (spec "What"); a secret is its name and |
| +// "Sealed", never its envelope, which no page renders. |
| type EnvCard struct { |
| + // Name is the environment's name, "" for the default bundle. |
| Name string |
| - // Vars are the names this bundle SETS, sorted. A named bundle overlays |
| - // the app's default per key, so this is what the environment overrides |
| - // or adds — not the whole set an instance bound to it ends up reading. |
| - Vars []EnvVarName |
| - // Hosts are the instances wired to this bundle. Empty is the case worth |
| - // looking at: a bundle nothing reads, which is where an abandoned store |
| - // hides. |
| - Hosts []string |
| - // HasStore and StoreBucket: whether this environment has an object store |
| - // of its own, and what it is called. An environment store bills whether |
| - // or not any instance reads the bundle, and teardown is explicit, so the |
| - // pairing of "no hosts" with "has a store" is the thing this section |
| - // exists to make visible. |
| + // Bundle is the form's prefix for this card: "default" or Name. |
| + Bundle string |
| + // Title is what the card is called: "All environments" or Name. |
| + Title string |
| + // Version is the bundle's version as read (appconfig.BundleVersion's |
| + // wire form), the one a save writes at. |
| + Version string |
| + // Vars are the variables this bundle sets, sorted, then any staged new |
| + // ones. A named bundle overlays the default per key, so a named card is |
| + // what the environment overrides or adds. |
| + Vars []EnvVarRow |
| + // UsedBy are the instances that read this bundle: routes bound to the |
| + // environment, or for the default card routes bound to none. Empty is |
| + // the case worth looking at: a bundle nothing reads, which is where an |
| + // abandoned store hides. |
| + UsedBy []string |
| + // HasStore and StoreBucket: whether this environment has an object |
| + // store of its own, and what it is called. An environment store bills |
| + // whether or not any instance reads the bundle, and teardown is |
| + // explicit, so the pairing of "no hosts" with "has a store" is the thing |
| + // this section exists to make visible. Always false on the default card |
| + // (the app's own store is under Storage). |
| HasStore bool |
| StoreBucket string |
| + |
| + // stored is the bundle's vars as read, which a staged form is compared |
| + // against. |
| + stored map[string]appconfig.Var |
| } |
| -// EnvVarName is a variable's name and whether it is sealed — enough to see |
| -// the shape of a bundle without seeing into it. |
| -type EnvVarName struct { |
| +// EnvVarRow is one variable on a card. Value is an ordinary setting's value |
| +// (the staged one when it is changed) and always "" for a secret. Staged is |
| +// "", "new", "changed" or "removed". Open draws the row's Edit panel open. |
| +type EnvVarRow struct { |
| Name string |
| Secret bool |
| + Value string |
| + Staged string |
| + Open bool |
| } |
| // MailCard is the Settings tab's view of the app sender, apps/<acct>/<app>/ |
| @@ -396,6 +434,7 @@ func (s *Server) assembleSettings(ctx context.Context, p *page, acct *Account, r |
| } |
| if reads.envs { |
| sv.Envs, sv.EnvsUnavailable = s.envCards(ctx, acct, p.AppName, p.Detail.Routes) |
| + s.envSection(ctx, sv, acct, p.AppName) |
| } |
| if reads.store { |
| sv.Store = s.storeCard(ctx, acct, p.AppName) |
| @@ -512,42 +551,36 @@ func (s *Server) storeCard(ctx context.Context, acct *Account, app string) *Stor |
| return s.storeCardFor(rec, "") |
| } |
| -// envCards is one card per named config environment, sorted by name, with |
| -// the second return saying the listing itself failed — the difference |
| -// between "this app has no environments" and "I could not find out", which |
| -// the section must not collapse. |
| +// envCards is the default bundle's card, then one card per named config |
| +// environment sorted by name, with the second return saying a read failed |
| +// (the default bundle or the listing): the difference between "this app |
| +// has no environments" and "I could not find out", which the section must |
| +// not collapse. Read budget (spec, codex 9): one GetBundle for the default |
| +// bundle, the listing, and one GetBundle per named bundle. |
| // |
| -// A single unreadable bundle is skipped and logged rather than blanking the |
| -// list: the other environments are real, their instances are really bound to |
| -// them, and their stores are really billing. Same trade storeEnvCards makes, |
| -// for the same reason. |
| +// A single unreadable named bundle is skipped and logged rather than |
| +// blanking the list: the other environments are real, their instances are |
| +// really bound to them, and their stores are really billing. Same trade |
| +// storeEnvCards makes, for the same reason. |
| func (s *Server) envCards(ctx context.Context, acct *Account, app string, routes []RouteView) ([]*EnvCard, bool) { |
| + m, ver, err := appconfig.GetBundle(ctx, s.cfg.Releases, acct.Sqid, app, "") |
| + if err != nil { |
| + log.Printf("console: settings default bundle %s/%s: %v", acct.Sqid, app, err) |
| + return nil, true |
| + } |
| + cards := []*EnvCard{envCardOf("", m, ver, routes)} |
| names, err := appconfig.ListEnvironments(ctx, s.cfg.Releases, acct.Sqid, app) |
| if err != nil { |
| log.Printf("console: settings environments %s/%s: %v", acct.Sqid, app, err) |
| - return nil, true |
| + return cards, true |
| } |
| - cards := make([]*EnvCard, 0, len(names)) |
| for _, name := range names { |
| - m, merr := appconfig.LoadEnvironment(ctx, s.cfg.Releases, acct.Sqid, app, name) |
| + m, ver, merr := appconfig.GetBundle(ctx, s.cfg.Releases, acct.Sqid, app, name) |
| if merr != nil { |
| log.Printf("console: settings environment %s/%s/%s: %v", acct.Sqid, app, name, merr) |
| continue |
| } |
| - card := &EnvCard{Name: name} |
| - varNames := make([]string, 0, len(m.Vars)) |
| - for k := range m.Vars { |
| - varNames = append(varNames, k) |
| - } |
| - sort.Strings(varNames) |
| - for _, k := range varNames { |
| - card.Vars = append(card.Vars, EnvVarName{Name: k, Secret: m.Vars[k].Kind == "secret"}) |
| - } |
| - for _, rt := range routes { |
| - if rt.Environment == name { |
| - card.Hosts = append(card.Hosts, rt.Host) |
| - } |
| - } |
| + card := envCardOf(name, m, ver, routes) |
| // The store is read through the same door the storage section uses, |
| // so the two sections cannot disagree about whether one exists. |
| if rec, _, rerr := objstore.GetIn(ctx, s.cfg.Releases, acct.Sqid, app, name); rerr != nil { |
| @@ -566,6 +599,33 @@ func (s *Server) envCards(ctx context.Context, acct *Account, app string, routes |
| return cards, false |
| } |
| +// envCardOf is one bundle's card: name "" is the default bundle. |
| +func envCardOf(name string, m *appconfig.Manifest, ver appconfig.BundleVersion, routes []RouteView) *EnvCard { |
| + card := &EnvCard{Name: name, Bundle: name, Title: name, Version: ver.String(), stored: m.Vars} |
| + if name == "" { |
| + card.Bundle, card.Title = appconfig.DefaultBundle, envCopyDraft.AllTitle |
| + } |
| + keys := make([]string, 0, len(m.Vars)) |
| + for k := range m.Vars { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + for _, k := range keys { |
| + v := m.Vars[k] |
| + row := EnvVarRow{Name: k, Secret: v.Kind == "secret"} |
| + if !row.Secret { |
| + row.Value = v.Value |
| + } |
| + card.Vars = append(card.Vars, row) |
| + } |
| + for _, rt := range routes { |
| + if rt.Environment == name { |
| + card.UsedBy = append(card.UsedBy, rt.Host) |
| + } |
| + } |
| + return card |
| +} |
| + |
| // storeEnvCards is one card per environment store, in the order |
| // StoreEnvironments returns them (sorted). nil on a read failure, matching |
| // storeCard's own discipline: the page says nothing rather than claiming an |
diff --git a/internal/console/appsettings_env_test.go b/internal/console/appsettings_env_test.go| index db234834f..82eb1d91f 100644 |
| --- a/internal/console/appsettings_env_test.go |
| +++ b/internal/console/appsettings_env_test.go |
| @@ -46,30 +46,27 @@ func TestSettingsPageShowsEnvironments(t *testing.T) { |
| t.Fatalf("environments page = %d:\n%s", status, body) |
| } |
| for _, want := range []string{ |
| - "acme", // the bundle |
| - "APP_ORIGIN", // a name it sets |
| - "ACME_API_KEY", // including the sealed one, by name |
| - "carlos-bab-sprout-acme", // the store that belongs to it |
| - "no instances", // nothing is bound to it |
| - "no instance reads it", // ...so the bucket is billing for nobody |
| + "acme", // the bundle |
| + "APP_ORIGIN", // a name it sets |
| + "https://acme.example.com", // and an ordinary setting's value (spec "What") |
| + "ACME_API_KEY", // including the sealed one, by name |
| + "carlos-bab-sprout-acme", // the store that belongs to it |
| + "Nothing uses this yet.", // nothing is bound to it |
| + "no instance reads it", // ...so the bucket is billing for nobody |
| } { |
| if !strings.Contains(body, want) { |
| t.Fatalf("the environments section is missing %q:\n%s", want, body) |
| } |
| } |
| - // NAMES, never values. This page has never shown a config value, and an |
| - // environment bundle is exactly where a per-tenant origin or credential |
| - // sits — so this is the assertion that keeps it that way. |
| - if strings.Contains(body, "https://acme.example.com") { |
| - t.Fatalf("the environments section printed a config VALUE:\n%s", body) |
| - } |
| + // A secret is its name and "Sealed", never its envelope: no page |
| + // renders a stored envelope. |
| if strings.Contains(body, "sealed-envelope-bytes") { |
| t.Fatalf("the environments section printed a sealed envelope:\n%s", body) |
| } |
| } |
| -// An app with no named environments says so, and says how to make one — |
| -// rather than rendering an empty shell that reads like a failure. |
| +// An app with no config at all still gets its All environments card, with |
| +// the add row, so the first setting can be added here. |
| func TestSettingsPageEnvironmentsEmptyState(t *testing.T) { |
| fx := newConsoleFixture(t) |
| freshApp(t, fx, "bare") |
| @@ -79,10 +76,9 @@ func TestSettingsPageEnvironmentsEmptyState(t *testing.T) { |
| if status != http.StatusOK { |
| t.Fatalf("environments page = %d:\n%s", status, body) |
| } |
| - if !strings.Contains(body, "No named environments") { |
| - t.Fatalf("no empty-state line:\n%s", body) |
| - } |
| - if !strings.Contains(body, "carlos env set --app bare") { |
| - t.Fatalf("the empty state does not say how to make one:\n%s", body) |
| + for _, want := range []string{`<h3 class="envhead">All environments</h3>`, `name="add.default.name"`, `name="ver.default" value="absent"`} { |
| + if !strings.Contains(body, want) { |
| + t.Fatalf("empty state missing %q:\n%s", want, body) |
| + } |
| } |
| } |
diff --git a/internal/console/configseal.js b/internal/console/configseal.js| index cc2b53b15..ab246964c 100644 |
| --- a/internal/console/configseal.js |
| +++ b/internal/console/configseal.js |
| @@ -127,11 +127,13 @@ |
| // The plaintext inputs this submit must seal: every enabled |
| // [data-secret-input] still carrying a name, and the value input a |
| - // ticked [data-secret-toggle] points at (data-secret-for=<id>). |
| + // ticked [data-secret-toggle] points at (data-secret-for=<id>). A |
| + // [data-secret-optional] input (an existing secret's Replace field) left |
| + // empty means "keep the secret as it is", not an empty secret. |
| function secretInputs(form) { |
| var out = []; |
| form.querySelectorAll("[data-secret-input]").forEach(function (el) { |
| - if (!el.disabled && el.name) out.push({input: el, required: true}); |
| + if (!el.disabled && el.name) out.push({input: el, required: !el.hasAttribute("data-secret-optional")}); |
| }); |
| form.querySelectorAll("[data-secret-toggle]").forEach(function (box) { |
| var el = box.checked && box.dataset.secretFor && document.getElementById(box.dataset.secretFor); |
diff --git a/internal/console/envcopy.go b/internal/console/envcopy.go| new file mode 100644 |
| index 000000000..3de39a3ca |
| --- /dev/null |
| +++ b/internal/console/envcopy.go |
| @@ -0,0 +1,312 @@ |
| +package console |
| + |
| +import ( |
| + "strconv" |
| + "strings" |
| +) |
| + |
| +// envPageCopy is every string the app settings page's editable Environments |
| +// section shows (console secrets, Task 7), and the save outcome Task 8 |
| +// renders. A draft from the approved mockup until the copy pass: one struct, |
| +// so that pass edits one place, and TestEnvCopyNoDashes keeps the house |
| +// rule. {console} is the console's name (fillConsoleName); {name}, {env}, |
| +// {hosts}, {fleet}, {n} and {changes} are filled where the line is drawn. |
| +type envPageCopy struct { |
| + Intro string |
| + AllTitle string |
| + UsedBy string // {hosts} |
| + UsedByNone string |
| + Sealed string |
| + Edit string |
| + Close string |
| + Remove string |
| + Undo string |
| + NewValueFor string // {name}, a label read aloud, not shown |
| + NewValue string // the Replace placeholder |
| + NameLabel string |
| + ValueLabel string |
| + NamePlace string |
| + ValuePlace string |
| + Secret string |
| + Add string |
| + Stage string // applies an Edit panel's change to the draft |
| + SealingNote string |
| + NeedsScript string |
| + KeylessFlt string // {fleet} |
| + NoKey string |
| + SealOff string // the key could not be read just now |
| + StoreUnread string // a named environment's store nothing reads |
| + StoreNamed string // the same, with its {bucket} |
| + StoreLink string |
| + |
| + // Staged rows' chips. |
| + New string |
| + NewSecret string |
| + Changed string |
| + Removed string |
| + |
| + // The save bar. |
| + Save string |
| + Discard string |
| + SummaryOne string // {change} {env} |
| + SummaryMany string // {n} {env} {changes} |
| + ChangeNew string // {name} |
| + ChangeNewSec string // {name} |
| + ChangeValue string // {name} |
| + ChangeSecret string // {name} |
| + ChangeRemoved string // {name} |
| + |
| + // Refusals while staging. |
| + OneBundle string // {env} |
| + Unsealed string |
| + AddNoName string |
| + AddNameTaken string // {name} {env} |
| + AddEmptySec string |
| + SaveSoon string // save and check are Task 8's |
| + CouldNotRead string |
| + EnvelopeStale string // {name} |
| + |
| + // The browser sealing script's refusals (data-msg-* on the form). |
| + MsgChars string |
| + MsgEmpty string |
| + MsgSeal string |
| + MsgChanged string |
| + |
| + // One line per configRefusalCode, for a person (Task 8 renders them). |
| + RefEnvName string |
| + RefEnvDefault string |
| + RefVarName string // {name} |
| + RefVarValue string // {name} |
| + RefEnvEnvelope string // {name} |
| + RefSecretEnvelope string // {name} |
| + RefSecretPlaintext string // {name} |
| + RefVarKind string // {name} |
| + RefKeylessFleet string // {fleet} |
| + RefSealedWrongKey string // {name} |
| + RefSealedUnchecked string // {name} |
| + RefSealedOld string // {name} |
| + RefNotFound string |
| + RefConflict string |
| + RefNothingToRemove string // {name} |
| + RefStore string |
| + RefSealKey string |
| + |
| + // After you save (Task 8). |
| + OutcomeHead string |
| + SavedOne string // {env} |
| + SavedMany string // {n} {env} |
| + OutcomeSelf string |
| + OutcomeSelfHelp string |
| + OutcomeYou string |
| + OutcomeYouHelp string |
| + OutcomeAsleep string |
| + OutcomeAsleepHlp string |
| + OutcomeCantSee string |
| + OutcomeCantHelp string // {host} |
| + OutcomePartial string |
| + OutcomeSeeRun string |
| +} |
| + |
| +// envCopyDraft is the section's copy before {console} is filled. |
| +var envCopyDraft = envPageCopy{ |
| + Intro: "Settings your app reads when it starts. Anything a named environment doesn't set comes from All environments.", |
| + AllTitle: "All environments", |
| + UsedBy: "Used by {hosts}", |
| + UsedByNone: "Nothing uses this yet.", |
| + Sealed: "Sealed", |
| + Edit: "Edit", |
| + Close: "Close", |
| + Remove: "Remove", |
| + Undo: "Undo", |
| + NewValueFor: "New value for {name}", |
| + NewValue: "New value", |
| + NameLabel: "Name", |
| + ValueLabel: "Value", |
| + NamePlace: "NAME", |
| + ValuePlace: "Value", |
| + Secret: "Secret", |
| + Add: "Add", |
| + Stage: "Change", |
| + SealingNote: "Secrets are sealed in your browser. Nobody can read them back, only replace them.", |
| + NeedsScript: "Setting a secret here needs JavaScript. Your agent or the carlos CLI can set one without it.", |
| + KeylessFlt: "{fleet} has no secrets key yet, so secrets can't be set for this app. Ordinary settings still work.", |
| + NoKey: "{console} has no secrets key set up, so secrets can't be set here. Ordinary settings still work.", |
| + StoreUnread: "This environment has its own object store, but no instance reads it. The bucket still exists and still costs money. Nothing removes a store on its own, so it stays until you destroy it.", |
| + StoreNamed: "This environment has its own object store, {bucket}, but no instance reads it. The bucket still exists and still costs money. Nothing removes a store on its own, so it stays until you destroy it.", |
| + StoreLink: "See it under Storage", |
| + SealOff: "{console} couldn't read this app's secrets key just now, so secrets can't be set. Try again in a moment.", |
| + |
| + New: "New", |
| + NewSecret: "New secret", |
| + Changed: "Changed", |
| + Removed: "Removed", |
| + |
| + Save: "Save", |
| + Discard: "Discard", |
| + SummaryOne: "1 change: {change} in {env}.", |
| + SummaryMany: "{n} changes in {env}: {changes}.", |
| + ChangeNew: "new setting {name}", |
| + ChangeNewSec: "new secret {name}", |
| + ChangeValue: "{name} changed", |
| + ChangeSecret: "new value for secret {name}", |
| + ChangeRemoved: "{name} removed", |
| + |
| + OneBundle: "You can change one environment at a time. Save or discard your changes to {env} first.", |
| + Unsealed: "A secret reached {console} without being sealed in your browser, so it was thrown away. If it was a real credential, treat it as exposed and replace it.", |
| + 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.", |
| + |
| + MsgChars: "A value can't contain a backslash, a quote, a newline or a NUL character.", |
| + MsgEmpty: "A secret can't be empty.", |
| + MsgSeal: "Your browser couldn't seal this value, so nothing was sent.", |
| + MsgChanged: "The form changed while sealing, so nothing was sent. Check it and save again.", |
| + |
| + RefEnvName: "That environment name isn't valid.", |
| + RefEnvDefault: "That environment name isn't valid.", |
| + RefVarName: "{name} isn't a valid name. Use letters, digits and underscores, and start with a letter or underscore.", |
| + RefVarValue: "The value of {name} can't contain a backslash, a quote, a newline or a NUL character.", |
| + RefEnvEnvelope: "{name} is an ordinary setting but arrived sealed. Reload the page and try again.", |
| + RefSecretEnvelope: "The sealed value for {name} couldn't be read. Enter it again.", |
| + RefSecretPlaintext: "{name} reached {console} without being sealed, so it was thrown away. If it was a real credential, treat it as exposed and replace it.", |
| + RefVarKind: "{name} isn't a setting or a secret. Reload the page and try again.", |
| + RefKeylessFleet: "{fleet} has no secrets key yet, so secrets can't be set for this app.", |
| + RefSealedWrongKey: "{name} was sealed to a key this app's boxes don't hold. Reload the page and enter it again.", |
| + RefSealedUnchecked: "{console} couldn't check which key sealed {name}. Reload the page and enter it again.", |
| + RefSealedOld: "{name} was sealed in an older format this app's boxes don't accept. Reload the page and enter it again.", |
| + RefNotFound: "This app or environment isn't here any more.", |
| + RefConflict: "Someone else saved these settings first. Your other changes are still here; enter your secrets again.", |
| + RefNothingToRemove: "{name} is already gone.", |
| + RefStore: "Couldn't save just now. Nothing changed. Try again.", |
| + RefSealKey: "Couldn't read this app's secrets key just now. Nothing changed. Try again.", |
| + |
| + OutcomeHead: "After you save", |
| + SavedOne: "Saved 1 change to {env}.", |
| + SavedMany: "Saved {n} changes to {env}.", |
| + OutcomeSelf: "Updates itself", |
| + OutcomeSelfHelp: "it restarts with the new settings on its own, within a minute.", |
| + OutcomeYou: "Restart it yourself", |
| + OutcomeYouHelp: "{console} delivered the settings but can't restart this one for you.", |
| + 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}.", |
| + OutcomePartial: "Copies on other boxes may not all be listed here.", |
| + OutcomeSeeRun: "See what's running", |
| +} |
| + |
| +// envCopyFor is the section's copy for a console called consoleName. |
| +func envCopyFor(consoleName string) envPageCopy { |
| + c := envCopyDraft |
| + fillConsoleName(&c, consoleName) |
| + return c |
| +} |
| + |
| +// envFill fills one line's placeholders, given as name, value pairs. |
| +func envFill(line string, kv ...string) string { |
| + pairs := make([]string, 0, len(kv)) |
| + for i := 0; i+1 < len(kv); i += 2 { |
| + pairs = append(pairs, "{"+kv[i]+"}", kv[i+1]) |
| + } |
| + return strings.NewReplacer(pairs...).Replace(line) |
| +} |
| + |
| +// UsedByLine is the card's subtitle: the hosts that read the bundle, or |
| +// the line for a bundle nothing reads. |
| +func (c envPageCopy) UsedByLine(hosts []string) string { |
| + if len(hosts) == 0 { |
| + return c.UsedByNone |
| + } |
| + return envFill(c.UsedBy, "hosts", strings.Join(hosts, ", ")) |
| +} |
| + |
| +// NewValueLabel is the hidden label of a variable's Replace field. |
| +func (c envPageCopy) NewValueLabel(name string) string { |
| + return envFill(c.NewValueFor, "name", name) |
| +} |
| + |
| +// StoreUnreadLine is the line under a card whose store nothing reads. |
| +func (c envPageCopy) StoreUnreadLine(bucket string) string { |
| + if bucket == "" { |
| + return c.StoreUnread |
| + } |
| + return envFill(c.StoreNamed, "bucket", bucket) |
| +} |
| + |
| +// KeylessLine is the keyless-fleet explanation for fleet. |
| +func (c envPageCopy) KeylessLine(fleet string) string { |
| + return envFill(c.KeylessFlt, "fleet", fleet) |
| +} |
| + |
| +// summary is the save bar's line for d, in title's words. |
| +func (c envPageCopy) summary(d *envDraft, title string) string { |
| + var changes []string |
| + for _, ch := range d.changes() { |
| + var line string |
| + switch ch.kind { |
| + case envChangeNew: |
| + line = c.ChangeNew |
| + case envChangeNewSecret: |
| + line = c.ChangeNewSec |
| + case envChangeValue: |
| + line = c.ChangeValue |
| + case envChangeSecret: |
| + line = c.ChangeSecret |
| + case envChangeRemoved: |
| + line = c.ChangeRemoved |
| + } |
| + changes = append(changes, envFill(line, "name", ch.name)) |
| + } |
| + if len(changes) == 1 { |
| + return envFill(c.SummaryOne, "change", changes[0], "env", title) |
| + } |
| + return envFill(c.SummaryMany, "n", strconv.Itoa(len(changes)), "env", title, "changes", strings.Join(changes, ", ")) |
| +} |
| + |
| +// staging is a staging refusal's line. |
| +func (c envPageCopy) staging(ref *envFormRefusal) string { |
| + line := map[string]string{ |
| + envRefuseUnsealed: c.Unsealed, |
| + envRefuseOneBundle: c.OneBundle, |
| + envRefuseNoName: c.AddNoName, |
| + envRefuseVarName: c.RefVarName, |
| + envRefuseTaken: c.AddNameTaken, |
| + 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) |
| +} |
| + |
| +// refusal is configRefusalCode's line for a person (Task 8's save), with |
| +// the var and fleet filled. |
| +func (c envPageCopy) refusal(ref *configRefusal, fleet string) string { |
| + line := map[configRefusalCode]string{ |
| + configRefusalEnvName: c.RefEnvName, |
| + configRefusalEnvDefault: c.RefEnvDefault, |
| + configRefusalVarName: c.RefVarName, |
| + configRefusalVarValue: c.RefVarValue, |
| + configRefusalEnvEnvelope: c.RefEnvEnvelope, |
| + configRefusalSecretEnvelope: c.RefSecretEnvelope, |
| + configRefusalSecretPlaintext: c.RefSecretPlaintext, |
| + configRefusalVarKind: c.RefVarKind, |
| + configRefusalKeylessFleet: c.RefKeylessFleet, |
| + configRefusalSealedWrongKey: c.RefSealedWrongKey, |
| + configRefusalSealedUnchecked: c.RefSealedUnchecked, |
| + configRefusalSealedOld: c.RefSealedOld, |
| + configRefusalNotFound: c.RefNotFound, |
| + configRefusalConflict: c.RefConflict, |
| + configRefusalNothingToRemove: c.RefNothingToRemove, |
| + configRefusalStore: c.RefStore, |
| + configRefusalSealKey: c.RefSealKey, |
| + }[ref.Code] |
| + if line == "" { |
| + line = c.RefStore |
| + } |
| + return envFill(line, "name", ref.Var, "fleet", fleet) |
| +} |
diff --git a/internal/console/envform.go b/internal/console/envform.go| new file mode 100644 |
| index 000000000..f87d1ba38 |
| --- /dev/null |
| +++ b/internal/console/envform.go |
| @@ -0,0 +1,603 @@ |
| +// The app settings page's editable Environments section (console secrets, |
| +// Task 7): one form over every bundle card, staged changes carried in its |
| +// own fields (no server-side draft, spec "Left to the builder"), one bundle |
| +// staged at a time because Save is one config write. |
| +// |
| +// Form protocol, POST /a/{sqid}/apps/{app}/settings/environments: |
| +// |
| +// csrf the session token |
| +// bundle the bundle with staged changes, "" when none |
| +// ver.<b> every card's version as the page showed it |
| +// sealed_to the fingerprint of the key the page seals to |
| +// val.<b>.<NAME> an existing ordinary setting's value (prefilled) |
| +// sec.<b>.<NAME> an existing secret's Replace field: plaintext, |
| +// rendered disabled, enabled and stripped by the |
| +// sealing script; never accepted here |
| +// env.<b>.<NAME> the Replace field's envelope |
| +// new.<b>.<NAME> a staged new ordinary setting |
| +// newenv.<b>.<NAME> a staged secret's envelope, new or replacing |
| +// rm.<b> a staged removal (repeated) |
| +// add.<b>.name, .value the add row; .secret ticks it secret, and then |
| +// addenv.<b> carries the sealed value and .value must be gone |
| +// op add:<b> | remove:<b>.<NAME> | undo:<b>.<NAME> | |
| +// discard | stage | save | check |
| +// |
| +// <b> is "default" for the default bundle or the environment's name. |
| +// Anything else posted, and any secret plaintext, is refused with the |
| +// Unsealed copy and thrown away, never echoed. |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/subtle" |
| + "errors" |
| + "log" |
| + "net/http" |
| + "net/url" |
| + "sort" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| +) |
| + |
| +// envSealView is what the page's form tells the sealing script: the key, |
| +// the envelope version ("1" or "2", decided as the config GET decides), the |
| +// binding for v2, and the key's fingerprint for sealed_to. |
| +type envSealView struct { |
| + Pub string |
| + Version string |
| + Account string |
| + App string |
| + SealedTo string |
| +} |
| + |
| +// envSection fills the section's editing half of sv: who may edit, the |
| +// seal key, the copy and the script. |
| +func (s *Server) envSection(ctx context.Context, sv *SettingsView, acct *Account, app string) { |
| + sv.EnvCopy = envCopyFor(s.consoleName()) |
| + sv.ConfigSealJS = configSealJS |
| + // Any account member may edit (spec "Other calls"); accountApp has |
| + // already admitted only members, so a bucket is the one condition. |
| + sv.EnvCanEdit = s.cfg.Releases != nil |
| + sealer, err := s.sealKeyFor(ctx, acct.Sqid, app) |
| + var keyless errFleetNoSecretsKey |
| + switch { |
| + case err == nil: |
| + v := &envSealView{Pub: sealer.PublicKeyB64(), Version: "1", SealedTo: sealer.Fingerprint()} |
| + // handleAPIConfigGet's rule: secrets_account present means v2. |
| + if sealer.Bound() { |
| + v.Version, v.Account, v.App = "2", acct.Sqid, app |
| + } |
| + sv.EnvSeal = v |
| + case errors.As(err, &keyless): |
| + sv.EnvSealOff, sv.EnvSealFleet = "keyless", keyless.Fleet |
| + case errors.Is(err, errNoDeploymentKey), errors.Is(err, errDeploymentKeyUnreadable): |
| + if errors.Is(err, errDeploymentKeyUnreadable) { |
| + log.Printf("console: settings seal key %s/%s: %v", acct.Sqid, app, err) |
| + } |
| + sv.EnvSealOff = "no-key" |
| + default: |
| + log.Printf("console: settings seal key %s/%s: %v", acct.Sqid, app, err) |
| + sv.EnvSealOff = "unavailable" |
| + } |
| +} |
| + |
| +// envDraft is one bundle's staged changes: changed values of existing |
| +// ordinary settings, new ordinary settings, secrets (new or replacing, as |
| +// envelopes) and removals. Version is the bundle's version as the page |
| +// that staged them showed it, which Save writes at. |
| +type envDraft struct { |
| + Bundle string |
| + Version string |
| + Values map[string]string |
| + New map[string]string |
| + Secrets map[string]string |
| + Unset []string |
| + |
| + // The add row to draw again after a refused add: its bundle, name and |
| + // (ordinary only) value. A secret's value is never drawn. |
| + AddBundle, AddName, AddValue string |
| + AddSecret bool |
| + |
| + stored map[string]appconfig.Var |
| +} |
| + |
| +func newEnvDraft(card *EnvCard) *envDraft { |
| + return &envDraft{Bundle: card.Bundle, Version: card.Version, Values: map[string]string{}, |
| + New: map[string]string{}, Secrets: map[string]string{}, stored: card.stored} |
| +} |
| + |
| +// Empty reports whether nothing is staged. |
| +func (d *envDraft) Empty() bool { |
| + return d == nil || len(d.Values)+len(d.New)+len(d.Secrets)+len(d.Unset) == 0 |
| +} |
| + |
| +func (d *envDraft) removing(name string) bool { |
| + for _, n := range d.Unset { |
| + if n == name { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// drop forgets everything staged for name. |
| +func (d *envDraft) drop(name string) { |
| + delete(d.Values, name) |
| + delete(d.New, name) |
| + delete(d.Secrets, name) |
| + out := d.Unset[:0] |
| + for _, n := range d.Unset { |
| + if n != name { |
| + out = append(out, n) |
| + } |
| + } |
| + d.Unset = out |
| +} |
| + |
| +// envName is the bundle's environment name as writeConfig takes it: "" for |
| +// the default bundle. |
| +func (d *envDraft) envName() string { |
| + if d.Bundle == appconfig.DefaultBundle { |
| + return "" |
| + } |
| + return d.Bundle |
| +} |
| + |
| +// writeInput is the draft as writeConfig's sets and unsets (Task 8's save), |
| +// each secret marked sealed to sealedTo. |
| +func (d *envDraft) writeInput(sealedTo string) (map[string]configVarIn, []string) { |
| + in := map[string]configVarIn{} |
| + for k, v := range d.Values { |
| + in[k] = configVarIn{Kind: "env", Value: v} |
| + } |
| + for k, v := range d.New { |
| + in[k] = configVarIn{Kind: "env", Value: v} |
| + } |
| + for k, e := range d.Secrets { |
| + in[k] = configVarIn{Kind: "secret", Envelope: e, SealedTo: sealedTo} |
| + } |
| + return in, append([]string(nil), d.Unset...) |
| +} |
| + |
| +type envChangeKind int |
| + |
| +const ( |
| + envChangeNew envChangeKind = iota |
| + envChangeNewSecret |
| + envChangeValue |
| + envChangeSecret |
| + envChangeRemoved |
| +) |
| + |
| +type envChange struct { |
| + name string |
| + kind envChangeKind |
| +} |
| + |
| +// changes is the draft one change per name, sorted by name. |
| +func (d *envDraft) changes() []envChange { |
| + var out []envChange |
| + for k := range d.Values { |
| + out = append(out, envChange{k, envChangeValue}) |
| + } |
| + for k := range d.New { |
| + out = append(out, envChange{k, envChangeNew}) |
| + } |
| + for k := range d.Secrets { |
| + if _, ok := d.stored[k]; ok { |
| + out = append(out, envChange{k, envChangeSecret}) |
| + } else { |
| + out = append(out, envChange{k, envChangeNewSecret}) |
| + } |
| + } |
| + for _, k := range d.Unset { |
| + out = append(out, envChange{k, envChangeRemoved}) |
| + } |
| + sort.Slice(out, func(i, j int) bool { return out[i].name < out[j].name }) |
| + return out |
| +} |
| + |
| +// envFormRefusal is a staging refusal: what went wrong (the envRefuse* |
| +// codes), the var it is about and the card it names ("" if none). The |
| +// section's copy words it (envPageCopy.staging). |
| +type envFormRefusal struct { |
| + Code string |
| + Var string |
| + Env string |
| +} |
| + |
| +// The staging refusals. |
| +const ( |
| + envRefuseUnsealed = "unsealed" |
| + envRefuseOneBundle = "one-bundle" |
| + envRefuseNoName = "no-name" |
| + envRefuseVarName = "var-name" |
| + envRefuseTaken = "taken" |
| + envRefuseEmptySec = "empty-secret" |
| + envRefuseVarValue = "var-value" |
| + envRefuseEnvelope = "envelope" |
| + envRefuseSaveSoon = "save-soon" |
| + envRefuseUnread = "unread" |
| +) |
| + |
| +// envFormOp is a parsed op button. |
| +type envFormOp struct { |
| + verb string // add, remove, undo, discard, stage, save, check |
| + bundle string |
| + name string |
| +} |
| + |
| +func parseEnvOp(raw string) (envFormOp, bool) { |
| + verb, rest, _ := strings.Cut(raw, ":") |
| + switch verb { |
| + case "discard", "stage", "save", "check": |
| + return envFormOp{verb: verb}, rest == "" |
| + case "add": |
| + return envFormOp{verb: verb, bundle: rest}, rest != "" |
| + case "remove", "undo": |
| + b, n, ok := strings.Cut(rest, ".") |
| + return envFormOp{verb: verb, bundle: b, name: n}, ok && b != "" && n != "" |
| + } |
| + return envFormOp{}, false |
| +} |
| + |
| +// envField splits a posted field name into its kind, bundle and var name. |
| +// 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": |
| + return key, "", "", true |
| + } |
| + kind, rest, found := strings.Cut(key, ".") |
| + if !found || rest == "" { |
| + return "", "", "", false |
| + } |
| + switch kind { |
| + case "ver", "rm", "addenv": |
| + return kind, rest, "", !strings.Contains(rest, ".") |
| + case "val", "sec", "env", "new", "newenv": |
| + b, n, ok := strings.Cut(rest, ".") |
| + return kind, b, n, ok && b != "" && n != "" |
| + case "add": |
| + b, part, ok := strings.Cut(rest, ".") |
| + if !ok || (part != "name" && part != "value" && part != "secret") { |
| + return "", "", "", false |
| + } |
| + return "add." + part, b, "", true |
| + } |
| + return "", "", "", false |
| +} |
| + |
| +// parseEnvForm reads the posted form against the cards as read now and |
| +// returns the draft to draw, with the op applied, and the refusal to show |
| +// with it (nil when there is none). It writes nothing; save and check are |
| +// returned as the draft they would write (the caller acts on the op). |
| +// |
| +// Secret plaintext never survives it: a non-empty sec.* field, an add row |
| +// ticked Secret that still carries its value, or a field the protocol does |
| +// not name, is refused with the Unsealed copy and its value dropped. |
| +func parseEnvForm(r *http.Request, cards []*EnvCard) (*envDraft, *envFormRefusal) { |
| + byBundle := map[string]*EnvCard{} |
| + for _, card := range cards { |
| + byBundle[card.Bundle] = card |
| + } |
| + var ref *envFormRefusal |
| + refuse := func(r *envFormRefusal) { |
| + if ref == nil { |
| + ref = r |
| + } |
| + } |
| + unsealed := false |
| + form := r.PostForm |
| + for key, vs := range form { |
| + kind, _, _, ok := envField(key) |
| + if !ok { |
| + unsealed = true |
| + continue |
| + } |
| + if kind == "sec" { |
| + for _, v := range vs { |
| + if v != "" { |
| + unsealed = true |
| + } |
| + } |
| + } |
| + } |
| + |
| + posted := form.Get("bundle") |
| + op, opOK := parseEnvOp(form.Get("op")) |
| + if !opOK { |
| + op = envFormOp{verb: "stage"} |
| + } |
| + if op.verb == "discard" { |
| + if unsealed { |
| + return nil, &envFormRefusal{Code: envRefuseUnsealed} |
| + } |
| + return nil, nil |
| + } |
| + |
| + // Every bundle's changes as posted. |
| + drafts := map[string]*envDraft{} |
| + draftFor := func(card *EnvCard) *envDraft { |
| + d := drafts[card.Bundle] |
| + if d == nil { |
| + d = newEnvDraft(card) |
| + drafts[card.Bundle] = d |
| + } |
| + return d |
| + } |
| + for _, card := range cards { |
| + b := card.Bundle |
| + d := draftFor(card) |
| + if v, ok := appconfig.ParseBundleVersion(form.Get("ver." + b)); ok { |
| + d.Version = v.String() |
| + } |
| + // A card that changed since the page was drawn, and holds nothing |
| + // staged, shows its fresh values: its posted ones are what the page |
| + // showed, not edits. |
| + fresh := d.Version == card.Version |
| + for name, v := range card.stored { |
| + switch v.Kind { |
| + case "secret": |
| + if e := form.Get("env." + b + "." + name); e != "" { |
| + if appconfig.CheckEnvelope(e) != nil { |
| + refuse(&envFormRefusal{Code: envRefuseEnvelope, Var: name}) |
| + continue |
| + } |
| + d.Secrets[name] = e |
| + } |
| + default: |
| + if vals, ok := form["val."+b+"."+name]; ok && len(vals) == 1 && vals[0] != v.Value && (fresh || b == posted) { |
| + d.Values[name] = vals[0] |
| + } |
| + } |
| + } |
| + for key, vs := range form { |
| + kind, fb, name, _ := envField(key) |
| + if fb != b || len(vs) == 0 { |
| + continue |
| + } |
| + switch kind { |
| + case "new": |
| + if _, exists := card.stored[name]; !exists && appconfig.ValidVarName(name) { |
| + d.New[name] = vs[0] |
| + } |
| + case "newenv": |
| + if !appconfig.ValidVarName(name) { |
| + continue |
| + } |
| + if appconfig.CheckEnvelope(vs[0]) != nil { |
| + refuse(&envFormRefusal{Code: envRefuseEnvelope, Var: name}) |
| + continue |
| + } |
| + delete(d.New, name) |
| + d.Secrets[name] = vs[0] |
| + case "rm": |
| + for _, n := range vs { |
| + if _, exists := card.stored[n]; exists && !d.removing(n) { |
| + d.Unset = append(d.Unset, n) |
| + } |
| + } |
| + } |
| + } |
| + for _, n := range d.Unset { |
| + delete(d.Values, n) |
| + delete(d.Secrets, n) |
| + } |
| + } |
| + |
| + // The op. |
| + switch op.verb { |
| + case "remove", "undo": |
| + if card := byBundle[op.bundle]; card != nil && !unsealed { |
| + d := draftFor(card) |
| + d.drop(op.name) |
| + if _, exists := card.stored[op.name]; exists && op.verb == "remove" { |
| + d.Unset = append(d.Unset, op.name) |
| + sort.Strings(d.Unset) |
| + } |
| + } |
| + case "add", "stage": |
| + b := op.bundle |
| + if op.verb == "stage" { |
| + // Enter in an add row submits the form's default button, the |
| + // hidden stage: a typed name there means add. |
| + for _, card := range cards { |
| + if strings.TrimSpace(form.Get("add."+card.Bundle+".name")) != "" { |
| + b = card.Bundle |
| + break |
| + } |
| + } |
| + } |
| + if card := byBundle[b]; card != nil { |
| + if r := envAdd(form, card, draftFor(card), &unsealed); r != nil { |
| + refuse(r) |
| + } |
| + } |
| + } |
| + |
| + // One bundle at a time: the posted one if it has changes, else the |
| + // first card that does. |
| + var keep *envDraft |
| + var others bool |
| + if d := drafts[posted]; d != nil && !d.Empty() { |
| + keep = d |
| + } |
| + for _, card := range cards { |
| + d := drafts[card.Bundle] |
| + if d.Empty() && d.AddBundle == "" { |
| + continue |
| + } |
| + if keep == nil { |
| + keep = d |
| + } else if d != keep { |
| + others = true |
| + } |
| + } |
| + if unsealed { |
| + ref = &envFormRefusal{Code: envRefuseUnsealed} |
| + } else if others && keep != nil { |
| + ref = &envFormRefusal{Code: envRefuseOneBundle, Env: byBundle[keep.Bundle].Title} |
| + } |
| + return keep, ref |
| +} |
| + |
| +// envAdd stages the add row of card into d, or says why not. A secret row |
| +// must arrive sealed (addenv.<b>) with its value field gone; one that |
| +// still carries the value sets *unsealed and is dropped. |
| +func envAdd(form url.Values, card *EnvCard, d *envDraft, unsealed *bool) *envFormRefusal { |
| + b := card.Bundle |
| + name := strings.TrimSpace(form.Get("add." + b + ".name")) |
| + value, hasValue := form.Get("add."+b+".value"), form.Has("add."+b+".value") |
| + secret := form.Get("add."+b+".secret") != "" |
| + envelope := form.Get("addenv." + b) |
| + if secret && hasValue && value != "" { |
| + *unsealed = true |
| + return nil |
| + } |
| + redraw := func(code string) *envFormRefusal { |
| + d.AddBundle, d.AddName, d.AddSecret = b, name, secret |
| + if !secret { |
| + d.AddValue = value |
| + } |
| + return &envFormRefusal{Code: code, Var: name, Env: card.Title} |
| + } |
| + if name == "" { |
| + if value == "" && envelope == "" { |
| + return nil // an untouched row |
| + } |
| + return redraw(envRefuseNoName) |
| + } |
| + if !appconfig.ValidVarName(name) { |
| + return redraw(envRefuseVarName) |
| + } |
| + _, stored := card.stored[name] |
| + _, staged := d.New[name] |
| + _, stagedSecret := d.Secrets[name] |
| + if (stored && !d.removing(name)) || staged || (stagedSecret && !stored) { |
| + return redraw(envRefuseTaken) |
| + } |
| + d.drop(name) |
| + if secret { |
| + if envelope == "" { |
| + return redraw(envRefuseEmptySec) |
| + } |
| + if appconfig.CheckEnvelope(envelope) != nil { |
| + return redraw(envRefuseEnvelope) |
| + } |
| + d.Secrets[name] = envelope |
| + return nil |
| + } |
| + if appconfig.ValidVarValue(value) != nil { |
| + return redraw(envRefuseVarValue) |
| + } |
| + if v, ok := card.stored[name]; ok && v.Kind != "secret" { |
| + // Removed, then added back: a changed value, or nothing. |
| + if v.Value != value { |
| + d.Values[name] = value |
| + } |
| + return nil |
| + } |
| + d.New[name] = value |
| + return nil |
| +} |
| + |
| +// applyEnvDraft draws d onto its card: staged rows marked, changed values |
| +// shown, new ones appended; and the save bar's line. |
| +func applyEnvDraft(sv *SettingsView, d *envDraft, ref *envFormRefusal) { |
| + sv.EnvDraft = d |
| + if ref != nil { |
| + sv.EnvError = sv.EnvCopy.staging(ref) |
| + } |
| + if d == nil { |
| + return |
| + } |
| + for _, card := range sv.Envs { |
| + if card.Bundle != d.Bundle { |
| + continue |
| + } |
| + card.Version = d.Version |
| + for i := range card.Vars { |
| + row := &card.Vars[i] |
| + switch { |
| + case d.removing(row.Name): |
| + row.Staged = "removed" |
| + case row.Secret && d.Secrets[row.Name] != "": |
| + row.Staged = "changed" |
| + case !row.Secret: |
| + if v, ok := d.Values[row.Name]; ok { |
| + row.Value, row.Staged = v, "changed" |
| + } |
| + } |
| + if ref != nil && ref.Var == row.Name { |
| + row.Open = true |
| + } |
| + } |
| + var added []EnvVarRow |
| + for k, v := range d.New { |
| + added = append(added, EnvVarRow{Name: k, Value: v, Staged: "new"}) |
| + } |
| + for k := range d.Secrets { |
| + if _, ok := d.stored[k]; !ok { |
| + added = append(added, EnvVarRow{Name: k, Secret: true, Staged: "new"}) |
| + } |
| + } |
| + sort.Slice(added, func(i, j int) bool { return added[i].Name < added[j].Name }) |
| + card.Vars = append(card.Vars, added...) |
| + if !d.Empty() { |
| + sv.EnvSummary = sv.EnvCopy.summary(d, card.Title) |
| + } |
| + } |
| +} |
| + |
| +// 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. |
| +func (s *Server) handleEnvForm(w http.ResponseWriter, r *http.Request) { |
| + _, raw, _, _, _, ok := s.accountApp(w, r) |
| + if !ok { |
| + return |
| + } |
| + if subtle.ConstantTimeCompare([]byte(r.PostFormValue("csrf")), []byte(raw)) != 1 { |
| + s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.") |
| + return |
| + } |
| + p, acct, ok := s.appPage(w, r, "settings") |
| + if !ok { |
| + return |
| + } |
| + setAppSettingsSection(&p, "environments") |
| + s.populateAppSettings(r, &p, acct, "environments") |
| + sv := p.Settings |
| + if sv == nil || !sv.EnvCanEdit || sv.EnvsUnavailable { |
| + if sv != nil && sv.EnvCanEdit { |
| + sv.EnvError = sv.EnvCopy.staging(&envFormRefusal{Code: envRefuseUnread}) |
| + } |
| + s.render(w, http.StatusConflict, "app_settings", p) |
| + return |
| + } |
| + d, ref := parseEnvForm(r, sv.Envs) |
| + op, _ := parseEnvOp(r.PostFormValue("op")) |
| + if ref == nil && (op.verb == "save" || op.verb == "check") { |
| + s.envFormSave(w, r, p, d, op.verb) |
| + return |
| + } |
| + applyEnvDraft(sv, d, ref) |
| + status := http.StatusOK |
| + if ref != nil { |
| + status = http.StatusBadRequest |
| + } |
| + 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| new file mode 100644 |
| index 000000000..90e9693ec |
| --- /dev/null |
| +++ b/internal/console/envform_test.go |
| @@ -0,0 +1,726 @@ |
| +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. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "html" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "reflect" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "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. |
| +type envWriteSpy struct { |
| + release.Store |
| + prefix string |
| + mu sync.Mutex |
| + writes []string |
| +} |
| + |
| +func (s *envWriteSpy) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if s.prefix != "" && strings.HasPrefix(key, s.prefix) { |
| + s.mu.Lock() |
| + s.writes = append(s.writes, key) |
| + s.mu.Unlock() |
| + return "", os.ErrPermission |
| + } |
| + return s.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +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) |
| + s.mu.Unlock() |
| + return os.ErrPermission |
| + } |
| + return s.Store.Delete(ctx, key) |
| +} |
| + |
| +func (s *envWriteSpy) none(t *testing.T) { |
| + t.Helper() |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if len(s.writes) > 0 { |
| + t.Fatalf("the staging form wrote %v", s.writes) |
| + } |
| +} |
| + |
| +// envFx is a console with a deployment secrets key, the app shop with |
| +// LOG_LEVEL=info and a sealed STRIPE_KEY in its default bundle, writes |
| +// under shop refused, and paul signed in. |
| +type envFx struct { |
| + fx *consoleFixture |
| + c *http.Client |
| + priv string |
| + pub string |
| + spy *envWriteSpy |
| + envelope string // a valid envelope sealed to pub for bab/shop |
| +} |
| + |
| +func newEnvFx(t *testing.T) *envFx { |
| + t.Helper() |
| + spy := &envWriteSpy{} |
| + fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, WrapReleases: func(s release.Store) release.Store { |
| + spy.Store = s |
| + return spy |
| + }}) |
| + priv, pub, err := appconfig.GenerateKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.srv.cfg.SecretsPub = pub |
| + if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + if err := appconfig.SetEnv(ctx, fx.rel, fx.sqid, "shop", map[string]string{"LOG_LEVEL": "info"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e := &envFx{fx: fx, priv: priv, pub: pub, spy: spy} |
| + e.envelope = e.seal(t, "stored-secret") |
| + if err := appconfig.SetSecret(ctx, fx.rel, fx.sqid, "shop", map[string]appconfig.Var{ |
| + "STRIPE_KEY": {Kind: "secret", Envelope: e.envelope}, |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + spy.prefix = release.AppPrefix(fx.sqid, "shop") |
| + e.c = signInPaul(t, fx) |
| + return e |
| +} |
| + |
| +func (e *envFx) seal(t *testing.T, plaintext string) string { |
| + t.Helper() |
| + pub, err := appconfig.ParsePublicKey(e.pub, "test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + env, err := appconfig.SealUnbound(pub, []byte(plaintext)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return env |
| +} |
| + |
| +func (e *envFx) page(t *testing.T) string { |
| + t.Helper() |
| + status, _, body := get(t, e.c, e.fx.u("/apps/shop/settings/environments")) |
| + if status != http.StatusOK { |
| + t.Fatalf("environments page = %d:\n%s", status, body) |
| + } |
| + return body |
| +} |
| + |
| +// post sends fields with op to the form and returns the answer. |
| +func (e *envFx) post(t *testing.T, fields url.Values, op string) (int, string) { |
| + t.Helper() |
| + f := url.Values{} |
| + for k, v := range fields { |
| + f[k] = append([]string(nil), v...) |
| + } |
| + f.Set("op", op) |
| + status, _, body := postForm(t, e.c, e.fx.u("/apps/shop/settings/environments"), f) |
| + return status, body |
| +} |
| + |
| +var ( |
| + envFormRe = regexp.MustCompile(`(?s)<form method="post" action="[^"]*/settings/environments".*?</form>`) |
| + envInputRe = regexp.MustCompile(`<input\b[^>]*>`) |
| + envAttrRe = regexp.MustCompile(`([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:="([^"]*)")?`) |
| +) |
| + |
| +// envSection is the section's form markup. |
| +func envSection(t *testing.T, body string) string { |
| + t.Helper() |
| + m := envFormRe.FindString(body) |
| + if m == "" { |
| + t.Fatalf("no environments form:\n%s", body) |
| + } |
| + return m |
| +} |
| + |
| +func envAttrs(tag string) map[string]string { |
| + out := map[string]string{} |
| + for _, m := range envAttrRe.FindAllStringSubmatch(strings.TrimSuffix(strings.TrimPrefix(tag, "<input"), ">"), -1) { |
| + out[m[1]] = html.UnescapeString(m[2]) |
| + } |
| + return out |
| +} |
| + |
| +// envFields is what a browser would post from the section's form: every |
| +// named, enabled input, checkboxes only when checked. Buttons are left to |
| +// post's op. |
| +func envFields(t *testing.T, body string) url.Values { |
| + t.Helper() |
| + out := url.Values{} |
| + for _, tag := range envInputRe.FindAllString(envSection(t, body), -1) { |
| + a := envAttrs(tag) |
| + _, disabled := a["disabled"] |
| + _, checked := a["checked"] |
| + if a["name"] == "" || disabled || (a["type"] == "checkbox" && !checked) { |
| + continue |
| + } |
| + out.Add(a["name"], a["value"]) |
| + } |
| + return out |
| +} |
| + |
| +func mustContain(t *testing.T, body string, want ...string) { |
| + t.Helper() |
| + for _, w := range want { |
| + if !strings.Contains(body, w) { |
| + t.Fatalf("missing %q in:\n%s", w, body) |
| + } |
| + } |
| +} |
| + |
| +func mustNotContain(t *testing.T, body string, bad ...string) { |
| + t.Helper() |
| + for _, b := range bad { |
| + if strings.Contains(body, b) { |
| + t.Fatalf("unexpected %q in:\n%s", b, body) |
| + } |
| + } |
| +} |
| + |
| +func TestEnvSectionDefaultFirst(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + freshApp(t, fx, "sprout") |
| + ctx := context.Background() |
| + // A named bundle and no default one: the default card is still drawn, |
| + // and first. |
| + if _, err := appconfig.ApplyEnvironment(ctx, fx.rel, release.OpsAccount, "sprout", "acme", |
| + map[string]appconfig.Var{"APP_ORIGIN": {Kind: "env", Value: "https://acme.example.com"}}, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + c := signInPaul(t, fx) |
| + check := func(wantDefaultVar bool) { |
| + t.Helper() |
| + _, _, body := get(t, c, fx.u("/apps/sprout/settings/environments")) |
| + form := envSection(t, body) |
| + heads := regexp.MustCompile(`<h3 class="envhead">([^<]*)</h3>`).FindAllStringSubmatch(form, -1) |
| + if len(heads) != 2 || heads[0][1] != "All environments" || heads[1][1] != "acme" { |
| + t.Fatalf("cards = %v, want All environments then acme", heads) |
| + } |
| + if got := strings.Contains(form, `name="val.default.PORT"`); got != wantDefaultVar { |
| + t.Fatalf("default card shows PORT = %v, want %v", got, wantDefaultVar) |
| + } |
| + if !wantDefaultVar { |
| + mustContain(t, form, `name="ver.default" value="absent"`) |
| + } |
| + } |
| + check(false) |
| + if err := appconfig.SetEnv(ctx, fx.rel, fx.sqid, "sprout", map[string]string{"PORT": "8080"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + check(true) |
| +} |
| + |
| +// A console without a deployment bucket cannot assemble an app page at |
| +// all, so the section's no-bucket branch is drawn straight from the |
| +// template, as assembleSettings leaves the view: NoBucket and no editing. |
| +// The POST door says 409 for the same console shape (handleEnvForm). |
| +func TestEnvSectionReadOnlyForNoBucket(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + p := page{Nav: "/a/shop", SettingsSection: "environments", Detail: &AppView{App: "sprout"}, Account: &Account{Name: "shop", Sqid: "bab"}, AppName: "sprout", |
| + Settings: &SettingsView{NoBucket: true}} |
| + rec := httptest.NewRecorder() |
| + fx.srv.render(rec, http.StatusOK, "app_settings", p) |
| + body := rec.Body.String() |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("render = %d:\n%s", rec.Code, body) |
| + } |
| + mustContain(t, body, "no deployment bucket on this host", "No named environments", "carlos env set --app sprout") |
| + mustNotContain(t, body, `/settings/environments"`, "data-secret-input", `class="savebar"`) |
| +} |
| + |
| +func TestEnvFormCSRF(t *testing.T) { |
| + e := newEnvFx(t) |
| + f := envFields(t, e.page(t)) |
| + f.Set("csrf", "not-the-token") |
| + f.Set("add.default.name", "MODE") |
| + f.Set("add.default.value", "fast") |
| + status, body := e.post(t, f, "add:default") |
| + if status != http.StatusForbidden { |
| + t.Fatalf("bad CSRF = %d, want 403", status) |
| + } |
| + mustNotContain(t, body, "MODE", "fast", `class="savebar"`) |
| + e.spy.none(t) |
| +} |
| + |
| +func TestEnvFormNonMember404(t *testing.T) { |
| + e := newEnvFx(t) |
| + e.fx.setUser("bob@keymail.dev") |
| + bob := newBrowser(t) |
| + signUp(t, e.fx, bob, "code-env-bob") |
| + form := url.Values{"csrf": {sessionToken(t, e.fx, bob)}, "op": {"add:default"}, "add.default.name": {"X"}, "add.default.value": {"1"}} |
| + s1, _, real := postForm(t, bob, e.fx.u("/apps/shop/settings/environments"), form) |
| + s2, _, ghost := postForm(t, bob, e.fx.u("/apps/no-such-app/settings/environments"), form) |
| + if s1 != http.StatusNotFound || s1 != s2 || real != ghost { |
| + t.Fatalf("non-member: real app %d %q, unknown app %d %q; want identical 404s", s1, real, s2, ghost) |
| + } |
| + e.spy.none(t) |
| +} |
| + |
| +func TestEnvFormStageAddRemoveUndoDiscard(t *testing.T) { |
| + e := newEnvFx(t) |
| + body := e.page(t) |
| + mustNotContain(t, body, `class="savebar"`) |
| + mustContain(t, body, `<span class="envvar-value">info</span>`, `<span class="envvar-value small">Sealed</span>`) |
| + |
| + // Add an ordinary setting. |
| + f := envFields(t, body) |
| + f.Set("add.default.name", "MODE") |
| + f.Set("add.default.value", "fast") |
| + status, body := e.post(t, f, "add:default") |
| + if status != http.StatusOK { |
| + t.Fatalf("add = %d:\n%s", status, body) |
| + } |
| + mustContain(t, body, `class="savebar"`, "1 change: new setting MODE in All environments.", |
| + `name="new.default.MODE" value="fast"`, `name="bundle" value="default"`) |
| + |
| + // Add a secret, as the sealing script posts it: the box ticked, the |
| + // envelope, and no value field. |
| + f = envFields(t, body) |
| + added := e.seal(t, "whsec-plaintext") |
| + f.Set("add.default.name", "WEBHOOK_SECRET") |
| + f.Set("add.default.secret", "1") |
| + f.Del("add.default.value") |
| + f.Set("addenv.default", added) |
| + status, body = e.post(t, f, "add:default") |
| + if status != http.StatusOK { |
| + t.Fatalf("add secret = %d:\n%s", status, body) |
| + } |
| + mustContain(t, body, "2 changes in All environments: new setting MODE, new secret WEBHOOK_SECRET.", ">New secret<") |
| + if got := envFields(t, body).Get("newenv.default.WEBHOOK_SECRET"); got != added { |
| + t.Fatalf("carried envelope = %q, want the posted one", got) |
| + } |
| + |
| + // Remove an existing setting, then take it back. |
| + status, body = e.post(t, envFields(t, body), "remove:default.LOG_LEVEL") |
| + if status != http.StatusOK { |
| + t.Fatalf("remove = %d:\n%s", status, body) |
| + } |
| + mustContain(t, body, `name="rm.default" value="LOG_LEVEL"`, ">Removed<", "LOG_LEVEL removed") |
| + status, body = e.post(t, envFields(t, body), "undo:default.LOG_LEVEL") |
| + if status != http.StatusOK { |
| + t.Fatalf("undo = %d", status) |
| + } |
| + mustNotContain(t, body, `name="rm.default"`, "LOG_LEVEL removed") |
| + mustContain(t, body, "2 changes") |
| + |
| + // Undo the new setting: one change left. |
| + status, body = e.post(t, envFields(t, body), "undo:default.MODE") |
| + if status != http.StatusOK { |
| + t.Fatalf("undo new = %d", status) |
| + } |
| + mustContain(t, body, "1 change: new secret WEBHOOK_SECRET in All environments.") |
| + mustNotContain(t, body, `name="new.default.MODE"`) |
| + |
| + // Replace the stored secret and change a value through the Edit panels |
| + // (the hidden default button, Enter). |
| + f = envFields(t, body) |
| + replaced := e.seal(t, "new-stripe") |
| + f.Set("env.default.STRIPE_KEY", replaced) |
| + f.Set("val.default.LOG_LEVEL", "debug") |
| + status, body = e.post(t, f, "stage") |
| + if status != http.StatusOK { |
| + t.Fatalf("stage = %d:\n%s", status, body) |
| + } |
| + mustContain(t, body, "3 changes in All environments: LOG_LEVEL changed, new value for secret STRIPE_KEY, new secret WEBHOOK_SECRET.", |
| + `name="val.default.LOG_LEVEL" value="debug"`) |
| + if got := envFields(t, body).Get("newenv.default.STRIPE_KEY"); got != replaced { |
| + t.Fatalf("carried replacement = %q, want the posted one", got) |
| + } |
| + |
| + // Undo the value change: the field goes back to the stored value. |
| + status, body = e.post(t, envFields(t, body), "undo:default.LOG_LEVEL") |
| + if status != http.StatusOK { |
| + t.Fatalf("undo value = %d", status) |
| + } |
| + mustContain(t, body, `name="val.default.LOG_LEVEL" value="info"`, "2 changes") |
| + |
| + // Discard: nothing staged, no bar. |
| + status, body = e.post(t, envFields(t, body), "discard") |
| + if status != http.StatusOK { |
| + t.Fatalf("discard = %d", status) |
| + } |
| + mustNotContain(t, body, `class="savebar"`, "newenv.", `name="new.`, `name="bundle" value="default"`) |
| + |
| + // 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.") |
| + |
| + 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 { |
| + t.Fatalf("stored bundle moved: %+v %v", m, err) |
| + } |
| +} |
| + |
| +func TestEnvFormOneBundleAtATime(t *testing.T) { |
| + e := newEnvFx(t) |
| + 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) |
| + } |
| + f := envFields(t, e.page(t)) |
| + f.Set("add.default.name", "MODE") |
| + f.Set("add.default.value", "fast") |
| + status, body := e.post(t, f, "add:default") |
| + if status != http.StatusOK { |
| + t.Fatalf("add = %d", status) |
| + } |
| + |
| + // Staging into staging while All environments has changes is refused, |
| + // and the default card's draft is kept as it was. |
| + f = envFields(t, body) |
| + f.Set("add.staging.name", "OTHER") |
| + f.Set("add.staging.value", "x") |
| + status, body = e.post(t, f, "add:staging") |
| + if status != http.StatusBadRequest { |
| + t.Fatalf("second bundle = %d, want 400", status) |
| + } |
| + mustContain(t, body, "You can change one environment at a time. Save or discard your changes to All environments first.", |
| + `name="new.default.MODE" value="fast"`, `name="bundle" value="default"`) |
| + mustNotContain(t, body, `name="new.staging.OTHER"`) |
| + |
| + // So is an edit in another card's panel. |
| + f = envFields(t, body) |
| + f.Set("val.staging.LOG_LEVEL", "warn") |
| + status, body = e.post(t, f, "stage") |
| + if status != http.StatusBadRequest { |
| + t.Fatalf("edit in a second bundle = %d, want 400", status) |
| + } |
| + mustContain(t, body, `name="val.staging.LOG_LEVEL" value="debug"`, `name="new.default.MODE"`) |
| + |
| + // Discarding frees the page for the other card. |
| + _, body = e.post(t, envFields(t, body), "discard") |
| + f = envFields(t, body) |
| + f.Set("add.staging.name", "OTHER") |
| + f.Set("add.staging.value", "x") |
| + status, body = e.post(t, f, "add:staging") |
| + if status != http.StatusOK { |
| + t.Fatalf("add to staging = %d:\n%s", status, body) |
| + } |
| + mustContain(t, body, "1 change: new setting OTHER in staging.", `name="bundle" value="staging"`) |
| + e.spy.none(t) |
| +} |
| + |
| +func TestEnvFormRefusesSecretPlaintext(t *testing.T) { |
| + const plain = "pl41ntext-s3cret" |
| + e := newEnvFx(t) |
| + base := envFields(t, e.page(t)) |
| + for _, c := range []struct { |
| + name string |
| + edit func(url.Values) |
| + op string |
| + }{ |
| + {"replace field", func(f url.Values) { f.Set("sec.default.STRIPE_KEY", plain) }, "stage"}, |
| + {"secret add with its value", func(f url.Values) { |
| + f.Set("add.default.name", "API_TOKEN") |
| + f.Set("add.default.secret", "1") |
| + f.Set("add.default.value", plain) |
| + }, "add:default"}, |
| + {"secret add with value and envelope", func(f url.Values) { |
| + f.Set("add.default.name", "API_TOKEN") |
| + f.Set("add.default.secret", "1") |
| + f.Set("add.default.value", plain) |
| + f.Set("addenv.default", e.seal(t, plain)) |
| + }, "add:default"}, |
| + {"a field the form doesn't have", func(f url.Values) { f.Set("secret.default.API_TOKEN", plain) }, "stage"}, |
| + {"an odd field on discard", func(f url.Values) { f.Set("value", plain) }, "discard"}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + f := url.Values{} |
| + for k, v := range base { |
| + f[k] = append([]string(nil), v...) |
| + } |
| + c.edit(f) |
| + status, body := e.post(t, f, c.op) |
| + if status != http.StatusBadRequest { |
| + t.Fatalf("status = %d, want 400", status) |
| + } |
| + mustContain(t, body, "without being sealed in your browser, so it was thrown away") |
| + mustNotContain(t, body, plain, "API_TOKEN", `class="savebar"`) |
| + }) |
| + } |
| + e.spy.none(t) |
| +} |
| + |
| +func TestEnvSecretControlsDisabledWithoutScript(t *testing.T) { |
| + e := newEnvFx(t) |
| + form := envSection(t, e.page(t)) |
| + controls := 0 |
| + for _, tag := range regexp.MustCompile(`<input\b[^>]*data-secret-(?:input|toggle)[^>]*>`).FindAllString(form, -1) { |
| + controls++ |
| + a := envAttrs(tag) |
| + if _, ok := a["disabled"]; !ok { |
| + t.Errorf("secret control not disabled: %s", tag) |
| + } |
| + if _, ok := a["data-secret-input"]; ok { |
| + if _, has := a["value"]; has { |
| + t.Errorf("secret input carries a value: %s", tag) |
| + } |
| + } |
| + } |
| + if controls != 2 { // STRIPE_KEY's Replace, the add row's Secret box |
| + t.Fatalf("found %d secret controls, want 2:\n%s", controls, form) |
| + } |
| + mustContain(t, form, "<noscript>", "Setting a secret here needs JavaScript.") |
| + mustNotContain(t, form, e.envelope) |
| +} |
| + |
| +func TestEnvSealAttributes(t *testing.T) { |
| + formTag := func(t *testing.T, body string) map[string]string { |
| + t.Helper() |
| + tag := regexp.MustCompile(`<form method="post" action="[^"]*/settings/environments"[^>]*>`).FindString(body) |
| + if tag == "" { |
| + t.Fatalf("no form:\n%s", body) |
| + } |
| + return envAttrs(strings.Replace(tag, "<form", "<input", 1)) |
| + } |
| + sealedTo := func(t *testing.T, body string) string { |
| + t.Helper() |
| + return envFields(t, body).Get("sealed_to") |
| + } |
| + |
| + t.Run("platform app v1", func(t *testing.T) { |
| + appconfig.SetBoundSealing(false) |
| + e := newEnvFx(t) |
| + body := e.page(t) |
| + a := formTag(t, body) |
| + fp, _ := appconfig.PublicFingerprint(e.pub) |
| + if a["data-seal-pub"] != e.pub || a["data-seal-version"] != "1" || sealedTo(t, body) != fp { |
| + t.Fatalf("form = %v sealed_to %q, want v1 to the deployment key %s", a, sealedTo(t, body), fp) |
| + } |
| + if _, ok := a["data-account"]; ok { |
| + t.Fatalf("v1 form carries data-account: %v", a) |
| + } |
| + if a["data-msg-chars"] != envCopyDraft.MsgChars || a["data-msg-changed"] != envCopyDraft.MsgChanged { |
| + t.Fatalf("the script's refusals are not the copy's: %v", a) |
| + } |
| + }) |
| + t.Run("platform app v2", func(t *testing.T) { |
| + appconfig.SetBoundSealing(true) |
| + t.Cleanup(func() { appconfig.SetBoundSealing(false) }) |
| + e := newEnvFx(t) |
| + a := formTag(t, e.page(t)) |
| + if a["data-seal-version"] != "2" || a["data-account"] != e.fx.sqid || a["data-app"] != "shop" { |
| + t.Fatalf("form = %v, want v2 bound to %s/shop", a, e.fx.sqid) |
| + } |
| + }) |
| + t.Run("fleet app", func(t *testing.T) { |
| + appconfig.SetBoundSealing(false) |
| + fx, _, k := skFleetShop(t, "code-env-fleet", true) |
| + c := signInPaul(t, fx) |
| + _, _, body := get(t, c, fx.u("/apps/shop/settings/environments")) |
| + a := formTag(t, body) |
| + if a["data-seal-pub"] != k.pub || a["data-seal-version"] != "2" || a["data-account"] != fx.sqid || a["data-app"] != "shop" || sealedTo(t, body) != k.fp { |
| + t.Fatalf("form = %v sealed_to %q, want v2 to home's key %s", a, sealedTo(t, body), k.fp) |
| + } |
| + }) |
| + t.Run("keyless fleet", func(t *testing.T) { |
| + fx, _, _ := skFleetShop(t, "code-env-keyless", false) |
| + c := signInPaul(t, fx) |
| + _, _, body := get(t, c, fx.u("/apps/shop/settings/environments")) |
| + a := formTag(t, body) |
| + if _, ok := a["data-seal-pub"]; ok { |
| + t.Fatalf("keyless fleet form carries a key: %v", a) |
| + } |
| + form := envSection(t, body) |
| + mustContain(t, form, "home has no secrets key yet, so secrets can't be set for this app.", |
| + `<input type="checkbox" id="add.default.secret" name="add.default.secret" value="1" disabled>`) |
| + mustNotContain(t, form, "data-secret-", `name="sealed_to"`) |
| + mustNotContain(t, body, "carlosConfigSeal") |
| + }) |
| + t.Run("no deployment key", func(t *testing.T) { |
| + e := newEnvFx(t) |
| + e.fx.srv.cfg.SecretsPub = "" |
| + form := envSection(t, e.page(t)) |
| + mustContain(t, form, "has no secrets key set up, so secrets can't be set here.") |
| + mustNotContain(t, form, "data-secret-", "data-seal-pub") |
| + }) |
| +} |
| + |
| +func TestEnvCopyNoDashes(t *testing.T) { |
| + rv := reflect.ValueOf(envCopyFor("Example Cloud")) |
| + for i := 0; i < rv.NumField(); i++ { |
| + f, name := rv.Field(i).String(), rv.Type().Field(i).Name |
| + if f == "" { |
| + t.Errorf("%s is empty", name) |
| + } |
| + if strings.ContainsAny(f, "\u2014\u2013") { |
| + t.Errorf("%s has an em or en dash: %q", name, f) |
| + } |
| + if strings.Contains(f, "{console}") { |
| + t.Errorf("%s still has {console}: %q", name, f) |
| + } |
| + } |
| + // Every config refusal has a line of its own. |
| + c := envCopyFor("Example Cloud") |
| + for _, code := range []configRefusalCode{ |
| + configRefusalEnvName, configRefusalEnvDefault, configRefusalVarName, configRefusalVarValue, |
| + configRefusalEnvEnvelope, configRefusalSecretEnvelope, configRefusalSecretPlaintext, configRefusalVarKind, |
| + configRefusalKeylessFleet, configRefusalSealedWrongKey, configRefusalSealedUnchecked, configRefusalSealedOld, |
| + configRefusalNotFound, configRefusalConflict, configRefusalNothingToRemove, configRefusalStore, configRefusalSealKey, |
| + } { |
| + line := c.refusal(&configRefusal{Code: code, Var: "API_KEY"}, "home") |
| + if line == "" || strings.Contains(line, "{") { |
| + t.Errorf("%s: %q", code, line) |
| + } |
| + if code != configRefusalStore && line == c.RefStore { |
| + t.Errorf("%s has no line of its own", code) |
| + } |
| + } |
| +} |
| + |
| +// writeInput is the draft as Task 8's save hands it to writeConfig. |
| +func TestEnvDraftWriteInput(t *testing.T) { |
| + d := &envDraft{Bundle: "default", Values: map[string]string{"A": "1"}, New: map[string]string{"B": "2"}, |
| + Secrets: map[string]string{"C": "env"}, Unset: []string{"D"}} |
| + in, unset := d.writeInput("fp") |
| + want := map[string]configVarIn{"A": {Kind: "env", Value: "1"}, "B": {Kind: "env", Value: "2"}, "C": {Kind: "secret", Envelope: "env", SealedTo: "fp"}} |
| + if !reflect.DeepEqual(in, want) || !reflect.DeepEqual(unset, []string{"D"}) || d.envName() != "" { |
| + t.Fatalf("writeInput = %v %v %q", in, unset, d.envName()) |
| + } |
| +} |
| + |
| +// TestEnvFormChromium renders the section from a fixture console and drives |
| +// 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. |
| +func TestEnvFormChromium(t *testing.T) { |
| + chromium, err := exec.LookPath("chromium") |
| + if err != nil { |
| + t.Skip("no installed headless browser") |
| + } |
| + node := nodeOrSkip(t) |
| + appconfig.SetBoundSealing(true) |
| + t.Cleanup(func() { appconfig.SetBoundSealing(false) }) |
| + e := newEnvFx(t) |
| + 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) |
| + } |
| + page := e.page(t) |
| + action := html.UnescapeString(regexp.MustCompile(`<form method="post" action="([^"]*/settings/environments)"`).FindStringSubmatch(page)[1]) |
| + |
| + var mu sync.Mutex |
| + var posts []url.Values |
| + mux := http.NewServeMux() |
| + mux.HandleFunc("GET /page", func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| + _, _ = w.Write([]byte(page)) |
| + }) |
| + mux.HandleFunc("POST "+action, func(w http.ResponseWriter, r *http.Request) { |
| + if err := r.ParseForm(); err != nil { |
| + t.Error(err) |
| + } |
| + mu.Lock() |
| + posts = append(posts, r.PostForm) |
| + mu.Unlock() |
| + http.Redirect(w, r, "/posted", http.StatusSeeOther) |
| + }) |
| + mux.HandleFunc("GET /posted", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("posted")) }) |
| + ts := httptest.NewServer(mux) // 127.0.0.1 |
| + defer ts.Close() |
| + |
| + const secret, replaced = "whsec_0123456789abcdef", "sk_live_replaced" |
| + type scene struct { |
| + URL string `json:"url"` |
| + Fill map[string]string `json:"fill"` |
| + Tick []string `json:"tick"` |
| + Click string `json:"click"` |
| + } |
| + scenes := []scene{ |
| + {ts.URL + "/page", map[string]string{"add.default.name": "WEBHOOK_SECRET", "add.default.value": secret}, []string{"add.default.secret"}, "add:default"}, |
| + {ts.URL + "/page", map[string]string{"sec.default.STRIPE_KEY": replaced}, nil, "stage"}, |
| + } |
| + payload, _ := json.Marshal(scenes) |
| + ctx, cancel := context.WithTimeout(t.Context(), 90*time.Second) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, node, "testdata/configseal_browser.mjs", chromium, t.TempDir(), string(payload)) |
| + if out, err := cmd.CombinedOutput(); err != nil { |
| + t.Fatalf("browser: %v\n%s", err, out) |
| + } |
| + |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if len(posts) != 2 { |
| + t.Fatalf("%d posts, want 2: %v", len(posts), posts) |
| + } |
| + for i, f := range posts { |
| + for k, vs := range f { |
| + if strings.HasPrefix(k, "sec.") { |
| + 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) { |
| + t.Errorf("post %d: field %s carries plaintext", i, k) |
| + } |
| + } |
| + } |
| + } |
| + add, rep := posts[0], posts[1] |
| + if _, ok := add["add.default.value"]; ok { |
| + t.Error("add: the value field was posted") |
| + } |
| + if add.Get("op") != "add:default" || add.Get("add.default.secret") != "1" || add.Get("env.default.STRIPE_KEY") != "" { |
| + t.Errorf("add posted %v", add) |
| + } |
| + if rep.Get("op") != "stage" || rep.Get("addenv.default") != "" { |
| + t.Errorf("replace posted %v", rep) |
| + } |
| + 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")}) |
| + |
| + // What the browser sent stages on the real console. |
| + status, _, body := postForm(t, e.c, e.fx.u("/apps/shop/settings/environments"), add) |
| + if status != http.StatusOK { |
| + t.Fatalf("console staging the browser's add = %d:\n%s", status, body) |
| + } |
| + mustContain(t, body, "1 change: new secret WEBHOOK_SECRET in All environments.") |
| + mustNotContain(t, body, secret) |
| + e.spy.none(t) |
| + |
| + if dir := os.Getenv("ENV_FORM_SHOTS"); dir != "" { |
| + // The staged page, so the save bar shows too. |
| + page = body |
| + for _, w := range []string{"390", "1280"} { |
| + shot := filepath.Join(dir, "env-"+w+".png") |
| + out, err := exec.CommandContext(ctx, chromium, "--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-sandbox", |
| + "--virtual-time-budget=2000", "--user-data-dir="+t.TempDir(), "--window-size="+w+",2400", |
| + "--screenshot="+shot, ts.URL+"/page").CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("screenshot %s: %v\n%s", w, err, out) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/console/gettingstarted.go b/internal/console/gettingstarted.go| index 54eb20306..786508090 100644 |
| --- a/internal/console/gettingstarted.go |
| +++ b/internal/console/gettingstarted.go |
| @@ -194,11 +194,18 @@ func gsDomainApp(apps []appRow, live map[string]bool) string { |
| // gettingStartedCopyFor is c with {console} replaced by consoleName in |
| // every string field, so no field can render the placeholder. |
| func gettingStartedCopyFor(c gettingStartedCopy, consoleName string) gettingStartedCopy { |
| - rv := reflect.ValueOf(&c).Elem() |
| + fillConsoleName(&c, consoleName) |
| + return c |
| +} |
| + |
| +// fillConsoleName replaces {console} with name in every string field of the |
| +// struct ptr points at, so no field of a copy struct can render the |
| +// placeholder. |
| +func fillConsoleName(ptr any, name string) { |
| + rv := reflect.ValueOf(ptr).Elem() |
| for i := 0; i < rv.NumField(); i++ { |
| if f := rv.Field(i); f.Kind() == reflect.String { |
| - f.SetString(strings.ReplaceAll(f.String(), "{console}", consoleName)) |
| + f.SetString(strings.ReplaceAll(f.String(), "{console}", name)) |
| } |
| } |
| - return c |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 9276d541b..d99cc2407 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -2109,6 +2109,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| s.registerRoute("GET /a/{sqid}/apps/{app}/settings", s.handleAppSettings) |
| s.registerRoute("GET /a/{sqid}/apps/{app}/settings/{section}", s.handleAppSettings) |
| s.registerRoute("GET /a/{sqid}/apps/{app}/settings/index", s.handleAppSettingsIndex) |
| + // The Environments section's one form (envform.go): any member, CSRF; |
| + // staging re-renders, Save writes one bundle. |
| + s.registerRoute("POST /a/{sqid}/apps/{app}/settings/environments", s.handleEnvForm) |
| // The pipeline settings page (pipelinepage.go, release pipelines v2 §5) |
| // is the Settings tab's Release pipeline section; the old GET answers |
| // with a 303 to it, after accountApp's gates. POST goes through the same |
diff --git a/internal/console/templates/app_settings.html b/internal/console/templates/app_settings.html| index 8759188be..609d76fe7 100644 |
| --- a/internal/console/templates/app_settings.html |
| +++ b/internal/console/templates/app_settings.html |
| @@ -267,30 +267,26 @@ offers the final console-record step.</p> |
| {{if eq .SettingsSection "environments"}} |
| {{if .Settings.NoBucket}}<p class="banner error">no deployment bucket on this host — this console cannot read config</p>{{end}} |
| {{if .Settings.EnvsUnavailable}}<p class="banner error">Could not read this app's environments. Please try again.</p>{{end}} |
| -{{if .Settings}} |
| +{{if .Settings}}{{if .Settings.EnvCanEdit}}{{template "app_settings_envs" .}}{{else}} |
| <h2>Environments</h2> |
| <p class="small">A named environment is a config bundle that overlays this |
| app's default one, per key. An instance bound to it reads the app's config |
| with these values on top — which is how two instances of one app serve |
| different origins, and how one of them gets a bucket of its own.</p> |
| {{if .Settings.Envs}} |
| -{{range .Settings.Envs}} |
| +{{range .Settings.Envs}}{{if .Name}} |
| <h3><code>{{.Name}}</code></h3> |
| <div class="tablewrap"> |
| <table> |
| <tr><th>Sets</th><th>Read by</th><th>Object store</th></tr> |
| <tr> |
| <td>{{if .Vars}}{{range $i, $v := .Vars}}{{if $i}}, {{end}}<code>{{$v.Name}}</code>{{if $v.Secret}} <span class="small">sealed</span>{{end}}{{end}}{{else}}<span title="the bundle exists but sets nothing">—</span>{{end}}</td> |
| - <td>{{if .Hosts}}{{range $i, $h := .Hosts}}{{if $i}}, {{end}}<a href="{{$.Nav}}/apps/{{$.Detail.App}}/instances/{{$h}}">{{$h}}</a>{{end}}{{else}}<span title="no instance is bound to this bundle">no instances</span>{{end}}</td> |
| + <td>{{if .UsedBy}}{{range $i, $h := .UsedBy}}{{if $i}}, {{end}}<a href="{{$.Nav}}/apps/{{$.Detail.App}}/instances/{{$h}}">{{$h}}</a>{{end}}{{else}}<span title="no instance is bound to this bundle">no instances</span>{{end}}</td> |
| <td>{{if .HasStore}}{{if .StoreBucket}}<code>{{.StoreBucket}}</code>{{else}}declared{{end}}{{else}}<span title="this environment has no store of its own">—</span>{{end}}</td> |
| </tr> |
| </table> |
| </div> |
| -{{if and .HasStore (not .Hosts)}}<p class="small">This environment has an object |
| -store but no instance reads it. The bucket still exists and still costs — |
| -destroying a store is always deliberate, so nothing has removed it. Its card is |
| -under <a href="{{$.Nav}}/apps/{{$.Detail.App}}/settings/storage">Storage</a>.</p>{{end}} |
| -{{end}} |
| +{{end}}{{end}} |
| <p class="small">Values are not shown here. Read them with <code>carlos env list |
| --app {{.Detail.App}} --environment <name></code>; secrets list by name only, |
| wherever you ask.</p> |
| @@ -301,7 +297,7 @@ default config bundle. Add one with <code>carlos env set --app {{.Detail.App}} |
| <code>carlos instances set-environment --app {{.Detail.App}} --host <h> |
| --environment <name></code>.</p> |
| {{end}}{{end}} |
| -{{end}} |
| +{{end}}{{end}} |
| {{end}} |
| {{if eq .SettingsSection "storage"}} |
| {{if .Settings.NoBucket}}<p class="banner error">no deployment bucket on this host — this console cannot serve object storage</p>{{end}} |
| @@ -630,3 +626,91 @@ blocks deletion. Turn the safety delay off on the <a href="{{.Nav}}/apps/{{.AppN |
| </div> |
| </div> |
| {{template "bottom" .}}{{end}} |
| + |
| +{{/* The editable Environments section (envform.go has the form protocol). |
| + Secret plaintext fields render disabled and carry no value; the |
| + sealing script enables them, seals on submit and strips them, so with |
| + scripts off no secret can be typed or sent. */}} |
| +{{define "app_settings_envs"}}{{$s := .Settings}}{{$c := $s.EnvCopy}}{{$d := $s.EnvDraft}}{{$seal := $s.EnvSeal}} |
| +<h2>Environments</h2> |
| +<p class="small">{{$c.Intro}}</p> |
| +{{if $s.EnvError}}<p class="banner error" role="alert">{{$s.EnvError}}</p>{{end}} |
| +<form method="post" action="{{.Nav}}/apps/{{.Detail.App}}/settings/environments"{{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). */}} |
| + <button type="submit" name="op" value="stage" class="visually-hidden" tabindex="-1" aria-hidden="true">{{$c.Stage}}</button> |
| + <input type="hidden" name="bundle" value="{{if $d}}{{if not $d.Empty}}{{$d.Bundle}}{{end}}{{end}}"> |
| + {{with $seal}}<input type="hidden" name="sealed_to" value="{{.SealedTo}}">{{end}} |
| +{{range $s.Envs}}{{$b := .Bundle}} |
| + <input type="hidden" name="ver.{{$b}}" value="{{.Version}}"> |
| + <h3 class="envhead">{{.Title}}</h3> |
| + <p class="small">{{$c.UsedByLine .UsedBy}}</p> |
| + {{if .Vars}}<div class="tablewrap"> |
| + <ul class="envvars"> |
| + {{range .Vars}}<li>{{if eq .Staged "removed"}}<div class="envvar-row"><code class="envvar-name">{{.Name}}</code><span class="envvar-value"><span class="chip chip-canary">{{$c.Removed}}</span></span><button type="submit" class="linkish" name="op" value="undo:{{$b}}.{{.Name}}" data-seal-skip>{{$c.Undo}}</button></div> |
| + {{- else if eq .Staged "new"}}<div class="envvar-row"><code class="envvar-name">{{.Name}}</code><span class="envvar-value">{{if not .Secret}}{{.Value}} {{end}}<span class="chip chip-canary">{{if .Secret}}{{$c.NewSecret}}{{else}}{{$c.New}}{{end}}</span></span><button type="submit" class="linkish" name="op" value="undo:{{$b}}.{{.Name}}" data-seal-skip>{{$c.Undo}}</button></div> |
| + {{- else if and .Secret .Staged}}<div class="envvar-row"><code class="envvar-name">{{.Name}}</code><span class="envvar-value"><span class="chip chip-canary">{{$c.Changed}}</span></span><button type="submit" class="linkish" name="op" value="undo:{{$b}}.{{.Name}}" data-seal-skip>{{$c.Undo}}</button></div> |
| + {{- else}}<details class="envvar"{{if .Open}} open{{end}}><summary><code class="envvar-name">{{.Name}}</code><span class="envvar-value{{if .Secret}} small{{end}}">{{if .Secret}}{{$c.Sealed}}{{else}}{{.Value}}{{end}}{{if .Staged}} <span class="chip chip-canary">{{$c.Changed}}</span>{{end}}</span><span class="envvar-edit">{{if .Open}}{{$c.Close}}{{else}}{{$c.Edit}}{{end}}</span></summary> |
| + <div class="envvar-panel settings-row"> |
| + {{- if .Secret}}{{$id := printf "sec.%s.%s" $b .Name}} |
| + <label class="visually-hidden" for="{{$id}}">{{$c.NewValueLabel .Name}}</label> |
| + {{- if $seal}} |
| + <input type="password" id="{{$id}}" name="{{$id}}" placeholder="{{$c.NewValue}}" autocomplete="off" data-secret-input data-secret-optional disabled> |
| + <input type="hidden" name="env.{{$b}}.{{.Name}}" data-envelope-for="{{$id}}"> |
| + <button type="submit" class="btn-sm btn-secondary" name="op" value="stage">{{$c.Stage}}</button> |
| + {{- else}} |
| + <input type="password" id="{{$id}}" placeholder="{{$c.NewValue}}" autocomplete="off" disabled> |
| + {{- end}} |
| + {{- else}}{{$id := printf "val.%s.%s" $b .Name}} |
| + <label class="visually-hidden" for="{{$id}}">{{$c.NewValueLabel .Name}}</label> |
| + <input type="text" id="{{$id}}" name="{{$id}}" value="{{.Value}}" autocomplete="off"> |
| + <button type="submit" class="btn-sm btn-secondary" name="op" value="stage">{{$c.Stage}}</button> |
| + {{- end}} |
| + {{if .Staged}}<button type="submit" class="linkish" name="op" value="undo:{{$b}}.{{.Name}}" data-seal-skip>{{$c.Undo}}</button>{{end}} |
| + <button type="submit" class="linkish danger" name="op" value="remove:{{$b}}.{{.Name}}" data-seal-skip>{{$c.Remove}}</button> |
| + {{- if .Secret}}{{if $seal}} |
| + <noscript><span class="small">{{$c.NeedsScript}}</span></noscript> |
| + <span class="small error" data-seal-error="sec.{{$b}}.{{.Name}}" hidden></span>{{end}}{{end}} |
| + </div> |
| + </details>{{end}}</li> |
| + {{end}}</ul> |
| + </div>{{end}} |
| + {{$addName := printf "add.%s.name" $b}}{{$addValue := printf "add.%s.value" $b}}{{$redraw := and $d (eq $d.AddBundle $b)}} |
| + <div class="settings-row addvar"> |
| + <label class="visually-hidden" for="{{$addName}}">{{$c.NameLabel}}</label> |
| + <input type="text" id="{{$addName}}" name="{{$addName}}" placeholder="{{$c.NamePlace}}" autocomplete="off" spellcheck="false"{{if $redraw}} value="{{$d.AddName}}"{{end}}> |
| + <label class="visually-hidden" for="{{$addValue}}">{{$c.ValueLabel}}</label> |
| + <input type="text" id="{{$addValue}}" name="{{$addValue}}" placeholder="{{$c.ValuePlace}}" autocomplete="off"{{if $redraw}} value="{{$d.AddValue}}"{{end}}> |
| + <label class="small"><input type="checkbox" id="add.{{$b}}.secret" name="add.{{$b}}.secret" value="1"{{if $seal}} data-secret-toggle data-secret-for="{{$addValue}}" data-name-from="{{$addName}}"{{end}}{{if $redraw}}{{if $d.AddSecret}} checked{{end}}{{end}} disabled> {{$c.Secret}}</label> |
| + {{- if $seal}} |
| + <input type="hidden" name="addenv.{{$b}}" data-envelope-for="{{$addValue}}">{{end}} |
| + <button type="submit" class="btn-sm btn-secondary" name="op" value="add:{{$b}}">{{$c.Add}}</button> |
| + {{- if $seal}} |
| + <span class="small error" data-seal-error="{{$addValue}}" hidden></span>{{end}} |
| + </div> |
| + {{if eq $b "default"}}{{if $seal}}<p class="small">{{$c.SealingNote}}</p> |
| + <noscript><p class="small">{{$c.NeedsScript}}</p></noscript> |
| + {{- else if eq $s.EnvSealOff "keyless"}}<p class="small">{{$c.KeylessLine $s.EnvSealFleet}}</p> |
| + {{- else if eq $s.EnvSealOff "no-key"}}<p class="small">{{$c.NoKey}}</p> |
| + {{- else}}<p class="small">{{$c.SealOff}}</p>{{end}}{{end}} |
| + {{if and .HasStore (not .UsedBy)}}<p class="small">{{$c.StoreUnreadLine .StoreBucket}} <a href="{{$.Nav}}/apps/{{$.Detail.App}}/settings/storage">{{$c.StoreLink}}</a></p>{{end}} |
| +{{end}} |
| +{{- with $d}}{{$b := .Bundle}} |
| + {{- range $k, $v := .New}} |
| + <input type="hidden" name="new.{{$b}}.{{$k}}" value="{{$v}}">{{end}} |
| + {{- range $k, $v := .Secrets}} |
| + <input type="hidden" name="newenv.{{$b}}.{{$k}}" value="{{$v}}">{{end}} |
| + {{- range .Unset}} |
| + <input type="hidden" name="rm.{{$b}}" value="{{.}}">{{end}} |
| + {{- if not .Empty}} |
| + <div class="savebar"> |
| + <p class="small">{{$s.EnvSummary}}</p> |
| + <div class="actions"> |
| + <button type="submit" class="linkish" name="op" value="discard" data-seal-skip>{{$c.Discard}}</button> |
| + <button type="submit" class="btn-sm" name="op" value="save">{{$c.Save}}</button> |
| + </div> |
| + </div>{{end}} |
| +{{- end}} |
| +</form> |
| +{{if $seal}}<script>{{$s.ConfigSealJS}}</script>{{end}} |
| +{{end}} |
diff --git a/internal/console/templates/console_chrome.html b/internal/console/templates/console_chrome.html| index dcfe696db..8494b3bb2 100644 |
| --- a/internal/console/templates/console_chrome.html |
| +++ b/internal/console/templates/console_chrome.html |
| @@ -253,6 +253,41 @@ |
| .settings-content :is(.tile, .tablewrap, .rung) { background-color: var(--rst-surface-2); box-shadow: none; } |
| .settings-content > h2:first-child { margin-top: 0; } |
| .danger-head { color: var(--bad); } |
| + /* Variable rows (the Environments section, console secrets): one compact |
| + row per variable, an Edit reveal holding Replace and Remove, the add |
| + row, and the save bar that shows while something is staged. .outcomes |
| + is the after-save list, a host per row with its chip. */ |
| + .envvars { list-style: none; margin: 0; padding: 0; } |
| + .envvars > li { border-bottom: 1px solid var(--rule); } |
| + .envvars > li:last-child { border-bottom: 0; } |
| + .envvar > summary, .envvar-row { display: flex; align-items: baseline; gap: 0.75rem; padding: 0.55rem 0.9rem; list-style: none; } |
| + .envvar > summary { cursor: pointer; } |
| + .envvar > summary::-webkit-details-marker { display: none; } |
| + .envvar-name { flex: none; } |
| + .envvar-value { flex: 1; min-width: 0; text-align: right; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.9rem; } |
| + .outcomes .envvar-row { flex-wrap: wrap; justify-content: space-between; row-gap: 0.3rem; } |
| + .outcomes .envvar-value { flex: none; } |
| + .envvar-edit { flex: none; color: var(--accent); font-size: 0.9rem; } |
| + .envvar[open] .envvar-edit { color: var(--muted); } |
| + .envvar-panel { padding: 0 0.9rem 0.6rem; } |
| + .envvar-panel .settings-row { margin: 0; } |
| + .envvar-panel input[type=text], .envvar-panel input[type=password] { flex: 1; min-width: 8rem; } |
| + .envhead { margin: 1.75rem 0 0.15rem; } |
| + .envhead + .small { margin: 0 0 0.6rem; } |
| + .addvar { margin: 0.6rem 0 0.25rem; } |
| + .addvar input[name$=".name"] { flex: 0 1 9rem; min-width: 6rem; } |
| + .addvar input[name$=".value"] { flex: 1 1 8rem; min-width: 6rem; } |
| + .addvar + .small { margin: 0 0 0.5rem; } |
| + /* On a phone the name takes the first line and the value shares the |
| + second with the Secret box and Add. */ |
| + @media (max-width: 40rem) { .addvar input[name$=".name"] { flex-basis: 100%; } } |
| + .savebar { |
| + position: sticky; bottom: 0.75rem; display: flex; flex-wrap: wrap; gap: 0.5rem 0.9rem; align-items: center; |
| + margin: 1.5rem 0 1rem; padding: 0.6rem 0.9rem; background: var(--accent-soft); |
| + border: 1px solid var(--rule); border-radius: var(--rst-radius); |
| + } |
| + .savebar p { margin: 0; flex: 1 1 12rem; } |
| + .savebar .actions { display: flex; gap: 0.9rem; align-items: center; } |
| p { max-width: 40rem; margin: 0 0 1rem; } |
| .lede { font-size: 1.15rem; color: var(--muted); } |
| .small { font-size: 0.9rem; color: var(--muted); } |