diff --git a/.codescene/code-health-rules.json b/.codescene/code-health-rules.json index ddf445f..afa4138 100644 --- a/.codescene/code-health-rules.json +++ b/.codescene/code-health-rules.json @@ -10,7 +10,8 @@ { "matching_content_path": "pluginkit/settings/parse.go", "rules": [ - { "name": "String Heavy Function Arguments", "weight": 0.0 } + { "name": "String Heavy Function Arguments", "weight": 0.0 }, + { "name": "Primitive Obsession", "weight": 0.0 } ] } ] diff --git a/pluginkit/CHANGELOG.md b/pluginkit/CHANGELOG.md index e7e95b7..661f104 100644 --- a/pluginkit/CHANGELOG.md +++ b/pluginkit/CHANGELOG.md @@ -11,7 +11,7 @@ Releases of this module are tagged `pluginkit/vX.Y.Z`. Releases up to - `Failure.Reason` is the plugin's own error with nothing in front, and a recovered panic reads `panicked: `. `Failure.Err` keeps the whole text, so log lines read as before. - A boot whose context ends pauses nothing, and a store read or write that fails is returned to the application. - `pluginstoretest.Run` checks any `PluginStore` against the contract, and `pluginstoretest.NewMemory` is a store in memory that keeps it. -- `Installed` lists one `InstalledPlugin` per installed plugin, with the JSON names `id`, `name`, `description`, `version`, `status`, `paused_step` and `paused_reason`, sorted by name without regard to case, then by id. It leaves out a plugin the records hold as not installed and a record with no manifest, and lists a manifest with no record as active. The step and the reason are empty unless the plugin is paused. +- `Installed` lists one `InstalledPlugin` per installed plugin, with the JSON names `id`, `name`, `description`, `version`, `status`, `paused_step`, `paused_reason` and `has_settings`, sorted by name without regard to case, then by id. It leaves out a plugin the records hold as not installed and a record with no manifest, and lists a manifest with no record as active. The step and the reason are empty unless the plugin is paused, and `has_settings` is true when the manifest declares a setting. - `wire.Manifest` reads `description`, which no longer sits in `Extra`, a breaking change. - `wire.Manifest` reads `graphql` as `GraphQL`, which no longer sits in `Extra`, a breaking change. - `wire` rejects a manifest that spells a key it reads in another case, such as `Name`, repeats a name in one object, or holds text that is not valid UTF-8, as bytes or as an escaped surrogate with no pair, a breaking change. @@ -21,8 +21,13 @@ Releases of this module are tagged `pluginkit/vX.Y.Z`. Releases up to - `RoutesEach` reads each plugin's routes and public paths inside a recover, and fails at the new `StepRoutes` a plugin whose `Routes` or `PublicPaths` panics, or whose `Routes` answers no handler. - `settings.Check` checks the settings a plugin declares: seven types (`text`, `count`, `flag`, `duration`, `choice`, `secret`, `lines`), each key lowercase words joined by one underscore and outside the starts the application reserves, whole-number bounds on a count only, the options of a choice, a default for a count, a duration and a choice that its type accepts, a flag default of true or false, no default for a secret, and no `of`. A plugin with settings may not hold two hyphens in a row in its id or end it with one. - `settings.Name` names the variable of each setting from the application's prefix, the plugin's id and the key. -- `Schema.Resolve` works out each value from the environment values the application found, then from the default. An empty value counts as unset, and a value its type rejects is named by its variable. +- `Schema.Resolve` takes `Sources`, the environment values by variable name and the saved values by key, and works out each value from the environment, then the saved value, then the default, setting its `Source`. A blank environment value counts as unset, for a secret too, and one its type rejects is named by its variable. A saved value its type no longer takes is reported as a `RejectedSavedValue` so the default applies, and a saved secret is never taken. - A secret's value is a `settings.Hidden`, which prints, logs and encodes as `set` or `not set`. +- `settings.Field` keeps the `label` and `help` a manifest declares as `Label` and `Help`. +- `Schema.CheckChange` checks a change against the schema and the environment before it is saved, and answers its first problem as a `ChangeError` of the kind `unknown`, `locked` or `invalid`. +- A value its type rejects is a `settings.ValueError`, whose `Reason` is `not_whole`, `below_min`, `above_max`, `not_flag`, `not_duration`, `not_positive` or `not_option`, and whose text reads as before. A saved secret is reported with the reason `environment_only`. +- `Schema.FormFields` describes each field for a settings form as a `FormField`, in manifest order, and a secret only as set or not set. +- A duration `Value` keeps the text it was read from in `Text`, so `2h` stays `2h`. - `ScreenGate` is an optional interface whose `ShowsScreens` tells an application whether a plugin's admin menu entries and screens show for the caller in the context. - The module needs Go 1.27.4. diff --git a/pluginkit/features/features_test.go b/pluginkit/features/features_test.go index a875aa3..23abd25 100644 --- a/pluginkit/features/features_test.go +++ b/pluginkit/features/features_test.go @@ -66,6 +66,14 @@ func TestSettingsDeclarations(t *testing.T) { runFeature(t, "settings-declarations.feature", initializeSettings()) } +func TestSettingsSaved(t *testing.T) { + runFeature(t, "settings-saved.feature", initializeSettings()) +} + +func TestSettingsChanges(t *testing.T) { + runFeature(t, "settings-changes.feature", initializeSettings()) +} + func TestScreenGate(t *testing.T) { runFeature(t, "screen-gate.feature", initializeScreenGate(t)) } diff --git a/pluginkit/features/installed.feature b/pluginkit/features/installed.feature index 6dd7fe0..392d175 100644 --- a/pluginkit/features/installed.feature +++ b/pluginkit/features/installed.feature @@ -3,11 +3,11 @@ Feature: Listing the installed plugins WordPress lists its installed plugins. The list joins the manifest of each compiled plugin with the record the store keeps of it. Each row holds the plugin's id, the name, description and version its manifest - gives, and the state its record holds. A paused row also holds the step - the plugin failed at and its own error, kept apart, so a screen can - build its sentence for the step from a translated template. A plugin - the application has not installed and a record whose plugin is no - longer compiled are left out. + gives, whether it declares any settings, and the state its record + holds. A paused row also holds the step the plugin failed at and its + own error, kept apart, so a screen can build its sentence for the step + from a translated template. A plugin the application has not installed + and a record whose plugin is no longer compiled are left out. Scenario: An active plugin is listed with the name, description and version of its manifest Given the compiled plugins "feed" @@ -64,6 +64,16 @@ Feature: Listing the installed plugins When the application lists the installed plugins Then the list holds "feed" as "active" with no description and no version + Scenario: A plugin whose manifest declares a setting is listed with settings + Given the compiled plugins "events" and "feed" + And the manifest of "events" names it "Events" + And the manifest of "feed" names it "Feed" + And the manifest of "feed" declares the setting "title" + And the store holds no record + When the application lists the installed plugins + Then the list holds "feed" with settings + And the list holds "events" without settings + Scenario: The plugins are listed by name, then by id Given the compiled plugins "events", "feed" and "gallery" And the manifest of "events" names it "Calendar" diff --git a/pluginkit/features/settings-changes.feature b/pluginkit/features/settings-changes.feature new file mode 100644 index 0000000..ac6fb14 --- /dev/null +++ b/pluginkit/features/settings-changes.feature @@ -0,0 +1,126 @@ +Feature: Checking a change to a plugin's settings before it is saved + A downstream application lets an administrator change a plugin's + settings, and checks each change against the plugin's settings and the + environment before anything is saved. A change is accepted whole, or + rejected at its first problem with its kind, its key and why: a key the + plugin does not declare, a key the environment sets, a secret, which + comes from the environment only, or a value its type rejects. Keys the + plugin does not declare come first, sorted, then the declared fields in + the manifest's order. The application turns the kind and the reason into + its own answer. + + Background: + Given the application names plugin variables under "APP_PLUGIN_" + And the plugin "notes" declares these settings: + | key | type | default | min | max | options | + | title | text | Notes | | | | + | per_page | count | 10 | 1 | 50 | | + | open | flag | false | | | | + | keep_for | duration | 720h | | | | + | order | choice | newest | | | newest, oldest | + | tags | lines | news | | | | + | api_key | secret | | | | | + + Scenario: A change to declared settings is accepted + When a change to "notes" sets these settings: + | key | value | + | title | Field Notes | + | per_page | 25 | + | open | true | + | keep_for | 48h | + | order | oldest | + | tags | news, events | + Then the change is accepted + + Scenario: A change to a key the plugin does not declare is rejected as unknown + When a change to "notes" sets "colour" to "green" + Then the change is rejected as "unknown" for "colour" + + Scenario: A change to a field the environment sets is rejected as locked, naming its variable + Given the environment holds "Garden Notes" in "APP_PLUGIN_NOTES__TITLE" + When a change to "notes" sets "title" to "Field Notes" + Then the change is rejected as "locked" for "title" + And the rejection names the variable "APP_PLUGIN_NOTES__TITLE" + + Scenario: A blank value in the environment locks nothing + Given the environment holds " " in "APP_PLUGIN_NOTES__TITLE" + When a change to "notes" sets "title" to "Field Notes" + Then the change is accepted + + Scenario Outline: A value its type rejects is rejected as invalid with its reason + When a change to "notes" sets "" to "" + Then the change is rejected as "invalid" for "" with the reason "" + + Examples: + | key | value | reason | + | per_page | banana | not_whole | + | per_page | 2.5 | not_whole | + | per_page | 0 | below_min | + | per_page | 60 | above_max | + | open | maybe | not_flag | + | keep_for | soon | not_duration | + | keep_for | -1h | not_positive | + | order | random | not_option | + + Scenario Outline: A count out of its bounds gives the bound its check used + When a change to "notes" sets "" to "" + Then the change is rejected as "invalid" for "" with the reason "" + And the rejection gives only the + + Examples: + | key | value | reason | bound | limit | + | per_page | 0 | below_min | min | 1 | + | per_page | 60 | above_max | max | 50 | + + Scenario: A choice outside its options gives the options + When a change to "notes" sets "order" to "random" + Then the change is rejected as "invalid" for "order" with the reason "not_option" + And the rejection gives the options "newest, oldest" + + Scenario: A change to a secret is rejected, because a secret comes from the environment only + When a change to "notes" sets "api_key" to "key-for-example" + Then the change is rejected as "invalid" for "api_key" with the reason "environment_only" + And the reason does not hold "key-for-example" + + Scenario: A change to a secret the environment sets is rejected as locked + Given the environment holds "key-for-example" in "APP_PLUGIN_NOTES__API_KEY" + When a change to "notes" sets "api_key" to "another-key-for-example" + Then the change is rejected as "locked" for "api_key" + And the rejection names the variable "APP_PLUGIN_NOTES__API_KEY" + And the reason does not hold "key-for-example" + + Scenario Outline: An empty value is accepted for a text or a lines field + When a change to "notes" sets "" to "" + Then the change is accepted + + Examples: + | key | + | title | + | tags | + + Scenario Outline: An empty value is rejected for a type that has no empty value + When a change to "notes" sets "" to "" + Then the change is rejected as "invalid" for "" with the reason "" + + Examples: + | key | reason | + | per_page | not_whole | + | open | not_flag | + | keep_for | not_duration | + | order | not_option | + + Scenario: Keys the plugin does not declare are answered first, sorted + Given the environment holds "Garden Notes" in "APP_PLUGIN_NOTES__TITLE" + When a change to "notes" sets these settings: + | key | value | + | title | Field Notes | + | zebra | stripes | + | colour | green | + Then the change is rejected as "unknown" for "colour" + + Scenario: The declared fields are answered in the manifest's order + When a change to "notes" sets these settings: + | key | value | + | order | random | + | per_page | banana | + Then the change is rejected as "invalid" for "per_page" with the reason "not_whole" diff --git a/pluginkit/features/settings-saved.feature b/pluginkit/features/settings-saved.feature new file mode 100644 index 0000000..c2e9b88 --- /dev/null +++ b/pluginkit/features/settings-saved.feature @@ -0,0 +1,144 @@ +Feature: Working out each plugin setting from the environment, the saved value and its default + A downstream application lets an administrator save a plugin's settings + and hands the saved values in beside the environment values it found. + Each value comes from the environment, then the saved value, then the + default, and says where it came from. A value in the environment locks + its field, and the saved value under it waits. A saved empty text is a + real value. A saved value its type no longer takes falls back to the + default and is reported with its reason, so the plugin still starts. A + secret comes from the environment only, so a saved one is never taken. + Each field is then described for a settings form, and a secret only as + set or not set. + + Background: + Given the application names plugin variables under "APP_PLUGIN_" + And the plugin "notes" declares these settings: + | key | type | default | min | max | options | label | help | + | title | text | Notes | | | | Title | Shown above the notes. | + | per_page | count | 10 | 1 | 50 | | Per page | | + | open | flag | false | | | | Open | | + | keep_for | duration | 720h | | | | Keep for | | + | order | choice | newest | | | newest, oldest | Order | | + | tags | lines | news | | | | Tags | | + | api_key | secret | | | | | API key | | + + Scenario Outline: A saved value wins over the default + Given "" is saved as "" + When the settings of "notes" are worked out + Then "" reads "" + And the source of "" is "saved" + And no saved value is reported as rejected + + Examples: + | key | value | read | + | title | Field Notes | Field Notes | + | per_page | 25 | 25 | + | open | true | true | + | keep_for | 48h | 48h | + | order | oldest | oldest | + | tags | news,, events | news, events | + + Scenario: A setting nobody saved and the environment does not hold takes its default + When the settings of "notes" are worked out + Then "title" reads "Notes" + And the source of "title" is "default" + + Scenario: A value in the environment wins over a saved value and locks its field + Given "title" is saved as "Field Notes" + And the environment holds "Garden Notes" in "APP_PLUGIN_NOTES__TITLE" + When the settings of "notes" are worked out + Then "title" reads "Garden Notes" + And the source of "title" is "environment" + And the form shows "title" locked by "APP_PLUGIN_NOTES__TITLE" + + Scenario: A blank value in the environment counts as unset, so the saved value applies + Given "title" is saved as "Field Notes" + And the environment holds " " in "APP_PLUGIN_NOTES__TITLE" + When the settings of "notes" are worked out + Then "title" reads "Field Notes" + And the source of "title" is "saved" + + Scenario: A saved value under a value in the environment is not read + Given "per_page" is saved as "banana" + And the environment holds "25" in "APP_PLUGIN_NOTES__PER_PAGE" + When the settings of "notes" are worked out + Then "per_page" reads "25" + And no saved value is reported as rejected + + Scenario Outline: A saved empty text is a real value and wins over the default + Given "" is saved as "" + When the settings of "notes" are worked out + Then "" reads "" + And the source of "" is "saved" + And the form shows "" with the value "" + + Examples: + | key | + | title | + | tags | + + Scenario Outline: A saved value its type no longer takes falls back to the default and is reported + Given "" is saved as "" + When the settings of "notes" are worked out + Then "" reads "" + And the source of "" is "default" + And the only saved value reported as rejected is "", with the reason "" + + Examples: + | key | value | read | reason | + | per_page | banana | 10 | not_whole | + | per_page | | 10 | not_whole | + | per_page | 0 | 10 | below_min | + | per_page | 60 | 10 | above_max | + | open | maybe | false | not_flag | + | keep_for | soon | 720h | not_duration | + | keep_for | -1h | 720h | not_positive | + | order | random | newest | not_option | + + Scenario: A saved secret is never taken and never shows + Given "api_key" is saved as "key-for-example" + When the settings of "notes" are worked out + Then "api_key" reads "not set" + And the source of "api_key" is "default" + And the only saved value reported as rejected is "api_key", with the reason "environment_only" + And no saved value reported as rejected holds "key-for-example" + And the form shows "api_key" as not set + And no print, log or encoding of the settings holds "key-for-example" + And no encoding of the form fields holds "key-for-example" + + Scenario: A saved value under a key the plugin no longer declares is left out + Given "colour" is saved as "green" + When the settings of "notes" are worked out + Then no setting "colour" is worked out + And no saved value is reported as rejected + + Scenario: Each field is described for a settings form, in the manifest's order + Given "title" is saved as "Field Notes" + And the environment holds "25" in "APP_PLUGIN_NOTES__PER_PAGE" + And the environment holds "key-for-example" in "APP_PLUGIN_NOTES__API_KEY" + When the settings of "notes" are worked out + Then the form fields encode as: + """ + [ + {"key": "title", "type": "text", "label": "Title", "help": "Shown above the notes.", "default": "Notes", "value": "Field Notes", "source": "saved", "locked": false, "env": "APP_PLUGIN_NOTES__TITLE"}, + {"key": "per_page", "type": "count", "label": "Per page", "min": 1, "max": 50, "default": "10", "value": "25", "source": "environment", "locked": true, "env": "APP_PLUGIN_NOTES__PER_PAGE"}, + {"key": "open", "type": "flag", "label": "Open", "default": "false", "value": "false", "source": "default", "locked": false, "env": "APP_PLUGIN_NOTES__OPEN"}, + {"key": "keep_for", "type": "duration", "label": "Keep for", "default": "720h", "value": "720h", "source": "default", "locked": false, "env": "APP_PLUGIN_NOTES__KEEP_FOR"}, + {"key": "order", "type": "choice", "label": "Order", "options": ["newest", "oldest"], "default": "newest", "value": "newest", "source": "default", "locked": false, "env": "APP_PLUGIN_NOTES__ORDER"}, + {"key": "tags", "type": "lines", "label": "Tags", "default": "news", "value": "news", "source": "default", "locked": false, "env": "APP_PLUGIN_NOTES__TAGS"}, + {"key": "api_key", "type": "secret", "label": "API key", "set": true, "source": "environment", "locked": true, "env": "APP_PLUGIN_NOTES__API_KEY"} + ] + """ + And no encoding of the form fields holds "key-for-example" + + Scenario Outline: A count and a flag are described in their plain form, a duration as written + Given the environment holds "" in "" + When the settings of "notes" are worked out + Then the form shows "" with the value "" + + Examples: + | key | variable | value | shown | + | per_page | APP_PLUGIN_NOTES__PER_PAGE | 020 | 20 | + | open | APP_PLUGIN_NOTES__OPEN | 1 | true | + | keep_for | APP_PLUGIN_NOTES__KEEP_FOR | 2h | 2h | + | tags | APP_PLUGIN_NOTES__TAGS | news,, events | news, events | diff --git a/pluginkit/features/steps_installed_test.go b/pluginkit/features/steps_installed_test.go index 9ec28c8..6d2b1a6 100644 --- a/pluginkit/features/steps_installed_test.go +++ b/pluginkit/features/steps_installed_test.go @@ -19,24 +19,31 @@ type installedWorld struct { named map[string]string described map[string]string versions map[string]string + settings map[string][]wire.Setting listed []pluginkit.InstalledPlugin } +// declaresSetting has the manifest of the plugin id declare a text setting under key. +func (w *installedWorld) declaresSetting(id, key string) { + w.settings[id] = append(w.settings[id], wire.Setting{Key: key, Type: "text"}) +} + // list joins the manifest of each compiled plugin with the store's records, as an application lists its plugins. func (w *installedWorld) list() { manifests := make([]wire.Manifest, 0, len(w.boot.compiled)) for _, id := range w.boot.compiled { manifests = append(manifests, wire.Manifest{ - ID: id, Name: w.named[id], Description: w.described[id], Version: w.versions[id], + ID: id, Name: w.named[id], Description: w.described[id], Version: w.versions[id], Settings: w.settings[id], }) } w.listed = pluginkit.Installed(manifests, w.boot.seeds) } -// row returns the row the plugin id should have in state, with the name, description and version its manifest gives. +// row returns the row the plugin id should have in state, with the words and the settings its manifest gives. func (w *installedWorld) row(id string, state pluginkit.PluginState) pluginkit.InstalledPlugin { return pluginkit.InstalledPlugin{ ID: id, Name: w.named[id], Description: w.described[id], Version: w.versions[id], State: state, + HasSettings: len(w.settings[id]) > 0, } } @@ -69,6 +76,23 @@ func (w *installedWorld) holdsPaused(id, step, reason string) error { return w.holds(want) } +// holdsSettings checks that the row of the plugin id says it declares settings when with reads with, none otherwise. +func (w *installedWorld) holdsSettings(id, with string) error { + want := w.listedRow(id) + want.HasSettings = with == "with" + return w.holds(want) +} + +// listedRow returns the listed row of the plugin id, a row with only the id when the list holds none. +func (w *installedWorld) listedRow(id string) pluginkit.InstalledPlugin { + for _, plugin := range w.listed { + if plugin.ID == id { + return plugin + } + } + return pluginkit.InstalledPlugin{ID: id} +} + // namesInOrder checks that the list holds exactly the plugins of list, in order. func (w *installedWorld) namesInOrder(list string) error { ids := make([]string, 0, len(w.listed)) @@ -94,10 +118,11 @@ func initializeInstalled(t *testing.T) func(*godog.ScenarioContext) { return func(sc *godog.ScenarioContext) { w := &installedWorld{ boot: newBootWorld(t), named: map[string]string{}, described: map[string]string{}, - versions: map[string]string{}, + versions: map[string]string{}, settings: map[string][]wire.Setting{}, } givenBoot(sc, w.boot) sc.Step(`^the manifest of "([^"]*)" names it "([^"]*)"$`, func(id, name string) { set(w.named, id, name) }) + sc.Step(`^the manifest of "([^"]*)" declares the setting "([^"]*)"$`, w.declaresSetting) sc.Step(`^the manifest of "([^"]*)" describes it as "([^"]*)"$`, func(id, text string) { set(w.described, id, text) }) sc.Step(`^the manifest of "([^"]*)" gives the version "([^"]*)"$`, @@ -106,6 +131,7 @@ func initializeInstalled(t *testing.T) func(*godog.ScenarioContext) { sc.Step(`^the list holds "([^"]*)" as "(active|inactive)"$`, w.holdsAs) sc.Step(`^the list holds "([^"]*)" as "(active|inactive)" with no description and no version$`, w.holdsBare) sc.Step(`^the list holds "([^"]*)" as paused at "([^"]*)", its reason reading "(.*)"$`, w.holdsPaused) + sc.Step(`^the list holds "([^"]*)" (with|without) settings$`, w.holdsSettings) sc.Step(`^the list names ((?:"[^"]*"(?:, | and )?)+), in that order$`, w.namesInOrder) sc.Step(`^the list leaves out "([^"]*)"$`, w.leavesOut) } diff --git a/pluginkit/features/steps_settings_test.go b/pluginkit/features/steps_settings_test.go index eac0207..5e62c33 100644 --- a/pluginkit/features/steps_settings_test.go +++ b/pluginkit/features/steps_settings_test.go @@ -8,7 +8,9 @@ import ( "errors" "fmt" "log/slog" + "reflect" "regexp" + "slices" "strconv" "strings" "time" @@ -19,12 +21,15 @@ import ( "github.com/gopherium/framework/pluginkit/wire" ) -// settingsWorld is what one scenario of the settings features declares, finds and works out. +// settingsWorld is what one scenario of the settings features declares, finds, saves and works out. type settingsWorld struct { rules settings.Rules declared map[string][]wire.Setting found map[string]string + saved map[string]string + schema settings.Schema values settings.Values + rejected []settings.RejectedSavedValue err error } @@ -137,18 +142,28 @@ func columnsOf(table *godog.Table) map[string]int { return columns } -// settingOf reads the cells of one row of a settings table under columns. +// settingOf reads the cells of one row of a settings table under columns, the label and help only under their headings. func settingOf(cells []string, columns map[string]int) (wire.Setting, error) { cell := func(name string) string { return cells[columns[name]] } low, lowErr := boundOf(cell("min")) high, highErr := boundOf(cell("max")) setting := wire.Setting{ Key: cell("key"), Type: cell("type"), Default: cell("default"), + Label: optionalCell(cells, columns, "label"), Help: optionalCell(cells, columns, "help"), Min: low, Max: high, Options: optionsOf(cell("options")), } return setting, errors.Join(lowErr, highErr) } +// optionalCell returns the cell under the heading name, empty when the table has no such heading. +func optionalCell(cells []string, columns map[string]int, name string) string { + i, ok := columns[name] + if !ok { + return "" + } + return cells[i] +} + // namesUnder sets the prefix of every variable. func (w *settingsWorld) namesUnder(prefix string) { w.rules.Prefix = prefix @@ -200,6 +215,11 @@ func (w *settingsWorld) holds(value, variable string) { w.found[variable] = value } +// savedAs puts value among the values an administrator saved, under key. +func (w *settingsWorld) savedAs(key, value string) { + w.saved[key] = value +} + // declaredBy returns the settings plugin id declared, an error when the scenario declared none for it. func (w *settingsWorld) declaredBy(id string) ([]wire.Setting, error) { declared, ok := w.declared[id] @@ -232,16 +252,41 @@ func (w *settingsWorld) checked(id string) error { return nil } -// workedOut checks the settings of plugin id, then works them out from the environment and keeps what it answers. +// workedOut checks the settings of plugin id, then works them out from the environment and the saved values. func (w *settingsWorld) workedOut(id string) error { schema, err := w.schemaOf(id) if err != nil { return err } - w.values, w.err = schema.Resolve(w.found) + w.schema = schema + w.values, w.rejected, w.err = schema.Resolve(settings.Sources{Env: w.found, Saved: w.saved}) return nil } +// changed checks change against the settings of plugin id and the environment, and keeps its rejection. +func (w *settingsWorld) changed(id string, change map[string]string) error { + schema, err := w.schemaOf(id) + if err != nil { + return err + } + w.err = schema.CheckChange(change, w.found) + return nil +} + +// changes checks a change to plugin id that sets key to value. +func (w *settingsWorld) changes(id, key, value string) error { + return w.changed(id, map[string]string{key: value}) +} + +// changesTable checks a change to plugin id that sets each key of table to the value beside it. +func (w *settingsWorld) changesTable(id string, table *godog.Table) error { + change := make(map[string]string, len(table.Rows)-1) + for _, row := range table.Rows[1:] { + change[row.Cells[0].Value] = row.Cells[1].Value + } + return w.changed(id, change) +} + // variableOf returns the variable that sets key of plugin id. func (w *settingsWorld) variableOf(id, key string) (string, error) { schema, err := w.schemaOf(id) @@ -306,14 +351,31 @@ func written(kind, text string) string { return text } -// reads fails unless the worked out key reads want. -func (w *settingsWorld) reads(key, want string) error { +// resolved fails when working out the settings was rejected. +func (w *settingsWorld) resolved() error { if w.err != nil { return fmt.Errorf("the settings were rejected: %w", w.err) } + return nil +} + +// valueOf returns the worked out value of key, an error when the settings were rejected or hold no key. +func (w *settingsWorld) valueOf(key string) (settings.Value, error) { + if err := w.resolved(); err != nil { + return settings.Value{}, err + } value, ok := w.values[key] if !ok { - return fmt.Errorf("no setting %q was worked out", key) + return settings.Value{}, fmt.Errorf("no setting %q was worked out", key) + } + return value, nil +} + +// reads fails unless the worked out key reads want. +func (w *settingsWorld) reads(key, want string) error { + value, err := w.valueOf(key) + if err != nil { + return err } if got := reading(value); got != written(value.Type, want) { return fmt.Errorf("%s reads %q, want %q", key, got, want) @@ -321,6 +383,70 @@ func (w *settingsWorld) reads(key, want string) error { return nil } +// sourceIs fails unless the worked out key came from source. +func (w *settingsWorld) sourceIs(key, source string) error { + value, err := w.valueOf(key) + if err != nil { + return err + } + if value.Source != source { + return fmt.Errorf("%s came from %q, want %q", key, value.Source, source) + } + return nil +} + +// notWorkedOut fails unless the settings were worked out with no setting under key. +func (w *settingsWorld) notWorkedOut(key string) error { + if err := w.resolved(); err != nil { + return err + } + if _, ok := w.values[key]; ok { + return fmt.Errorf("a setting %q was worked out", key) + } + return nil +} + +// noneRejected fails unless the settings were worked out with no saved value reported as rejected. +func (w *settingsWorld) noneRejected() error { + if err := w.resolved(); err != nil { + return err + } + if len(w.rejected) != 0 { + return fmt.Errorf("%d saved values were reported as rejected, the first %q", len(w.rejected), w.rejected[0].Key) + } + return nil +} + +// onlyRejected fails unless key is the one saved value reported as rejected, with a value error of reason. +func (w *settingsWorld) onlyRejected(key, reason string) error { + if err := w.resolved(); err != nil { + return err + } + if len(w.rejected) != 1 { + return fmt.Errorf("%d saved values were reported as rejected, want 1", len(w.rejected)) + } + report := w.rejected[0] + var rejection *settings.ValueError + if !errors.As(report.Err, &rejection) { + return fmt.Errorf("the saved value %q was reported with %v, want a value error", report.Key, report.Err) + } + if report.Key != key || rejection.Reason != reason { + return fmt.Errorf("the saved value %q was reported as rejected with %q, want %q with %q", + report.Key, rejection.Reason, key, reason) + } + return nil +} + +// rejectedLacks fails when any print, log or encoding of a saved value reported as rejected or its error holds text. +func (w *settingsWorld) rejectedLacks(text string) error { + for _, report := range w.rejected { + if err := nowhereIn("the error of "+report.Key, report.Err, text); err != nil { + return err + } + } + return nowhereIn("the saved values reported as rejected", w.rejected, text) +} + // readsTable fails unless the worked out settings are those of table, each reading the value beside it. func (w *settingsWorld) readsTable(table *godog.Table) error { if got, want := len(w.values), len(table.Rows)-1; got != want { @@ -353,15 +479,12 @@ func (w *settingsWorld) passed() error { return nil } -// reasonLacks fails unless the last rejection is there and does not hold text. +// reasonLacks fails unless the last rejection is there and no print, log or encoding of it holds text. func (w *settingsWorld) reasonLacks(text string) error { if w.err == nil { return errors.New("nothing was rejected") } - if strings.Contains(w.err.Error(), text) { - return fmt.Errorf("the reason %q holds %q", w.err, text) - } - return nil + return nowhereIn("the reason", w.err, text) } // revealed fails unless the secret key reveals want. @@ -428,20 +551,196 @@ func (w *settingsWorld) showsAs(want, key string) error { return nil } -// nowhere fails when any print, log or encoding of the worked out settings holds text. -func (w *settingsWorld) nowhere(text string) error { +// nowhereIn fails when any print, log or encoding of value, named what, holds text. +func nowhereIn(what string, value any, text string) error { all := map[string]func(any) string{"%#v": printer("%#v")} for name, render := range renderers { all[name] = render } for name, render := range all { - if out := render(w.values); strings.Contains(out, text) { - return fmt.Errorf("%s of the settings holds %q: %s", name, text, out) + if out := render(value); strings.Contains(out, text) { + return fmt.Errorf("%s of %s holds %q: %s", name, what, text, out) } } return nil } +// nowhere fails when any print, log or encoding of the worked out settings holds text. +func (w *settingsWorld) nowhere(text string) error { + return nowhereIn("the settings", w.values, text) +} + +// formFieldOf returns the form field of key, described from the worked out settings. +func (w *settingsWorld) formFieldOf(key string) (settings.FormField, error) { + if err := w.resolved(); err != nil { + return settings.FormField{}, err + } + for _, field := range w.schema.FormFields(w.values) { + if field.Key == key { + return field, nil + } + } + return settings.FormField{}, fmt.Errorf("the form shows no field %q", key) +} + +// formLocked fails unless the form shows key locked by variable. +func (w *settingsWorld) formLocked(key, variable string) error { + field, err := w.formFieldOf(key) + if err != nil { + return err + } + if !field.Locked || field.Env != variable { + return fmt.Errorf("the form shows %s locked %t by %s, want locked by %s", key, field.Locked, field.Env, variable) + } + return nil +} + +// formValue fails unless the form shows key with the value want. +func (w *settingsWorld) formValue(key, want string) error { + field, err := w.formFieldOf(key) + if err != nil { + return err + } + if field.Value == nil { + return fmt.Errorf("the form shows %s with no value, want %q", key, want) + } + if *field.Value != want { + return fmt.Errorf("the form shows %s with the value %q, want %q", key, *field.Value, want) + } + return nil +} + +// formNotSet fails unless the form shows the secret key as not set, with no value. +func (w *settingsWorld) formNotSet(key string) error { + field, err := w.formFieldOf(key) + if err != nil { + return err + } + if field.Set == nil || *field.Set { + return fmt.Errorf("the form shows %s with set %s, want false", key, encoding(field.Set)) + } + if field.Value != nil { + return fmt.Errorf("the form shows the secret %s with a value", key) + } + return nil +} + +// formEncodes fails unless the form fields encode as the JSON of want, the order of keys aside. +func (w *settingsWorld) formEncodes(want *godog.DocString) error { + if err := w.resolved(); err != nil { + return err + } + data, err := json.Marshal(w.schema.FormFields(w.values)) + if err != nil { + return err + } + var got, wanted any + if err := errors.Join(json.Unmarshal(data, &got), json.Unmarshal([]byte(want.Content), &wanted)); err != nil { + return err + } + if !reflect.DeepEqual(got, wanted) { + return fmt.Errorf("the form fields encode as %s, want %s", data, want.Content) + } + return nil +} + +// formLacks fails when any print, log or encoding of the form fields holds text. +func (w *settingsWorld) formLacks(text string) error { + if err := w.resolved(); err != nil { + return err + } + return nowhereIn("the form fields", w.schema.FormFields(w.values), text) +} + +// changeError returns the rejection of the last change as a change error, an error when it holds none. +func (w *settingsWorld) changeError() (*settings.ChangeError, error) { + var problem *settings.ChangeError + if !errors.As(w.err, &problem) { + return nil, fmt.Errorf("the change was not rejected as a change error: %v", w.err) + } + return problem, nil +} + +// changeAccepted fails unless the last change was accepted. +func (w *settingsWorld) changeAccepted() error { + if w.err != nil { + return fmt.Errorf("the change was rejected: %w", w.err) + } + return nil +} + +// rejectedAs returns the rejection of the last change, an error unless it is of kind for key. +func (w *settingsWorld) rejectedAs(kind, key string) (*settings.ChangeError, error) { + problem, err := w.changeError() + if err != nil { + return nil, err + } + if problem.Kind != kind || problem.Key != key { + return nil, fmt.Errorf("the change was rejected as %q for %q, want %q for %q", problem.Kind, problem.Key, kind, key) + } + return problem, nil +} + +// changeRejected fails unless the last change was rejected as kind for key. +func (w *settingsWorld) changeRejected(kind, key string) error { + _, err := w.rejectedAs(kind, key) + return err +} + +// changeRejectedWith fails unless the last change was rejected as kind for key with reason. +func (w *settingsWorld) changeRejectedWith(kind, key, reason string) error { + problem, err := w.rejectedAs(kind, key) + if err != nil { + return err + } + if problem.Reason != reason { + return fmt.Errorf("the change to %s was rejected with the reason %q, want %q", key, problem.Reason, reason) + } + return nil +} + +// namesVariable fails unless the rejection of the last change names variable. +func (w *settingsWorld) namesVariable(variable string) error { + problem, err := w.changeError() + if err != nil { + return err + } + if problem.Env != variable { + return fmt.Errorf("the rejection names the variable %q, want %q", problem.Env, variable) + } + return nil +} + +// givesOnly fails unless the rejection of the last change gives the bound which at limit, and no other bound or option. +func (w *settingsWorld) givesOnly(which string, limit int) error { + problem, err := w.changeError() + if err != nil { + return err + } + want := settings.ChangeError{Max: &limit} + if which == "min" { + want = settings.ChangeError{Min: &limit} + } + got := settings.ChangeError{Min: problem.Min, Max: problem.Max, Options: problem.Options} + if !reflect.DeepEqual(got, want) { + return fmt.Errorf("the rejection gives the min %s, the max %s and the options %q, want only the %s %d", + encoding(problem.Min), encoding(problem.Max), problem.Options, which, limit) + } + return nil +} + +// givesOptions fails unless the rejection of the last change gives the options of the comma list. +func (w *settingsWorld) givesOptions(list string) error { + problem, err := w.changeError() + if err != nil { + return err + } + if want := optionsOf(list); !slices.Equal(problem.Options, want) { + return fmt.Errorf("the rejection gives the options %q, want %q", problem.Options, want) + } + return nil +} + // givenSettings binds the steps that set up a settings scenario. func givenSettings(sc *godog.ScenarioContext, w *settingsWorld) { sc.Step(`^the application names plugin variables under "([^"]*)"$`, w.namesUnder) @@ -450,12 +749,15 @@ func givenSettings(sc *godog.ScenarioContext, w *settingsWorld) { sc.Step(`^the plugin "([^"]*)" declares no settings$`, w.declaresNone) sc.Step(`^the plugin "([^"]*)" declares (a .+|the text setting .+)$`, w.declares) sc.Step(`^the environment holds "([^"]*)" in "([^"]*)"$`, w.holds) + sc.Step(`^"([^"]*)" is saved as "([^"]*)"$`, w.savedAs) } -// whenSettings binds the steps that check and work out the settings. +// whenSettings binds the steps that check and work out the settings and check a change to them. func whenSettings(sc *godog.ScenarioContext, w *settingsWorld) { sc.Step(`^the settings of "([^"]*)" are checked$`, w.checked) sc.Step(`^the settings of "([^"]*)" are worked out$`, w.workedOut) + sc.Step(`^a change to "([^"]*)" sets "([^"]*)" to "([^"]*)"$`, w.changes) + sc.Step(`^a change to "([^"]*)" sets these settings:$`, w.changesTable) } // thenSettings binds the steps that check what the settings read and why they were rejected. @@ -473,12 +775,43 @@ func thenSettings(sc *godog.ScenarioContext, w *settingsWorld) { sc.Step(`^no print, log or encoding of the settings holds "([^"]*)"$`, w.nowhere) } +// thenSaved binds the steps that check where each value came from and which saved values were reported. +func thenSaved(sc *godog.ScenarioContext, w *settingsWorld) { + sc.Step(`^the source of "([^"]*)" is "([^"]*)"$`, w.sourceIs) + sc.Step(`^no setting "([^"]*)" is worked out$`, w.notWorkedOut) + sc.Step(`^no saved value is reported as rejected$`, w.noneRejected) + sc.Step(`^the only saved value reported as rejected is "([^"]*)", with the reason "([^"]*)"$`, w.onlyRejected) + sc.Step(`^no saved value reported as rejected holds "([^"]*)"$`, w.rejectedLacks) +} + +// thenForm binds the steps that check how each field is described for a settings form. +func thenForm(sc *godog.ScenarioContext, w *settingsWorld) { + sc.Step(`^the form shows "([^"]*)" locked by "([^"]*)"$`, w.formLocked) + sc.Step(`^the form shows "([^"]*)" with the value "([^"]*)"$`, w.formValue) + sc.Step(`^the form shows "([^"]*)" as not set$`, w.formNotSet) + sc.Step(`^the form fields encode as:$`, w.formEncodes) + sc.Step(`^no encoding of the form fields holds "([^"]*)"$`, w.formLacks) +} + +// thenChange binds the steps that check whether a change was accepted and why it was rejected. +func thenChange(sc *godog.ScenarioContext, w *settingsWorld) { + sc.Step(`^the change is accepted$`, w.changeAccepted) + sc.Step(`^the change is rejected as "([^"]*)" for "([^"]*)"$`, w.changeRejected) + sc.Step(`^the change is rejected as "([^"]*)" for "([^"]*)" with the reason "([^"]*)"$`, w.changeRejectedWith) + sc.Step(`^the rejection names the variable "([^"]*)"$`, w.namesVariable) + sc.Step(`^the rejection gives only the (min|max) (-?\d+)$`, w.givesOnly) + sc.Step(`^the rejection gives the options "([^"]*)"$`, w.givesOptions) +} + // initializeSettings gives each scenario of the settings features a world of its own and its steps. func initializeSettings() func(*godog.ScenarioContext) { return func(sc *godog.ScenarioContext) { - w := &settingsWorld{declared: map[string][]wire.Setting{}, found: map[string]string{}} + w := &settingsWorld{declared: map[string][]wire.Setting{}, found: map[string]string{}, saved: map[string]string{}} givenSettings(sc, w) whenSettings(sc, w) thenSettings(sc, w) + thenSaved(sc, w) + thenForm(sc, w) + thenChange(sc, w) } } diff --git a/pluginkit/installed.go b/pluginkit/installed.go index 0babe3a..bc2b043 100644 --- a/pluginkit/installed.go +++ b/pluginkit/installed.go @@ -10,7 +10,7 @@ import ( "github.com/gopherium/framework/pluginkit/wire" ) -// InstalledPlugin is one compiled plugin a Plugins screen lists, with its state and why it paused. +// InstalledPlugin is one compiled plugin a Plugins screen lists: its state, why it paused and whether it has settings. type InstalledPlugin struct { ID string `json:"id"` Name string `json:"name"` @@ -19,6 +19,7 @@ type InstalledPlugin struct { State PluginState `json:"status"` PausedStep Step `json:"paused_step"` PausedReason string `json:"paused_reason"` + HasSettings bool `json:"has_settings"` } // Installed lists each manifest the records hold as installed, by name then id, one with no record as active. @@ -46,7 +47,7 @@ func byName(a, b InstalledPlugin) int { func installedFrom(manifest wire.Manifest, record PluginRecord) InstalledPlugin { plugin := InstalledPlugin{ ID: manifest.ID, Name: manifest.Name, Description: manifest.Description, Version: manifest.Version, - State: record.State, + State: record.State, HasSettings: len(manifest.Settings) > 0, } if record.State == PluginPaused { plugin.PausedStep, plugin.PausedReason = record.Step, record.LastError diff --git a/pluginkit/installed_test.go b/pluginkit/installed_test.go index 12656d7..3fbdd28 100644 --- a/pluginkit/installed_test.go +++ b/pluginkit/installed_test.go @@ -160,6 +160,22 @@ func TestInstalledComparesNamesWithoutRegardToCase(t *testing.T) { wantEqual(t, "ids", idsOf(got), []string{"lower", "upper", "bold", "zines"}) } +func TestInstalledSaysWhetherAPluginDeclaresSettings(t *testing.T) { + t.Parallel() + + feed := feedManifest() + feed.Settings = []wire.Setting{{Key: "title", Type: "text"}} + manifests := []wire.Manifest{manifestOf("events", "Events"), feed} + + got := pluginkit.Installed(manifests, nil) + + withSettings := feedRow(pluginkit.PluginActive) + withSettings.HasSettings = true + wantEqual(t, "listed", got, []pluginkit.InstalledPlugin{ + {ID: "events", Name: "Events", State: pluginkit.PluginActive}, withSettings, + }) +} + func TestInstalledAnswersAnEmptyListThatEncodesAsOne(t *testing.T) { t.Parallel() @@ -175,11 +191,12 @@ func TestInstalledPluginEncodesUnderTheNamesAScreenReads(t *testing.T) { t.Parallel() row := feedRow(pluginkit.PluginPaused) - row.PausedStep, row.PausedReason = pluginkit.StepStart, "no route table" + row.PausedStep, row.PausedReason, row.HasSettings = pluginkit.StepStart, "no route table", true data, err := json.Marshal(row) assertErrorFree(t, err) wantEqual(t, "JSON", string(data), `{"id":"feed","name":"Feed","description":"`+feedDescription+ - `","version":"0.0.1","status":"paused","paused_step":"start","paused_reason":"no route table"}`) + `","version":"0.0.1","status":"paused","paused_step":"start","paused_reason":"no route table",`+ + `"has_settings":true}`) } diff --git a/pluginkit/settings/change.go b/pluginkit/settings/change.go new file mode 100644 index 0000000..9a4dced --- /dev/null +++ b/pluginkit/settings/change.go @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "errors" + "fmt" + "maps" + "math" + "slices" + "strings" +) + +const ( + // KindUnknown is the kind of a change to a key the schema does not declare. + KindUnknown = "unknown" + // KindLocked is the kind of a change to a field whose variable holds a value. + KindLocked = "locked" + // KindInvalid is the kind of a change to a value its field rejects. + KindInvalid = "invalid" +) + +// ChangeError is the first problem a change holds, with the bound the check used in Min or Max. +type ChangeError struct { + Kind string + Key string + Env string + Reason string + Min *int + Max *int + Options []string +} + +// Error returns the key and its problem. +func (e *ChangeError) Error() string { + switch e.Kind { + case KindUnknown: + return e.Key + ": no setting has this key" + case KindLocked: + return e.Key + ": locked by " + e.Env + } + return e.Key + ": value rejected as " + e.Reason +} + +// CheckChange checks a change against the schema and the environment, answering the first problem it holds. +func (s Schema) CheckChange(change, env map[string]string) error { + if key, found := s.undeclared(change); found { + return &ChangeError{Kind: KindUnknown, Key: key} + } + for _, field := range s.Fields { + value, changed := change[field.Key] + if !changed { + continue + } + if err := field.checkChange(value, env[field.Env]); err != nil { + return err + } + } + return nil +} + +// undeclared returns the first key of change in sorted order that the schema does not declare, and whether one is. +func (s Schema) undeclared(change map[string]string) (string, bool) { + for _, key := range slices.Sorted(maps.Keys(change)) { + if !s.declares(key) { + return key, true + } + } + return "", false +} + +// declares reports whether the schema holds a field with key. +func (s Schema) declares(key string) bool { + return slices.ContainsFunc(s.Fields, func(field Field) bool { return field.Key == key }) +} + +// checkChange answers the problem of value as a change to the field while its variable holds held, nil for none. +func (f Field) checkChange(value, held string) error { + if strings.TrimSpace(held) != "" { + return &ChangeError{Kind: KindLocked, Key: f.Key, Env: f.Env} + } + if f.Type == TypeSecret { + return f.invalid(ReasonEnvironmentOnly) + } + parse, err := parserOf(f.Type) + if err != nil { + return fmt.Errorf("%s: %w", f.Key, err) + } + _, err = parse(f, value) + var rejection *ValueError + if errors.As(err, &rejection) { + return f.invalid(rejection.Reason) + } + return err +} + +// invalid returns the change error of a value the field rejects for reason, with the bound or options it names. +func (f Field) invalid(reason string) *ChangeError { + problem := &ChangeError{Kind: KindInvalid, Key: f.Key, Env: f.Env, Reason: reason} + switch reason { + case ReasonBelowMin: + floor := orElse(f.Min, math.MinInt) + problem.Min = &floor + case ReasonAboveMax: + ceiling := orElse(f.Max, math.MaxInt) + problem.Max = &ceiling + case ReasonNotOption: + problem.Options = slices.Clone(f.Options) + } + return problem +} diff --git a/pluginkit/settings/change_test.go b/pluginkit/settings/change_test.go new file mode 100644 index 0000000..f7c2a03 --- /dev/null +++ b/pluginkit/settings/change_test.go @@ -0,0 +1,366 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "errors" + "fmt" + "math" + "reflect" + "strconv" + "strings" + "testing" + + "github.com/gopherium/framework/pluginkit/wire" +) + +// anotherSecret is a second secret text a change may hold beside the one the environment holds. +const anotherSecret = "another-key-for-example" + +// changeSchema returns the checked schema of a plugin notes with a setting of each type and a count per set of bounds. +func changeSchema(t *testing.T) Schema { + t.Helper() + schema, err := Check("notes", []wire.Setting{ + {Key: "title", Type: TypeText, Default: "Notes"}, + {Key: "per_page", Type: TypeCount, Default: "10", Min: number(1), Max: number(50)}, + {Key: "total", Type: TypeCount, Default: "0"}, + {Key: "seats", Type: TypeCount, Default: "1", Min: number(1)}, + {Key: "slots", Type: TypeCount, Default: "1", Max: number(50)}, + {Key: "open", Type: TypeFlag, Default: "false"}, + {Key: "keep_for", Type: TypeDuration, Default: "720h"}, + {Key: "order", Type: TypeChoice, Default: "newest", Options: []string{"newest", "oldest"}}, + {Key: "tags", Type: TypeLines, Default: "news"}, + {Key: "api_key", Type: TypeSecret}, + }, appRules) + if err != nil { + t.Fatalf("Check = %v", err) + } + return schema +} + +// changeCase is one change, the environment beside it and the problem CheckChange answers, nil for none. +type changeCase struct { + change map[string]string + env map[string]string + want *ChangeError +} + +// runChanges checks the change of each case against the change schema and compares the problem it answers. +func runChanges(t *testing.T, cases []changeCase) { + t.Helper() + schema := changeSchema(t) + for _, c := range cases { + checkChangeCase(t, schema, c) + } +} + +// checkChangeCase checks one case's change against schema and reports any difference from the case. +func checkChangeCase(t *testing.T, schema Schema, c changeCase) { + t.Helper() + err := schema.CheckChange(c.change, c.env) + if c.want == nil { + if err != nil { + t.Errorf("CheckChange(%v, %v) = %v, want nil", c.change, c.env, err) + } + return + } + var got *ChangeError + if !errors.As(err, &got) { + t.Errorf("CheckChange(%v, %v) = %v, want the change error %s", c.change, c.env, err, described(c.want)) + return + } + if !reflect.DeepEqual(got, c.want) { + t.Errorf("CheckChange(%v, %v) = %s, want %s", c.change, c.env, described(got), described(c.want)) + } +} + +// described returns every field of a change error, the bounds by the numbers they point to. +func described(e *ChangeError) string { + return fmt.Sprintf("{Kind:%q Key:%q Env:%q Reason:%q Min:%s Max:%s Options:%#v}", + e.Kind, e.Key, e.Env, e.Reason, pointed(e.Min), pointed(e.Max), e.Options) +} + +// pointed returns the number n points to as text, nil when n is nil. +func pointed(n *int) string { + if n == nil { + return "nil" + } + return strconv.Itoa(*n) +} + +// invalidAs returns the change error of a value the field key of the change schema rejects for reason. +func invalidAs(key, reason string) *ChangeError { + return &ChangeError{Kind: KindInvalid, Key: key, Env: Name(appRules.Prefix, "notes", key), Reason: reason} +} + +// lockedBy returns the change error of the field key of the change schema, which its variable sets. +func lockedBy(key string) *ChangeError { + return &ChangeError{Kind: KindLocked, Key: key, Env: Name(appRules.Prefix, "notes", key)} +} + +// belowMin returns the change error of a value below floor, the bound the check of the field key used. +func belowMin(key string, floor int) *ChangeError { + problem := invalidAs(key, ReasonBelowMin) + problem.Min = &floor + return problem +} + +// aboveMax returns the change error of a value above ceiling, the bound the check of the field key used. +func aboveMax(key string, ceiling int) *ChangeError { + problem := invalidAs(key, ReasonAboveMax) + problem.Max = &ceiling + return problem +} + +// notOption returns the change error of a value that is none of the options of order. +func notOption() *ChangeError { + problem := invalidAs("order", ReasonNotOption) + problem.Options = []string{"newest", "oldest"} + return problem +} + +func TestKindsReadAsTheNamesAnApplicationSends(t *testing.T) { + cases := []struct { + got, want string + }{ + {KindUnknown, "unknown"}, + {KindLocked, "locked"}, + {KindInvalid, "invalid"}, + } + for _, c := range cases { + if c.got != c.want { + t.Errorf("kind %q, want %q", c.got, c.want) + } + } +} + +func TestCheckChangeAcceptsAChangeToDeclaredSettings(t *testing.T) { + top, bottom := strconv.Itoa(math.MaxInt), strconv.Itoa(math.MinInt) + runChanges(t, []changeCase{ + {change: nil}, + {change: map[string]string{}}, + {change: map[string]string{ + "title": "Field Notes", "per_page": "25", "open": "true", "keep_for": "48h", + "order": "oldest", "tags": "news, events", + }}, + {change: map[string]string{"per_page": " 25 ", "open": " 1 ", "keep_for": " 2h ", "order": " newest "}}, + {change: map[string]string{"per_page": "1", "seats": "1", "slots": "50"}}, + {change: map[string]string{"per_page": "50", "total": top, "seats": top, "slots": bottom}}, + {change: map[string]string{"total": bottom, "open": "F", "keep_for": "1ns"}}, + {change: map[string]string{"title": "Field Notes"}, env: map[string]string{"APP_PLUGIN_OTHER__TITLE": "Other"}}, + {change: map[string]string{"order": "oldest"}, env: map[string]string{"APP_PLUGIN_NOTES__TITLE": "Garden Notes"}}, + {change: map[string]string{"title": "Field Notes"}, + env: map[string]string{"APP_PLUGIN_NOTES__API_KEY": knownSecret}}, + }) +} + +func TestCheckChangeAcceptsAnEmptyTextOrLines(t *testing.T) { + runChanges(t, []changeCase{ + {change: map[string]string{"title": ""}}, + {change: map[string]string{"tags": ""}}, + {change: map[string]string{"title": " ", "tags": " , ,"}}, + }) +} + +func TestCheckChangeRejectsAnEmptyValueOfATypeThatHasNone(t *testing.T) { + runChanges(t, []changeCase{ + {change: map[string]string{"per_page": ""}, want: invalidAs("per_page", ReasonNotWhole)}, + {change: map[string]string{"total": " "}, want: invalidAs("total", ReasonNotWhole)}, + {change: map[string]string{"open": ""}, want: invalidAs("open", ReasonNotFlag)}, + {change: map[string]string{"keep_for": ""}, want: invalidAs("keep_for", ReasonNotDuration)}, + {change: map[string]string{"order": ""}, want: notOption()}, + }) +} + +func TestCheckChangeRejectsAValueItsTypeRejectsWithItsReason(t *testing.T) { + runChanges(t, []changeCase{ + {change: map[string]string{"per_page": "banana"}, want: invalidAs("per_page", ReasonNotWhole)}, + {change: map[string]string{"per_page": "2.5"}, want: invalidAs("per_page", ReasonNotWhole)}, + {change: map[string]string{"total": "1e3"}, want: invalidAs("total", ReasonNotWhole)}, + {change: map[string]string{"per_page": "0"}, want: belowMin("per_page", 1)}, + {change: map[string]string{"per_page": "60"}, want: aboveMax("per_page", 50)}, + {change: map[string]string{"open": "maybe"}, want: invalidAs("open", ReasonNotFlag)}, + {change: map[string]string{"keep_for": "soon"}, want: invalidAs("keep_for", ReasonNotDuration)}, + {change: map[string]string{"keep_for": "-1h"}, want: invalidAs("keep_for", ReasonNotPositive)}, + {change: map[string]string{"keep_for": "0s"}, want: invalidAs("keep_for", ReasonNotPositive)}, + {change: map[string]string{"order": "random"}, want: notOption()}, + {change: map[string]string{"order": "Newest"}, want: notOption()}, + }) +} + +func TestCheckChangeGivesOnlyTheBoundItsCheckUsed(t *testing.T) { + above := strconv.FormatUint(uint64(math.MaxInt)+1, 10) + below := "-" + strconv.FormatUint(uint64(math.MaxInt)+2, 10) + runChanges(t, []changeCase{ + {change: map[string]string{"per_page": "0"}, want: belowMin("per_page", 1)}, + {change: map[string]string{"per_page": "-4"}, want: belowMin("per_page", 1)}, + {change: map[string]string{"per_page": "51"}, want: aboveMax("per_page", 50)}, + {change: map[string]string{"per_page": beyondEveryInt}, want: aboveMax("per_page", 50)}, + {change: map[string]string{"total": above}, want: aboveMax("total", math.MaxInt)}, + {change: map[string]string{"total": below}, want: belowMin("total", math.MinInt)}, + {change: map[string]string{"seats": "0"}, want: belowMin("seats", 1)}, + {change: map[string]string{"seats": beyondEveryInt}, want: aboveMax("seats", math.MaxInt)}, + {change: map[string]string{"slots": "51"}, want: aboveMax("slots", 50)}, + {change: map[string]string{"slots": "-" + beyondEveryInt}, want: belowMin("slots", math.MinInt)}, + }) +} + +func TestCheckChangeGivesTheOptionsOfAChoiceApartFromTheSchema(t *testing.T) { + schema := changeSchema(t) + var problem *ChangeError + if err := schema.CheckChange(map[string]string{"order": "random"}, nil); !errors.As(err, &problem) { + t.Fatalf("CheckChange = %v, want a change error", err) + } + problem.Options[0] = "changed" + if got := schema.Fields[7].Options[0]; got != "newest" { + t.Errorf("the first option of order became %q after the rejection changed", got) + } +} + +func TestCheckChangeRejectsAKeyTheSchemaDoesNotDeclare(t *testing.T) { + runChanges(t, []changeCase{ + {change: map[string]string{"colour": "green"}, want: &ChangeError{Kind: KindUnknown, Key: "colour"}}, + {change: map[string]string{"Title": "Field Notes"}, want: &ChangeError{Kind: KindUnknown, Key: "Title"}}, + {change: map[string]string{"": "Field Notes"}, want: &ChangeError{Kind: KindUnknown, Key: ""}}, + {change: map[string]string{"title": "Field Notes", "colour": "green"}, + want: &ChangeError{Kind: KindUnknown, Key: "colour"}}, + }) +} + +func TestCheckChangeAnswersTheUndeclaredKeysFirstSortedByKey(t *testing.T) { + change := map[string]string{ + "title": "Field Notes", "zebra": "stripes", "colour": "green", "per_page": "banana", "mood": "calm", + "api_key": knownSecret, "apple": "red", "order": "random", + } + env := map[string]string{"APP_PLUGIN_NOTES__TITLE": "Garden Notes"} + for range 32 { + runChanges(t, []changeCase{{change: change, env: env, want: &ChangeError{Kind: KindUnknown, Key: "apple"}}}) + } +} + +func TestCheckChangeAnswersTheDeclaredFieldsInTheManifestsOrder(t *testing.T) { + runChanges(t, []changeCase{ + {change: map[string]string{"order": "random", "per_page": "banana"}, want: invalidAs("per_page", ReasonNotWhole)}, + {change: map[string]string{"tags": "", "keep_for": "soon", "open": "maybe"}, want: invalidAs("open", ReasonNotFlag)}, + {change: map[string]string{"api_key": knownSecret, "order": "random"}, want: notOption()}, + {change: map[string]string{"title": "Field Notes", "per_page": "banana"}, + env: map[string]string{"APP_PLUGIN_NOTES__TITLE": "Garden Notes"}, want: lockedBy("title")}, + {change: map[string]string{"per_page": "banana", "order": "oldest"}, + env: map[string]string{"APP_PLUGIN_NOTES__ORDER": "newest"}, want: invalidAs("per_page", ReasonNotWhole)}, + {change: map[string]string{"title": "Field Notes", "order": "random"}, want: notOption()}, + }) +} + +func TestCheckChangeRejectsAFieldTheEnvironmentSetsAsLocked(t *testing.T) { + runChanges(t, []changeCase{ + {change: map[string]string{"title": "Field Notes"}, + env: map[string]string{"APP_PLUGIN_NOTES__TITLE": "Garden Notes"}, want: lockedBy("title")}, + {change: map[string]string{"title": "Garden Notes"}, + env: map[string]string{"APP_PLUGIN_NOTES__TITLE": " Garden Notes "}, want: lockedBy("title")}, + {change: map[string]string{"per_page": "25"}, + env: map[string]string{"APP_PLUGIN_NOTES__PER_PAGE": "25"}, want: lockedBy("per_page")}, + {change: map[string]string{"per_page": "banana"}, + env: map[string]string{"APP_PLUGIN_NOTES__PER_PAGE": "25"}, want: lockedBy("per_page")}, + {change: map[string]string{"tags": ""}, + env: map[string]string{"APP_PLUGIN_NOTES__TAGS": ","}, want: lockedBy("tags")}, + }) +} + +func TestCheckChangeLetsABlankVariableLockNothing(t *testing.T) { + cases := make([]changeCase, 0, 3) + for _, blank := range []string{"", " ", "\t\n"} { + cases = append(cases, changeCase{ + change: map[string]string{"title": "Field Notes"}, + env: map[string]string{"APP_PLUGIN_NOTES__TITLE": blank}, + }) + } + runChanges(t, cases) +} + +func TestCheckChangeRejectsASecretBecauseItComesFromTheEnvironmentOnly(t *testing.T) { + runChanges(t, []changeCase{ + {change: map[string]string{"api_key": knownSecret}, want: invalidAs("api_key", ReasonEnvironmentOnly)}, + {change: map[string]string{"api_key": ""}, want: invalidAs("api_key", ReasonEnvironmentOnly)}, + {change: map[string]string{"api_key": knownSecret}, + env: map[string]string{"APP_PLUGIN_NOTES__API_KEY": " "}, want: invalidAs("api_key", ReasonEnvironmentOnly)}, + }) +} + +func TestCheckChangeRejectsASecretTheEnvironmentSetsAsLocked(t *testing.T) { + runChanges(t, []changeCase{ + {change: map[string]string{"api_key": anotherSecret}, + env: map[string]string{"APP_PLUGIN_NOTES__API_KEY": knownSecret}, want: lockedBy("api_key")}, + }) +} + +func TestChangeErrorSaysTheKeyAndItsProblem(t *testing.T) { + cases := []struct { + problem *ChangeError + want string + }{ + {&ChangeError{Kind: KindUnknown, Key: "colour"}, "colour: no setting has this key"}, + {lockedBy("title"), "title: locked by APP_PLUGIN_NOTES__TITLE"}, + {invalidAs("per_page", ReasonNotWhole), "per_page: value rejected as not_whole"}, + {belowMin("per_page", 1), "per_page: value rejected as below_min"}, + {invalidAs("api_key", ReasonEnvironmentOnly), "api_key: value rejected as environment_only"}, + } + for _, c := range cases { + if got := c.problem.Error(); got != c.want { + t.Errorf("Error() = %q, want %q", got, c.want) + } + } +} + +func TestCheckChangeNeverShowsTheValueOfASecret(t *testing.T) { + schema := changeSchema(t) + cases := []struct { + change, env map[string]string + }{ + {change: map[string]string{"api_key": knownSecret}}, + {change: map[string]string{"api_key": anotherSecret}, + env: map[string]string{"APP_PLUGIN_NOTES__API_KEY": knownSecret}}, + {change: map[string]string{"api_key": knownSecret, "per_page": "banana"}}, + {change: map[string]string{"api_key": knownSecret, "colour": "green"}}, + } + for _, c := range cases { + rejectsShowingNoSecret(t, c.change, schema.CheckChange(c.change, c.env)) + } +} + +// rejectsShowingNoSecret fails t unless err rejects change and no rendering of it shows a test secret. +func rejectsShowingNoSecret(t *testing.T, change map[string]string, err error) { + t.Helper() + if err == nil { + t.Fatalf("CheckChange(%v) = nil, want a rejection", change) + } + for _, out := range renderings(err) { + if strings.Contains(out, knownSecret) || strings.Contains(out, anotherSecret) { + t.Errorf("a rendering of the rejection of %v shows a secret: %q", change, out) + } + } +} + +func TestCheckChangeRejectsAFieldOfAnUnknownTypeByItsKey(t *testing.T) { + schema := Schema{ID: "notes", Fields: []Field{{Key: "mood", Type: "colour", Env: "APP_PLUGIN_NOTES__MOOD"}}} + err := schema.CheckChange(map[string]string{"mood": "blue"}, nil) + want := `mood: type "colour" is not one of text, count, flag, duration, choice, secret, lines` + if err == nil || err.Error() != want { + t.Fatalf("CheckChange = %v, want %q", err, want) + } + var problem *ChangeError + if errors.As(err, &problem) { + t.Errorf("CheckChange answered the change error %s for a schema it cannot read", described(problem)) + } +} + +func TestCheckChangeOfASchemaWithNoFieldsRejectsEveryKey(t *testing.T) { + schema := Schema{ID: "notes"} + if err := schema.CheckChange(nil, nil); err != nil { + t.Errorf("CheckChange(nil) = %v, want nil", err) + } + var problem *ChangeError + err := schema.CheckChange(map[string]string{"title": "Field Notes"}, nil) + if !errors.As(err, &problem) || !reflect.DeepEqual(problem, &ChangeError{Kind: KindUnknown, Key: "title"}) { + t.Errorf("CheckChange = %v, want the key title rejected as unknown", err) + } +} diff --git a/pluginkit/settings/check.go b/pluginkit/settings/check.go index 9698809..35118b3 100644 --- a/pluginkit/settings/check.go +++ b/pluginkit/settings/check.go @@ -85,7 +85,7 @@ func checkShape(setting wire.Setting) error { return nil } -// fieldOf returns the field of setting, its bounds read as whole numbers with min not above max. +// fieldOf returns the field of setting with its label and help, its bounds whole numbers with min not above max. func fieldOf(setting wire.Setting) (Field, error) { low, err := wholeBound("min", setting.Min) if err != nil { @@ -101,6 +101,8 @@ func fieldOf(setting wire.Setting) (Field, error) { return Field{ Key: setting.Key, Type: setting.Type, + Label: setting.Label, + Help: setting.Help, Default: setting.Default, Min: low, Max: high, diff --git a/pluginkit/settings/check_test.go b/pluginkit/settings/check_test.go index 2ef7965..92c290c 100644 --- a/pluginkit/settings/check_test.go +++ b/pluginkit/settings/check_test.go @@ -144,7 +144,8 @@ func TestCheckAnswersEachSettingReadyToResolve(t *testing.T) { } one, fifty := 1, 50 want := Schema{ID: "notes", Fields: []Field{ - {Key: "title", Type: TypeText, Env: "APP_PLUGIN_NOTES__TITLE", Default: "Notes"}, + {Key: "title", Type: TypeText, Label: "Title", Help: "The title readers see", Env: "APP_PLUGIN_NOTES__TITLE", + Default: "Notes"}, {Key: "per_page", Type: TypeCount, Env: "APP_PLUGIN_NOTES__PER_PAGE", Default: "10", Min: &one, Max: &fifty}, {Key: "open", Type: TypeFlag, Env: "APP_PLUGIN_NOTES__OPEN"}, {Key: "keep_for", Type: TypeDuration, Env: "APP_PLUGIN_NOTES__KEEP_FOR", Default: "720h"}, @@ -158,6 +159,38 @@ func TestCheckAnswersEachSettingReadyToResolve(t *testing.T) { } } +func TestCheckKeepsTheLabelAndHelpOfEachSetting(t *testing.T) { + declared := everyType() + for i := range declared { + declared[i].Label, declared[i].Help = "Label of "+declared[i].Key, "Help for "+declared[i].Key + } + schema, err := Check("notes", declared, appRules) + if err != nil { + t.Fatalf("Check = %v, want nil", err) + } + if len(schema.Fields) != len(declared) { + t.Fatalf("Check answered %d fields, want %d", len(schema.Fields), len(declared)) + } + for i, field := range schema.Fields { + if field.Label != declared[i].Label { + t.Errorf("%s: label %q, want %q", field.Key, field.Label, declared[i].Label) + } + if field.Help != declared[i].Help { + t.Errorf("%s: help %q, want %q", field.Key, field.Help, declared[i].Help) + } + } +} + +func TestCheckLeavesTheLabelAndHelpEmptyWhenTheManifestGivesNone(t *testing.T) { + schema, err := Check("notes", []wire.Setting{{Key: "title", Type: TypeText}}, appRules) + if err != nil { + t.Fatalf("Check = %v, want nil", err) + } + if field := schema.Fields[0]; field.Label != "" || field.Help != "" { + t.Errorf("a setting with no label or help answered %q and %q", field.Label, field.Help) + } +} + func TestCheckTakesTheDefaultsEachTypeAccepts(t *testing.T) { declared := []wire.Setting{ {Key: "open", Type: TypeFlag, Default: "true"}, diff --git a/pluginkit/settings/formfield.go b/pluginkit/settings/formfield.go new file mode 100644 index 0000000..13289df --- /dev/null +++ b/pluginkit/settings/formfield.go @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "slices" + "strconv" + "strings" +) + +// FormField describes one setting for a settings form, never holding a secret's value. +type FormField struct { + Key string `json:"key"` + Type string `json:"type"` + Label string `json:"label,omitempty"` + Help string `json:"help,omitempty"` + Min *int `json:"min,omitempty"` + Max *int `json:"max,omitempty"` + Options []string `json:"options,omitempty"` + Default string `json:"default,omitempty"` + Value *string `json:"value,omitempty"` + Set *bool `json:"set,omitempty"` + Source string `json:"source"` + Locked bool `json:"locked"` + Env string `json:"env"` +} + +// FormFields describes each field for a settings form, in manifest order, never holding a secret's value. +func (s Schema) FormFields(values Values) []FormField { + described := make([]FormField, 0, len(s.Fields)) + for _, field := range s.Fields { + described = append(described, field.formField(values[field.Key])) + } + return described +} + +// formField describes the field with value for a settings form, a secret only as set or not set. +func (f Field) formField(value Value) FormField { + described := FormField{ + Key: f.Key, + Type: f.Type, + Label: f.Label, + Help: f.Help, + Min: copied(f.Min), + Max: copied(f.Max), + Options: slices.Clone(f.Options), + Source: value.Source, + Locked: value.Source == SourceEnvironment, + Env: f.Env, + } + if f.Type == TypeSecret { + set := value.Secret.reveal != nil + described.Set = &set + return described + } + shown := shownAs(f.Type, value) + described.Default, described.Value = strings.TrimSpace(f.Default), &shown + return described +} + +// shownAs returns value as the text a form shows for the setting type kind. +func shownAs(kind string, value Value) string { + switch kind { + case TypeCount: + return strconv.Itoa(value.Count) + case TypeFlag: + return strconv.FormatBool(value.Flag) + case TypeLines: + return strings.Join(value.Lines, ", ") + } + return value.Text +} + +// copied returns a new pointer to the number n points to, nil when n is nil. +func copied(n *int) *int { + if n == nil { + return nil + } + number := *n + return &number +} diff --git a/pluginkit/settings/formfield_test.go b/pluginkit/settings/formfield_test.go new file mode 100644 index 0000000..9100100 --- /dev/null +++ b/pluginkit/settings/formfield_test.go @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "bytes" + "encoding/json" + "strings" + "testing" + "time" + + "github.com/gopherium/framework/pluginkit/wire" +) + +// formSchema returns the checked schema of a plugin notes that declares a setting of each type with its label. +func formSchema(t *testing.T) Schema { + t.Helper() + schema, err := Check("notes", []wire.Setting{ + {Key: "title", Type: TypeText, Default: "Notes", Label: "Title", Help: "Shown above the notes."}, + {Key: "per_page", Type: TypeCount, Default: "10", Min: number(1), Max: number(50), Label: "Per page"}, + {Key: "open", Type: TypeFlag, Default: "false", Label: "Open"}, + {Key: "keep_for", Type: TypeDuration, Default: "720h", Label: "Keep for"}, + {Key: "order", Type: TypeChoice, Default: "newest", Options: []string{"newest", "oldest"}, Label: "Order"}, + {Key: "tags", Type: TypeLines, Default: "news", Label: "Tags"}, + {Key: "api_key", Type: TypeSecret, Label: "API key"}, + }, appRules) + if err != nil { + t.Fatalf("Check = %v", err) + } + return schema +} + +// formValues returns values of the form schema as an application finds them, title saved and per_page and api_key set. +func formValues() Values { + return Values{ + "title": {Type: TypeText, Source: SourceSaved, Text: "Field Notes"}, + "per_page": {Type: TypeCount, Source: SourceEnvironment, Count: 25}, + "open": {Type: TypeFlag, Source: SourceDefault}, + "keep_for": {Type: TypeDuration, Source: SourceDefault, Text: "720h", Duration: 720 * time.Hour}, + "order": {Type: TypeChoice, Source: SourceDefault, Text: "newest"}, + "tags": {Type: TypeLines, Source: SourceDefault, Lines: []string{"news"}}, + "api_key": {Type: TypeSecret, Source: SourceEnvironment, Secret: hide(knownSecret)}, + } +} + +// oneField describes field for a form with value, as the only field of a plugin notes. +func oneField(field Field, value Value) FormField { + return Schema{ID: "notes", Fields: []Field{field}}.FormFields(Values{field.Key: value})[0] +} + +// sameJSON fails the test when value does not encode as want, read with its spaces and line breaks dropped. +func sameJSON(t *testing.T, value any, want string) { + t.Helper() + var compact bytes.Buffer + if err := json.Compact(&compact, []byte(want)); err != nil { + t.Fatalf("the wanted JSON does not read: %v", err) + } + if got := encoded(value); got != compact.String() { + t.Errorf("JSON = %s\nwant %s", got, compact.String()) + } +} + +func TestFormFieldsEncodeEachTypeInTheManifestsOrder(t *testing.T) { + sameJSON(t, formSchema(t).FormFields(formValues()), `[ + {"key": "title", "type": "text", "label": "Title", "help": "Shown above the notes.", "default": "Notes", + "value": "Field Notes", "source": "saved", "locked": false, "env": "APP_PLUGIN_NOTES__TITLE"}, + {"key": "per_page", "type": "count", "label": "Per page", "min": 1, "max": 50, "default": "10", + "value": "25", "source": "environment", "locked": true, "env": "APP_PLUGIN_NOTES__PER_PAGE"}, + {"key": "open", "type": "flag", "label": "Open", "default": "false", + "value": "false", "source": "default", "locked": false, "env": "APP_PLUGIN_NOTES__OPEN"}, + {"key": "keep_for", "type": "duration", "label": "Keep for", "default": "720h", + "value": "720h", "source": "default", "locked": false, "env": "APP_PLUGIN_NOTES__KEEP_FOR"}, + {"key": "order", "type": "choice", "label": "Order", "options": ["newest", "oldest"], "default": "newest", + "value": "newest", "source": "default", "locked": false, "env": "APP_PLUGIN_NOTES__ORDER"}, + {"key": "tags", "type": "lines", "label": "Tags", "default": "news", + "value": "news", "source": "default", "locked": false, "env": "APP_PLUGIN_NOTES__TAGS"}, + {"key": "api_key", "type": "secret", "label": "API key", + "set": true, "source": "environment", "locked": true, "env": "APP_PLUGIN_NOTES__API_KEY"} + ]`) +} + +func TestFormFieldsShowEachValueInItsPlainForm(t *testing.T) { + cases := []struct { + kind string + value Value + want string + }{ + {TypeCount, Value{Type: TypeCount, Count: 20}, "20"}, + {TypeCount, Value{Type: TypeCount, Count: -3}, "-3"}, + {TypeCount, Value{Type: TypeCount}, "0"}, + {TypeFlag, Value{Type: TypeFlag, Flag: true}, "true"}, + {TypeFlag, Value{Type: TypeFlag}, "false"}, + {TypeDuration, Value{Type: TypeDuration, Text: "2h", Duration: 2 * time.Hour}, "2h"}, + {TypeDuration, Value{Type: TypeDuration, Text: "1h30m", Duration: 90 * time.Minute}, "1h30m"}, + {TypeText, Value{Type: TypeText, Text: "Field Notes"}, "Field Notes"}, + {TypeText, Value{Type: TypeText}, ""}, + {TypeChoice, Value{Type: TypeChoice, Text: "oldest"}, "oldest"}, + {TypeLines, Value{Type: TypeLines, Lines: []string{"news", "events"}}, "news, events"}, + {TypeLines, Value{Type: TypeLines, Lines: []string{"news"}}, "news"}, + {TypeLines, Value{Type: TypeLines}, ""}, + } + for _, c := range cases { + got := oneField(Field{Key: "shown", Type: c.kind, Env: "APP_PLUGIN_NOTES__SHOWN"}, c.value).Value + if got == nil { + t.Errorf("%s %+v has no value, want %q", c.kind, c.value, c.want) + continue + } + if *got != c.want { + t.Errorf("%s %+v shows %q, want %q", c.kind, c.value, *got, c.want) + } + } +} + +func TestFormFieldsKeepASavedEmptyValue(t *testing.T) { + title := Field{Key: "title", Type: TypeText, Env: "APP_PLUGIN_NOTES__TITLE", Default: "Notes"} + sameJSON(t, oneField(title, Value{Type: TypeText, Source: SourceSaved}), `{"key": "title", "type": "text", + "default": "Notes", "value": "", "source": "saved", "locked": false, "env": "APP_PLUGIN_NOTES__TITLE"}`) + tags := Field{Key: "tags", Type: TypeLines, Env: "APP_PLUGIN_NOTES__TAGS", Default: "news"} + sameJSON(t, oneField(tags, Value{Type: TypeLines, Source: SourceSaved}), `{"key": "tags", "type": "lines", + "default": "news", "value": "", "source": "saved", "locked": false, "env": "APP_PLUGIN_NOTES__TAGS"}`) +} + +func TestFormFieldsGiveASecretOnlyWhetherItIsSet(t *testing.T) { + key := Field{Key: "api_key", Type: TypeSecret, Label: "API key", Env: "APP_PLUGIN_NOTES__API_KEY"} + sameJSON(t, oneField(key, Value{Type: TypeSecret, Source: SourceEnvironment, Secret: hide(knownSecret)}), + `{"key": "api_key", "type": "secret", "label": "API key", + "set": true, "source": "environment", "locked": true, "env": "APP_PLUGIN_NOTES__API_KEY"}`) + sameJSON(t, oneField(key, Value{Type: TypeSecret, Source: SourceDefault}), + `{"key": "api_key", "type": "secret", "label": "API key", + "set": false, "source": "default", "locked": false, "env": "APP_PLUGIN_NOTES__API_KEY"}`) +} + +func TestFormFieldsNeverGiveTheDefaultOfASecret(t *testing.T) { + key := Field{Key: "api_key", Type: TypeSecret, Env: "APP_PLUGIN_NOTES__API_KEY", Default: knownSecret} + got := oneField(key, Value{Type: TypeSecret, Source: SourceDefault}) + if got.Default != "" { + t.Errorf("a secret with a default describes the default %q, want none", got.Default) + } + if got.Value != nil { + t.Errorf("a secret describes the value %q, want none", *got.Value) + } +} + +func TestFormFieldsLockOnlyAValueFromTheEnvironment(t *testing.T) { + cases := []struct { + source string + locked bool + }{ + {SourceEnvironment, true}, + {SourceSaved, false}, + {SourceDefault, false}, + {"", false}, + } + title := Field{Key: "title", Type: TypeText, Env: "APP_PLUGIN_NOTES__TITLE"} + for _, c := range cases { + got := oneField(title, Value{Type: TypeText, Source: c.source, Text: "Notes"}) + if got.Locked != c.locked { + t.Errorf("a value from %q is locked %t, want %t", c.source, got.Locked, c.locked) + } + if got.Source != c.source { + t.Errorf("a value from %q describes the source %q", c.source, got.Source) + } + if got.Env != "APP_PLUGIN_NOTES__TITLE" { + t.Errorf("a value from %q names the variable %q, want APP_PLUGIN_NOTES__TITLE", c.source, got.Env) + } + } +} + +func TestFormFieldsGiveTheBoundsOfACountOnlyWhenGiven(t *testing.T) { + cases := []struct { + min, max *int + bounds string + }{ + {bound(1), bound(50), `"min": 1, "max": 50,`}, + {bound(0), nil, `"min": 0,`}, + {nil, bound(50), `"max": 50,`}, + {nil, nil, ``}, + } + for _, c := range cases { + seats := Field{Key: "seats", Type: TypeCount, Env: "APP_PLUGIN_NOTES__SEATS", Default: "1", Min: c.min, Max: c.max} + sameJSON(t, oneField(seats, Value{Type: TypeCount, Source: SourceDefault, Count: 1}), + `{"key": "seats", "type": "count", `+c.bounds+` "default": "1", + "value": "1", "source": "default", "locked": false, "env": "APP_PLUGIN_NOTES__SEATS"}`) + } +} + +func TestFormFieldsGiveTheDefaultTrimmed(t *testing.T) { + cases := []struct { + field Field + want string + }{ + {Field{Key: "title", Type: TypeText, Default: " Notes \t"}, "Notes"}, + {Field{Key: "per_page", Type: TypeCount, Default: " 10 "}, "10"}, + {Field{Key: "tags", Type: TypeLines, Default: " news, events "}, "news, events"}, + {Field{Key: "title", Type: TypeText}, ""}, + } + for _, c := range cases { + if got := oneField(c.field, Value{Type: c.field.Type}).Default; got != c.want { + t.Errorf("the default %q of %s is described as %q, want %q", c.field.Default, c.field.Key, got, c.want) + } + } +} + +func TestFormFieldsOfASchemaWithNoFieldsEncodeAsAnEmptyList(t *testing.T) { + sameJSON(t, Schema{ID: "notes"}.FormFields(Values{"title": {Type: TypeText, Text: "Notes"}}), `[]`) +} + +func TestFormFieldsLeaveTheSchemaAlone(t *testing.T) { + schema := formSchema(t) + before := encoded(schema) + fields := schema.FormFields(formValues()) + *fields[1].Min, *fields[1].Max, fields[4].Options[0] = 7, 8, "changed" + if after := encoded(schema); after != before { + t.Errorf("a change to the form fields changed the schema to %s, want %s", after, before) + } +} + +func TestFormFieldsNeverShowTheValueOfASecret(t *testing.T) { + fields := formSchema(t).FormFields(formValues()) + for _, value := range []any{fields, &fields, fields[6], &fields[6]} { + for _, out := range renderings(value) { + if strings.Contains(out, knownSecret) { + t.Errorf("a rendering of the form fields shows the secret: %q", out) + } + } + } +} diff --git a/pluginkit/settings/parse.go b/pluginkit/settings/parse.go index 938d4b0..3722fa4 100644 --- a/pluginkit/settings/parse.go +++ b/pluginkit/settings/parse.go @@ -12,6 +12,36 @@ import ( "time" ) +const ( + // ReasonNotWhole is the reason a count rejects a value that is not a whole number. + ReasonNotWhole = "not_whole" + // ReasonBelowMin is the reason a count rejects a value below its min, or below every int when it has none. + ReasonBelowMin = "below_min" + // ReasonAboveMax is the reason a count rejects a value above its max, or above every int when it has none. + ReasonAboveMax = "above_max" + // ReasonNotFlag is the reason a flag rejects a value that is not true or false. + ReasonNotFlag = "not_flag" + // ReasonNotDuration is the reason a duration rejects a value that is not a duration. + ReasonNotDuration = "not_duration" + // ReasonNotPositive is the reason a duration rejects a value that does not stand above zero. + ReasonNotPositive = "not_positive" + // ReasonNotOption is the reason a choice rejects a value that is not one of its options. + ReasonNotOption = "not_option" + // ReasonEnvironmentOnly is the reason a secret rejects a value from anywhere but the environment. + ReasonEnvironmentOnly = "environment_only" +) + +// ValueError is a value its field's type rejects: the reason it names and the text it prints. +type ValueError struct { + Reason string + text string +} + +// Error returns the text of the rejection. +func (e *ValueError) Error() string { + return e.text +} + // parser reads one value of a field's type. type parser func(field Field, value string) (Value, error) @@ -40,7 +70,17 @@ func parserOf(kind string) (parser, error) { // complaint returns the error saying what a value must be and the value it is. func complaint(must, value string) error { - return fmt.Errorf("%s, got %q", must, value) + return errors.New(saying(must, value)) +} + +// rejected returns the value error of reason, saying what the value must be and the value it is. +func rejected(reason, must, value string) *ValueError { + return &ValueError{Reason: reason, text: saying(must, value)} +} + +// saying returns the text saying what a value must be and the value it is. +func saying(must, value string) string { + return fmt.Sprintf("%s, got %q", must, value) } // parseText reads value as text with its surrounding spaces trimmed. @@ -53,24 +93,24 @@ func parseCount(field Field, value string) (Value, error) { value = strings.TrimSpace(value) read, err := strconv.ParseInt(value, 10, 0) if err != nil && !errors.Is(err, strconv.ErrRange) { - return Value{}, complaint("must be a whole number", value) + return Value{}, rejected(ReasonNotWhole, "must be a whole number", value) } - if rule := beyond(field, read, err != nil); rule != "" { - return Value{}, complaint(rule, value) + if reason, rule := beyond(field, read, err != nil); rule != "" { + return Value{}, rejected(reason, rule, value) } return Value{Type: TypeCount, Count: int(read)}, nil } -// beyond returns the bound of field that read breaks, empty when read stands within them. -func beyond(field Field, read int64, overflowed bool) string { +// beyond returns the reason and the rule of the bound of field that read breaks, both empty within them. +func beyond(field Field, read int64, overflowed bool) (reason, rule string) { floor, ceiling := orElse(field.Min, math.MinInt), orElse(field.Max, math.MaxInt) switch { case read < int64(floor), overflowed && read == math.MinInt: - return "must stand at or above " + strconv.Itoa(floor) + return ReasonBelowMin, "must stand at or above " + strconv.Itoa(floor) case read > int64(ceiling), overflowed: - return "must stand at or below " + strconv.Itoa(ceiling) + return ReasonAboveMax, "must stand at or below " + strconv.Itoa(ceiling) } - return "" + return "", "" } // orElse returns the number n points to, fallback when n is nil. @@ -86,29 +126,29 @@ func parseFlag(_ Field, value string) (Value, error) { value = strings.TrimSpace(value) read, err := strconv.ParseBool(value) if err != nil { - return Value{}, complaint("must be true or false", value) + return Value{}, rejected(ReasonNotFlag, "must be true or false", value) } return Value{Type: TypeFlag, Flag: read}, nil } -// parseDuration reads value as a duration above zero. +// parseDuration reads value as a duration above zero and keeps the trimmed text it read. func parseDuration(_ Field, value string) (Value, error) { value = strings.TrimSpace(value) read, err := time.ParseDuration(value) if err != nil { - return Value{}, complaint("must be a duration like 30s", value) + return Value{}, rejected(ReasonNotDuration, "must be a duration like 30s", value) } if read <= 0 { - return Value{}, complaint("must stand above zero", value) + return Value{}, rejected(ReasonNotPositive, "must stand above zero", value) } - return Value{Type: TypeDuration, Duration: read}, nil + return Value{Type: TypeDuration, Text: value, Duration: read}, nil } // parseChoice reads value as one of the field's options. func parseChoice(field Field, value string) (Value, error) { value = strings.TrimSpace(value) if !slices.Contains(field.Options, value) { - return Value{}, complaint("must be one of "+strings.Join(field.Options, ", "), value) + return Value{}, rejected(ReasonNotOption, "must be one of "+strings.Join(field.Options, ", "), value) } return Value{Type: TypeChoice, Text: value}, nil } diff --git a/pluginkit/settings/parse_test.go b/pluginkit/settings/parse_test.go index 7a420b6..e3f6e6d 100644 --- a/pluginkit/settings/parse_test.go +++ b/pluginkit/settings/parse_test.go @@ -3,6 +3,7 @@ package settings import ( + "errors" "math" "reflect" "strconv" @@ -18,12 +19,13 @@ func bound(n int) *int { return &n } -// parseCase is one value a parser reads and the reading or the error it answers. +// parseCase is one value a parser reads and the reading, or the error text and reason, it answers. type parseCase struct { - field Field - value string - want Value - err string + field Field + value string + want Value + err string + reason string } // runParse reads each case's value with the parser of its field's type and compares what it answers. @@ -52,12 +54,20 @@ func checkParse(t *testing.T, c parseCase) { } } -// wantError reports err when it is not the error the case expects. +// wantError reports err when it is not the value error the case expects, by its text and its reason. func wantError(t *testing.T, c parseCase, err error) { t.Helper() if err == nil || err.Error() != c.err { t.Errorf("%s %q: error %v, want %q", c.field.Type, c.value, err, c.err) } + var valueErr *ValueError + if !errors.As(err, &valueErr) { + t.Errorf("%s %q: error %v is no value error", c.field.Type, c.value, err) + return + } + if valueErr.Reason != c.reason { + t.Errorf("%s %q: reason %q, want %q", c.field.Type, c.value, valueErr.Reason, c.reason) + } } // sameValue reports whether two values hold the same reading, a secret compared by its text. @@ -94,11 +104,11 @@ func TestParseCountReadsAWholeNumber(t *testing.T) { func TestParseCountRejectsAnythingButAWholeNumber(t *testing.T) { open := Field{Type: TypeCount} runParse(t, []parseCase{ - {field: open, value: "banana", err: `must be a whole number, got "banana"`}, - {field: open, value: "2.5", err: `must be a whole number, got "2.5"`}, - {field: open, value: "1e3", err: `must be a whole number, got "1e3"`}, - {field: open, value: "", err: `must be a whole number, got ""`}, - {field: open, value: " 2 5 ", err: `must be a whole number, got "2 5"`}, + {field: open, value: "banana", err: `must be a whole number, got "banana"`, reason: ReasonNotWhole}, + {field: open, value: "2.5", err: `must be a whole number, got "2.5"`, reason: ReasonNotWhole}, + {field: open, value: "1e3", err: `must be a whole number, got "1e3"`, reason: ReasonNotWhole}, + {field: open, value: "", err: `must be a whole number, got ""`, reason: ReasonNotWhole}, + {field: open, value: " 2 5 ", err: `must be a whole number, got "2 5"`, reason: ReasonNotWhole}, }) } @@ -107,9 +117,10 @@ func TestParseCountKeepsWithinItsBounds(t *testing.T) { runParse(t, []parseCase{ {field: seats, value: "1", want: Value{Type: TypeCount, Count: 1}}, {field: seats, value: "50", want: Value{Type: TypeCount, Count: 50}}, - {field: seats, value: "60", err: `must stand at or below 50, got "60"`}, - {field: seats, value: "0", err: `must stand at or above 1, got "0"`}, - {field: seats, value: "-4", err: `must stand at or above 1, got "-4"`}, + {field: seats, value: "51", err: `must stand at or below 50, got "51"`, reason: ReasonAboveMax}, + {field: seats, value: "60", err: `must stand at or below 50, got "60"`, reason: ReasonAboveMax}, + {field: seats, value: "0", err: `must stand at or above 1, got "0"`, reason: ReasonBelowMin}, + {field: seats, value: "-4", err: `must stand at or above 1, got "-4"`, reason: ReasonBelowMin}, }) } @@ -117,13 +128,30 @@ func TestParseCountRejectsANumberPastTheInt(t *testing.T) { top, bottom := strconv.Itoa(math.MaxInt), strconv.Itoa(math.MinInt) runParse(t, []parseCase{ {field: Field{Type: TypeCount}, value: beyondEveryInt, - err: "must stand at or below " + top + `, got "` + beyondEveryInt + `"`}, + err: "must stand at or below " + top + `, got "` + beyondEveryInt + `"`, reason: ReasonAboveMax}, {field: Field{Type: TypeCount}, value: "-" + beyondEveryInt, - err: "must stand at or above " + bottom + `, got "-` + beyondEveryInt + `"`}, + err: "must stand at or above " + bottom + `, got "-` + beyondEveryInt + `"`, reason: ReasonBelowMin}, {field: Field{Type: TypeCount, Max: bound(50)}, value: beyondEveryInt, - err: `must stand at or below 50, got "` + beyondEveryInt + `"`}, + err: `must stand at or below 50, got "` + beyondEveryInt + `"`, reason: ReasonAboveMax}, {field: Field{Type: TypeCount, Min: bound(1)}, value: "-" + beyondEveryInt, - err: `must stand at or above 1, got "-` + beyondEveryInt + `"`}, + err: `must stand at or above 1, got "-` + beyondEveryInt + `"`, reason: ReasonBelowMin}, + {field: Field{Type: TypeCount, Min: bound(1)}, value: beyondEveryInt, + err: "must stand at or below " + top + `, got "` + beyondEveryInt + `"`, reason: ReasonAboveMax}, + {field: Field{Type: TypeCount, Max: bound(50)}, value: "-" + beyondEveryInt, + err: "must stand at or above " + bottom + `, got "-` + beyondEveryInt + `"`, reason: ReasonBelowMin}, + }) +} + +func TestParseCountWithNoBoundsRejectsTheFirstNumberPastEachIntLimit(t *testing.T) { + open := Field{Type: TypeCount} + top, bottom := strconv.Itoa(math.MaxInt), strconv.Itoa(math.MinInt) + above := strconv.FormatUint(uint64(math.MaxInt)+1, 10) + below := "-" + strconv.FormatUint(uint64(math.MaxInt)+2, 10) + runParse(t, []parseCase{ + {field: open, value: above, err: "must stand at or below " + top + `, got "` + above + `"`, + reason: ReasonAboveMax}, + {field: open, value: below, err: "must stand at or above " + bottom + `, got "` + below + `"`, + reason: ReasonBelowMin}, }) } @@ -142,22 +170,35 @@ func TestParseFlagReadsEveryWordParseBoolTakes(t *testing.T) { func TestParseFlagRejectsAnotherWord(t *testing.T) { flag := Field{Type: TypeFlag} runParse(t, []parseCase{ - {field: flag, value: "maybe", err: `must be true or false, got "maybe"`}, - {field: flag, value: "yes", err: `must be true or false, got "yes"`}, + {field: flag, value: "maybe", err: `must be true or false, got "maybe"`, reason: ReasonNotFlag}, + {field: flag, value: "yes", err: `must be true or false, got "yes"`, reason: ReasonNotFlag}, + {field: flag, value: "", err: `must be true or false, got ""`, reason: ReasonNotFlag}, }) } func TestParseDurationReadsADurationAboveZero(t *testing.T) { keep := Field{Type: TypeDuration} runParse(t, []parseCase{ - {field: keep, value: "30s", want: Value{Type: TypeDuration, Duration: 30 * time.Second}}, - {field: keep, value: " 720h ", want: Value{Type: TypeDuration, Duration: 720 * time.Hour}}, - {field: keep, value: "1h30m", want: Value{Type: TypeDuration, Duration: 90 * time.Minute}}, - {field: keep, value: "soon", err: `must be a duration like 30s, got "soon"`}, - {field: keep, value: "30", err: `must be a duration like 30s, got "30"`}, - {field: keep, value: "-1h", err: `must stand above zero, got "-1h"`}, - {field: keep, value: "0s", err: `must stand above zero, got "0s"`}, - {field: keep, value: "9999999999h", err: `must be a duration like 30s, got "9999999999h"`}, + {field: keep, value: "30s", want: Value{Type: TypeDuration, Text: "30s", Duration: 30 * time.Second}}, + {field: keep, value: " 720h ", want: Value{Type: TypeDuration, Text: "720h", Duration: 720 * time.Hour}}, + {field: keep, value: "1h30m", want: Value{Type: TypeDuration, Text: "1h30m", Duration: 90 * time.Minute}}, + {field: keep, value: "1ns", want: Value{Type: TypeDuration, Text: "1ns", Duration: time.Nanosecond}}, + {field: keep, value: "soon", err: `must be a duration like 30s, got "soon"`, reason: ReasonNotDuration}, + {field: keep, value: "30", err: `must be a duration like 30s, got "30"`, reason: ReasonNotDuration}, + {field: keep, value: "", err: `must be a duration like 30s, got ""`, reason: ReasonNotDuration}, + {field: keep, value: "-1h", err: `must stand above zero, got "-1h"`, reason: ReasonNotPositive}, + {field: keep, value: "0s", err: `must stand above zero, got "0s"`, reason: ReasonNotPositive}, + {field: keep, value: "9999999999h", err: `must be a duration like 30s, got "9999999999h"`, + reason: ReasonNotDuration}, + }) +} + +func TestParseDurationKeepsTheTextItReadTrimmed(t *testing.T) { + keep := Field{Type: TypeDuration} + runParse(t, []parseCase{ + {field: keep, value: "2h", want: Value{Type: TypeDuration, Text: "2h", Duration: 2 * time.Hour}}, + {field: keep, value: " 90m\t", want: Value{Type: TypeDuration, Text: "90m", Duration: 90 * time.Minute}}, + {field: keep, value: "1h0m0s", want: Value{Type: TypeDuration, Text: "1h0m0s", Duration: time.Hour}}, }) } @@ -166,8 +207,9 @@ func TestParseChoiceReadsOneOfItsOptions(t *testing.T) { runParse(t, []parseCase{ {field: order, value: "oldest", want: Value{Type: TypeChoice, Text: "oldest"}}, {field: order, value: " newest ", want: Value{Type: TypeChoice, Text: "newest"}}, - {field: order, value: "random", err: `must be one of newest, oldest, got "random"`}, - {field: order, value: "Newest", err: `must be one of newest, oldest, got "Newest"`}, + {field: order, value: "random", err: `must be one of newest, oldest, got "random"`, reason: ReasonNotOption}, + {field: order, value: "Newest", err: `must be one of newest, oldest, got "Newest"`, reason: ReasonNotOption}, + {field: order, value: "", err: `must be one of newest, oldest, got ""`, reason: ReasonNotOption}, }) } @@ -200,6 +242,37 @@ func TestParseSecretFillsOnlyTheSecret(t *testing.T) { } } +func TestReasonsReadAsTheNamesAnApplicationSends(t *testing.T) { + cases := []struct { + got, want string + }{ + {ReasonNotWhole, "not_whole"}, + {ReasonBelowMin, "below_min"}, + {ReasonAboveMax, "above_max"}, + {ReasonNotFlag, "not_flag"}, + {ReasonNotDuration, "not_duration"}, + {ReasonNotPositive, "not_positive"}, + {ReasonNotOption, "not_option"}, + {ReasonEnvironmentOnly, "environment_only"}, + } + for _, c := range cases { + if c.got != c.want { + t.Errorf("reason %q, want %q", c.got, c.want) + } + } +} + +func TestAnOptionThatStartsWithASpaceIsNoValueRejection(t *testing.T) { + err := trimmedOptions([]string{" newest"}) + if want := `an option must not start or end with a space, got " newest"`; err == nil || err.Error() != want { + t.Fatalf("trimmedOptions = %v, want %q", err, want) + } + var valueErr *ValueError + if errors.As(err, &valueErr) { + t.Errorf("the option error %v names the reason %q, want no value error", err, valueErr.Reason) + } +} + func TestParserOfRejectsAnUnknownType(t *testing.T) { for _, kind := range []string{"colour", "picker", "content", "", "Text"} { _, err := parserOf(kind) diff --git a/pluginkit/settings/resolve.go b/pluginkit/settings/resolve.go index bd807b2..73119c8 100644 --- a/pluginkit/settings/resolve.go +++ b/pluginkit/settings/resolve.go @@ -7,38 +7,76 @@ import ( "strings" ) -// Resolve works out each field's value from found, the environment values by variable name, then from its default. -func (s Schema) Resolve(found map[string]string) (Values, error) { +// Sources holds what an application found for a schema: environment values by variable name and saved values by key. +type Sources struct { + Env map[string]string + Saved map[string]string +} + +// RejectedSavedValue is a saved value its field no longer takes, so the default applies. +type RejectedSavedValue struct { + Key string + Err error +} + +// Resolve works out each field from the environment, then the saved value, then the default. +func (s Schema) Resolve(found Sources) (Values, []RejectedSavedValue, error) { values := make(Values, len(s.Fields)) + var rejected []RejectedSavedValue for _, field := range s.Fields { - value, err := field.read(field.pick(found[field.Env])) + value, report, err := field.resolve(found) if err != nil { - return nil, fmt.Errorf("%s: %w", field.Env, err) + return nil, nil, fmt.Errorf("%s: %w", field.Env, err) + } + if report != nil { + rejected = append(rejected, *report) } values[field.Key] = value } - return values, nil + return values, rejected, nil } -// pick returns the environment's value of the field, its default when the value is blank, a secret taking no default. -func (f Field) pick(found string) string { - if f.Type == TypeSecret { - return found +// resolve returns the field's value from found, with the report of a saved value it passed over for the default. +func (f Field) resolve(found Sources) (Value, *RejectedSavedValue, error) { + parse, err := parserOf(f.Type) + if err != nil { + return Value{}, nil, err } - if value := strings.TrimSpace(found); value != "" { - return value + if env := found.Env[f.Env]; strings.TrimSpace(env) != "" { + value, err := parse(f, env) + value.Source = SourceEnvironment + return value, nil, err } - return strings.TrimSpace(f.Default) + saved, isSaved := found.Saved[f.Key] + if !isSaved { + value, err := f.byDefault(parse) + return value, nil, err + } + value, rejection := f.fromSaved(parse, saved) + if rejection == nil { + return value, nil, nil + } + value, err = f.byDefault(parse) + return value, &RejectedSavedValue{Key: f.Key, Err: rejection}, err } -// read returns value read by the field's type, the zero value of the type when value is empty. -func (f Field) read(value string) (Value, error) { - parse, err := parserOf(f.Type) - if err != nil { - return Value{}, err +// fromSaved returns the saved value read by parse, or why the field rejects it, a secret rejecting any saved value. +func (f Field) fromSaved(parse parser, saved string) (Value, error) { + if f.Type == TypeSecret { + return Value{}, &ValueError{Reason: ReasonEnvironmentOnly, text: "a secret comes from the environment only"} } - if value == "" { - return Value{Type: f.Type}, nil + value, err := parse(f, saved) + value.Source = SourceSaved + return value, err +} + +// byDefault returns the field's default read by parse, the zero value of its type when it has none or is a secret. +func (f Field) byDefault(parse parser) (Value, error) { + text := strings.TrimSpace(f.Default) + if text == "" || f.Type == TypeSecret { + return Value{Type: f.Type, Source: SourceDefault}, nil } - return parse(f, value) + value, err := parse(f, text) + value.Source = SourceDefault + return value, err } diff --git a/pluginkit/settings/resolve_test.go b/pluginkit/settings/resolve_test.go index e08ba09..066b8f3 100644 --- a/pluginkit/settings/resolve_test.go +++ b/pluginkit/settings/resolve_test.go @@ -3,6 +3,7 @@ package settings import ( + "errors" "maps" "slices" "strings" @@ -12,6 +13,9 @@ import ( "github.com/gopherium/framework/pluginkit/wire" ) +// savedSecretText is the text that reports a saved secret, which never quotes it. +const savedSecretText = "a secret comes from the environment only" + // notesSchema returns the checked schema of a plugin notes that declares one setting of each type. func notesSchema(t *testing.T) Schema { t.Helper() @@ -25,85 +29,277 @@ func notesSchema(t *testing.T) Schema { return schema } -// resolved works out the notes settings from found and fails the test on an error. -func resolved(t *testing.T, found map[string]string) Values { +// inEnv returns the sources of an application that found env in the environment and nothing saved. +func inEnv(env map[string]string) Sources { + return Sources{Env: env} +} + +// savedAs returns the sources of an application that found nothing in the environment and saved holds. +func savedAs(saved map[string]string) Sources { + return Sources{Saved: saved} +} + +// resolvedWithReports works out the notes settings from found and fails the test on an error. +func resolvedWithReports(t *testing.T, found Sources) (Values, []RejectedSavedValue) { t.Helper() - values, err := notesSchema(t).Resolve(found) + values, rejected, err := notesSchema(t).Resolve(found) if err != nil { t.Fatalf("Resolve = %v", err) } + return values, rejected +} + +// resolved works out the notes settings from found and fails the test on an error or a report. +func resolved(t *testing.T, found Sources) Values { + t.Helper() + values, rejected := resolvedWithReports(t, found) + if rejected != nil { + t.Errorf("Resolve reported %+v, want nil", rejected) + } return values } -func TestResolveTakesEachDefaultWhenTheEnvironmentHoldsNone(t *testing.T) { - for _, found := range []map[string]string{nil, {}, {"APP_PLUGIN_OTHER__TITLE": "Other"}} { - values := resolved(t, found) - want := Values{ - "title": {Type: TypeText, Text: "Notes"}, - "per_page": {Type: TypeCount, Count: 10}, - "open": {Type: TypeFlag}, - "keep_for": {Type: TypeDuration, Duration: 720 * time.Hour}, - "order": {Type: TypeChoice, Text: "newest"}, - "tags": {Type: TypeLines, Lines: []string{"news"}}, - "api_key": {Type: TypeSecret}, - } - sameValues(t, values, want) +// defaults returns the notes values when each one comes from its default. +func defaults() Values { + return Values{ + "title": {Type: TypeText, Source: SourceDefault, Text: "Notes"}, + "per_page": {Type: TypeCount, Source: SourceDefault, Count: 10}, + "open": {Type: TypeFlag, Source: SourceDefault}, + "keep_for": {Type: TypeDuration, Source: SourceDefault, Text: "720h", Duration: 720 * time.Hour}, + "order": {Type: TypeChoice, Source: SourceDefault, Text: "newest"}, + "tags": {Type: TypeLines, Source: SourceDefault, Lines: []string{"news"}}, + "api_key": {Type: TypeSecret, Source: SourceDefault}, } } -func TestResolveLetsTheEnvironmentWinOverTheDefault(t *testing.T) { - values := resolved(t, map[string]string{ +// everyVariable returns an environment that sets each notes setting. +func everyVariable() map[string]string { + return map[string]string{ "APP_PLUGIN_NOTES__TITLE": " Field Notes ", "APP_PLUGIN_NOTES__PER_PAGE": "25", "APP_PLUGIN_NOTES__OPEN": "true", - "APP_PLUGIN_NOTES__KEEP_FOR": "48h", + "APP_PLUGIN_NOTES__KEEP_FOR": " 48h ", "APP_PLUGIN_NOTES__ORDER": "oldest", "APP_PLUGIN_NOTES__TAGS": "news,, events", "APP_PLUGIN_NOTES__API_KEY": knownSecret, + } +} + +// fromEnvironment returns the notes values everyVariable works out to. +func fromEnvironment() Values { + return Values{ + "title": {Type: TypeText, Source: SourceEnvironment, Text: "Field Notes"}, + "per_page": {Type: TypeCount, Source: SourceEnvironment, Count: 25}, + "open": {Type: TypeFlag, Source: SourceEnvironment, Flag: true}, + "keep_for": {Type: TypeDuration, Source: SourceEnvironment, Text: "48h", Duration: 48 * time.Hour}, + "order": {Type: TypeChoice, Source: SourceEnvironment, Text: "oldest"}, + "tags": {Type: TypeLines, Source: SourceEnvironment, Lines: []string{"news", "events"}}, + "api_key": {Type: TypeSecret, Source: SourceEnvironment, Secret: hide(knownSecret)}, + } +} + +// wantReport is the report a test wants: the key and the reason and text of its value error. +type wantReport struct { + key, reason, text string +} + +// onlyReport fails the test unless rejected holds one report, the one want describes. +func onlyReport(t *testing.T, rejected []RejectedSavedValue, want wantReport) { + t.Helper() + if len(rejected) != 1 { + t.Errorf("Resolve reported %+v, want one report of %s", rejected, want.key) + return + } + sameReport(t, rejected[0], want) +} + +// sameReport fails the test unless report is the one want describes. +func sameReport(t *testing.T, report RejectedSavedValue, want wantReport) { + t.Helper() + var valueErr *ValueError + if report.Key != want.key || !errors.As(report.Err, &valueErr) { + t.Errorf("report %+v, want a value error of %s", report, want.key) + return + } + if valueErr.Reason != want.reason || valueErr.Error() != want.text { + t.Errorf("%s reported as %q reading %q, want %q reading %q", + want.key, valueErr.Reason, valueErr, want.reason, want.text) + } +} + +// keysOf returns the key of each report, in its order. +func keysOf(rejected []RejectedSavedValue) []string { + keys := make([]string, 0, len(rejected)) + for _, report := range rejected { + keys = append(keys, report.Key) + } + return keys +} + +func TestResolveTakesEachDefaultWhenTheEnvironmentHoldsNone(t *testing.T) { + for _, found := range []Sources{ + {}, + {Env: map[string]string{}, Saved: map[string]string{}}, + inEnv(map[string]string{"APP_PLUGIN_OTHER__TITLE": "Other"}), + } { + sameValues(t, resolved(t, found), defaults()) + } +} + +func TestResolveLetsTheEnvironmentWinOverTheDefault(t *testing.T) { + sameValues(t, resolved(t, inEnv(everyVariable())), fromEnvironment()) +} + +func TestResolveLetsASavedValueWinOverTheDefault(t *testing.T) { + values := resolved(t, savedAs(map[string]string{ + "title": " Field Notes ", "per_page": "25", "open": "true", "keep_for": " 48h ", "order": "oldest", + "tags": "news,, events", + })) + want := defaults() + want["title"] = Value{Type: TypeText, Source: SourceSaved, Text: "Field Notes"} + want["per_page"] = Value{Type: TypeCount, Source: SourceSaved, Count: 25} + want["open"] = Value{Type: TypeFlag, Source: SourceSaved, Flag: true} + want["keep_for"] = Value{Type: TypeDuration, Source: SourceSaved, Text: "48h", Duration: 48 * time.Hour} + want["order"] = Value{Type: TypeChoice, Source: SourceSaved, Text: "oldest"} + want["tags"] = Value{Type: TypeLines, Source: SourceSaved, Lines: []string{"news", "events"}} + sameValues(t, values, want) +} + +func TestResolveLetsTheEnvironmentWinOverASavedValue(t *testing.T) { + values := resolved(t, Sources{Env: everyVariable(), Saved: map[string]string{ + "title": "Saved Notes", "per_page": "30", "open": "false", "keep_for": "2h", "order": "newest", + "tags": "saved", "api_key": "saved-key", + }}) + sameValues(t, values, fromEnvironment()) +} + +func TestResolveLetsASavedValueApplyUnderABlankVariable(t *testing.T) { + for _, blank := range []string{"", " ", "\t"} { + values := resolved(t, Sources{ + Env: map[string]string{"APP_PLUGIN_NOTES__TITLE": blank, "APP_PLUGIN_NOTES__PER_PAGE": blank}, + Saved: map[string]string{"title": "Field Notes", "per_page": "25"}, + }) + want := defaults() + want["title"] = Value{Type: TypeText, Source: SourceSaved, Text: "Field Notes"} + want["per_page"] = Value{Type: TypeCount, Source: SourceSaved, Count: 25} + sameValues(t, values, want) + } +} + +func TestResolveKeepsASavedEmptyTextOrEmptyLinesOverTheDefault(t *testing.T) { + for _, empty := range []string{"", " ", " , ,"} { + values := resolved(t, savedAs(map[string]string{"title": empty, "tags": empty})) + want := defaults() + want["title"] = Value{Type: TypeText, Source: SourceSaved, Text: strings.TrimSpace(empty)} + want["tags"] = Value{Type: TypeLines, Source: SourceSaved} + sameValues(t, values, want) + } +} + +func TestResolveFallsBackToTheDefaultForASavedValueItsTypeRejects(t *testing.T) { + cases := []struct { + key, saved, reason, text string + }{ + {"per_page", "banana", ReasonNotWhole, `must be a whole number, got "banana"`}, + {"per_page", "", ReasonNotWhole, `must be a whole number, got ""`}, + {"per_page", " 0 ", ReasonBelowMin, `must stand at or above 1, got "0"`}, + {"per_page", "60", ReasonAboveMax, `must stand at or below 50, got "60"`}, + {"open", "maybe", ReasonNotFlag, `must be true or false, got "maybe"`}, + {"open", "", ReasonNotFlag, `must be true or false, got ""`}, + {"keep_for", "soon", ReasonNotDuration, `must be a duration like 30s, got "soon"`}, + {"keep_for", "", ReasonNotDuration, `must be a duration like 30s, got ""`}, + {"keep_for", "-1h", ReasonNotPositive, `must stand above zero, got "-1h"`}, + {"order", "random", ReasonNotOption, `must be one of newest, oldest, got "random"`}, + {"order", "", ReasonNotOption, `must be one of newest, oldest, got ""`}, + } + for _, c := range cases { + values, rejected := resolvedWithReports(t, savedAs(map[string]string{c.key: c.saved})) + sameValues(t, values, defaults()) + onlyReport(t, rejected, wantReport{c.key, c.reason, c.text}) + } +} + +func TestResolveNeverTakesASavedSecretAndReportsItWithoutItsValue(t *testing.T) { + for _, found := range []Sources{ + savedAs(map[string]string{"api_key": knownSecret}), + savedAs(map[string]string{"api_key": ""}), + {Env: map[string]string{"APP_PLUGIN_NOTES__API_KEY": " "}, Saved: map[string]string{"api_key": knownSecret}}, + } { + values, rejected := resolvedWithReports(t, found) + sameValues(t, values, defaults()) + onlyReport(t, rejected, wantReport{"api_key", ReasonEnvironmentOnly, savedSecretText}) + for _, out := range renderings(rejected) { + if strings.Contains(out, knownSecret) { + t.Errorf("a rendering of the reports shows the secret: %q", out) + } + } + } +} + +func TestResolveNeitherReadsNorReportsASavedValueUnderAVariableThatHoldsOne(t *testing.T) { + values := resolved(t, Sources{ + Env: map[string]string{"APP_PLUGIN_NOTES__PER_PAGE": "25", "APP_PLUGIN_NOTES__API_KEY": knownSecret}, + Saved: map[string]string{"per_page": "banana", "api_key": "saved-key"}, + }) + want := defaults() + want["per_page"] = Value{Type: TypeCount, Source: SourceEnvironment, Count: 25} + want["api_key"] = Value{Type: TypeSecret, Source: SourceEnvironment, Secret: hide(knownSecret)} + sameValues(t, values, want) +} + +func TestResolveIgnoresSavedKeysTheSchemaDoesNotDeclare(t *testing.T) { + values := resolved(t, Sources{ + Env: map[string]string{"title": "Keyed Notes"}, + Saved: map[string]string{"colour": "green", "APP_PLUGIN_NOTES__TITLE": "Named Notes"}, }) - want := Values{ - "title": {Type: TypeText, Text: "Field Notes"}, - "per_page": {Type: TypeCount, Count: 25}, - "open": {Type: TypeFlag, Flag: true}, - "keep_for": {Type: TypeDuration, Duration: 48 * time.Hour}, - "order": {Type: TypeChoice, Text: "oldest"}, - "tags": {Type: TypeLines, Lines: []string{"news", "events"}}, - "api_key": {Type: TypeSecret, Secret: hide(knownSecret)}, + sameValues(t, values, defaults()) +} + +func TestResolveReportsEachRejectedSavedValueInTheManifestsOrder(t *testing.T) { + values, rejected := resolvedWithReports(t, savedAs(map[string]string{ + "order": "random", "api_key": knownSecret, "per_page": "banana", "title": "Field Notes", "open": "maybe", + })) + if got, want := keysOf(rejected), []string{"per_page", "open", "order", "api_key"}; !slices.Equal(got, want) { + t.Fatalf("Resolve reported %q, want %q", got, want) } + sameReport(t, rejected[0], wantReport{"per_page", ReasonNotWhole, `must be a whole number, got "banana"`}) + sameReport(t, rejected[1], wantReport{"open", ReasonNotFlag, `must be true or false, got "maybe"`}) + sameReport(t, rejected[2], wantReport{"order", ReasonNotOption, `must be one of newest, oldest, got "random"`}) + sameReport(t, rejected[3], wantReport{"api_key", ReasonEnvironmentOnly, savedSecretText}) + want := defaults() + want["title"] = Value{Type: TypeText, Source: SourceSaved, Text: "Field Notes"} sameValues(t, values, want) } func TestResolveCountsAnEmptyOrBlankValueAsUnset(t *testing.T) { for _, empty := range []string{"", " ", "\t"} { - values := resolved(t, map[string]string{"APP_PLUGIN_NOTES__PER_PAGE": empty, "APP_PLUGIN_NOTES__TITLE": empty}) - if got := values["per_page"].Count; got != 10 { - t.Errorf("per_page with %q = %d, want the default 10", empty, got) - } - if got := values["title"].Text; got != "Notes" { - t.Errorf("title with %q = %q, want the default Notes", empty, got) - } + values := resolved(t, inEnv(map[string]string{ + "APP_PLUGIN_NOTES__PER_PAGE": empty, "APP_PLUGIN_NOTES__TITLE": empty, + })) + sameValues(t, values, defaults()) } } func TestResolveLetsAListOfOnlyCommasClearTheDefaultList(t *testing.T) { - values := resolved(t, map[string]string{"APP_PLUGIN_NOTES__TAGS": " , ,"}) - if got := values["tags"].Lines; got != nil { - t.Errorf("tags with only commas = %q, want no items in place of the default news", got) + values := resolved(t, inEnv(map[string]string{"APP_PLUGIN_NOTES__TAGS": " , ,"})) + if got := values["tags"]; !sameValue(got, Value{Type: TypeLines, Source: SourceEnvironment}) { + t.Errorf("tags with only commas = %+v, want no items in place of the default news", got) } } func TestResolveTakesASecretOnlyFromTheEnvironmentAndAsWritten(t *testing.T) { cases := []struct { - value, want string + value string + want Value }{ - {"", ""}, - {" ", " "}, - {" key-for-example ", " key-for-example "}, + {"", Value{Type: TypeSecret, Source: SourceDefault}}, + {" ", Value{Type: TypeSecret, Source: SourceDefault}}, + {" key-for-example ", Value{Type: TypeSecret, Source: SourceEnvironment, Secret: hide(" key-for-example ")}}, } for _, c := range cases { - values := resolved(t, map[string]string{"APP_PLUGIN_NOTES__API_KEY": c.value}) - if got := values["api_key"].Secret.Reveal(); got != c.want { - t.Errorf("api_key with %q reveals %q, want %q", c.value, got, c.want) + got := resolved(t, inEnv(map[string]string{"APP_PLUGIN_NOTES__API_KEY": c.value}))["api_key"] + if !sameValue(got, c.want) { + t.Errorf("api_key with %q = %+v revealing %q, want %+v", c.value, got, got.Secret.Reveal(), c.want) } } } @@ -112,17 +308,18 @@ func TestResolveNeverTakesTheDefaultOfASecret(t *testing.T) { schema := Schema{ID: "notes", Fields: []Field{ {Key: "api_key", Type: TypeSecret, Env: "APP_PLUGIN_NOTES__API_KEY", Default: knownSecret}, }} - values, err := schema.Resolve(nil) + values, rejected, err := schema.Resolve(Sources{}) if err != nil { t.Fatalf("Resolve = %v", err) } - if got := values["api_key"].Secret.String(); got != "not set" { - t.Errorf("a secret with a default and no variable reads %q, want not set", got) + sameValues(t, values, Values{"api_key": {Type: TypeSecret, Source: SourceDefault}}) + if rejected != nil { + t.Errorf("Resolve reported %+v, want nil", rejected) } } func TestResolveFillsOnlyTheSecretOfASecret(t *testing.T) { - got := resolved(t, map[string]string{"APP_PLUGIN_NOTES__API_KEY": knownSecret})["api_key"] + got := resolved(t, inEnv(map[string]string{"APP_PLUGIN_NOTES__API_KEY": knownSecret}))["api_key"] if got.Text != "" || got.Lines != nil { t.Errorf("a secret filled %+v beside its Secret", got) } @@ -135,11 +332,18 @@ func TestResolveGivesTheZeroValueWhenNeitherSourceHoldsOne(t *testing.T) { if err != nil { t.Fatalf("Check = %v", err) } - values, err := schema.Resolve(map[string]string{"APP_PLUGIN_NOTES__OPEN": " "}) + values, rejected, err := schema.Resolve(inEnv(map[string]string{"APP_PLUGIN_NOTES__OPEN": " "})) if err != nil { t.Fatalf("Resolve = %v", err) } - sameValues(t, values, Values{"title": {Type: TypeText}, "open": {Type: TypeFlag}, "tags": {Type: TypeLines}}) + sameValues(t, values, Values{ + "title": {Type: TypeText, Source: SourceDefault}, + "open": {Type: TypeFlag, Source: SourceDefault}, + "tags": {Type: TypeLines, Source: SourceDefault}, + }) + if rejected != nil { + t.Errorf("Resolve reported %+v, want nil", rejected) + } } func TestResolveNamesTheVariableOfAValueItsTypeRejects(t *testing.T) { @@ -156,22 +360,47 @@ func TestResolveNamesTheVariableOfAValueItsTypeRejects(t *testing.T) { {"APP_PLUGIN_NOTES__ORDER", "random", `APP_PLUGIN_NOTES__ORDER: must be one of newest, oldest, got "random"`}, } for _, c := range cases { - values, err := notesSchema(t).Resolve(map[string]string{c.variable: c.value}) + values, rejected, err := notesSchema(t).Resolve(inEnv(map[string]string{c.variable: c.value})) if err == nil || err.Error() != c.want { t.Errorf("%s=%q: Resolve = %v, want %q", c.variable, c.value, err, c.want) } - if values != nil { - t.Errorf("%s=%q: Resolve answered %v beside its error", c.variable, c.value, values) + if values != nil || rejected != nil { + t.Errorf("%s=%q: Resolve answered %v and %v beside its error", c.variable, c.value, values, rejected) + } + } +} + +func TestResolveRejectsAValueInTheEnvironmentWhateverIsSaved(t *testing.T) { + _, _, err := notesSchema(t).Resolve(Sources{ + Env: map[string]string{"APP_PLUGIN_NOTES__PER_PAGE": "banana"}, + Saved: map[string]string{"per_page": "25", "order": "random"}, + }) + if want := `APP_PLUGIN_NOTES__PER_PAGE: must be a whole number, got "banana"`; err == nil || err.Error() != want { + t.Errorf("Resolve = %v, want %q", err, want) + } +} + +func TestResolveNamesTheVariableOfADefaultItsTypeRejects(t *testing.T) { + schema := Schema{ID: "notes", Fields: []Field{ + {Key: "per_page", Type: TypeCount, Env: "APP_PLUGIN_NOTES__PER_PAGE", Default: "lots"}, + }} + for _, found := range []Sources{{}, savedAs(map[string]string{"per_page": "banana"})} { + values, rejected, err := schema.Resolve(found) + if want := `APP_PLUGIN_NOTES__PER_PAGE: must be a whole number, got "lots"`; err == nil || err.Error() != want { + t.Errorf("Resolve = %v, want %q", err, want) + } + if values != nil || rejected != nil { + t.Errorf("Resolve answered %v and %v beside its error", values, rejected) } } } func TestResolveAnswersTheFirstRejectedValueInTheManifestsOrder(t *testing.T) { - _, err := notesSchema(t).Resolve(map[string]string{ + _, _, err := notesSchema(t).Resolve(inEnv(map[string]string{ "APP_PLUGIN_NOTES__ORDER": "random", "APP_PLUGIN_NOTES__PER_PAGE": "banana", "APP_PLUGIN_NOTES__OPEN": "maybe", - }) + })) if want := `APP_PLUGIN_NOTES__PER_PAGE: must be a whole number, got "banana"`; err == nil || err.Error() != want { t.Errorf("Resolve = %v, want %q", err, want) } @@ -179,7 +408,10 @@ func TestResolveAnswersTheFirstRejectedValueInTheManifestsOrder(t *testing.T) { func TestResolveNeverQuotesASecretBesideARejectedValue(t *testing.T) { for _, neighbour := range []string{"APP_PLUGIN_NOTES__PER_PAGE", "APP_PLUGIN_NOTES__OPEN"} { - _, err := notesSchema(t).Resolve(map[string]string{"APP_PLUGIN_NOTES__API_KEY": knownSecret, neighbour: "banana"}) + _, _, err := notesSchema(t).Resolve(Sources{ + Env: map[string]string{"APP_PLUGIN_NOTES__API_KEY": knownSecret, neighbour: "banana"}, + Saved: map[string]string{"api_key": knownSecret}, + }) if err == nil || strings.Contains(err.Error(), knownSecret) { t.Errorf("Resolve = %v, want an error that does not hold the secret", err) } @@ -188,25 +420,35 @@ func TestResolveNeverQuotesASecretBesideARejectedValue(t *testing.T) { func TestResolveRejectsAFieldOfAnUnknownTypeByItsVariable(t *testing.T) { schema := Schema{ID: "notes", Fields: []Field{{Key: "mood", Type: "colour", Env: "APP_PLUGIN_NOTES__MOOD"}}} - _, err := schema.Resolve(map[string]string{"APP_PLUGIN_NOTES__MOOD": "blue"}) want := `APP_PLUGIN_NOTES__MOOD: type "colour" is not one of text, count, flag, duration, choice, secret, lines` - if err == nil || err.Error() != want { - t.Errorf("Resolve = %v, want %q", err, want) + for _, found := range []Sources{ + {}, inEnv(map[string]string{"APP_PLUGIN_NOTES__MOOD": "blue"}), savedAs(map[string]string{"mood": "blue"}), + } { + _, _, err := schema.Resolve(found) + if err == nil || err.Error() != want { + t.Errorf("Resolve = %v, want %q", err, want) + } } } func TestResolveOfASchemaWithNoFieldsAnswersNoValues(t *testing.T) { - values, err := Schema{ID: "notes"}.Resolve(map[string]string{"APP_PLUGIN_NOTES__TITLE": "Notes"}) + values, rejected, err := Schema{ID: "notes"}.Resolve(Sources{ + Env: map[string]string{"APP_PLUGIN_NOTES__TITLE": "Notes"}, + Saved: map[string]string{"title": "Notes"}, + }) if err != nil { t.Fatalf("Resolve = %v", err) } if values == nil || len(values) != 0 { t.Errorf("Resolve = %#v, want an empty map", values) } + if rejected != nil { + t.Errorf("Resolve reported %+v, want nil", rejected) + } } func TestResolvedValuesNeverShowAKnownSecret(t *testing.T) { - values := resolved(t, map[string]string{"APP_PLUGIN_NOTES__API_KEY": knownSecret}) + values := resolved(t, inEnv(map[string]string{"APP_PLUGIN_NOTES__API_KEY": knownSecret})) for _, value := range []any{values, &values, values["api_key"], map[string]Values{"notes": values}} { for _, out := range renderings(value) { if strings.Contains(out, knownSecret) { diff --git a/pluginkit/settings/settings.go b/pluginkit/settings/settings.go index 6269bbc..1743207 100644 --- a/pluginkit/settings/settings.go +++ b/pluginkit/settings/settings.go @@ -26,16 +26,27 @@ const ( TypeLines = "lines" ) +const ( + // SourceEnvironment says a value came from the environment. + SourceEnvironment = "environment" + // SourceSaved says a value came from the values an administrator saved. + SourceSaved = "saved" + // SourceDefault says a value came from the setting's default. + SourceDefault = "default" +) + // Rules is what one application sets for every plugin: the start of each variable name and the key starts it reserves. type Rules struct { Prefix string Reserved []string } -// Field is one checked setting: its key, its type, the variable that sets it and the rules its value follows. +// Field is one checked setting: its key, type, label and help, the variable that sets it and the rules of its value. type Field struct { Key string Type string + Label string + Help string Env string Default string Min *int @@ -49,9 +60,10 @@ type Schema struct { Fields []Field } -// Value is one resolved setting, with the reading of its type filled in. +// Value is one resolved setting, with where it came from and the reading of its type filled in. type Value struct { Type string + Source string Text string Count int Flag bool diff --git a/pluginkit/settings/settings_test.go b/pluginkit/settings/settings_test.go index c763a14..142037e 100644 --- a/pluginkit/settings/settings_test.go +++ b/pluginkit/settings/settings_test.go @@ -53,6 +53,28 @@ func renderings(value any) []string { return append(append(prints(value), logged(value)...), encoded(value)) } +func TestSourcesReadAsTheNamesAnApplicationSends(t *testing.T) { + cases := []struct { + got, want string + }{ + {SourceEnvironment, "environment"}, + {SourceSaved, "saved"}, + {SourceDefault, "default"}, + } + for _, c := range cases { + if c.got != c.want { + t.Errorf("source %q, want %q", c.got, c.want) + } + } +} + +func TestValueKeepsWhereItCameFrom(t *testing.T) { + value := Value{Type: TypeText, Source: SourceSaved, Text: "Field Notes"} + if got := encoded(value); !strings.Contains(got, `"Source":"saved"`) { + t.Errorf("the JSON of a saved value %s does not say it was saved", got) + } +} + func TestHiddenRevealsItsText(t *testing.T) { if got := hide(knownSecret).Reveal(); got != knownSecret { t.Errorf("Reveal() = %q, want %q", got, knownSecret) @@ -138,8 +160,8 @@ func TestHiddenNeverShowsItsTextWhereverItSits(t *testing.T) { "slice": []Hidden{h}, "unexported field": holder{secret: h}, "unexported pointer": &holder{secret: h}, - "value": Value{Type: TypeSecret, Secret: h}, - "values": Values{"api_key": {Type: TypeSecret, Secret: h}}, + "value": Value{Type: TypeSecret, Source: SourceEnvironment, Secret: h}, + "values": Values{"api_key": {Type: TypeSecret, Source: SourceEnvironment, Secret: h}}, "any map": map[string]any{"api_key": h}, } for place, value := range places {