carlos / platform Public

console: env form admits, reads and carries a post exactly once

Astra round 1 on Tasks 7 and 8. One admission path for every op:
session, body cap, URL-encoded only, checked parse, field cap, CSRF,
membership, one write budget, then the page. The whole post is
classified before any op: duplicates, odd flags, unknown fields, a var
staged two ways, and plaintext in any card's add row on any op are
refused unread.

Edits are val against the orig they were drawn with, and carried sets
stay sets, so a moved bundle reaches the conflict path intact. Each
envelope keeps the key that sealed it (fp.*); Save refuses one sealed
to a key that is no longer the app's. Save stages its own card's add
row and refuses another card's. A bundle that will not read keeps the
posted draft with Save off. Outcome copy says only what the classifier
establishes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 104ab3a031a99e7a6c2f409a2eeece11d1da6472 parent 37db190
8 files changed, +857 −214
  • internal/console/appsettings.go +8 −4
  • internal/console/envcopy.go +8 −10
  • internal/console/envform.go +332 −142
  • internal/console/envform_test.go +19 −6
  • internal/console/envformgate_test.go +425 −0
  • internal/console/envsave.go +22 −30
  • internal/console/envsave_test.go +22 −14
  • internal/console/templates/app_settings.html +21 −8

Intent

Human

<task-notification> <task-id>aa894398afc576125</task-id> <tool-use-id>toolu_01TYdgDTHbdnxn71ng9LJa1Z</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/abe35d56-e4c2-40df-9005-6e66b76b1f50/tasks/aa894398afc576125.output</output-file> <status>completed</status> <summary>Agent "Apply Luna copy table" 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>I applied the Luna copy table and committed it as 37db1908 (`copy: console secrets, Luna pass under Paul's delegation`). Both test runs pass: `go test ./internal/console -run 'Env|ConfigSeal|ConfigValue|SettingsPage'` and `go test . -run 'RestartNotice|FleetSecretsCopy'`. I added `SettingsPage` to the first filter so `TestSettingsPageShowsEnvironments`, which pins `UsedByNone`, also ran. I ran `gofmt` on the touched files. The skips and the "server" substitutions are as you specified. I updated the tests that pinned the old wording in `appconfig_cli_test.go` and in `appsettings_env_test.go`, `envform_test.go` and `envsave_test.go` under `internal/console`. `RefKeylessFleet` is not in the table, so I left its text alone and kept its test as it was.</result> <usage><subagent_tokens>55471</subagent_tokens><tool_uses>10</tool_uses><duration_ms>373210</duration_ms></usage> </task-notification>

diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go
index 2ed4c2fc1..6a83ac90b 100644
--- a/internal/console/appsettings.go
+++ b/internal/console/appsettings.go
@@ -142,6 +142,9 @@ type SettingsView struct {
// EnvOutcome is "After you save" (envsave.go): set after a Save that
// wrote, or a Retry; nil otherwise.
EnvOutcome *envOutcome
+ // EnvCarry is a post's draft drawn back as it came, when the bundles
+ // could not be read to draw it against (Save is off until they can).
+ EnvCarry []envCarryField
// EnvCopy is the section's words; ConfigSealJS the sealing script the
// page inlines.
EnvCopy envPageCopy
@@ -299,13 +302,14 @@ type EnvCard 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.
+// (the staged one when it is changed) and always "" for a secret. Open
+// draws the row's Edit panel open.
type EnvVarRow struct {
Name string
Secret bool
Value string
- Staged string
+ Orig string // an ordinary row's stored value: the form's orig.*
+ Staged string // "", "new", "changed", "replaced" (secret to ordinary), "removed"
Open bool
}
@@ -617,7 +621,7 @@ func envCardOf(name string, m *appconfig.Manifest, ver appconfig.BundleVersion,
v := m.Vars[k]
row := EnvVarRow{Name: k, Secret: v.Kind == "secret"}
if !row.Secret {
- row.Value = v.Value
+ row.Value, row.Orig = v.Value, v.Value
}
card.Vars = append(card.Vars, row)
}
diff --git a/internal/console/envcopy.go b/internal/console/envcopy.go
index 9334b3700..8333caf6d 100644
--- a/internal/console/envcopy.go
+++ b/internal/console/envcopy.go
@@ -103,7 +103,6 @@ type envPageCopy struct {
OutcomeAsleepHlp string
OutcomeCantSee string
OutcomeCantHelp string
- OutcomeCantCmd string // {host}, a command, shown as code
OutcomePartial string
OutcomeSeeRun string
// The Restart it yourself rows' How sentences. A sidecar's links to
@@ -127,6 +126,8 @@ type envPageCopy struct {
RateLimited string
NothingToSave string
CheckLimited string
+ KeyChanged string
+ TryAgain string
}
// envCopyDraft is the section's copy before {console} is filled.
@@ -209,14 +210,13 @@ var envCopyDraft = envPageCopy{
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.",
+ OutcomeSelfHelp: "{console} expects it to restart with the new settings by itself, or on its next wake.",
OutcomeYou: "Restart it yourself",
- OutcomeYouHelp: "{console} will deliver the settings but cannot restart this one for you.",
+ OutcomeYouHelp: "the settings go to it, but {console} cannot restart this one for you.",
OutcomeAsleep: "Asleep",
OutcomeAsleepHlp: "it picks up the change when it next wakes.",
OutcomeCantSee: "Can't see from here",
- OutcomeCantHelp: "it runs on a server {console} cannot check from here. It will pick up the change the next time it restarts, or you can restart it now:",
- OutcomeCantCmd: "carlos restart --host {host}",
+ OutcomeCantHelp: "{console} can't check this copy from here. See Running to check it.",
OutcomePartial: "Copies on other boxes may not all be listed here.",
OutcomeSeeRun: "See what's running",
@@ -239,6 +239,8 @@ var envCopyDraft = envPageCopy{
RateLimited: "Too many changes at once. Nothing was saved. Try again in a minute.",
NothingToSave: "There's nothing to save.",
CheckLimited: "Too many checks at once. Try again in a minute.",
+ KeyChanged: "This app's secrets key changed after you entered your secrets, so they were not saved. Enter your secrets again.",
+ TryAgain: "Try again",
}
// envCopyFor is the section's copy for a console called consoleName.
@@ -321,6 +323,7 @@ func (c envPageCopy) staging(ref *envFormRefusal) string {
envRefuseVarValue: c.RefVarValue,
envRefuseEnvelope: c.EnvelopeStale,
envRefuseUnread: c.CouldNotRead,
+ envRefuseKeyChange: c.KeyChanged,
}[ref.Code]
return envFill(line, "name", ref.Var, "env", ref.Env)
}
@@ -365,8 +368,3 @@ func (c envPageCopy) SavedLine(o *envOutcome) string {
func (c envPageCopy) UndelivLine(app string) string {
return envFill(c.OutcomeUndelivHlp, "app", app)
}
-
-// CantCmdLine is the command that restarts host from anywhere.
-func (c envPageCopy) CantCmdLine(host string) string {
- return envFill(c.OutcomeCantCmd, "host", host)
-}
diff --git a/internal/console/envform.go b/internal/console/envform.go
index ba53e7ca3..77061c0b9 100644
--- a/internal/console/envform.go
+++ b/internal/console/envform.go
@@ -3,30 +3,41 @@
// 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:
+// Form protocol, POST /a/{sqid}/apps/{app}/settings/environments, sent
+// application/x-www-form-urlencoded only:
//
// 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
+// sealed_to the fingerprint of the key the page seals to:
+// the provenance of the envelopes the browser
+// sealed for this submit (env.*, addenv.*)
// val.<b>.<NAME> an existing ordinary setting's value (prefilled)
+// orig.<b>.<NAME> the value that field was drawn with: an edit is
+// val != orig, whatever storage holds now
// 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
+// new.<b>.<NAME> a staged ordinary set: a new setting, or one
+// replacing a secret of that name
+// newenv.<b>.<NAME> a staged secret's envelope, new or replacing,
+// fp.<b>.<NAME> and the fingerprint of the key that sealed it
// 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
+// add.<b>.name, .value the add row; .secret ("" or "1") ticks it
+// addenv.<b> secret, and then carries the sealed value and
+// .value must be gone
// op add:<b> | remove:<b>.<NAME> | undo:<b>.<NAME> |
// discard | stage | save | check
// check_bundle Retry's own small form (op=check): the bundle a
// check_key save wrote, and each key it touched (repeated)
//
-// <b> is "default" for the default bundle or the environment's name.
-// Anything else posted, and any secret plaintext, is refused with the
-// Unsealed copy and thrown away, never echoed.
+// <b> is "default" for the default bundle or the environment's name. Only
+// rm.<b> and check_key repeat. Anything else posted twice, any field the
+// protocol does not name, any secret plaintext (a non-empty sec.*, or an
+// add row ticked Secret that still carries its value, on ANY op), and two
+// fields staging one var two ways are refused with the Unsealed copy before
+// any op runs: nothing is drawn back and nothing is written.
package console
import (
@@ -34,10 +45,12 @@ import (
"crypto/subtle"
"errors"
"log"
+ "mime"
"net/http"
"net/url"
"sort"
"strings"
+ "time"
"github.com/carlosframework/platform/internal/appconfig"
)
@@ -84,16 +97,22 @@ func (s *Server) envSection(ctx context.Context, sv *SettingsView, acct *Account
}
}
-// 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.
+// envSecret is one staged secret: its envelope and the fingerprint of the
+// key that sealed it, kept together through every round trip. The page's
+// current key never relabels an envelope it did not seal.
+type envSecret struct{ Envelope, FP string }
+
+// envDraft is one bundle's staged changes: ordinary sets (Values: changes
+// to settings drawn as ordinary rows; New: new settings, and ordinary
+// replacements of secrets), secrets (new or replacing, as envelopes with
+// their key) 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
+ Secrets map[string]envSecret
Unset []string
// The add row to draw again after a refused add: its bundle, name and
@@ -106,7 +125,7 @@ type envDraft struct {
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}
+ New: map[string]string{}, Secrets: map[string]envSecret{}, stored: card.stored}
}
// Empty reports whether nothing is staged.
@@ -146,9 +165,9 @@ func (d *envDraft) envName() string {
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) {
+// writeInput is the draft as writeConfig's sets and unsets (Save), each
+// secret marked sealed to the key that sealed it.
+func (d *envDraft) writeInput() (map[string]configVarIn, []string) {
in := map[string]configVarIn{}
for k, v := range d.Values {
in[k] = configVarIn{Kind: "env", Value: v}
@@ -157,11 +176,32 @@ func (d *envDraft) writeInput(sealedTo string) (map[string]configVarIn, []string
in[k] = configVarIn{Kind: "env", Value: v}
}
for k, e := range d.Secrets {
- in[k] = configVarIn{Kind: "secret", Envelope: e, SealedTo: sealedTo}
+ in[k] = configVarIn{Kind: "secret", Envelope: e.Envelope, SealedTo: e.FP}
}
return in, append([]string(nil), d.Unset...)
}
+// normalize puts each ordinary set where the card draws it: a set of a
+// name stored as an ordinary setting is that row's change (Values, dropped
+// when it equals what is stored: there is nothing to change), anything
+// else is a New row. Representation only: no set is lost.
+func (d *envDraft) normalize() {
+ for k, v := range d.New {
+ if s, ok := d.stored[k]; ok && s.Kind != "secret" {
+ delete(d.New, k)
+ if s.Value != v {
+ d.Values[k] = v
+ }
+ }
+ }
+ for k, v := range d.Values {
+ if s, ok := d.stored[k]; !ok || s.Kind == "secret" {
+ delete(d.Values, k)
+ d.New[k] = v
+ }
+ }
+}
+
type envChangeKind int
const (
@@ -184,7 +224,11 @@ func (d *envDraft) changes() []envChange {
out = append(out, envChange{k, envChangeValue})
}
for k := range d.New {
- out = append(out, envChange{k, envChangeNew})
+ if _, ok := d.stored[k]; ok {
+ out = append(out, envChange{k, envChangeValue})
+ } else {
+ out = append(out, envChange{k, envChangeNew})
+ }
}
for k := range d.Secrets {
if _, ok := d.stored[k]; ok {
@@ -220,6 +264,7 @@ const (
envRefuseVarValue = "var-value"
envRefuseEnvelope = "envelope"
envRefuseUnread = "unread"
+ envRefuseKeyChange = "key-changed"
)
// envFormOp is a parsed op button.
@@ -257,12 +302,12 @@ func envField(key string) (kind, bundle, name string, ok bool) {
switch kind {
case "ver", "rm", "addenv":
return kind, rest, "", !strings.Contains(rest, ".")
- case "val", "sec", "env", "new", "newenv":
+ case "val", "orig", "sec", "env", "new", "newenv", "fp":
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") {
+ if !ok || b == "" || (part != "name" && part != "value" && part != "secret") {
return "", "", "", false
}
return "add." + part, b, "", true
@@ -270,15 +315,103 @@ func envField(key string) (kind, bundle, name string, ok bool) {
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).
+// envFormMaxFields bounds one post's fields: far more than a page of
+// settings draws, few enough that a forged form cannot make one parse or
+// one draft expensive.
+const envFormMaxFields = 2000
+
+// envClassify reads the whole request once, before any op is looked at,
+// and reports whether it must be refused unread (the Unsealed copy, no
+// draft): a field the protocol does not name, a field that may appear once
+// posted twice, a Secret flag other than "" or "1", secret plaintext (a
+// non-empty sec.*, or any card's add row ticked Secret that still carries
+// its value), a val without the orig it was drawn with (or the reverse), a
+// carried envelope without its key (or the reverse), or one var staged two
+// ways at once. Every op passes through it: Save, Retry, Remove and
+// Discard as much as Add.
+func envClassify(form url.Values) bool {
+ type varKey struct{ b, n string }
+ ways := map[varKey]int{}
+ for key, vs := range form {
+ kind, b, n, ok := envField(key)
+ if !ok {
+ return true
+ }
+ if kind != "rm" && kind != "check_key" && len(vs) != 1 {
+ return true
+ }
+ v := ""
+ if len(vs) > 0 {
+ v = vs[0]
+ }
+ switch kind {
+ case "sec":
+ if v != "" {
+ return true
+ }
+ case "add.secret":
+ if v != "" && v != "1" {
+ return true
+ }
+ if v == "1" && form.Get("add."+b+".value") != "" {
+ return true
+ }
+ case "val":
+ if _, ok := form["orig."+b+"."+n]; !ok {
+ return true
+ }
+ ways[varKey{b, n}]++
+ case "orig":
+ if _, ok := form["val."+b+"."+n]; !ok {
+ return true
+ }
+ case "newenv":
+ if _, ok := form["fp."+b+"."+n]; !ok {
+ return true
+ }
+ ways[varKey{b, n}]++
+ case "fp":
+ if _, ok := form["newenv."+b+"."+n]; !ok {
+ return true
+ }
+ case "new":
+ ways[varKey{b, n}]++
+ case "env":
+ if v != "" {
+ ways[varKey{b, n}]++
+ }
+ case "rm":
+ for _, rn := range vs {
+ ways[varKey{b, rn}]++
+ }
+ }
+ }
+ for _, n := range ways {
+ if n > 1 {
+ return true
+ }
+ }
+ return false
+}
+
+// envAddFilled reports whether card b's add row holds anything typed or
+// sealed: a Save, or an op on another card, must not drop it unsaid.
+func envAddFilled(form url.Values, b string) bool {
+ return strings.TrimSpace(form.Get("add."+b+".name")) != "" || form.Get("add."+b+".value") != "" || form.Get("addenv."+b) != ""
+}
+
+// parseEnvForm reads the posted form, already through envClassify, 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) {
+// Every staged change is read from the form as the page drew it, before
+// anything is compared with storage: an edit is a val that differs from
+// its orig, a carried set or removal stays one whatever storage now holds,
+// so a bundle that moved meanwhile reaches Save's conflict path with the
+// changes intact rather than losing them here.
+func parseEnvForm(form url.Values, cards []*EnvCard) (*envDraft, *envFormRefusal) {
byBundle := map[string]*EnvCard{}
for _, card := range cards {
byBundle[card.Bundle] = card
@@ -289,32 +422,13 @@ func parseEnvForm(r *http.Request, cards []*EnvCard) (*envDraft, *envFormRefusal
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
- }
- }
- }
- }
-
+ sealedTo := form.Get("sealed_to")
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
}
@@ -334,64 +448,49 @@ func parseEnvForm(r *http.Request, cards []*EnvCard) (*envDraft, *envFormRefusal
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 "val":
+ if appconfig.ValidVarName(name) && vs[0] != form.Get("orig."+b+"."+name) {
+ d.Values[name] = vs[0]
+ }
case "new":
- if _, exists := card.stored[name]; !exists && appconfig.ValidVarName(name) {
+ if appconfig.ValidVarName(name) {
d.New[name] = vs[0]
}
- case "newenv":
- if !appconfig.ValidVarName(name) {
+ case "env", "newenv":
+ if vs[0] == "" || !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]
+ fp := sealedTo
+ if kind == "newenv" {
+ fp = form.Get("fp." + b + "." + name)
+ }
+ d.Secrets[name] = envSecret{Envelope: vs[0], FP: fp}
case "rm":
for _, n := range vs {
- if _, exists := card.stored[n]; exists && !d.removing(n) {
+ if appconfig.ValidVarName(n) && !d.removing(n) {
d.Unset = append(d.Unset, n)
}
}
}
}
- for _, n := range d.Unset {
- delete(d.Values, n)
- delete(d.Secrets, n)
- }
+ sort.Strings(d.Unset)
}
// The op.
+ adds := map[string]bool{} // add rows this op stages
switch op.verb {
case "remove", "undo":
- if card := byBundle[op.bundle]; card != nil && !unsealed {
+ if card := byBundle[op.bundle]; card != nil {
d := draftFor(card)
d.drop(op.name)
if _, exists := card.stored[op.name]; exists && op.verb == "remove" {
@@ -399,64 +498,73 @@ func parseEnvForm(r *http.Request, cards []*EnvCard) (*envDraft, *envFormRefusal
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
- }
+ case "add":
+ adds[op.bundle] = true
+ case "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")) != "" {
+ adds[card.Bundle] = true
+ break
}
}
- if card := byBundle[b]; card != nil {
- if r := envAdd(form, card, draftFor(card), &unsealed); r != nil {
+ case "save":
+ // Save takes what a filled add row holds as part of this save.
+ for _, card := range cards {
+ if envAddFilled(form, card.Bundle) {
+ adds[card.Bundle] = true
+ }
+ }
+ }
+ for _, card := range cards {
+ if adds[card.Bundle] {
+ if r := envAdd(form, card, draftFor(card), sealedTo); r != nil {
refuse(r)
}
}
}
+ for _, d := range drafts {
+ d.normalize()
+ }
// One bundle at a time: the posted one if it has changes, else the
- // first card that does.
+ // first card that does. A filled add row counts as a change of its
+ // card's, so nothing typed anywhere is dropped without a word.
+ changed := func(card *EnvCard) bool {
+ d := drafts[card.Bundle]
+ return !d.Empty() || d.AddBundle != "" || envAddFilled(form, card.Bundle)
+ }
var keep *envDraft
- var others bool
- if d := drafts[posted]; d != nil && !d.Empty() {
- keep = d
+ if card := byBundle[posted]; card != nil && changed(card) {
+ keep = drafts[posted]
}
+ others := false
for _, card := range cards {
- d := drafts[card.Bundle]
- if d.Empty() && d.AddBundle == "" {
+ if !changed(card) {
continue
}
if keep == nil {
- keep = d
- } else if d != keep {
+ keep = drafts[card.Bundle]
+ } else if drafts[card.Bundle] != keep {
others = true
}
}
- if unsealed {
- ref = &envFormRefusal{Code: envRefuseUnsealed}
- } else if others && keep != nil {
+ 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 {
+// arrives sealed (addenv.<b>, sealed to sealedTo) with its value field gone
+// (envClassify has already refused one that still carries it).
+func envAdd(form url.Values, card *EnvCard, d *envDraft, sealedTo string) *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") != ""
+ value := form.Get("add." + b + ".value")
+ secret := form.Get("add."+b+".secret") == "1"
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 {
@@ -475,8 +583,9 @@ func envAdd(form url.Values, card *EnvCard, d *envDraft, unsealed *bool) *envFor
}
_, stored := card.stored[name]
_, staged := d.New[name]
+ _, stagedValue := d.Values[name]
_, stagedSecret := d.Secrets[name]
- if (stored && !d.removing(name)) || staged || (stagedSecret && !stored) {
+ if (stored && !d.removing(name)) || staged || stagedValue || stagedSecret {
return redraw(envRefuseTaken)
}
d.drop(name)
@@ -487,25 +596,21 @@ func envAdd(form url.Values, card *EnvCard, d *envDraft, unsealed *bool) *envFor
if appconfig.CheckEnvelope(envelope) != nil {
return redraw(envRefuseEnvelope)
}
- d.Secrets[name] = envelope
+ d.Secrets[name] = envSecret{Envelope: envelope, FP: sealedTo}
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
- }
+ // Removed, then added back, ordinary: an explicit ordinary set, which
+ // normalize draws as the row's change or as the secret's replacement.
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.
+// shown, replacements of one kind by the other drawn as the new kind, new
+// ones appended; and the save bar's line.
func applyEnvDraft(sv *SettingsView, d *envDraft, ref *envFormRefusal) {
sv.EnvDraft = d
if ref != nil {
@@ -521,11 +626,18 @@ func applyEnvDraft(sv *SettingsView, d *envDraft, ref *envFormRefusal) {
card.Version = d.Version
for i := range card.Vars {
row := &card.Vars[i]
+ _, secretSet := d.Secrets[row.Name]
+ newValue, ordinarySet := d.New[row.Name]
switch {
case d.removing(row.Name):
row.Staged = "removed"
- case row.Secret && d.Secrets[row.Name] != "":
- row.Staged = "changed"
+ case secretSet:
+ // A secret's new value, or an ordinary setting replaced by
+ // a secret: drawn sealed.
+ row.Secret, row.Value, row.Staged = true, "", "changed"
+ case ordinarySet:
+ // A secret replaced by an ordinary setting.
+ row.Secret, row.Value, row.Staged = false, newValue, "replaced"
case !row.Secret:
if v, ok := d.Values[row.Name]; ok {
row.Value, row.Staged = v, "changed"
@@ -537,7 +649,9 @@ func applyEnvDraft(sv *SettingsView, d *envDraft, ref *envFormRefusal) {
}
var added []EnvVarRow
for k, v := range d.New {
- added = append(added, EnvVarRow{Name: k, Value: v, Staged: "new"})
+ if _, ok := d.stored[k]; !ok {
+ added = append(added, EnvVarRow{Name: k, Value: v, Staged: "new"})
+ }
}
for k := range d.Secrets {
if _, ok := d.stored[k]; !ok {
@@ -552,20 +666,89 @@ func applyEnvDraft(sv *SettingsView, d *envDraft, ref *envFormRefusal) {
}
}
-// handleEnvForm is the Environments section's one form: member-gated like
-// every app page (accountApp: a non-member's 404 is an unknown app's),
-// CSRF before anything is read from the form, then the draft re-rendered.
-// Nothing here writes: Save goes to envFormSave (envsave.go), the one
-// write, and Retry to envFormCheck, which only reads.
+// envCarryField is one posted field drawn back as it came (EnvCarry).
+type envCarryField struct{ Name, Value string }
+
+// envCarry is a post's draft fields as they came, for a response that
+// could not read the bundles to draw them against: nothing the person
+// staged is lost to a read that failed, and nothing is written until the
+// bundles read again. The post has been through envClassify, so none of it
+// is plaintext.
+func envCarry(form url.Values) []envCarryField {
+ var out []envCarryField
+ for k, vs := range form {
+ switch k {
+ case "csrf", "op", "check_bundle", "check_key":
+ continue
+ }
+ for _, v := range vs {
+ out = append(out, envCarryField{k, v})
+ }
+ }
+ sort.Slice(out, func(i, j int) bool {
+ if out[i].Name != out[j].Name {
+ return out[i].Name < out[j].Name
+ }
+ return out[i].Value < out[j].Value
+ })
+ return out
+}
+
+// handleEnvForm is the Environments section's one form. Admission, the
+// same for every op and in this order: the session; a total body cap; the
+// URL-encoded content type only (no multipart, so no file parts and no
+// spill to disk); the form parse, its error refused; the field cap; CSRF;
+// membership and the app (accountApp: a non-member's 404 is an unknown
+// app's); the write budget, one for every op; and only then the page and
+// the bundle reads. Then the whole request is classified (envClassify)
+// before any op runs. Nothing here writes: Save goes to envFormSave
+// (envsave.go), the one write, and Retry to envFormCheck, which only reads.
func (s *Server) handleEnvForm(w http.ResponseWriter, r *http.Request) {
- addr, raw, _, _, _, ok := s.accountApp(w, r)
- if !ok {
+ _, raw, sok := s.session(r)
+ if !sok {
+ http.Redirect(w, r, "/", http.StatusFound)
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, configPutMaxBytes)
+ if mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || mt != "application/x-www-form-urlencoded" {
+ s.renderMessage(w, r, http.StatusUnsupportedMediaType, "Refused", "This form can only be sent from its page.")
+ return
+ }
+ if err := r.ParseForm(); err != nil {
+ var tooBig *http.MaxBytesError
+ if errors.As(err, &tooBig) {
+ s.renderMessage(w, r, http.StatusRequestEntityTooLarge, "Refused", "This form is too large.")
+ return
+ }
+ s.renderMessage(w, r, http.StatusBadRequest, "Refused", "This form could not be read.")
+ return
+ }
+ fields := 0
+ for _, vs := range r.PostForm {
+ fields += len(vs)
+ }
+ if fields > envFormMaxFields {
+ s.renderMessage(w, r, http.StatusRequestEntityTooLarge, "Refused", "This form is too large.")
return
}
- if subtle.ConstantTimeCompare([]byte(r.PostFormValue("csrf")), []byte(raw)) != 1 {
+ if tok := r.PostForm["csrf"]; len(tok) != 1 || subtle.ConstantTimeCompare([]byte(tok[0]), []byte(raw)) != 1 {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
+ addr, _, _, _, _, ok := s.accountApp(w, r)
+ if !ok {
+ return
+ }
+ op, _ := parseEnvOp(r.PostForm.Get("op"))
+ if !s.allowWrite(Principal{Kind: PrincipalUser, Address: addr}, time.Now()) {
+ c := envCopyFor(s.consoleName())
+ line := c.RateLimited
+ if op.verb == "check" {
+ line = c.CheckLimited
+ }
+ s.renderMessage(w, r, http.StatusTooManyRequests, "Refused", line)
+ return
+ }
p, acct, ok := s.appPage(w, r, "settings")
if !ok {
return
@@ -573,21 +756,28 @@ func (s *Server) handleEnvForm(w http.ResponseWriter, r *http.Request) {
setAppSettingsSection(&p, "environments")
s.populateAppSettings(r, &p, acct, "environments")
sv := p.Settings
+ if sv != nil && sv.EnvCanEdit && envClassify(r.PostForm) {
+ applyEnvDraft(sv, nil, &envFormRefusal{Code: envRefuseUnsealed})
+ s.render(w, http.StatusBadRequest, "app_settings", p)
+ return
+ }
if sv == nil || !sv.EnvCanEdit || sv.EnvsUnavailable {
if sv != nil && sv.EnvCanEdit {
sv.EnvError = sv.EnvCopy.staging(&envFormRefusal{Code: envRefuseUnread})
+ // The draft rides along as posted, and Save is off until the
+ // bundles read again.
+ sv.Envs, sv.EnvCarry = nil, envCarry(r.PostForm)
}
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") {
- if op.verb == "save" {
- s.envFormSave(w, r, p, acct, addr, d)
- } else {
- s.envFormCheck(w, r, p, acct, addr)
- }
+ d, ref := parseEnvForm(r.PostForm, sv.Envs)
+ if ref == nil && op.verb == "save" {
+ s.envFormSave(w, r, p, acct, addr, d)
+ return
+ }
+ if ref == nil && op.verb == "check" {
+ s.envFormCheck(w, r, p, acct)
return
}
applyEnvDraft(sv, d, ref)
diff --git a/internal/console/envform_test.go b/internal/console/envform_test.go
index 051198d1a..629c74519 100644
--- a/internal/console/envform_test.go
+++ b/internal/console/envform_test.go
@@ -9,6 +9,7 @@ package console
import (
"context"
"encoding/json"
+ "errors"
"html"
"net/http"
"net/http/httptest"
@@ -33,10 +34,11 @@ import (
// through.
type envWriteSpy struct {
release.Store
- prefix string
- allow bool
- mu sync.Mutex
- writes []string
+ prefix string
+ allow bool
+ failGet string
+ mu sync.Mutex
+ writes []string
}
func (s *envWriteSpy) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
@@ -52,6 +54,17 @@ func (s *envWriteSpy) Put(ctx context.Context, key string, body []byte, ifMatch
return s.Store.Put(ctx, key, body, ifMatch)
}
+// Get fails a read of failGet, when set (a bundle that will not read).
+func (s *envWriteSpy) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.mu.Lock()
+ fail := s.failGet != "" && key == s.failGet
+ s.mu.Unlock()
+ if fail {
+ return nil, "", errors.New("injected read failure")
+ }
+ return s.Store.Get(ctx, key)
+}
+
func (s *envWriteSpy) Delete(ctx context.Context, key string) error {
if s.prefix != "" && strings.HasPrefix(key, s.prefix) {
s.mu.Lock()
@@ -604,8 +617,8 @@ func TestEnvCopyNoDashes(t *testing.T) {
// 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")
+ Secrets: map[string]envSecret{"C": {Envelope: "env", FP: "fp"}}, Unset: []string{"D"}}
+ in, unset := d.writeInput()
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())
diff --git a/internal/console/envformgate_test.go b/internal/console/envformgate_test.go
new file mode 100644
index 000000000..e16c402c3
--- /dev/null
+++ b/internal/console/envformgate_test.go
@@ -0,0 +1,425 @@
+package console
+
+// The Environments form door's admission and its reading of a post (Astra
+// round 1 on Tasks 7 and 8): every op goes through the same gates and the
+// same whole-request classification, staged changes survive round trips
+// and concurrent writes, and an envelope keeps the key that sealed it.
+
+import (
+ "bytes"
+ "context"
+ "mime/multipart"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+)
+
+// rawPost sends body to the form with contentType, as a browser on this
+// session would, bypassing url.Values encoding.
+func (e *envFx) rawPost(t *testing.T, contentType, body string) (int, string) {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodPost, e.fx.u("/apps/shop/settings/environments"), strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", contentType)
+ resp, err := e.c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ var buf bytes.Buffer
+ _, _ = buf.ReadFrom(resp.Body)
+ return resp.StatusCode, buf.String()
+}
+
+func (e *envFx) noWrites(t *testing.T) {
+ t.Helper()
+ if w := e.written(); len(w) != 0 {
+ t.Fatalf("wrote %v", w)
+ }
+}
+
+const envUnsealedLine = "without being sealed in your browser, so it was thrown away"
+
+// An add row ticked Secret that still carries its value is refused on every
+// op, Save included, and nothing is written or drawn back.
+func TestEnvFormAddRowPlaintextRefusedOnEveryOp(t *testing.T) {
+ const plain = "pl41n-on-save"
+ for _, op := range []string{"save", "check", "remove:default.LOG_LEVEL", "undo:default.LOG_LEVEL", "discard", "stage", "add:default"} {
+ t.Run(op, func(t *testing.T) {
+ e := newEnvFx(t)
+ e.saving()
+ f := envFields(t, e.page(t))
+ f.Set("val.default.LOG_LEVEL", "warn")
+ f.Set("add.default.name", "API_TOKEN")
+ f.Set("add.default.secret", "1")
+ f.Set("add.default.value", plain)
+ status, body := e.post(t, f, op)
+ if status != http.StatusBadRequest {
+ t.Fatalf("status = %d", status)
+ }
+ mustContain(t, body, envUnsealedLine)
+ mustNotContain(t, body, plain, "API_TOKEN", `class="env-outcome"`, `value="warn"`)
+ e.noWrites(t)
+ })
+ }
+}
+
+// Two Secret flags (the first empty) cannot make the server read the row
+// as ordinary and stage the plaintext.
+func TestEnvFormDuplicateSecretFlagRefused(t *testing.T) {
+ const plain = "pl41n-dup-flag"
+ e := newEnvFx(t)
+ e.saving()
+ f := envFields(t, e.page(t))
+ f.Set("add.default.name", "API_TOKEN")
+ f["add.default.secret"] = []string{"", "1"}
+ f.Set("add.default.value", plain)
+ status, body := e.post(t, f, "add:default")
+ if status != http.StatusBadRequest {
+ t.Fatalf("status = %d", status)
+ }
+ mustContain(t, body, envUnsealedLine)
+ mustNotContain(t, body, plain, `name="new.default.API_TOKEN"`)
+ e.noWrites(t)
+
+ // Nor can a flag that is neither "" nor "1", or any other repeated field.
+ for name, edit := range map[string]func(url.Values){
+ "odd flag": func(f url.Values) { f.Set("add.default.secret", "yes") },
+ "two values": func(f url.Values) { f["add.default.value"] = []string{"", plain} },
+ "two names": func(f url.Values) { f["add.default.name"] = []string{"API_TOKEN", "OTHER"} },
+ "two versions": func(f url.Values) { f["ver.default"] = append(f["ver.default"], "absent") },
+ "val, no orig": func(f url.Values) { f.Del("orig.default.LOG_LEVEL") },
+ "set two ways": func(f url.Values) { f.Set("new.default.LOG_LEVEL", plain) },
+ "carried, no fp": func(f url.Values) { f.Set("newenv.default.API_TOKEN", e.seal(t, plain)) },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := envFields(t, e.page(t))
+ f.Set("add.default.name", "API_TOKEN")
+ f.Set("add.default.value", plain)
+ edit(f)
+ status, body := e.post(t, f, "save")
+ if status != http.StatusBadRequest {
+ t.Fatalf("status = %d", status)
+ }
+ mustContain(t, body, envUnsealedLine)
+ mustNotContain(t, body, plain)
+ e.noWrites(t)
+ })
+ }
+}
+
+// A malformed escape in the body is a refused form, not a dropped field:
+// the Secret flag it carried cannot vanish and leave the plaintext ordinary.
+func TestEnvFormMalformedFormRefused(t *testing.T) {
+ const plain = "pl41n-malformed"
+ e := newEnvFx(t)
+ e.saving()
+ f := envFields(t, e.page(t))
+ f.Set("add.default.name", "API_TOKEN")
+ f.Set("add.default.value", plain)
+ f.Set("op", "add:default")
+ for _, body := range []string{f.Encode() + "&add.default.secret=%ZZ", f.Encode() + "&%ZZ=1"} {
+ status, out := e.rawPost(t, "application/x-www-form-urlencoded", body)
+ if status != http.StatusBadRequest {
+ t.Fatalf("malformed form = %d", status)
+ }
+ mustNotContain(t, out, plain, "API_TOKEN")
+ }
+ e.noWrites(t)
+}
+
+// The page's key changes between the page that sealed a replacement and the
+// stage that carries it on: the envelope keeps the old key's fingerprint
+// through the round trip, and the Save is refused rather than stored
+// labelled with the new key.
+func TestEnvSaveKeyRotatedAcrossStage(t *testing.T) {
+ e := newEnvFx(t)
+ e.saving()
+ oldFP, _ := appconfig.PublicFingerprint(e.pub)
+ f := envFields(t, e.page(t))
+ env := e.seal(t, "sealed-to-the-old-key")
+ f.Set("env.default.STRIPE_KEY", env)
+ status, body := e.post(t, f, "stage")
+ if status != http.StatusOK {
+ t.Fatalf("stage = %d", status)
+ }
+ // The key changes.
+ _, newPub, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ e.fx.srv.cfg.SecretsPub = newPub
+ status, body = e.post(t, envFields(t, body), "stage")
+ if status != http.StatusOK {
+ t.Fatalf("stage after the key change = %d", status)
+ }
+ newFP, _ := appconfig.PublicFingerprint(newPub)
+ carried := envFields(t, body)
+ if carried.Get("sealed_to") != newFP || carried.Get("fp.default.STRIPE_KEY") != oldFP || carried.Get("newenv.default.STRIPE_KEY") != env {
+ t.Fatalf("carried sealed_to %q fp %q, want the page on %s and the envelope still on %s",
+ carried.Get("sealed_to"), carried.Get("fp.default.STRIPE_KEY"), newFP, oldFP)
+ }
+ status, body = e.post(t, carried, "save")
+ if status != http.StatusConflict {
+ t.Fatalf("save = %d, want the key-changed refusal", status)
+ }
+ mustContain(t, envBanner(body), "This app&#39;s secrets key changed after you entered your secrets")
+ mustNotContain(t, body, env)
+ e.noWrites(t)
+ if m := e.stored(t); m.Vars["STRIPE_KEY"].Envelope != e.envelope {
+ t.Fatalf("stored STRIPE_KEY moved: %+v", m.Vars["STRIPE_KEY"])
+ }
+}
+
+// An edit made straight on the page (nothing staged first) survives
+// another writer's change: Save reaches the conflict path, the edit drawn
+// back, and the next Save lands it.
+func TestEnvSaveStaleDirectEdit(t *testing.T) {
+ e := newEnvFx(t)
+ e.saving()
+ f := envFields(t, e.page(t))
+ if f.Get("bundle") != "" {
+ t.Fatalf("bundle = %q, want nothing staged", f.Get("bundle"))
+ }
+ f.Set("val.default.LOG_LEVEL", "warn")
+ if err := appconfig.SetEnv(context.Background(), e.fx.rel, e.fx.sqid, "shop", map[string]string{"OTHER": "1"}); err != nil {
+ t.Fatal(err)
+ }
+ e.saving()
+ status, body := e.post(t, f, "save")
+ if status != http.StatusConflict {
+ t.Fatalf("save = %d, want the conflict path", status)
+ }
+ e.noWrites(t)
+ mustContain(t, body, `name="val.default.LOG_LEVEL" value="warn"`, "1 change: LOG_LEVEL changed in All environments.")
+ if status, body = e.post(t, envFields(t, body), "save"); status != http.StatusOK {
+ t.Fatalf("re-save = %d:\n%s", status, envBanner(body))
+ }
+ if m := e.stored(t); m.Vars["LOG_LEVEL"].Value != "warn" || m.Vars["OTHER"].Value != "1" {
+ t.Fatalf("stored = %+v", m.Vars)
+ }
+}
+
+// A staged new setting whose name another writer then creates is kept, as
+// a change to that setting, and saves.
+func TestEnvSaveStaleNewName(t *testing.T) {
+ e := newEnvFx(t)
+ e.saving()
+ 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)
+ }
+ if err := appconfig.SetEnv(context.Background(), e.fx.rel, e.fx.sqid, "shop", map[string]string{"MODE": "slow"}); err != nil {
+ t.Fatal(err)
+ }
+ e.saving()
+ status, body = e.post(t, envFields(t, body), "save")
+ if status != http.StatusConflict {
+ t.Fatalf("save = %d, want the conflict path", status)
+ }
+ e.noWrites(t)
+ mustContain(t, body, `name="val.default.MODE" value="fast"`, `name="orig.default.MODE" value="slow"`)
+ if status, body = e.post(t, envFields(t, body), "save"); status != http.StatusOK {
+ t.Fatalf("re-save = %d:\n%s", status, envBanner(body))
+ }
+ if got := e.stored(t).Vars["MODE"].Value; got != "fast" {
+ t.Fatalf("stored MODE = %q", got)
+ }
+}
+
+// Remove a secret, add the name back as an ordinary setting, Save: the
+// replacement is an explicit ordinary set and lands.
+func TestEnvSaveSecretToOrdinary(t *testing.T) {
+ e := newEnvFx(t)
+ e.saving()
+ status, body := e.post(t, envFields(t, e.page(t)), "remove:default.STRIPE_KEY")
+ if status != http.StatusOK {
+ t.Fatalf("remove = %d", status)
+ }
+ f := envFields(t, body)
+ f.Set("add.default.name", "STRIPE_KEY")
+ f.Set("add.default.value", "now-ordinary")
+ status, body = e.post(t, f, "add:default")
+ if status != http.StatusOK {
+ t.Fatalf("add back = %d:\n%s", status, envBanner(body))
+ }
+ mustContain(t, body, `name="new.default.STRIPE_KEY" value="now-ordinary"`, "1 change: STRIPE_KEY changed in All environments.")
+ mustNotContain(t, body, `name="rm.default"`)
+ if status, body = e.post(t, envFields(t, body), "save"); status != http.StatusOK {
+ t.Fatalf("save = %d:\n%s", status, envBanner(body))
+ }
+ if v := e.stored(t).Vars["STRIPE_KEY"]; v.Kind != "env" || v.Value != "now-ordinary" || v.Envelope != "" {
+ t.Fatalf("stored STRIPE_KEY = %+v", v)
+ }
+}
+
+// Save accounts for every card's add row: another card's filled row
+// refuses it; the saving card's own row is part of it.
+func TestEnvSaveOtherCardAddRow(t *testing.T) {
+ setup := func(t *testing.T) (*envFx, url.Values) {
+ e := newEnvFx(t)
+ e.saving()
+ if _, err := appconfig.ApplyEnvironment(context.Background(), e.fx.rel, e.fx.sqid, "shop", "staging",
+ map[string]appconfig.Var{"LOG_LEVEL": {Kind: "env", Value: "debug"}}, nil); err != nil {
+ t.Fatal(err)
+ }
+ e.saving()
+ f := envFields(t, e.page(t))
+ f.Set("val.default.LOG_LEVEL", "warn")
+ return e, f
+ }
+ t.Run("another card", func(t *testing.T) {
+ e, f := setup(t)
+ f.Set("add.staging.name", "EXTRA")
+ f.Set("add.staging.value", "y")
+ status, body := e.post(t, f, "save")
+ if status != http.StatusBadRequest {
+ t.Fatalf("save = %d, want 400", status)
+ }
+ mustContain(t, envBanner(body), "You can change one environment at a time.")
+ e.noWrites(t)
+ })
+ t.Run("another card's sealed add", func(t *testing.T) {
+ e, f := setup(t)
+ f.Set("add.staging.name", "EXTRA")
+ f.Set("add.staging.secret", "1")
+ f.Del("add.staging.value")
+ f.Set("addenv.staging", e.seal(t, "x"))
+ if status, _ := e.post(t, f, "save"); status != http.StatusBadRequest {
+ t.Fatalf("save = %d, want 400", status)
+ }
+ e.noWrites(t)
+ })
+ t.Run("the saving card", func(t *testing.T) {
+ e, f := setup(t)
+ f.Set("add.default.name", "MODE")
+ f.Set("add.default.value", "fast")
+ status, body := e.post(t, f, "save")
+ if status != http.StatusOK {
+ t.Fatalf("save = %d:\n%s", status, envBanner(body))
+ }
+ mustContain(t, body, "Saved 2 changes to All environments.")
+ if m := e.stored(t); m.Vars["LOG_LEVEL"].Value != "warn" || m.Vars["MODE"].Value != "fast" {
+ t.Fatalf("stored = %+v", m.Vars)
+ }
+ })
+}
+
+// Only a URL-encoded form within the body cap and the field cap is read.
+func TestEnvFormBoundedInput(t *testing.T) {
+ e := newEnvFx(t)
+ e.saving()
+ f := envFields(t, e.page(t))
+ f.Set("val.default.LOG_LEVEL", "warn")
+ f.Set("op", "save")
+
+ var mp bytes.Buffer
+ mw := multipart.NewWriter(&mp)
+ for k, vs := range f {
+ for _, v := range vs {
+ _ = mw.WriteField(k, v)
+ }
+ }
+ part, _ := mw.CreateFormFile("upload", "x.bin")
+ _, _ = part.Write([]byte("unexpected file"))
+ _ = mw.Close()
+ if status, _ := e.rawPost(t, mw.FormDataContentType(), mp.String()); status != http.StatusUnsupportedMediaType {
+ t.Fatalf("multipart = %d, want 415", status)
+ }
+ if status, _ := e.rawPost(t, "text/plain", f.Encode()); status != http.StatusUnsupportedMediaType {
+ t.Fatalf("text/plain = %d, want 415", status)
+ }
+ big := f.Encode() + "&new.default.PAD=" + strings.Repeat("a", configPutMaxBytes)
+ if status, _ := e.rawPost(t, "application/x-www-form-urlencoded", big); status != http.StatusRequestEntityTooLarge {
+ t.Fatalf("over the body cap = %d, want 413", status)
+ }
+ many := f.Encode() + strings.Repeat("&rm.default=X", envFormMaxFields)
+ if status, _ := e.rawPost(t, "application/x-www-form-urlencoded", many); status != http.StatusRequestEntityTooLarge {
+ t.Fatalf("over the field cap = %d, want 413", status)
+ }
+ e.noWrites(t)
+ if got := e.stored(t).Vars["LOG_LEVEL"].Value; got != "info" {
+ t.Fatalf("stored LOG_LEVEL = %q", got)
+ }
+}
+
+// A bundle that will not read keeps the posted draft (values, envelopes,
+// their keys, versions) with Save off; once it reads again, the carried
+// draft saves.
+func TestEnvSaveReadRefusalKeepsDraft(t *testing.T) {
+ e := newEnvFx(t)
+ e.saving()
+ f := envFields(t, e.page(t))
+ env := e.seal(t, "carried")
+ f.Set("add.default.name", "WEBHOOK_SECRET")
+ f.Set("add.default.secret", "1")
+ f.Del("add.default.value")
+ f.Set("addenv.default", env)
+ status, body := e.post(t, f, "add:default")
+ if status != http.StatusOK {
+ t.Fatalf("add = %d", status)
+ }
+ f = envFields(t, body)
+ f.Set("new.default.MODE", "fast")
+ ver := f.Get("ver.default")
+
+ e.spy.mu.Lock()
+ e.spy.failGet = appconfig.Key(e.fx.sqid, "shop")
+ e.spy.mu.Unlock()
+ status, body = e.post(t, f, "save")
+ if status != http.StatusConflict {
+ t.Fatalf("save on an unreadable bundle = %d", status)
+ }
+ e.noWrites(t)
+ mustContain(t, body, `name="new.default.MODE" value="fast"`, `name="newenv.default.WEBHOOK_SECRET" value="`,
+ `name="fp.default.WEBHOOK_SECRET" value="`+f.Get("sealed_to")+`"`, `name="ver.default" value="`+ver+`"`,
+ `name="op" value="stage" data-seal-skip>Try again</button>`)
+ mustNotContain(t, body, `name="op" value="save"`)
+ if got := envFields(t, body).Get("newenv.default.WEBHOOK_SECRET"); got != env {
+ t.Fatalf("carried envelope = %q", got)
+ }
+
+ e.spy.mu.Lock()
+ e.spy.failGet = ""
+ e.spy.mu.Unlock()
+ if status, body = e.post(t, envFields(t, body), "save"); status != http.StatusOK {
+ t.Fatalf("save once it reads = %d:\n%s", status, envBanner(body))
+ }
+ if m := e.stored(t); m.Vars["MODE"].Value != "fast" || m.Vars["WEBHOOK_SECRET"].Envelope != env {
+ t.Fatalf("stored = %+v", m.Vars)
+ }
+}
+
+// CSRF comes before membership and the app (a bad token reads the same for
+// a real app and an unknown one), and every op spends the write budget.
+func TestEnvFormGateOrderAndBudget(t *testing.T) {
+ e := newEnvFx(t)
+ form := url.Values{"csrf": {"not-the-token"}, "op": {"stage"}}
+ s1, _, real := postForm(t, e.c, e.fx.u("/apps/shop/settings/environments"), form)
+ s2, _, ghost := postForm(t, e.c, e.fx.u("/apps/no-such-app/settings/environments"), form)
+ if s1 != http.StatusForbidden || s2 != s1 || real != ghost {
+ t.Fatalf("bad CSRF: real %d, unknown %d; want identical 403s", s1, s2)
+ }
+ f := envFields(t, e.page(t))
+ for i := 0; i < cliWriteBurst+3; i++ {
+ status, body := e.post(t, f, "stage")
+ if status == http.StatusOK {
+ continue
+ }
+ if status != http.StatusTooManyRequests || i == 0 {
+ t.Fatalf("stage %d = %d", i, status)
+ }
+ mustNotContain(t, body, "data-env-form")
+ e.spy.none(t)
+ return
+ }
+ t.Fatalf("staging was never rate-limited in %d posts", cliWriteBurst+3)
+}
diff --git a/internal/console/envsave.go b/internal/console/envsave.go
index ba0129f19..a3464d256 100644
--- a/internal/console/envsave.go
+++ b/internal/console/envsave.go
@@ -15,7 +15,6 @@ import (
"fmt"
"net/http"
"sort"
- "time"
"github.com/carlosframework/platform/internal/appconfig"
)
@@ -121,11 +120,19 @@ func (s *Server) envFormSave(w http.ResponseWriter, r *http.Request, p page, acc
s.render(w, http.StatusOK, "app_settings", p)
return
}
- if !s.allowWrite(Principal{Kind: PrincipalUser, Address: addr}, time.Now()) {
- applyEnvDraft(sv, d, nil)
- sv.EnvError = c.RateLimited
- s.render(w, http.StatusTooManyRequests, "app_settings", p)
- return
+ // Every envelope must have been sealed to the key the app's boxes hold
+ // now. Each carries the key that sealed it; one sealed before the key
+ // changed is refused here, with every envelope dropped (they all came
+ // from pages that sealed to the old key) and the rest kept.
+ if seal := sv.EnvSeal; seal != nil {
+ for _, sec := range d.Secrets {
+ if sec.FP != seal.SealedTo {
+ d.Secrets = map[string]envSecret{}
+ applyEnvDraft(sv, d, &envFormRefusal{Code: envRefuseKeyChange})
+ s.render(w, http.StatusConflict, "app_settings", p)
+ return
+ }
+ }
}
ctx := r.Context()
card := envCardFor(sv.Envs, d.Bundle)
@@ -138,7 +145,7 @@ func (s *Server) envFormSave(w http.ResponseWriter, r *http.Request, p page, acc
if !verOK || card == nil {
ref = &configRefusal{Code: configRefusalConflict, Status: http.StatusConflict}
} else {
- in, unset := d.writeInput(r.PostFormValue("sealed_to"))
+ in, unset := d.writeInput()
removed, ref = s.writeConfig(ctx, acct, p.AppName, d.envName(), &want, in, unset)
if ref == nil {
bundle := configBundleName(d.envName())
@@ -178,7 +185,7 @@ func (s *Server) envFormSave(w http.ResponseWriter, r *http.Request, p page, acc
case configRefusalKeylessFleet, configRefusalSealedWrongKey, configRefusalSealedUnchecked, configRefusalSealedOld:
// Every secret on the page was sealed by the same page to the same
// key: if one is refused for its key, all of them would be.
- d.Secrets = map[string]string{}
+ d.Secrets = map[string]envSecret{}
default:
if ref.Var != "" {
d.drop(ref.Var)
@@ -198,16 +205,9 @@ func (s *Server) envFormSave(w http.ResponseWriter, r *http.Request, p page, acc
// Retry form carries, and no write. Only names are read from it, each
// checked; anything else is refused rather than classified as something
// it is not (fewer keys would hide a route the shadowing test should show).
-func (s *Server) envFormCheck(w http.ResponseWriter, r *http.Request, p page, acct *Account, addr string) {
+func (s *Server) envFormCheck(w http.ResponseWriter, r *http.Request, p page, acct *Account) {
sv := p.Settings
c := sv.EnvCopy
- // The same budget as Save: each check reads the app's records and box
- // reports.
- if !s.allowWrite(Principal{Kind: PrincipalUser, Address: addr}, time.Now()) {
- sv.EnvError = c.CheckLimited
- s.render(w, http.StatusTooManyRequests, "app_settings", p)
- return
- }
bundle := r.PostFormValue("check_bundle")
card := envCardFor(sv.Envs, bundle)
keys := r.PostForm["check_key"]
@@ -272,30 +272,22 @@ func envOpenRow(sv *SettingsView, bundle, name string) {
}
// rebase is d's ordinary changes over card as it is now, at its version:
-// changed values and new settings kept where they still differ (a setting
-// someone else made secret is theirs now), removals of what is still
-// there. Secrets are dropped.
+// every ordinary set kept (normalize draws it as the row's change, a new
+// row, or a secret's replacement, and drops only one that now equals what
+// is stored), removals of what is still there. Secrets are dropped.
func (d *envDraft) rebase(card *EnvCard) *envDraft {
nd := newEnvDraft(card)
- put := func(k, v string) {
- stored, ok := card.stored[k]
- switch {
- case !ok:
- nd.New[k] = v
- case stored.Kind != "secret" && stored.Value != v:
- nd.Values[k] = v
- }
- }
for k, v := range d.Values {
- put(k, v)
+ nd.New[k] = v
}
for k, v := range d.New {
- put(k, v)
+ nd.New[k] = v
}
for _, k := range d.Unset {
if _, ok := card.stored[k]; ok {
nd.Unset = append(nd.Unset, k)
}
}
+ nd.normalize()
return nd
}
diff --git a/internal/console/envsave_test.go b/internal/console/envsave_test.go
index 2dcc259ae..db293a949 100644
--- a/internal/console/envsave_test.go
+++ b/internal/console/envsave_test.go
@@ -219,7 +219,9 @@ func TestEnvSaveRefusalsPersonCopy(t *testing.T) {
t.Fatalf("wrote %v", w)
}
})
- t.Run("sealed-wrong-key", func(t *testing.T) {
+ t.Run("key-changed", func(t *testing.T) {
+ // An envelope that says it was sealed to a key other than the app's
+ // now: refused at this door, every envelope dropped.
e := newEnvFx(t)
e.saving()
f := envFields(t, e.page(t))
@@ -227,10 +229,10 @@ func TestEnvSaveRefusalsPersonCopy(t *testing.T) {
f.Set("env.default.STRIPE_KEY", env)
f.Set("sealed_to", strings.Repeat("0", 64))
status, body := e.post(t, f, "save")
- if status != http.StatusBadRequest {
+ if status != http.StatusConflict {
t.Fatalf("status = %d", status)
}
- mustContain(t, body, "STRIPE_KEY was sealed to a key this app&#39;s servers don&#39;t have. Reload the page and enter it again.")
+ mustContain(t, envBanner(body), "This app&#39;s secrets key changed after you entered your secrets, so they were not saved. Enter your secrets again.")
mustNotContain(t, body, env)
if w := e.written(); len(w) != 0 {
t.Fatalf("wrote %v", w)
@@ -285,20 +287,24 @@ func TestEnvSaveRefusalsPersonCopy(t *testing.T) {
withKey bool
edit func(url.Values, skFleetKey, *consoleFixture) string
}{
- {"sealed-unchecked", "Example Cloud couldn&#39;t check which key sealed API_KEY.", true, func(f url.Values, k skFleetKey, fx *consoleFixture) string {
+ // No key named for the envelope: this door cannot say it is the
+ // fleet's, so it is refused as sealed to another key.
+ {"unchecked", "This app&#39;s secrets key changed after you entered your secrets", true, func(f url.Values, k skFleetKey, fx *consoleFixture) string {
env := skSeal(t, fx, k.pub, true)
f.Set("newenv.default.API_KEY", env)
- f.Del("sealed_to")
+ f.Set("fp.default.API_KEY", "")
return env
}},
{"sealed-old", "API_KEY was sealed in an older format this app&#39;s servers don&#39;t accept.", true, func(f url.Values, k skFleetKey, fx *consoleFixture) string {
env := skSeal(t, fx, k.pub, false)
f.Set("newenv.default.API_KEY", env)
+ f.Set("fp.default.API_KEY", k.fp)
return env
}},
{"keyless-fleet", "home has no secrets key yet, so secrets can&#39;t be set for this app.", false, func(f url.Values, k skFleetKey, fx *consoleFixture) string {
env := skSeal(t, fx, k.pub, true)
f.Set("newenv.default.API_KEY", env)
+ f.Set("fp.default.API_KEY", k.fp)
return env
}},
} {
@@ -327,13 +333,13 @@ func TestEnvSaveSealedToChecked(t *testing.T) {
other := skNewKey(t)
env := skSeal(t, fx, k.pub, true)
f.Set("newenv.default.API_KEY", env)
- f.Set("sealed_to", other.fp)
+ f.Set("fp.default.API_KEY", other.fp)
f.Set("op", "save")
status, _, body := postForm(t, c, fx.u("/apps/shop/settings/environments"), f)
- if status != http.StatusBadRequest {
- t.Fatalf("wrong sealed_to = %d:\n%s", status, body)
+ if status != http.StatusConflict {
+ t.Fatalf("wrong key = %d:\n%s", status, body)
}
- mustContain(t, envBanner(body), "API_KEY was sealed to a key this app&#39;s servers don&#39;t have.")
+ mustContain(t, envBanner(body), "This app&#39;s secrets key changed after you entered your secrets, so they were not saved.")
mustNotContain(t, body, env, "newenv.")
if m := skStored(t, fx); m != nil {
if _, ok := m.Vars["API_KEY"]; ok {
@@ -341,7 +347,7 @@ func TestEnvSaveSealedToChecked(t *testing.T) {
}
}
// The right key lands.
- f.Set("sealed_to", k.fp)
+ f.Set("fp.default.API_KEY", k.fp)
if status, _, body = postForm(t, c, fx.u("/apps/shop/settings/environments"), f); status != http.StatusOK {
t.Fatalf("right sealed_to = %d:\n%s", status, envBanner(body))
}
@@ -399,7 +405,7 @@ func TestEnvSaveOutcomeBuckets(t *testing.T) {
row("remote.shop.example.com", "chip-health-unknown\">Can&#39;t see"),
"addr.shop.example.com: your app runs this one itself. Restart it the way you started it.",
`worker.shop.example.com: a background worker. <a href="/a/`+e.fx.srv.mustAccountName(t)+`/apps/shop/instances">Check Running</a> and restart the app if it hasn&#39;t picked this up.`,
- "<code>carlos restart --host remote.shop.example.com</code>",
+ e.fx.srv.consoleName()+" can&#39;t check this copy from here. See Running to check it.",
"Copies on other boxes may not all be listed here.")
mustNotContain(t, out, "Nothing on this box uses", "unused", `name="op" value="check"`)
// Restart it yourself: each row its How sentence, and no control.
@@ -564,8 +570,10 @@ func TestEnvSaveRateLimited(t *testing.T) {
if i == 0 {
t.Fatal("the first save was refused")
}
- mustContain(t, envBanner(body), "Too many changes at once. Nothing was saved. Try again in a minute.")
- mustContain(t, body, fmt.Sprintf(`name="val.default.LOG_LEVEL" value="v%d"`, i))
+ // Refused at the door, before the page or a bundle is read: a
+ // message, no form drawn, nothing written.
+ mustContain(t, body, "Too many changes at once. Nothing was saved. Try again in a minute.")
+ mustNotContain(t, body, "data-env-form", fmt.Sprintf("v%d", i))
if got := e.stored(t).Vars["LOG_LEVEL"].Value; got != fmt.Sprintf("v%d", i-1) {
t.Fatalf("stored LOG_LEVEL = %q after a refused save, want v%d", got, i-1)
}
@@ -624,7 +632,7 @@ func TestEnvSaveCheckRateLimited(t *testing.T) {
if status != http.StatusTooManyRequests || i == 0 {
t.Fatalf("check %d = %d", i, status)
}
- mustContain(t, envBanner(body), "Too many checks at once. Try again in a minute.")
+ mustContain(t, body, "Too many checks at once. Try again in a minute.")
mustNotContain(t, body, `class="env-outcome"`)
// The same budget: a Save now is refused too.
f := envFields(t, e.page(t))
diff --git a/internal/console/templates/app_settings.html b/internal/console/templates/app_settings.html
index d18f34742..f288e814f 100644
--- a/internal/console/templates/app_settings.html
+++ b/internal/console/templates/app_settings.html
@@ -640,8 +640,9 @@ blocks deletion. Turn the safety delay off on the <a href="{{.Nav}}/apps/{{.AppN
<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>
+ {{- if not $s.EnvCarry}}{{/* carried as posted otherwise, sealed_to naming the key the carried envelopes were sealed to */}}
<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}}
+ {{with $seal}}<input type="hidden" name="sealed_to" value="{{.SealedTo}}">{{end}}{{end}}
{{range $s.Envs}}{{$b := .Bundle}}
<input type="hidden" name="ver.{{$b}}" value="{{.Version}}">
<h3 class="envhead">{{.Title}}</h3>
@@ -649,7 +650,7 @@ blocks deletion. Turn the safety delay off on the <a href="{{.Nav}}/apps/{{.AppN
{{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 or (eq .Staged "new") (eq .Staged "replaced")}}<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 eq .Staged "replaced"}}{{$c.Changed}}{{else 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"><span class="envvar-when-closed">{{$c.Edit}}</span><span class="envvar-when-open">{{$c.Close}}</span></span></summary>
<div class="envvar-panel settings-row">
@@ -664,6 +665,7 @@ blocks deletion. Turn the safety delay off on the <a href="{{.Nav}}/apps/{{.AppN
{{- 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">
+ <input type="hidden" name="orig.{{$b}}.{{.Name}}" value="{{.Orig}}">
{{- 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>
@@ -698,7 +700,8 @@ blocks deletion. Turn the safety delay off on the <a href="{{.Nav}}/apps/{{.AppN
{{- 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}}
+ <input type="hidden" name="newenv.{{$b}}.{{$k}}" value="{{$v.Envelope}}">
+ <input type="hidden" name="fp.{{$b}}.{{$k}}" value="{{$v.FP}}">{{end}}
{{- range .Unset}}
<input type="hidden" name="rm.{{$b}}" value="{{.}}">{{end}}
{{- end}}
@@ -706,13 +709,26 @@ blocks deletion. Turn the safety delay off on the <a href="{{.Nav}}/apps/{{.AppN
un-hidden by the script below on the first edit in a panel (Save
diffs val.* against the bundle shown), and always shown with scripts
off. */}}
+ {{- range $s.EnvCarry}}
+ <input type="hidden" name="{{.Name}}" value="{{.Value}}">{{end}}
+ {{- if $s.EnvCarry}}
+ {{/* The bundles could not be read: the draft rides along as posted, and
+ Save is off until they can be (Try again stages it against them). */}}
+ <div class="savebar">
+ <p class="small">{{$c.Unsaved}}</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="stage" data-seal-skip>{{$c.TryAgain}}</button>
+ </div>
+ </div>
+ {{- else}}
<div class="savebar"{{if or (not $d) $d.Empty}} hidden{{end}}>
<p class="small">{{if $s.EnvSummary}}{{$s.EnvSummary}}{{else}}{{$c.Unsaved}}{{end}}</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>
+ </div>{{end}}
<noscript><style>.savebar[hidden] { display: flex; }</style></noscript>
</form>
{{with $s.EnvOutcome}}{{template "app_settings_env_outcome" $}}{{end}}
@@ -764,10 +780,7 @@ blocks deletion. Turn the safety delay off on the <a href="{{.Nav}}/apps/{{.AppN
{{- if $o.NotRunning}}
<li><strong>{{$c.OutcomeNotRunning}}:</strong> {{$c.OutcomeNotRunHlp}}</li>{{end}}
{{- if $o.Unseen}}
- <li><strong>{{$c.OutcomeCantSee}}:</strong> {{$c.OutcomeCantHelp}}
- <ul>{{range $o.Unseen}}
- <li><code>{{$c.CantCmdLine .}}</code></li>{{end}}
- </ul></li>{{end}}
+ <li><strong>{{$c.OutcomeCantSee}}:</strong> {{$c.OutcomeCantHelp}}</li>{{end}}
{{- if $o.Blocked}}
<li><strong>{{$c.OutcomeBlocked}}:</strong> {{$c.OutcomeBlockedHlp}}
<ul>{{range $o.Blocked}}