From cac48b054c6012ecc3e324a0e79433dbe5f98152 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:09:50 +0100 Subject: [PATCH 01/12] test(pluginkit): pin how plugin settings are checked and worked out --- pluginkit/features/features_test.go | 8 ++ .../features/settings-declarations.feature | 80 ++++++++++++ pluginkit/features/settings.feature | 120 ++++++++++++++++++ 3 files changed, 208 insertions(+) create mode 100644 pluginkit/features/settings-declarations.feature create mode 100644 pluginkit/features/settings.feature diff --git a/pluginkit/features/features_test.go b/pluginkit/features/features_test.go index c4ef5bc..1287039 100644 --- a/pluginkit/features/features_test.go +++ b/pluginkit/features/features_test.go @@ -53,3 +53,11 @@ func TestBoot(t *testing.T) { func TestRoutes(t *testing.T) { runFeature(t, "routes.feature", initializeRoutes()) } + +func TestSettings(t *testing.T) { + runFeature(t, "settings.feature", func(*godog.ScenarioContext) {}) +} + +func TestSettingsDeclarations(t *testing.T) { + runFeature(t, "settings-declarations.feature", func(*godog.ScenarioContext) {}) +} diff --git a/pluginkit/features/settings-declarations.feature b/pluginkit/features/settings-declarations.feature new file mode 100644 index 0000000..424732f --- /dev/null +++ b/pluginkit/features/settings-declarations.feature @@ -0,0 +1,80 @@ +Feature: Checking the settings a plugin declares + Before a plugin registers, a downstream application checks the settings + its plugin.json declares. Each type has its own rules for bounds, options + and defaults, each key follows one shape, and the application reserves + key starts of its own. A declaration outside the rules is rejected with + the setting's place, its key and the rule it breaks. The rejection of a + secret never quotes its default, because plugin.json is public. + + Background: + Given the application names plugin variables under "APP_PLUGIN_" + And the application reserves the key starts "job_" and "db_" + + @wip + Scenario: A plugin that declares one setting of each type passes the check + Given the plugin "notes" declares these settings: + | key | type | default | min | max | options | + | title | text | Notes | | | | + | per_page | count | 10 | 1 | 50 | | + | open | flag | | | | | + | keep_for | duration | 720h | | | | + | order | choice | newest | | | newest, oldest | + | tags | lines | | | | | + | api_key | secret | | | | | + When the settings of "notes" are checked + Then the settings pass the check + + @wip + Scenario Outline: A declaration outside the rules is rejected with its reason + Given the plugin "notes" declares + When the settings of "notes" are checked + Then the check rejects them with "" + + Examples: + | declaration | reason | + | a setting "mood" of the type "colour" | settings[0] mood: type "colour" is not one of text, count, flag, duration, choice, secret, lines | + | a text setting "Max__Seats" | settings[0] Max__Seats: a key is lowercase words joined by one underscore | + | a text setting "_title" | settings[0] _title: a key is lowercase words joined by one underscore | + | a text setting "job_every" | settings[0] job_every: a key must not start with job_ or db_ | + | a text setting "db_conns" | settings[0] db_conns: a key must not start with job_ or db_ | + | the text setting "title" twice | settings[1] title: the key is declared twice | + | a count "max_seats" with no default | settings[0] max_seats: a count needs a default | + | a count "max_seats" with the default "lots" | settings[0] max_seats: the default must be a whole number, got "lots" | + | a count "max_seats" from 1 to 50 with the default "60" | settings[0] max_seats: the default must stand at or below 50, got "60" | + | a count "max_seats" from 10 to 5 with the default "7" | settings[0] max_seats: min 10 stands above max 5 | + | a count "max_seats" from 1.5 with the default "4" | settings[0] max_seats: min 1.5 is not a whole number | + | a text "title" with the max 80 | settings[0] title: min and max apply only to a count | + | a lines "tags" with the min 1 | settings[0] tags: min and max apply only to a count | + | a text "title" with the options "a" and "b" | settings[0] title: options apply only to a choice | + | a choice "order" with no options | settings[0] order: a choice needs options | + | a choice "order" of "newest" and "oldest" with no default | settings[0] order: a choice needs a default | + | a choice "order" of "newest" and "oldest" with the default "random" | settings[0] order: the default must be one of newest, oldest, got "random" | + | a duration "keep_for" with no default | settings[0] keep_for: a duration needs a default | + | a duration "keep_for" with the default "soon" | settings[0] keep_for: the default must be a duration like 30s, got "soon" | + | a flag "open" with the default "maybe" | settings[0] open: the default must be true or false, got "maybe" | + | a secret "api_key" with the default "key-for-example" | settings[0] api_key: a secret takes no default, because plugin.json is public | + | a text "title" that names the content type "post" | settings[0] title: a text setting takes no of field | + + @wip + Scenario: The rejection of a secret's default never quotes it + Given the plugin "notes" declares a secret "api_key" with the default "key-for-example" + When the settings of "notes" are checked + Then the check rejects them with "settings[0] api_key: a secret takes no default, because plugin.json is public" + And the reason does not hold "key-for-example" + + @wip + Scenario Outline: A plugin with settings keeps its id clear of doubled and trailing hyphens + Given the plugin "" declares the text setting "title" + When the settings of "" are checked + Then the check rejects them with "the id must not hold two hyphens in a row or end with one when the plugin has settings" + + Examples: + | id | + | notes--pro | + | notes- | + + @wip + Scenario: A plugin with no settings keeps any id the wiring takes + Given the plugin "notes--pro" declares no settings + When the settings of "notes--pro" are checked + Then the settings pass the check diff --git a/pluginkit/features/settings.feature b/pluginkit/features/settings.feature new file mode 100644 index 0000000..1252653 --- /dev/null +++ b/pluginkit/features/settings.feature @@ -0,0 +1,120 @@ +Feature: Working out each plugin setting from the environment and its default + A downstream application lists the settings each plugin declares in its + plugin.json. After the check, it looks up the environment variable of + each setting and works out each value from the values it found, reading + no environment itself. A value the environment holds wins over the + default, an empty value counts as unset, and a value its type rejects is + named by its variable. A secret comes from the environment only and + prints as set or not set, never as itself. + + 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 | | | | | + + @wip + Scenario: Each setting is read from a variable named after its plugin and its key + Then the settings of "notes" are read from these variables: + | key | variable | + | title | APP_PLUGIN_NOTES__TITLE | + | per_page | APP_PLUGIN_NOTES__PER_PAGE | + | open | APP_PLUGIN_NOTES__OPEN | + | keep_for | APP_PLUGIN_NOTES__KEEP_FOR | + | order | APP_PLUGIN_NOTES__ORDER | + | tags | APP_PLUGIN_NOTES__TAGS | + | api_key | APP_PLUGIN_NOTES__API_KEY | + + @wip + Scenario Outline: Each hyphen of a plugin id becomes an underscore in the variable + Given the plugin "" declares the text setting "max_seats" + Then the setting "max_seats" of "" is read from "" + + Examples: + | id | variable | + | events | APP_PLUGIN_EVENTS__MAX_SEATS | + | events-pro | APP_PLUGIN_EVENTS_PRO__MAX_SEATS | + | events-pro-max | APP_PLUGIN_EVENTS_PRO_MAX__MAX_SEATS | + + @wip + Scenario: Each setting takes its default when the environment holds none + When the settings of "notes" are worked out + Then the settings read: + | key | value | + | title | Notes | + | per_page | 10 | + | open | false | + | keep_for | 720h | + | order | newest | + | tags | news | + | api_key | not set | + + @wip + Scenario Outline: A value in the environment wins over the default + Given the environment holds "" in "" + When the settings of "notes" are worked out + Then "" reads "" + + Examples: + | key | variable | value | read | + | title | APP_PLUGIN_NOTES__TITLE | Field Notes | Field Notes | + | per_page | APP_PLUGIN_NOTES__PER_PAGE | 25 | 25 | + | open | APP_PLUGIN_NOTES__OPEN | true | true | + | keep_for | APP_PLUGIN_NOTES__KEEP_FOR | 48h | 48h | + | order | APP_PLUGIN_NOTES__ORDER | oldest | oldest | + | tags | APP_PLUGIN_NOTES__TAGS | news,, events | news, events | + | api_key | APP_PLUGIN_NOTES__API_KEY | key-for-example | set | + + @wip + Scenario: An empty value counts as unset + Given the environment holds "" in "APP_PLUGIN_NOTES__PER_PAGE" + And the environment holds "" in "APP_PLUGIN_NOTES__API_KEY" + When the settings of "notes" are worked out + Then "per_page" reads "10" + And "api_key" reads "not set" + + @wip + Scenario Outline: A value its type rejects is named by its variable + Given the environment holds "" in "" + When the settings of "notes" are worked out + Then the settings are rejected with "" + + Examples: + | variable | value | reason | + | APP_PLUGIN_NOTES__PER_PAGE | banana | APP_PLUGIN_NOTES__PER_PAGE: must be a whole number, got "banana" | + | APP_PLUGIN_NOTES__PER_PAGE | 2.5 | APP_PLUGIN_NOTES__PER_PAGE: must be a whole number, got "2.5" | + | APP_PLUGIN_NOTES__PER_PAGE | 60 | APP_PLUGIN_NOTES__PER_PAGE: must stand at or below 50, got "60" | + | APP_PLUGIN_NOTES__PER_PAGE | 0 | APP_PLUGIN_NOTES__PER_PAGE: must stand at or above 1, got "0" | + | APP_PLUGIN_NOTES__KEEP_FOR | soon | APP_PLUGIN_NOTES__KEEP_FOR: must be a duration like 30s, got "soon" | + | APP_PLUGIN_NOTES__KEEP_FOR | -1h | APP_PLUGIN_NOTES__KEEP_FOR: must stand above zero, got "-1h" | + | APP_PLUGIN_NOTES__OPEN | maybe | APP_PLUGIN_NOTES__OPEN: must be true or false, got "maybe" | + | APP_PLUGIN_NOTES__ORDER | random | APP_PLUGIN_NOTES__ORDER: must be one of newest, oldest, got "random" | + + @wip + Scenario: The first rejected value in the manifest's order is the one named + Given the environment holds "banana" in "APP_PLUGIN_NOTES__PER_PAGE" + And the environment holds "random" in "APP_PLUGIN_NOTES__ORDER" + When the settings of "notes" are worked out + Then the settings are rejected with "APP_PLUGIN_NOTES__PER_PAGE: must be a whole number, got "banana"" + + @wip + Scenario: A secret reads its value only when asked for and prints as set + Given the environment holds "key-for-example" in "APP_PLUGIN_NOTES__API_KEY" + When the settings of "notes" are worked out + Then the secret "api_key" reads "key-for-example" when asked for + And every print or log of the settings shows "set" for "api_key" + And no print, log or encoding of the settings holds "key-for-example" + + @wip + Scenario: A value rejected beside a secret never shows the secret + Given the environment holds "key-for-example" in "APP_PLUGIN_NOTES__API_KEY" + And the environment holds "banana" in "APP_PLUGIN_NOTES__PER_PAGE" + When the settings of "notes" are worked out + Then the settings are rejected with "APP_PLUGIN_NOTES__PER_PAGE: must be a whole number, got "banana"" + And the reason does not hold "key-for-example" From 45924488dfc9ac63d3ed13513550b2379483431b Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:09:51 +0100 Subject: [PATCH 02/12] feat(pluginkit): name each plugin setting's variable from its plugin and its key --- pluginkit/settings/name.go | 48 ++++++++++++++ pluginkit/settings/name_test.go | 110 ++++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+) create mode 100644 pluginkit/settings/name.go create mode 100644 pluginkit/settings/name_test.go diff --git a/pluginkit/settings/name.go b/pluginkit/settings/name.go new file mode 100644 index 0000000..93e6fd4 --- /dev/null +++ b/pluginkit/settings/name.go @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "errors" + "fmt" + "regexp" + "strings" +) + +// keyShape matches lowercase words of letters and digits joined by one underscore, the first starting with a letter. +var keyShape = regexp.MustCompile(`^[a-z][a-z0-9]*(_[a-z0-9]+)*$`) + +// Name returns the variable that sets key for plugin id under prefix. +func Name(prefix, id, key string) string { + return prefix + strings.ToUpper(strings.ReplaceAll(id, "-", "_")) + "__" + strings.ToUpper(key) +} + +// checkKey rejects a key that is not lowercase words joined by one underscore or that starts with a reserved word. +func checkKey(key string, reserved []string) error { + if !keyShape.MatchString(key) { + return errors.New("a key is lowercase words joined by one underscore") + } + for _, start := range reserved { + if strings.HasPrefix(key, start) { + return fmt.Errorf("a key must not start with %s", orList(reserved)) + } + } + return nil +} + +// checkID rejects the id of a plugin with settings when it holds two hyphens in a row or ends with one. +func checkID(id string) error { + if strings.Contains(id, "--") || strings.HasSuffix(id, "-") { + return fmt.Errorf("the id %s must not hold two hyphens in a row or end with one when the plugin has settings", id) + } + return nil +} + +// orList joins words with commas and an or before the last. +func orList(words []string) string { + last := len(words) - 1 + if last == 0 { + return words[0] + } + return strings.Join(words[:last], ", ") + " or " + words[last] +} diff --git a/pluginkit/settings/name_test.go b/pluginkit/settings/name_test.go new file mode 100644 index 0000000..d44f54b --- /dev/null +++ b/pluginkit/settings/name_test.go @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "testing" +) + +func TestNameJoinsThePrefixTheIDAndTheKeyInCapitals(t *testing.T) { + cases := []struct { + id, key, want string + }{ + {"feed", "title", "APP_PLUGIN_FEED__TITLE"}, + {"feed", "items", "APP_PLUGIN_FEED__ITEMS"}, + {"events", "max_seats", "APP_PLUGIN_EVENTS__MAX_SEATS"}, + {"events-pro", "max_seats", "APP_PLUGIN_EVENTS_PRO__MAX_SEATS"}, + {"events-pro-max", "max_seats", "APP_PLUGIN_EVENTS_PRO_MAX__MAX_SEATS"}, + {"notes2", "page2_size", "APP_PLUGIN_NOTES2__PAGE2_SIZE"}, + } + for _, c := range cases { + if got := Name("APP_PLUGIN_", c.id, c.key); got != c.want { + t.Errorf("Name(%q, %q) = %q, want %q", c.id, c.key, got, c.want) + } + } +} + +func TestNameNeverGivesTwoSettingsOneVariable(t *testing.T) { + ids := []string{"a", "a-b", "a-b-c", "ab", "hook", "hook-save", "x", "x-a", "x-a-b"} + keys := []string{"b", "c", "b_c", "a_b", "budget", "save_budget", "a", "a_b_c", "b2"} + seen := map[string][2]string{} + for _, id := range ids { + if err := checkID(id); err != nil { + t.Fatalf("checkID(%q) = %v, the case needs an id it accepts", id, err) + } + for _, key := range keys { + if err := checkKey(key, nil); err != nil { + t.Fatalf("checkKey(%q) = %v, the case needs a key it accepts", key, err) + } + name := Name("APP_PLUGIN_", id, key) + if first, taken := seen[name]; taken { + t.Errorf("%s names both %v and [%s %s]", name, first, id, key) + } + seen[name] = [2]string{id, key} + } + } +} + +func TestCheckKeyTakesLowercaseWordsJoinedByOneUnderscore(t *testing.T) { + for _, key := range []string{"title", "max_seats", "a", "page2", "a_b_c", "x_1"} { + if err := checkKey(key, []string{"job_", "db_"}); err != nil { + t.Errorf("checkKey(%q) = %v, want nil", key, err) + } + } +} + +func TestCheckKeyRejectsAnotherShape(t *testing.T) { + const want = "a key is lowercase words joined by one underscore" + keys := []string{"", "Max__Seats", "max__seats", "_title", "title_", "2title", "max-seats", "Title", "tïtle"} + for _, key := range keys { + err := checkKey(key, nil) + if err == nil || err.Error() != want { + t.Errorf("checkKey(%q) = %v, want %q", key, err, want) + } + } +} + +func TestCheckKeyRejectsAReservedStart(t *testing.T) { + cases := []struct { + key string + reserved []string + want string + }{ + {"job_every", []string{"job_", "db_"}, "a key must not start with job_ or db_"}, + {"db_conns", []string{"job_", "db_"}, "a key must not start with job_ or db_"}, + {"job_every", []string{"job_"}, "a key must not start with job_"}, + {"db_conns", []string{"job_", "tx_", "db_"}, "a key must not start with job_, tx_ or db_"}, + } + for _, c := range cases { + err := checkKey(c.key, c.reserved) + if err == nil || err.Error() != c.want { + t.Errorf("checkKey(%q, %q) = %v, want %q", c.key, c.reserved, err, c.want) + } + } +} + +func TestCheckKeyTakesAKeyThatOnlyHoldsAReservedWord(t *testing.T) { + for _, key := range []string{"job", "jobs", "db", "dbx_conns", "my_job_every"} { + if err := checkKey(key, []string{"job_", "db_"}); err != nil { + t.Errorf("checkKey(%q) = %v, want nil", key, err) + } + } +} + +func TestCheckIDRejectsDoubledAndTrailingHyphens(t *testing.T) { + for _, id := range []string{"notes--pro", "notes-", "a---b", "a-b-"} { + want := "the id " + id + " must not hold two hyphens in a row or end with one when the plugin has settings" + err := checkID(id) + if err == nil || err.Error() != want { + t.Errorf("checkID(%q) = %v, want %q", id, err, want) + } + } +} + +func TestCheckIDTakesSingleHyphensBetweenWords(t *testing.T) { + for _, id := range []string{"notes", "notes-pro", "a-b-c", "x2"} { + if err := checkID(id); err != nil { + t.Errorf("checkID(%q) = %v, want nil", id, err) + } + } +} From b3526abe8d9f4f40a78a092084da950983ae6c4c Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:09:52 +0100 Subject: [PATCH 03/12] feat(pluginkit): keep a secret's value out of every print, log and encoding --- pluginkit/settings/settings.go | 108 ++++++++++++++++++++ pluginkit/settings/settings_test.go | 152 ++++++++++++++++++++++++++++ 2 files changed, 260 insertions(+) create mode 100644 pluginkit/settings/settings.go create mode 100644 pluginkit/settings/settings_test.go diff --git a/pluginkit/settings/settings.go b/pluginkit/settings/settings.go new file mode 100644 index 0000000..6269bbc --- /dev/null +++ b/pluginkit/settings/settings.go @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package settings checks the settings a plugin declares, names the variable of each one and works out its value. +package settings + +import ( + "encoding/json" + "log/slog" + "time" +) + +const ( + // TypeText is any text, its surrounding spaces trimmed. + TypeText = "text" + // TypeCount is a whole number, within its min and max when they are given. + TypeCount = "count" + // TypeFlag is true or false, in any spelling strconv.ParseBool takes. + TypeFlag = "flag" + // TypeDuration is a duration above zero, such as 30s. + TypeDuration = "duration" + // TypeChoice is one of the setting's options. + TypeChoice = "choice" + // TypeSecret is any text, taken as written, from the environment only. + TypeSecret = "secret" + // TypeLines is a comma list, each item trimmed and the empty items dropped. + TypeLines = "lines" +) + +// 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. +type Field struct { + Key string + Type string + Env string + Default string + Min *int + Max *int + Options []string +} + +// Schema is one plugin's checked settings, in the order its manifest lists them. +type Schema struct { + ID string + Fields []Field +} + +// Value is one resolved setting, with the reading of its type filled in. +type Value struct { + Type string + Text string + Count int + Flag bool + Duration time.Duration + Lines []string + Secret Hidden +} + +// Values holds one plugin's resolved settings by key. +type Values map[string]Value + +// Hidden is a secret's value that prints as set or not set. +type Hidden struct { + reveal func() string +} + +// hide returns text as a Hidden, one with no value when text is empty. +func hide(text string) Hidden { + if text == "" { + return Hidden{} + } + return Hidden{reveal: func() string { return text }} +} + +// Reveal returns the secret's text. +func (h Hidden) Reveal() string { + if h.reveal == nil { + return "" + } + return h.reveal() +} + +// String returns set or not set. +func (h Hidden) String() string { + if h.reveal == nil { + return "not set" + } + return "set" +} + +// GoString returns set or not set. +func (h Hidden) GoString() string { + return h.String() +} + +// LogValue returns set or not set. +func (h Hidden) LogValue() slog.Value { + return slog.StringValue(h.String()) +} + +// MarshalJSON returns set or not set as a JSON string. +func (h Hidden) MarshalJSON() ([]byte, error) { + return json.Marshal(h.String()) +} diff --git a/pluginkit/settings/settings_test.go b/pluginkit/settings/settings_test.go new file mode 100644 index 0000000..c763a14 --- /dev/null +++ b/pluginkit/settings/settings_test.go @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "bytes" + "encoding/json" + "fmt" + "log/slog" + "strings" + "testing" +) + +// knownSecret is the text each test hides and then looks for in every print. +const knownSecret = "key-for-example" + +// holder keeps a secret in an unexported field, where fmt cannot call its methods. +type holder struct { + secret Hidden +} + +// verbs are the fmt verbs a print of a secret may use. +var verbs = []string{"%v", "%+v", "%#v", "%s", "%q", "%x", "%X", "%d", "%T", "%p"} + +// prints returns value through every verb in verbs. +func prints(value any) []string { + out := make([]string, 0, len(verbs)) + for _, verb := range verbs { + out = append(out, fmt.Sprintf(verb, value)) + } + return out +} + +// logged returns the lines slog's text and JSON handlers write for value under the key secret. +func logged(value any) []string { + var text, structured bytes.Buffer + slog.New(slog.NewTextHandler(&text, nil)).Info("read", "secret", value) + slog.New(slog.NewJSONHandler(&structured, nil)).Info("read", "secret", value) + return []string{text.String(), structured.String()} +} + +// encoded returns value encoded by encoding/json, the error text when it fails. +func encoded(value any) string { + data, err := json.Marshal(value) + if err != nil { + return err.Error() + } + return string(data) +} + +// renderings returns every print, log line and encoding of value. +func renderings(value any) []string { + return append(append(prints(value), logged(value)...), encoded(value)) +} + +func TestHiddenRevealsItsText(t *testing.T) { + if got := hide(knownSecret).Reveal(); got != knownSecret { + t.Errorf("Reveal() = %q, want %q", got, knownSecret) + } +} + +func TestHiddenTakesTheTextAsWritten(t *testing.T) { + if got := hide(" spaced key ").Reveal(); got != " spaced key " { + t.Errorf("Reveal() = %q, want the text untrimmed", got) + } +} + +func TestHiddenWithNoValueRevealsNothingAndReadsNotSet(t *testing.T) { + for _, h := range []Hidden{{}, hide("")} { + if got := h.Reveal(); got != "" { + t.Errorf("Reveal() = %q, want empty", got) + } + if got := h.String(); got != "not set" { + t.Errorf("String() = %q, want not set", got) + } + } +} + +func TestHiddenPrintsAsSetThroughEachPrinter(t *testing.T) { + h := hide(knownSecret) + cases := []struct { + name, got, want string + }{ + {"GoString", h.GoString(), "set"}, + {"LogValue", h.LogValue().String(), "set"}, + {"json", encoded(h), `"set"`}, + {"map", fmt.Sprintf(verbs[0], map[string]Hidden{"api_key": h}), "map[api_key:set]"}, + {"pointer", fmt.Sprintf(verbs[0], &h), "set"}, + {"slice", fmt.Sprintf(verbs[1], []Hidden{h}), "[set]"}, + } + for _, c := range cases { + if c.got != c.want { + t.Errorf("%s = %q, want %q", c.name, c.got, c.want) + } + } +} + +func TestHiddenPrintsAsSetThroughEachStringVerb(t *testing.T) { + want := map[string]string{"%v": "set", "%+v": "set", "%#v": "set", "%s": "set", "%q": `"set"`, "%x": "736574"} + for verb, text := range want { + if got := fmt.Sprintf(verb, hide(knownSecret)); got != text { + t.Errorf("%s = %q, want %q", verb, got, text) + } + } +} + +func TestHiddenWithNoValuePrintsAsNotSet(t *testing.T) { + h := Hidden{} + for _, verb := range []string{"%v", "%#v", "%s"} { + if got := fmt.Sprintf(verb, h); got != "not set" { + t.Errorf("%s = %q, want not set", verb, got) + } + } + if got := h.LogValue().String(); got != "not set" { + t.Errorf("LogValue() = %q, want not set", got) + } + if got := encoded(h); got != `"not set"` { + t.Errorf("json = %s, want \"not set\"", got) + } +} + +func TestHiddenLogsAsSetThroughBothHandlers(t *testing.T) { + lines := logged(hide(knownSecret)) + if !strings.Contains(lines[0], "secret=set") { + t.Errorf("text line %q does not hold secret=set", lines[0]) + } + if !strings.Contains(lines[1], `"secret":"set"`) { + t.Errorf("JSON line %q does not hold \"secret\":\"set\"", lines[1]) + } +} + +func TestHiddenNeverShowsItsTextWhereverItSits(t *testing.T) { + h := hide(knownSecret) + places := map[string]any{ + "alone": h, + "pointer": &h, + "map": map[string]Hidden{"api_key": h}, + "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}}, + "any map": map[string]any{"api_key": h}, + } + for place, value := range places { + for _, out := range renderings(value) { + if strings.Contains(out, knownSecret) { + t.Errorf("%s shows the secret in %q", place, out) + } + } + } +} From a742e7c1f9ea3c0a98a25b3bdab95cf6db78741c Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:09:52 +0100 Subject: [PATCH 04/12] feat(pluginkit): parse the seven setting types --- pluginkit/settings/parse.go | 130 +++++++++++++++++++ pluginkit/settings/parse_test.go | 210 +++++++++++++++++++++++++++++++ 2 files changed, 340 insertions(+) create mode 100644 pluginkit/settings/parse.go create mode 100644 pluginkit/settings/parse_test.go diff --git a/pluginkit/settings/parse.go b/pluginkit/settings/parse.go new file mode 100644 index 0000000..938d4b0 --- /dev/null +++ b/pluginkit/settings/parse.go @@ -0,0 +1,130 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "errors" + "fmt" + "math" + "slices" + "strconv" + "strings" + "time" +) + +// parser reads one value of a field's type. +type parser func(field Field, value string) (Value, error) + +// types lists the seven setting types in the order an error names them. +var types = []string{TypeText, TypeCount, TypeFlag, TypeDuration, TypeChoice, TypeSecret, TypeLines} + +// parsers holds the parser of each setting type. +var parsers = map[string]parser{ + TypeText: parseText, + TypeCount: parseCount, + TypeFlag: parseFlag, + TypeDuration: parseDuration, + TypeChoice: parseChoice, + TypeSecret: parseSecret, + TypeLines: parseLines, +} + +// parserOf returns the parser of the setting type kind, an error naming the seven types when kind is none of them. +func parserOf(kind string) (parser, error) { + parse, known := parsers[kind] + if !known { + return nil, fmt.Errorf("type %q is not one of %s", kind, strings.Join(types, ", ")) + } + return parse, nil +} + +// 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) +} + +// parseText reads value as text with its surrounding spaces trimmed. +func parseText(_ Field, value string) (Value, error) { + return Value{Type: TypeText, Text: strings.TrimSpace(value)}, nil +} + +// parseCount reads value as a whole number within the field's min and max. +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) + } + if rule := beyond(field, read, err != nil); rule != "" { + return Value{}, complaint(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 { + 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) + case read > int64(ceiling), overflowed: + return "must stand at or below " + strconv.Itoa(ceiling) + } + return "" +} + +// orElse returns the number n points to, fallback when n is nil. +func orElse(n *int, fallback int) int { + if n == nil { + return fallback + } + return *n +} + +// parseFlag reads value as true or false. +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{Type: TypeFlag, Flag: read}, nil +} + +// parseDuration reads value as a duration above zero. +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) + } + if read <= 0 { + return Value{}, complaint("must stand above zero", value) + } + return Value{Type: TypeDuration, 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{Type: TypeChoice, Text: value}, nil +} + +// parseSecret takes value as written and keeps it hidden. +func parseSecret(_ Field, value string) (Value, error) { + return Value{Type: TypeSecret, Secret: hide(value)}, nil +} + +// parseLines reads value as a comma list, each item trimmed and the empty items dropped. +func parseLines(_ Field, value string) (Value, error) { + var lines []string + for item := range strings.SplitSeq(value, ",") { + if item = strings.TrimSpace(item); item != "" { + lines = append(lines, item) + } + } + return Value{Type: TypeLines, Lines: lines}, nil +} diff --git a/pluginkit/settings/parse_test.go b/pluginkit/settings/parse_test.go new file mode 100644 index 0000000..17ec77b --- /dev/null +++ b/pluginkit/settings/parse_test.go @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "math" + "reflect" + "strconv" + "testing" + "time" +) + +// beyondEveryInt is a whole number past the int of every platform. +const beyondEveryInt = "99999999999999999999" + +// bound returns n as a bound of a count. +func bound(n int) *int { + return &n +} + +// parseCase is one value a parser reads and the reading or the error it answers. +type parseCase struct { + field Field + value string + want Value + err string +} + +// runParse reads each case's value with the parser of its field's type and compares what it answers. +func runParse(t *testing.T, cases []parseCase) { + t.Helper() + for _, c := range cases { + parse, err := parserOf(c.field.Type) + if err != nil { + t.Fatalf("parserOf(%q) = %v", c.field.Type, err) + } + got, err := parse(c.field, c.value) + if c.err != "" { + if err == nil || err.Error() != c.err { + t.Errorf("%s %q: error %v, want %q", c.field.Type, c.value, err, c.err) + } + continue + } + if err != nil { + t.Errorf("%s %q: error %v, want none", c.field.Type, c.value, err) + continue + } + if !sameValue(got, c.want) { + t.Errorf("%s %q = %+v, want %+v", c.field.Type, c.value, got, c.want) + } + } +} + +// sameValue reports whether two values hold the same reading, a secret compared by its text. +func sameValue(a, b Value) bool { + if a.Secret.Reveal() != b.Secret.Reveal() { + return false + } + a.Secret, b.Secret = Hidden{}, Hidden{} + return reflect.DeepEqual(a, b) +} + +func TestParseTextTrimsSurroundingSpaces(t *testing.T) { + text := Field{Type: TypeText} + runParse(t, []parseCase{ + {field: text, value: "Field Notes", want: Value{Type: TypeText, Text: "Field Notes"}}, + {field: text, value: " Field Notes \t", want: Value{Type: TypeText, Text: "Field Notes"}}, + {field: text, value: "", want: Value{Type: TypeText}}, + }) +} + +func TestParseCountReadsAWholeNumber(t *testing.T) { + open := Field{Type: TypeCount} + runParse(t, []parseCase{ + {field: open, value: "25", want: Value{Type: TypeCount, Count: 25}}, + {field: open, value: " 25 ", want: Value{Type: TypeCount, Count: 25}}, + {field: open, value: "+7", want: Value{Type: TypeCount, Count: 7}}, + {field: open, value: "0", want: Value{Type: TypeCount}}, + {field: open, value: "-3", want: Value{Type: TypeCount, Count: -3}}, + {field: open, value: strconv.Itoa(math.MaxInt), want: Value{Type: TypeCount, Count: math.MaxInt}}, + {field: open, value: strconv.Itoa(math.MinInt), want: Value{Type: TypeCount, Count: math.MinInt}}, + }) +} + +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"`}, + }) +} + +func TestParseCountKeepsWithinItsBounds(t *testing.T) { + seats := Field{Type: TypeCount, Min: bound(1), Max: bound(50)} + 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"`}, + }) +} + +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 + `"`}, + {field: Field{Type: TypeCount}, value: "-" + beyondEveryInt, + err: "must stand at or above " + bottom + `, got "-` + beyondEveryInt + `"`}, + {field: Field{Type: TypeCount, Max: bound(50)}, value: beyondEveryInt, + err: `must stand at or below 50, got "` + beyondEveryInt + `"`}, + {field: Field{Type: TypeCount, Min: bound(1)}, value: "-" + beyondEveryInt, + err: `must stand at or above 1, got "-` + beyondEveryInt + `"`}, + }) +} + +func TestParseFlagReadsEveryWordParseBoolTakes(t *testing.T) { + flag := Field{Type: TypeFlag} + cases := make([]parseCase, 0, 12) + for _, word := range []string{"true", "TRUE", "True", "t", "T", "1"} { + cases = append(cases, parseCase{field: flag, value: word, want: Value{Type: TypeFlag, Flag: true}}) + } + for _, word := range []string{"false", "FALSE", "False", "f", "F", " 0 "} { + cases = append(cases, parseCase{field: flag, value: word, want: Value{Type: TypeFlag}}) + } + runParse(t, cases) +} + +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"`}, + }) +} + +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"`}, + }) +} + +func TestParseChoiceReadsOneOfItsOptions(t *testing.T) { + order := Field{Type: TypeChoice, Options: []string{"newest", "oldest"}} + 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"`}, + }) +} + +func TestParseLinesTrimsEachItemAndDropsTheEmptyOnes(t *testing.T) { + tags := Field{Type: TypeLines} + runParse(t, []parseCase{ + {field: tags, value: "news", want: Value{Type: TypeLines, Lines: []string{"news"}}}, + {field: tags, value: "news,, events", want: Value{Type: TypeLines, Lines: []string{"news", "events"}}}, + {field: tags, value: " a , b ,c,", want: Value{Type: TypeLines, Lines: []string{"a", "b", "c"}}}, + {field: tags, value: " , ,", want: Value{Type: TypeLines}}, + {field: tags, value: "", want: Value{Type: TypeLines}}, + }) +} + +func TestParseSecretTakesTheTextAsWritten(t *testing.T) { + key := Field{Type: TypeSecret} + runParse(t, []parseCase{ + {field: key, value: "key-for-example", want: Value{Type: TypeSecret, Secret: hide("key-for-example")}}, + {field: key, value: " key-for-example ", want: Value{Type: TypeSecret, Secret: hide(" key-for-example ")}}, + {field: key, value: "a,b", want: Value{Type: TypeSecret, Secret: hide("a,b")}}, + {field: key, value: "", want: Value{Type: TypeSecret}}, + }) +} + +func TestParseSecretFillsOnlyTheSecret(t *testing.T) { + parse, _ := parserOf(TypeSecret) + got, _ := parse(Field{Type: TypeSecret}, knownSecret) + if got.Text != "" || got.Lines != nil { + t.Errorf("a secret filled %+v beside its Secret", got) + } +} + +func TestParserOfRejectsAnUnknownType(t *testing.T) { + for _, kind := range []string{"colour", "picker", "content", "", "Text"} { + _, err := parserOf(kind) + want := `type "` + kind + `" is not one of text, count, flag, duration, choice, secret, lines` + if err == nil || err.Error() != want { + t.Errorf("parserOf(%q) = %v, want %q", kind, err, want) + } + } +} + +func TestParserOfKnowsTheSevenTypes(t *testing.T) { + for _, kind := range []string{TypeText, TypeCount, TypeFlag, TypeDuration, TypeChoice, TypeSecret, TypeLines} { + if _, err := parserOf(kind); err != nil { + t.Errorf("parserOf(%q) = %v, want a parser", kind, err) + } + } +} From d94071367be6f6f4fb71eac28916c1d7d2e05f81 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:09:53 +0100 Subject: [PATCH 05/12] feat(pluginkit): check the settings a plugin declares against their types --- pluginkit/settings/check.go | 178 +++++++++++++++++++++++ pluginkit/settings/check_test.go | 237 +++++++++++++++++++++++++++++++ 2 files changed, 415 insertions(+) create mode 100644 pluginkit/settings/check.go create mode 100644 pluginkit/settings/check_test.go diff --git a/pluginkit/settings/check.go b/pluginkit/settings/check.go new file mode 100644 index 0000000..5c4368c --- /dev/null +++ b/pluginkit/settings/check.go @@ -0,0 +1,178 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "errors" + "fmt" + "math" + "slices" + "strconv" + "strings" + + "github.com/gopherium/framework/pluginkit/wire" +) + +// defaultRules holds the rule each setting type sets for its default. +var defaultRules = map[string]func(field Field) error{ + TypeText: anyDefault, + TypeCount: neededDefault, + TypeFlag: optionalDefault, + TypeDuration: neededDefault, + TypeChoice: choiceDefault, + TypeSecret: noDefault, + TypeLines: anyDefault, +} + +// Check checks the settings plugin id declares under rules and answers them ready to resolve. +func Check(id string, declared []wire.Setting, rules Rules) (Schema, error) { + if len(declared) == 0 { + return Schema{ID: id}, nil + } + if err := checkID(id); err != nil { + return Schema{}, err + } + fields := make([]Field, 0, len(declared)) + seen := make(map[string]bool, len(declared)) + for i, setting := range declared { + field, err := checkSetting(setting, rules.Reserved, seen) + if err != nil { + return Schema{}, fmt.Errorf("settings[%d] %s: %w", i, setting.Key, err) + } + field.Env = Name(rules.Prefix, id, field.Key) + fields = append(fields, field) + } + return Schema{ID: id, Fields: fields}, nil +} + +// checkSetting checks one declared setting, its key against reserved and the keys before it, and returns its field. +func checkSetting(setting wire.Setting, reserved []string, seen map[string]bool) (Field, error) { + if err := checkKey(setting.Key, reserved); err != nil { + return Field{}, err + } + if seen[setting.Key] { + return Field{}, errors.New("the key is declared twice") + } + seen[setting.Key] = true + if err := checkShape(setting); err != nil { + return Field{}, err + } + field, err := fieldOf(setting) + if err != nil { + return Field{}, err + } + if err := defaultRules[field.Type](field); err != nil { + return Field{}, err + } + return field, nil +} + +// checkShape rejects an unknown type, an of field, and bounds or options on a type that takes none. +func checkShape(setting wire.Setting) error { + if _, err := parserOf(setting.Type); err != nil { + return err + } + if setting.Of != "" { + return fmt.Errorf("a %s setting takes no of field", setting.Type) + } + bounded := setting.Min != nil || setting.Max != nil + if bounded && setting.Type != TypeCount { + return errors.New("min and max apply only to a count") + } + if len(setting.Options) > 0 && setting.Type != TypeChoice { + return errors.New("options apply only to a choice") + } + return nil +} + +// fieldOf returns the field of setting, its bounds read as whole numbers with min not above max. +func fieldOf(setting wire.Setting) (Field, error) { + low, err := wholeBound("min", setting.Min) + if err != nil { + return Field{}, err + } + high, err := wholeBound("max", setting.Max) + if err != nil { + return Field{}, err + } + if upsideDown(low, high) { + return Field{}, fmt.Errorf("min %d stands above max %d", *low, *high) + } + return Field{ + Key: setting.Key, + Type: setting.Type, + Default: setting.Default, + Min: low, + Max: high, + Options: slices.Clone(setting.Options), + }, nil +} + +// wholeBound returns the bound called name as a whole number, nil when it is absent. +func wholeBound(name string, bound *float64) (*int, error) { + if bound == nil { + return nil, nil + } + n, text := *bound, strconv.FormatFloat(*bound, 'f', -1, 64) + if n != math.Trunc(n) { + return nil, fmt.Errorf("%s %s is not a whole number", name, text) + } + if n < math.MinInt || n >= -math.MinInt { + return nil, fmt.Errorf("%s %s does not fit in a count", name, text) + } + whole := int(n) + return &whole, nil +} + +// upsideDown reports whether both bounds are given and low stands above high. +func upsideDown(low, high *int) bool { + if low == nil || high == nil { + return false + } + return *low > *high +} + +// anyDefault takes any default. +func anyDefault(Field) error { + return nil +} + +// optionalDefault takes no default or one its type reads. +func optionalDefault(field Field) error { + if strings.TrimSpace(field.Default) == "" { + return nil + } + return readDefault(field) +} + +// neededDefault rejects a missing default or one its type does not read. +func neededDefault(field Field) error { + if strings.TrimSpace(field.Default) == "" { + return fmt.Errorf("a %s needs a default", field.Type) + } + return readDefault(field) +} + +// choiceDefault rejects a choice with no options, then a default that is not one of them. +func choiceDefault(field Field) error { + if len(field.Options) == 0 { + return errors.New("a choice needs options") + } + return neededDefault(field) +} + +// noDefault rejects any default without quoting it. +func noDefault(field Field) error { + if field.Default != "" { + return errors.New("a secret takes no default, because plugin.json is public") + } + return nil +} + +// readDefault rejects a default the field's type does not read. +func readDefault(field Field) error { + if _, err := parsers[field.Type](field, field.Default); err != nil { + return fmt.Errorf("the default %w", err) + } + return nil +} diff --git a/pluginkit/settings/check_test.go b/pluginkit/settings/check_test.go new file mode 100644 index 0000000..e964f25 --- /dev/null +++ b/pluginkit/settings/check_test.go @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "math" + "reflect" + "strings" + "testing" + + "github.com/gopherium/framework/pluginkit/wire" +) + +// appRules are the rules of an application that names its variables under APP_PLUGIN_ and reserves job_ and db_. +var appRules = Rules{Prefix: "APP_PLUGIN_", Reserved: []string{"job_", "db_"}} + +// number returns n as a bound of a declared setting. +func number(n float64) *float64 { + return &n +} + +// everyType declares one setting of each of the seven types. +func everyType() []wire.Setting { + return []wire.Setting{ + {Key: "title", Type: TypeText, Default: "Notes", Label: "Title", Help: "The title readers see"}, + {Key: "per_page", Type: TypeCount, Default: "10", Min: number(1), Max: number(50)}, + {Key: "open", Type: TypeFlag}, + {Key: "keep_for", Type: TypeDuration, Default: "720h"}, + {Key: "order", Type: TypeChoice, Default: "newest", Options: []string{"newest", "oldest"}}, + {Key: "tags", Type: TypeLines}, + {Key: "api_key", Type: TypeSecret}, + } +} + +// rejection is one declaration Check rejects and the reason it answers. +type rejection struct { + name string + declared []wire.Setting + want string +} + +// rejections lists every rule a declaration can break, as the rows of the design name them. +var rejections = []rejection{ + {"unknown type", []wire.Setting{{Key: "mood", Type: "colour"}}, + `settings[0] mood: type "colour" is not one of text, count, flag, duration, choice, secret, lines`}, + {"key shape", []wire.Setting{{Key: "Max__Seats", Type: TypeText}}, + "settings[0] Max__Seats: a key is lowercase words joined by one underscore"}, + {"key starts with an underscore", []wire.Setting{{Key: "_title", Type: TypeText}}, + "settings[0] _title: a key is lowercase words joined by one underscore"}, + {"reserved job_", []wire.Setting{{Key: "title", Type: TypeText}, {Key: "job_every", Type: TypeText}}, + "settings[1] job_every: a key must not start with job_ or db_"}, + {"reserved db_", []wire.Setting{{Key: "db_conns", Type: TypeText}}, + "settings[0] db_conns: a key must not start with job_ or db_"}, + {"repeated key", []wire.Setting{{Key: "per_page", Type: TypeCount, Default: "1"}, {Key: "title", Type: TypeText}, + {Key: "title", Type: TypeText}}, "settings[2] title: the key is declared twice"}, + {"count with no default", []wire.Setting{{Key: "max_seats", Type: TypeCount}}, + "settings[0] max_seats: a count needs a default"}, + {"count with a blank default", []wire.Setting{{Key: "max_seats", Type: TypeCount, Default: " "}}, + "settings[0] max_seats: a count needs a default"}, + {"bad count default", []wire.Setting{{Key: "max_seats", Type: TypeCount, Default: "lots"}}, + `settings[0] max_seats: the default must be a whole number, got "lots"`}, + {"count default above max", []wire.Setting{{Key: "max_seats", Type: TypeCount, Default: "60", Min: number(1), + Max: number(50)}}, `settings[0] max_seats: the default must stand at or below 50, got "60"`}, + {"count default below min", []wire.Setting{{Key: "max_seats", Type: TypeCount, Default: "0", Min: number(1)}}, + `settings[0] max_seats: the default must stand at or above 1, got "0"`}, + {"bounds upside down", []wire.Setting{{Key: "max_seats", Type: TypeCount, Default: "7", Min: number(10), + Max: number(5)}}, "settings[0] max_seats: min 10 stands above max 5"}, + {"min not whole", []wire.Setting{{Key: "max_seats", Type: TypeCount, Default: "4", Min: number(1.5)}}, + "settings[0] max_seats: min 1.5 is not a whole number"}, + {"max not whole", []wire.Setting{{Key: "max_seats", Type: TypeCount, Default: "4", Max: number(9.25)}}, + "settings[0] max_seats: max 9.25 is not a whole number"}, + {"min past every int", []wire.Setting{{Key: "max_seats", Type: TypeCount, Default: "4", Min: number(1e20)}}, + "settings[0] max_seats: min 100000000000000000000 does not fit in a count"}, + {"max below every int", []wire.Setting{{Key: "max_seats", Type: TypeCount, Default: "4", Max: number(-1e20)}}, + "settings[0] max_seats: max -100000000000000000000 does not fit in a count"}, + {"max at two to the 63", []wire.Setting{{Key: "max_seats", Type: TypeCount, Default: "4", + Max: number(math.Exp2(63))}}, "settings[0] max_seats: max 9223372036854776000 does not fit in a count"}, + {"max on a text", []wire.Setting{{Key: "title", Type: TypeText, Max: number(80)}}, + "settings[0] title: min and max apply only to a count"}, + {"min on a lines", []wire.Setting{{Key: "tags", Type: TypeLines, Min: number(1)}}, + "settings[0] tags: min and max apply only to a count"}, + {"max on a secret", []wire.Setting{{Key: "api_key", Type: TypeSecret, Max: number(8)}}, + "settings[0] api_key: min and max apply only to a count"}, + {"options on a text", []wire.Setting{{Key: "title", Type: TypeText, Options: []string{"a", "b"}}}, + "settings[0] title: options apply only to a choice"}, + {"choice with no options", []wire.Setting{{Key: "order", Type: TypeChoice}}, + "settings[0] order: a choice needs options"}, + {"choice with no default", []wire.Setting{{Key: "order", Type: TypeChoice, Options: []string{"newest", "oldest"}}}, + "settings[0] order: a choice needs a default"}, + {"choice default not an option", []wire.Setting{{Key: "order", Type: TypeChoice, Default: "random", + Options: []string{"newest", "oldest"}}}, + `settings[0] order: the default must be one of newest, oldest, got "random"`}, + {"duration with no default", []wire.Setting{{Key: "keep_for", Type: TypeDuration}}, + "settings[0] keep_for: a duration needs a default"}, + {"bad duration default", []wire.Setting{{Key: "keep_for", Type: TypeDuration, Default: "soon"}}, + `settings[0] keep_for: the default must be a duration like 30s, got "soon"`}, + {"duration default not above zero", []wire.Setting{{Key: "keep_for", Type: TypeDuration, Default: "0s"}}, + `settings[0] keep_for: the default must stand above zero, got "0s"`}, + {"bad flag default", []wire.Setting{{Key: "open", Type: TypeFlag, Default: "maybe"}}, + `settings[0] open: the default must be true or false, got "maybe"`}, + {"default on a secret", []wire.Setting{{Key: "api_key", Type: TypeSecret, Default: "key-for-example"}}, + "settings[0] api_key: a secret takes no default, because plugin.json is public"}, + {"blank default on a secret", []wire.Setting{{Key: "api_key", Type: TypeSecret, Default: " "}}, + "settings[0] api_key: a secret takes no default, because plugin.json is public"}, + {"of on a text", []wire.Setting{{Key: "title", Type: TypeText, Of: "post"}}, + "settings[0] title: a text setting takes no of field"}, + {"of on a count", []wire.Setting{{Key: "per_page", Type: TypeCount, Default: "1", Of: "post"}}, + "settings[0] per_page: a count setting takes no of field"}, + {"of on a lines", []wire.Setting{{Key: "tags", Type: TypeLines, Of: "post"}}, + "settings[0] tags: a lines setting takes no of field"}, +} + +func TestCheckRejectsEachDeclarationOutsideTheRules(t *testing.T) { + for _, c := range rejections { + schema, err := Check("notes", c.declared, appRules) + if err == nil || err.Error() != c.want { + t.Errorf("%s: Check = %v, want %q", c.name, err, c.want) + } + if !reflect.DeepEqual(schema, Schema{}) { + t.Errorf("%s: Check answered %+v beside its error", c.name, schema) + } + } +} + +func TestCheckNeverQuotesTheDefaultOfASecret(t *testing.T) { + for _, secret := range []string{"key-for-example", " spaced ", "sk_live_example"} { + _, err := Check("notes", []wire.Setting{{Key: "api_key", Type: TypeSecret, Default: secret}}, appRules) + if err == nil || strings.Contains(err.Error(), secret) { + t.Errorf("Check of a secret default %q = %v, want an error that does not quote it", secret, err) + } + } +} + +func TestCheckAnswersEachSettingReadyToResolve(t *testing.T) { + schema, err := Check("notes", everyType(), appRules) + if err != nil { + t.Fatalf("Check = %v, want nil", err) + } + one, fifty := 1, 50 + want := Schema{ID: "notes", Fields: []Field{ + {Key: "title", Type: TypeText, 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"}, + {Key: "order", Type: TypeChoice, Env: "APP_PLUGIN_NOTES__ORDER", Default: "newest", + Options: []string{"newest", "oldest"}}, + {Key: "tags", Type: TypeLines, Env: "APP_PLUGIN_NOTES__TAGS"}, + {Key: "api_key", Type: TypeSecret, Env: "APP_PLUGIN_NOTES__API_KEY"}, + }} + if !reflect.DeepEqual(schema, want) { + t.Errorf("Check = %+v, want %+v", schema, want) + } +} + +func TestCheckTakesTheDefaultsEachTypeAccepts(t *testing.T) { + declared := []wire.Setting{ + {Key: "open", Type: TypeFlag, Default: "true"}, + {Key: "shut", Type: TypeFlag, Default: " F "}, + {Key: "tags", Type: TypeLines, Default: "news, events"}, + {Key: "title", Type: TypeText, Default: " Notes "}, + {Key: "quiet", Type: TypeFlag, Default: " "}, + {Key: "floor", Type: TypeCount, Default: "-5"}, + {Key: "lowest", Type: TypeCount, Default: "0", Min: number(float64(math.MinInt))}, + {Key: "ceiling", Type: TypeCount, Default: "5", Min: number(5), Max: number(5)}, + {Key: "keep_for", Type: TypeDuration, Default: " 1h "}, + {Key: "order", Type: TypeChoice, Default: " oldest ", Options: []string{"newest", "oldest"}}, + } + if _, err := Check("notes", declared, appRules); err != nil { + t.Errorf("Check = %v, want nil", err) + } +} + +func TestCheckAnswersTheFirstProblemInTheManifestsOrder(t *testing.T) { + declared := []wire.Setting{ + {Key: "title", Type: TypeText}, + {Key: "max_seats", Type: TypeCount}, + {Key: "mood", Type: "colour"}, + } + _, err := Check("notes", declared, appRules) + if want := "settings[1] max_seats: a count needs a default"; err == nil || err.Error() != want { + t.Errorf("Check = %v, want %q", err, want) + } +} + +func TestCheckRejectsTheIDOfAPluginWithSettingsBeforeItsSettings(t *testing.T) { + for _, id := range []string{"notes--pro", "notes-"} { + _, err := Check(id, []wire.Setting{{Key: "Bad", Type: "colour"}}, appRules) + want := "the id " + id + " must not hold two hyphens in a row or end with one when the plugin has settings" + if err == nil || err.Error() != want { + t.Errorf("Check(%q) = %v, want %q", id, err, want) + } + } +} + +func TestCheckKeepsAnyIDForAPluginWithNoSettings(t *testing.T) { + for _, declared := range [][]wire.Setting{nil, {}} { + schema, err := Check("notes--pro", declared, appRules) + if err != nil { + t.Errorf("Check = %v, want nil", err) + } + if !reflect.DeepEqual(schema, Schema{ID: "notes--pro"}) { + t.Errorf("Check = %+v, want a schema with no fields", schema) + } + } +} + +func TestCheckReservesNothingWhenTheRulesReserveNothing(t *testing.T) { + declared := []wire.Setting{{Key: "job_every", Type: TypeText}, {Key: "db_conns", Type: TypeText}} + if _, err := Check("notes", declared, Rules{Prefix: "APP_PLUGIN_"}); err != nil { + t.Errorf("Check = %v, want nil", err) + } +} + +func TestCheckKeepsTheOptionsApartFromTheDeclaration(t *testing.T) { + declared := []wire.Setting{{Key: "order", Type: TypeChoice, Default: "newest", Options: []string{"newest", "oldest"}}} + schema, err := Check("notes", declared, appRules) + if err != nil { + t.Fatalf("Check = %v, want nil", err) + } + declared[0].Options[0] = "changed" + if got := schema.Fields[0].Options[0]; got != "newest" { + t.Errorf("the field's first option became %q after the declaration changed", got) + } +} + +func TestCheckRejectsABoundThatIsNotANumber(t *testing.T) { + declared := []wire.Setting{{Key: "max_seats", Type: TypeCount, Default: "4", Min: number(math.NaN())}} + _, err := Check("notes", declared, appRules) + if want := "settings[0] max_seats: min NaN is not a whole number"; err == nil || err.Error() != want { + t.Errorf("Check = %v, want %q", err, want) + } + declared[0].Min = number(math.Inf(1)) + _, err = Check("notes", declared, appRules) + if want := "settings[0] max_seats: min +Inf does not fit in a count"; err == nil || err.Error() != want { + t.Errorf("Check = %v, want %q", err, want) + } +} From a2b8755fdcf0625c11e0752abf1b946c6979277e Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:09:54 +0100 Subject: [PATCH 06/12] feat(pluginkit): work out each plugin setting from the environment, then its default --- pluginkit/settings/resolve.go | 44 ++++++ pluginkit/settings/resolve_test.go | 234 +++++++++++++++++++++++++++++ 2 files changed, 278 insertions(+) create mode 100644 pluginkit/settings/resolve.go create mode 100644 pluginkit/settings/resolve_test.go diff --git a/pluginkit/settings/resolve.go b/pluginkit/settings/resolve.go new file mode 100644 index 0000000..bd807b2 --- /dev/null +++ b/pluginkit/settings/resolve.go @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "fmt" + "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) { + values := make(Values, len(s.Fields)) + for _, field := range s.Fields { + value, err := field.read(field.pick(found[field.Env])) + if err != nil { + return nil, fmt.Errorf("%s: %w", field.Env, err) + } + values[field.Key] = value + } + return values, 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 + } + if value := strings.TrimSpace(found); value != "" { + return value + } + return strings.TrimSpace(f.Default) +} + +// 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 + } + if value == "" { + return Value{Type: f.Type}, nil + } + return parse(f, value) +} diff --git a/pluginkit/settings/resolve_test.go b/pluginkit/settings/resolve_test.go new file mode 100644 index 0000000..e08ba09 --- /dev/null +++ b/pluginkit/settings/resolve_test.go @@ -0,0 +1,234 @@ +// SPDX-License-Identifier: Apache-2.0 + +package settings + +import ( + "maps" + "slices" + "strings" + "testing" + "time" + + "github.com/gopherium/framework/pluginkit/wire" +) + +// notesSchema returns the checked schema of a plugin notes that declares one setting of each type. +func notesSchema(t *testing.T) Schema { + t.Helper() + declared := everyType() + declared[2].Default = "false" + declared[5].Default = "news" + schema, err := Check("notes", declared, appRules) + if err != nil { + t.Fatalf("Check = %v", err) + } + 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 { + t.Helper() + values, err := notesSchema(t).Resolve(found) + if err != nil { + t.Fatalf("Resolve = %v", err) + } + 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) + } +} + +func TestResolveLetsTheEnvironmentWinOverTheDefault(t *testing.T) { + values := resolved(t, 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__ORDER": "oldest", + "APP_PLUGIN_NOTES__TAGS": "news,, events", + "APP_PLUGIN_NOTES__API_KEY": knownSecret, + }) + 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, 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) + } + } +} + +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) + } +} + +func TestResolveTakesASecretOnlyFromTheEnvironmentAndAsWritten(t *testing.T) { + cases := []struct { + value, want string + }{ + {"", ""}, + {" ", " "}, + {" key-for-example ", " 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) + } + } +} + +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) + 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) + } +} + +func TestResolveFillsOnlyTheSecretOfASecret(t *testing.T) { + got := resolved(t, 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) + } +} + +func TestResolveGivesTheZeroValueWhenNeitherSourceHoldsOne(t *testing.T) { + schema, err := Check("notes", []wire.Setting{ + {Key: "title", Type: TypeText}, {Key: "open", Type: TypeFlag}, {Key: "tags", Type: TypeLines}, + }, appRules) + if err != nil { + t.Fatalf("Check = %v", err) + } + values, err := schema.Resolve(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}}) +} + +func TestResolveNamesTheVariableOfAValueItsTypeRejects(t *testing.T) { + cases := []struct { + variable, value, want string + }{ + {"APP_PLUGIN_NOTES__PER_PAGE", "banana", `APP_PLUGIN_NOTES__PER_PAGE: must be a whole number, got "banana"`}, + {"APP_PLUGIN_NOTES__PER_PAGE", "2.5", `APP_PLUGIN_NOTES__PER_PAGE: must be a whole number, got "2.5"`}, + {"APP_PLUGIN_NOTES__PER_PAGE", "60", `APP_PLUGIN_NOTES__PER_PAGE: must stand at or below 50, got "60"`}, + {"APP_PLUGIN_NOTES__PER_PAGE", " 0 ", `APP_PLUGIN_NOTES__PER_PAGE: must stand at or above 1, got "0"`}, + {"APP_PLUGIN_NOTES__KEEP_FOR", "soon", `APP_PLUGIN_NOTES__KEEP_FOR: must be a duration like 30s, got "soon"`}, + {"APP_PLUGIN_NOTES__KEEP_FOR", "-1h", `APP_PLUGIN_NOTES__KEEP_FOR: must stand above zero, got "-1h"`}, + {"APP_PLUGIN_NOTES__OPEN", "maybe", `APP_PLUGIN_NOTES__OPEN: must be true or false, got "maybe"`}, + {"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}) + 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) + } + } +} + +func TestResolveAnswersTheFirstRejectedValueInTheManifestsOrder(t *testing.T) { + _, err := notesSchema(t).Resolve(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) + } +} + +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"}) + if err == nil || strings.Contains(err.Error(), knownSecret) { + t.Errorf("Resolve = %v, want an error that does not hold the secret", err) + } + } +} + +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) + } +} + +func TestResolveOfASchemaWithNoFieldsAnswersNoValues(t *testing.T) { + values, err := Schema{ID: "notes"}.Resolve(map[string]string{"APP_PLUGIN_NOTES__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) + } +} + +func TestResolvedValuesNeverShowAKnownSecret(t *testing.T) { + values := resolved(t, 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) { + t.Errorf("a rendering of the values shows the secret: %q", out) + } + } + } + if !strings.Contains(encoded(values), `"Secret":"set"`) { + t.Errorf("the JSON of the values %s does not mark the secret as set", encoded(values)) + } +} + +// sameValues fails the test when got and want hold different readings or different keys. +func sameValues(t *testing.T, got, want Values) { + t.Helper() + keys, wanted := slices.Sorted(maps.Keys(got)), slices.Sorted(maps.Keys(want)) + if !slices.Equal(keys, wanted) { + t.Errorf("keys %v, want %v", keys, wanted) + } + for key, value := range want { + if !sameValue(got[key], value) { + t.Errorf("%s = %+v, want %+v", key, got[key], value) + } + } +} From 152497a4f5ccde95636637fa7635c3dd1a75b85e Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:09:55 +0100 Subject: [PATCH 07/12] docs(pluginkit): list plugin settings under Unreleased --- pluginkit/CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pluginkit/CHANGELOG.md b/pluginkit/CHANGELOG.md index 6946c49..a7aa3de 100644 --- a/pluginkit/CHANGELOG.md +++ b/pluginkit/CHANGELOG.md @@ -13,6 +13,10 @@ Releases of this module are tagged `pluginkit/vX.Y.Z`. Releases up to - `Protect` takes the plugin's id and a `RouteSettings`, which holds the middleware as `Wrap`, a breaking change. - `Protect` recovers each panic of a plugin's handler, on its public paths too. While nothing went out, `RouteSettings.Answer` answers it, else the connection is cut, and `RouteSettings.Report` receives a `RouteFailure` with the stack. - `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. +- A secret's value is a `settings.Hidden`, which prints, logs and encodes as `set` or `not set`. - The module needs Go 1.27.4. ## 0.12.0 - 2026-11-07 From 2ae056ec627bd053057499f4a61799a8dfbf7783 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:09:55 +0100 Subject: [PATCH 08/12] test(pluginkit): run the plugin settings scenarios --- pluginkit/features/features_test.go | 4 +- .../features/settings-declarations.feature | 5 - pluginkit/features/settings.feature | 9 - pluginkit/features/steps_settings_test.go | 484 ++++++++++++++++++ 4 files changed, 486 insertions(+), 16 deletions(-) create mode 100644 pluginkit/features/steps_settings_test.go diff --git a/pluginkit/features/features_test.go b/pluginkit/features/features_test.go index 1287039..c3c2acb 100644 --- a/pluginkit/features/features_test.go +++ b/pluginkit/features/features_test.go @@ -55,9 +55,9 @@ func TestRoutes(t *testing.T) { } func TestSettings(t *testing.T) { - runFeature(t, "settings.feature", func(*godog.ScenarioContext) {}) + runFeature(t, "settings.feature", initializeSettings()) } func TestSettingsDeclarations(t *testing.T) { - runFeature(t, "settings-declarations.feature", func(*godog.ScenarioContext) {}) + runFeature(t, "settings-declarations.feature", initializeSettings()) } diff --git a/pluginkit/features/settings-declarations.feature b/pluginkit/features/settings-declarations.feature index 424732f..8a83f6a 100644 --- a/pluginkit/features/settings-declarations.feature +++ b/pluginkit/features/settings-declarations.feature @@ -10,7 +10,6 @@ Feature: Checking the settings a plugin declares Given the application names plugin variables under "APP_PLUGIN_" And the application reserves the key starts "job_" and "db_" - @wip Scenario: A plugin that declares one setting of each type passes the check Given the plugin "notes" declares these settings: | key | type | default | min | max | options | @@ -24,7 +23,6 @@ Feature: Checking the settings a plugin declares When the settings of "notes" are checked Then the settings pass the check - @wip Scenario Outline: A declaration outside the rules is rejected with its reason Given the plugin "notes" declares When the settings of "notes" are checked @@ -55,14 +53,12 @@ Feature: Checking the settings a plugin declares | a secret "api_key" with the default "key-for-example" | settings[0] api_key: a secret takes no default, because plugin.json is public | | a text "title" that names the content type "post" | settings[0] title: a text setting takes no of field | - @wip Scenario: The rejection of a secret's default never quotes it Given the plugin "notes" declares a secret "api_key" with the default "key-for-example" When the settings of "notes" are checked Then the check rejects them with "settings[0] api_key: a secret takes no default, because plugin.json is public" And the reason does not hold "key-for-example" - @wip Scenario Outline: A plugin with settings keeps its id clear of doubled and trailing hyphens Given the plugin "" declares the text setting "title" When the settings of "" are checked @@ -73,7 +69,6 @@ Feature: Checking the settings a plugin declares | notes--pro | | notes- | - @wip Scenario: A plugin with no settings keeps any id the wiring takes Given the plugin "notes--pro" declares no settings When the settings of "notes--pro" are checked diff --git a/pluginkit/features/settings.feature b/pluginkit/features/settings.feature index 1252653..4b498da 100644 --- a/pluginkit/features/settings.feature +++ b/pluginkit/features/settings.feature @@ -19,7 +19,6 @@ Feature: Working out each plugin setting from the environment and its default | tags | lines | news | | | | | api_key | secret | | | | | - @wip Scenario: Each setting is read from a variable named after its plugin and its key Then the settings of "notes" are read from these variables: | key | variable | @@ -31,7 +30,6 @@ Feature: Working out each plugin setting from the environment and its default | tags | APP_PLUGIN_NOTES__TAGS | | api_key | APP_PLUGIN_NOTES__API_KEY | - @wip Scenario Outline: Each hyphen of a plugin id becomes an underscore in the variable Given the plugin "" declares the text setting "max_seats" Then the setting "max_seats" of "" is read from "" @@ -42,7 +40,6 @@ Feature: Working out each plugin setting from the environment and its default | events-pro | APP_PLUGIN_EVENTS_PRO__MAX_SEATS | | events-pro-max | APP_PLUGIN_EVENTS_PRO_MAX__MAX_SEATS | - @wip Scenario: Each setting takes its default when the environment holds none When the settings of "notes" are worked out Then the settings read: @@ -55,7 +52,6 @@ Feature: Working out each plugin setting from the environment and its default | tags | news | | api_key | not set | - @wip Scenario Outline: A value in the environment wins over the default Given the environment holds "" in "" When the settings of "notes" are worked out @@ -71,7 +67,6 @@ Feature: Working out each plugin setting from the environment and its default | tags | APP_PLUGIN_NOTES__TAGS | news,, events | news, events | | api_key | APP_PLUGIN_NOTES__API_KEY | key-for-example | set | - @wip Scenario: An empty value counts as unset Given the environment holds "" in "APP_PLUGIN_NOTES__PER_PAGE" And the environment holds "" in "APP_PLUGIN_NOTES__API_KEY" @@ -79,7 +74,6 @@ Feature: Working out each plugin setting from the environment and its default Then "per_page" reads "10" And "api_key" reads "not set" - @wip Scenario Outline: A value its type rejects is named by its variable Given the environment holds "" in "" When the settings of "notes" are worked out @@ -96,14 +90,12 @@ Feature: Working out each plugin setting from the environment and its default | APP_PLUGIN_NOTES__OPEN | maybe | APP_PLUGIN_NOTES__OPEN: must be true or false, got "maybe" | | APP_PLUGIN_NOTES__ORDER | random | APP_PLUGIN_NOTES__ORDER: must be one of newest, oldest, got "random" | - @wip Scenario: The first rejected value in the manifest's order is the one named Given the environment holds "banana" in "APP_PLUGIN_NOTES__PER_PAGE" And the environment holds "random" in "APP_PLUGIN_NOTES__ORDER" When the settings of "notes" are worked out Then the settings are rejected with "APP_PLUGIN_NOTES__PER_PAGE: must be a whole number, got "banana"" - @wip Scenario: A secret reads its value only when asked for and prints as set Given the environment holds "key-for-example" in "APP_PLUGIN_NOTES__API_KEY" When the settings of "notes" are worked out @@ -111,7 +103,6 @@ Feature: Working out each plugin setting from the environment and its default And every print or log of the settings shows "set" for "api_key" And no print, log or encoding of the settings holds "key-for-example" - @wip Scenario: A value rejected beside a secret never shows the secret Given the environment holds "key-for-example" in "APP_PLUGIN_NOTES__API_KEY" And the environment holds "banana" in "APP_PLUGIN_NOTES__PER_PAGE" diff --git a/pluginkit/features/steps_settings_test.go b/pluginkit/features/steps_settings_test.go new file mode 100644 index 0000000..eac0207 --- /dev/null +++ b/pluginkit/features/steps_settings_test.go @@ -0,0 +1,484 @@ +// SPDX-License-Identifier: Apache-2.0 + +package features_test + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "log/slog" + "regexp" + "strconv" + "strings" + "time" + + "github.com/cucumber/godog" + + "github.com/gopherium/framework/pluginkit/settings" + "github.com/gopherium/framework/pluginkit/wire" +) + +// settingsWorld is what one scenario of the settings features declares, finds and works out. +type settingsWorld struct { + rules settings.Rules + declared map[string][]wire.Setting + found map[string]string + values settings.Values + err error +} + +// declaration reads the words of one declaration step as the settings they declare. +type declaration struct { + pattern *regexp.Regexp + build func(match []string) ([]wire.Setting, error) +} + +// declarations lists each declaration a scenario can make, in the words that name it. +var declarations = []declaration{ + {regexp.MustCompile(`^a setting "([^"]*)" of the type "([^"]*)"$`), func(m []string) ([]wire.Setting, error) { + return []wire.Setting{{Key: m[1], Type: m[2]}}, nil + }}, + {regexp.MustCompile(`^(?:a|the) text setting "([^"]*)"$`), func(m []string) ([]wire.Setting, error) { + return []wire.Setting{{Key: m[1], Type: settings.TypeText}}, nil + }}, + {regexp.MustCompile(`^the text setting "([^"]*)" twice$`), func(m []string) ([]wire.Setting, error) { + return []wire.Setting{{Key: m[1], Type: settings.TypeText}, {Key: m[1], Type: settings.TypeText}}, nil + }}, + {regexp.MustCompile(`^a (\w+) "([^"]*)" with no (?:default|options)$`), func(m []string) ([]wire.Setting, error) { + return []wire.Setting{{Key: m[2], Type: m[1]}}, nil + }}, + {regexp.MustCompile(`^a (\w+) "([^"]*)" with the default "([^"]*)"$`), func(m []string) ([]wire.Setting, error) { + return []wire.Setting{{Key: m[2], Type: m[1], Default: m[3]}}, nil + }}, + {regexp.MustCompile(`^a count "([^"]*)" from (\S+) to (\S+) with the default "([^"]*)"$`), countFromTo}, + {regexp.MustCompile(`^a count "([^"]*)" from (\S+) with the default "([^"]*)"$`), countFrom}, + {regexp.MustCompile(`^a (\w+) "([^"]*)" with the (min|max) (\S+)$`), withBound}, + {regexp.MustCompile(`^a (\w+) "([^"]*)" with the options "([^"]*)" and "([^"]*)"$`), + func(m []string) ([]wire.Setting, error) { + return []wire.Setting{{Key: m[2], Type: m[1], Options: []string{m[3], m[4]}}}, nil + }}, + {regexp.MustCompile(`^a choice "([^"]*)" of "([^"]*)" and "([^"]*)" with no default$`), + func(m []string) ([]wire.Setting, error) { + return []wire.Setting{{Key: m[1], Type: settings.TypeChoice, Options: []string{m[2], m[3]}}}, nil + }}, + {regexp.MustCompile(`^a choice "([^"]*)" of "([^"]*)" and "([^"]*)" with the default "([^"]*)"$`), + func(m []string) ([]wire.Setting, error) { + return []wire.Setting{{Key: m[1], Type: settings.TypeChoice, Options: []string{m[2], m[3]}, Default: m[4]}}, nil + }}, + {regexp.MustCompile(`^a (\w+) "([^"]*)" that names the content type "([^"]*)"$`), + func(m []string) ([]wire.Setting, error) { + return []wire.Setting{{Key: m[2], Type: m[1], Of: m[3]}}, nil + }}, +} + +// boundOf reads text as the min or max of a declared setting, nil when text is empty. +func boundOf(text string) (*float64, error) { + if text == "" { + return nil, nil + } + n, err := strconv.ParseFloat(text, 64) + if err != nil { + return nil, fmt.Errorf("the bound %q is not a number", text) + } + return &n, nil +} + +// countFromTo declares a count with a min, a max and a default. +func countFromTo(m []string) ([]wire.Setting, error) { + low, lowErr := boundOf(m[2]) + high, highErr := boundOf(m[3]) + if err := errors.Join(lowErr, highErr); err != nil { + return nil, err + } + return []wire.Setting{{Key: m[1], Type: settings.TypeCount, Min: low, Max: high, Default: m[4]}}, nil +} + +// countFrom declares a count with a min and a default. +func countFrom(m []string) ([]wire.Setting, error) { + low, err := boundOf(m[2]) + if err != nil { + return nil, err + } + return []wire.Setting{{Key: m[1], Type: settings.TypeCount, Min: low, Default: m[3]}}, nil +} + +// withBound declares a setting of any type with a min or a max. +func withBound(m []string) ([]wire.Setting, error) { + n, err := boundOf(m[4]) + if err != nil { + return nil, err + } + setting := wire.Setting{Key: m[2], Type: m[1], Max: n} + if m[3] == "min" { + setting.Min, setting.Max = n, nil + } + return []wire.Setting{setting}, nil +} + +// optionsOf reads a comma list of options, nil when text is empty. +func optionsOf(text string) []string { + if text == "" { + return nil + } + options := strings.Split(text, ",") + for i, option := range options { + options[i] = strings.TrimSpace(option) + } + return options +} + +// columnsOf maps each heading of table to its column. +func columnsOf(table *godog.Table) map[string]int { + columns := map[string]int{} + for i, cell := range table.Rows[0].Cells { + columns[cell.Value] = i + } + return columns +} + +// settingOf reads the cells of one row of a settings table under columns. +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"), + Min: low, Max: high, Options: optionsOf(cell("options")), + } + return setting, errors.Join(lowErr, highErr) +} + +// namesUnder sets the prefix of every variable. +func (w *settingsWorld) namesUnder(prefix string) { + w.rules.Prefix = prefix +} + +// reserves sets the two key starts the application reserves. +func (w *settingsWorld) reserves(first, second string) { + w.rules.Reserved = []string{first, second} +} + +// declaresTable has plugin id declare each setting of table. +func (w *settingsWorld) declaresTable(id string, table *godog.Table) error { + columns := columnsOf(table) + declared := make([]wire.Setting, 0, len(table.Rows)-1) + for _, row := range table.Rows[1:] { + cells := make([]string, 0, len(row.Cells)) + for _, cell := range row.Cells { + cells = append(cells, cell.Value) + } + setting, err := settingOf(cells, columns) + if err != nil { + return err + } + declared = append(declared, setting) + } + w.declared[id] = declared + return nil +} + +// declaresNone has plugin id declare no settings. +func (w *settingsWorld) declaresNone(id string) { + w.declared[id] = nil +} + +// declares has plugin id declare the settings the words name. +func (w *settingsWorld) declares(id, words string) error { + for _, d := range declarations { + if match := d.pattern.FindStringSubmatch(words); match != nil { + declared, err := d.build(match) + w.declared[id] = declared + return err + } + } + return fmt.Errorf("no declaration reads %q", words) +} + +// holds puts value in the environment the application found, under variable. +func (w *settingsWorld) holds(value, variable string) { + w.found[variable] = 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] + if !ok { + return nil, fmt.Errorf("the plugin %q declared nothing", id) + } + return declared, nil +} + +// schemaOf returns the checked settings of plugin id, an error when the check rejects them. +func (w *settingsWorld) schemaOf(id string) (settings.Schema, error) { + declared, err := w.declaredBy(id) + if err != nil { + return settings.Schema{}, err + } + schema, err := settings.Check(id, declared, w.rules) + if err != nil { + return settings.Schema{}, fmt.Errorf("the check rejected the settings: %w", err) + } + return schema, nil +} + +// checked checks the settings of plugin id and keeps the rejection. +func (w *settingsWorld) checked(id string) error { + declared, err := w.declaredBy(id) + if err != nil { + return err + } + _, w.err = settings.Check(id, declared, w.rules) + return nil +} + +// workedOut checks the settings of plugin id, then works them out from the environment and keeps what it answers. +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) + return nil +} + +// variableOf returns the variable that sets key of plugin id. +func (w *settingsWorld) variableOf(id, key string) (string, error) { + schema, err := w.schemaOf(id) + if err != nil { + return "", err + } + for _, field := range schema.Fields { + if field.Key == key { + return field.Env, nil + } + } + return "", fmt.Errorf("the plugin %q has no setting %q", id, key) +} + +// readFrom fails unless key of plugin id is set by variable. +func (w *settingsWorld) readFrom(key, id, variable string) error { + got, err := w.variableOf(id, key) + if err != nil { + return err + } + if got != variable { + return fmt.Errorf("%s of %s is read from %s, want %s", key, id, got, variable) + } + return nil +} + +// readFromTable fails unless each key of table is set by the variable beside it. +func (w *settingsWorld) readFromTable(id string, table *godog.Table) error { + for _, row := range table.Rows[1:] { + if err := w.readFrom(row.Cells[0].Value, id, row.Cells[1].Value); err != nil { + return err + } + } + return nil +} + +// reading returns a resolved value as the text a scenario writes it in. +func reading(value settings.Value) string { + switch value.Type { + case settings.TypeCount: + return strconv.Itoa(value.Count) + case settings.TypeFlag: + return strconv.FormatBool(value.Flag) + case settings.TypeDuration: + return value.Duration.String() + case settings.TypeLines: + return strings.Join(value.Lines, ", ") + case settings.TypeSecret: + return value.Secret.String() + } + return value.Text +} + +// written returns the text a scenario wants a value of kind to read, a duration in the form Duration.String gives. +func written(kind, text string) string { + if kind != settings.TypeDuration { + return text + } + if d, err := time.ParseDuration(text); err == nil { + return d.String() + } + return text +} + +// reads fails unless the worked out key reads want. +func (w *settingsWorld) reads(key, want string) error { + if w.err != nil { + return fmt.Errorf("the settings were rejected: %w", w.err) + } + value, ok := w.values[key] + if !ok { + return fmt.Errorf("no setting %q was worked out", key) + } + if got := reading(value); got != written(value.Type, want) { + return fmt.Errorf("%s reads %q, want %q", key, got, want) + } + return nil +} + +// 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 { + return fmt.Errorf("%d settings were worked out, want %d", got, want) + } + for _, row := range table.Rows[1:] { + if err := w.reads(row.Cells[0].Value, row.Cells[1].Value); err != nil { + return err + } + } + return nil +} + +// rejectedWith fails unless the last check or working out was rejected with want. +func (w *settingsWorld) rejectedWith(want string) error { + if w.err == nil { + return fmt.Errorf("the settings were not rejected, want %q", want) + } + if w.err.Error() != want { + return fmt.Errorf("the settings were rejected with %q, want %q", w.err, want) + } + return nil +} + +// passed fails unless the last check passed. +func (w *settingsWorld) passed() error { + if w.err != nil { + return fmt.Errorf("the check rejected the settings: %w", w.err) + } + return nil +} + +// reasonLacks fails unless the last rejection is there and does not hold 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 +} + +// revealed fails unless the secret key reveals want. +func (w *settingsWorld) revealed(key, want string) error { + if got := w.values[key].Secret.Reveal(); got != want { + return fmt.Errorf("the secret %s reveals %q, want %q", key, got, want) + } + return nil +} + +// dropTime leaves the time out of a log line, so two lines compare by what they log. +func dropTime(_ []string, attr slog.Attr) slog.Attr { + if attr.Key == slog.TimeKey { + return slog.Attr{} + } + return attr +} + +// textLine returns the line slog's text handler writes for value under the key setting. +func textLine(value any) string { + var out bytes.Buffer + slog.New(slog.NewTextHandler(&out, &slog.HandlerOptions{ReplaceAttr: dropTime})).Info("read", "setting", value) + return out.String() +} + +// jsonLine returns the line slog's JSON handler writes for value under the key setting. +func jsonLine(value any) string { + var out bytes.Buffer + slog.New(slog.NewJSONHandler(&out, &slog.HandlerOptions{ReplaceAttr: dropTime})).Info("read", "setting", value) + return out.String() +} + +// encoding returns value encoded by encoding/json, the error text when it fails. +func encoding(value any) string { + data, err := json.Marshal(value) + if err != nil { + return err.Error() + } + return string(data) +} + +// printer returns value through the fmt verb. +func printer(verb string) func(any) string { + return func(value any) string { return fmt.Sprintf(verb, value) } +} + +// renderers prints, logs and encodes a value in each way a site may show it. +var renderers = map[string]func(any) string{ + "%v": printer("%v"), "%+v": printer("%+v"), "%s": printer("%s"), "%q": printer("%q"), + "text log": textLine, "JSON log": jsonLine, "encoding/json": encoding, +} + +// showsAs fails unless every print and log of the secret key shows as the text want would. +func (w *settingsWorld) showsAs(want, key string) error { + secret := w.values[key].Secret + for name, render := range renderers { + if got, plain := render(secret), render(want); got != plain { + return fmt.Errorf("%s shows %s as %q, want %q", name, key, got, plain) + } + } + if got := printer("%#v")(secret); got != want { + return fmt.Errorf("%%#v shows %s as %q, want %q", key, got, want) + } + return nil +} + +// nowhere fails when any print, log or encoding of the worked out settings holds text. +func (w *settingsWorld) nowhere(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) + } + } + 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) + sc.Step(`^the application reserves the key starts "([^"]*)" and "([^"]*)"$`, w.reserves) + sc.Step(`^the plugin "([^"]*)" declares these settings:$`, w.declaresTable) + 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) +} + +// whenSettings binds the steps that check and work out the settings. +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) +} + +// thenSettings binds the steps that check what the settings read and why they were rejected. +func thenSettings(sc *godog.ScenarioContext, w *settingsWorld) { + sc.Step(`^the settings of "([^"]*)" are read from these variables:$`, w.readFromTable) + sc.Step(`^the setting "([^"]*)" of "([^"]*)" is read from "([^"]*)"$`, w.readFrom) + sc.Step(`^the settings read:$`, w.readsTable) + sc.Step(`^"([^"]*)" reads "([^"]*)"$`, w.reads) + sc.Step(`^the settings are rejected with "(.*)"$`, w.rejectedWith) + sc.Step(`^the check rejects them with "(.*)"$`, w.rejectedWith) + sc.Step(`^the settings pass the check$`, w.passed) + sc.Step(`^the reason does not hold "([^"]*)"$`, w.reasonLacks) + sc.Step(`^the secret "([^"]*)" reads "([^"]*)" when asked for$`, w.revealed) + sc.Step(`^every print or log of the settings shows "([^"]*)" for "([^"]*)"$`, w.showsAs) + sc.Step(`^no print, log or encoding of the settings holds "([^"]*)"$`, w.nowhere) +} + +// 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{}} + givenSettings(sc, w) + whenSettings(sc, w) + thenSettings(sc, w) + } +} From 57efc7cef91177d12403a2756a9ae1ba8e291330 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:27:34 +0100 Subject: [PATCH 09/12] fix(pluginkit): reject a choice option that starts or ends with a space --- pluginkit/settings/check.go | 15 ++++++++++++++- pluginkit/settings/check_test.go | 6 ++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/pluginkit/settings/check.go b/pluginkit/settings/check.go index 5c4368c..9698809 100644 --- a/pluginkit/settings/check.go +++ b/pluginkit/settings/check.go @@ -153,14 +153,27 @@ func neededDefault(field Field) error { return readDefault(field) } -// choiceDefault rejects a choice with no options, then a default that is not one of them. +// choiceDefault rejects a choice with no options or with an option no value can select, then a default outside them. func choiceDefault(field Field) error { if len(field.Options) == 0 { return errors.New("a choice needs options") } + if err := trimmedOptions(field.Options); err != nil { + return err + } return neededDefault(field) } +// trimmedOptions rejects the first option that starts or ends with a space. +func trimmedOptions(options []string) error { + for _, option := range options { + if option != strings.TrimSpace(option) { + return complaint("an option must not start or end with a space", option) + } + } + return nil +} + // noDefault rejects any default without quoting it. func noDefault(field Field) error { if field.Default != "" { diff --git a/pluginkit/settings/check_test.go b/pluginkit/settings/check_test.go index e964f25..2ef7965 100644 --- a/pluginkit/settings/check_test.go +++ b/pluginkit/settings/check_test.go @@ -85,6 +85,12 @@ var rejections = []rejection{ "settings[0] title: options apply only to a choice"}, {"choice with no options", []wire.Setting{{Key: "order", Type: TypeChoice}}, "settings[0] order: a choice needs options"}, + {"choice option with a space at its end", []wire.Setting{{Key: "order", Type: TypeChoice, Default: "oldest", + Options: []string{"newest ", "oldest"}}}, + `settings[0] order: an option must not start or end with a space, got "newest "`}, + {"choice option with a space at its start", []wire.Setting{{Key: "order", Type: TypeChoice, Default: "newest", + Options: []string{"newest", " oldest"}}}, + `settings[0] order: an option must not start or end with a space, got " oldest"`}, {"choice with no default", []wire.Setting{{Key: "order", Type: TypeChoice, Options: []string{"newest", "oldest"}}}, "settings[0] order: a choice needs a default"}, {"choice default not an option", []wire.Setting{{Key: "order", Type: TypeChoice, Default: "random", From 56536a75a2a1a393812c5837376c0e44b11e7bfc Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:27:35 +0100 Subject: [PATCH 10/12] test(pluginkit): pin that a choice option with a space at either end is rejected --- pluginkit/features/settings-declarations.feature | 1 + 1 file changed, 1 insertion(+) diff --git a/pluginkit/features/settings-declarations.feature b/pluginkit/features/settings-declarations.feature index 8a83f6a..1fbe3db 100644 --- a/pluginkit/features/settings-declarations.feature +++ b/pluginkit/features/settings-declarations.feature @@ -45,6 +45,7 @@ Feature: Checking the settings a plugin declares | a lines "tags" with the min 1 | settings[0] tags: min and max apply only to a count | | a text "title" with the options "a" and "b" | settings[0] title: options apply only to a choice | | a choice "order" with no options | settings[0] order: a choice needs options | + | a choice "order" of "new " and "oldest" with the default "oldest" | settings[0] order: an option must not start or end with a space, got "new " | | a choice "order" of "newest" and "oldest" with no default | settings[0] order: a choice needs a default | | a choice "order" of "newest" and "oldest" with the default "random" | settings[0] order: the default must be one of newest, oldest, got "random" | | a duration "keep_for" with no default | settings[0] keep_for: a duration needs a default | From 24477e412c7fa8657b3a22528ae1291e1af56afe Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:27:36 +0100 Subject: [PATCH 11/12] test(pluginkit): flatten the name collision test and the parse runner --- pluginkit/settings/name_test.go | 40 +++++++++++++++++++++------- pluginkit/settings/parse_test.go | 45 +++++++++++++++++++------------- 2 files changed, 58 insertions(+), 27 deletions(-) diff --git a/pluginkit/settings/name_test.go b/pluginkit/settings/name_test.go index d44f54b..cc152b3 100644 --- a/pluginkit/settings/name_test.go +++ b/pluginkit/settings/name_test.go @@ -27,24 +27,46 @@ func TestNameJoinsThePrefixTheIDAndTheKeyInCapitals(t *testing.T) { func TestNameNeverGivesTwoSettingsOneVariable(t *testing.T) { ids := []string{"a", "a-b", "a-b-c", "ab", "hook", "hook-save", "x", "x-a", "x-a-b"} keys := []string{"b", "c", "b_c", "a_b", "budget", "save_budget", "a", "a_b_c", "b2"} + acceptIDs(t, ids) + acceptKeys(t, keys) seen := map[string][2]string{} + for _, id := range ids { + for _, key := range keys { + claim(t, seen, id, key) + } + } +} + +// acceptIDs stops the test when checkID rejects one of ids. +func acceptIDs(t *testing.T, ids []string) { + t.Helper() for _, id := range ids { if err := checkID(id); err != nil { t.Fatalf("checkID(%q) = %v, the case needs an id it accepts", id, err) } - for _, key := range keys { - if err := checkKey(key, nil); err != nil { - t.Fatalf("checkKey(%q) = %v, the case needs a key it accepts", key, err) - } - name := Name("APP_PLUGIN_", id, key) - if first, taken := seen[name]; taken { - t.Errorf("%s names both %v and [%s %s]", name, first, id, key) - } - seen[name] = [2]string{id, key} + } +} + +// acceptKeys stops the test when checkKey rejects one of keys. +func acceptKeys(t *testing.T, keys []string) { + t.Helper() + for _, key := range keys { + if err := checkKey(key, nil); err != nil { + t.Fatalf("checkKey(%q) = %v, the case needs a key it accepts", key, err) } } } +// claim records the variable of id and key in seen, reporting a pair that already took it. +func claim(t *testing.T, seen map[string][2]string, id, key string) { + t.Helper() + name := Name("APP_PLUGIN_", id, key) + if first, taken := seen[name]; taken { + t.Errorf("%s names both %v and [%s %s]", name, first, id, key) + } + seen[name] = [2]string{id, key} +} + func TestCheckKeyTakesLowercaseWordsJoinedByOneUnderscore(t *testing.T) { for _, key := range []string{"title", "max_seats", "a", "page2", "a_b_c", "x_1"} { if err := checkKey(key, []string{"job_", "db_"}); err != nil { diff --git a/pluginkit/settings/parse_test.go b/pluginkit/settings/parse_test.go index 17ec77b..7a420b6 100644 --- a/pluginkit/settings/parse_test.go +++ b/pluginkit/settings/parse_test.go @@ -30,24 +30,33 @@ type parseCase struct { func runParse(t *testing.T, cases []parseCase) { t.Helper() for _, c := range cases { - parse, err := parserOf(c.field.Type) - if err != nil { - t.Fatalf("parserOf(%q) = %v", c.field.Type, err) - } - got, err := parse(c.field, c.value) - if c.err != "" { - if err == nil || err.Error() != c.err { - t.Errorf("%s %q: error %v, want %q", c.field.Type, c.value, err, c.err) - } - continue - } - if err != nil { - t.Errorf("%s %q: error %v, want none", c.field.Type, c.value, err) - continue - } - if !sameValue(got, c.want) { - t.Errorf("%s %q = %+v, want %+v", c.field.Type, c.value, got, c.want) - } + checkParse(t, c) + } +} + +// checkParse reads one case's value with the parser of its field's type and reports any difference from the case. +func checkParse(t *testing.T, c parseCase) { + t.Helper() + parse, err := parserOf(c.field.Type) + if err != nil { + t.Fatalf("parserOf(%q) = %v", c.field.Type, err) + } + got, err := parse(c.field, c.value) + switch { + case c.err != "": + wantError(t, c, err) + case err != nil: + t.Errorf("%s %q: error %v, want none", c.field.Type, c.value, err) + case !sameValue(got, c.want): + t.Errorf("%s %q = %+v, want %+v", c.field.Type, c.value, got, c.want) + } +} + +// wantError reports err when it is not the error the case expects. +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) } } From 0c55abe3913d7370ac9bed2af9d34dac8278ac74 Mon Sep 17 00:00:00 2001 From: SirLouen Date: Sun, 15 Nov 2026 19:27:36 +0100 Subject: [PATCH 12/12] chore(codescene): skip the string heavy rule in the settings parsers --- .codescene/code-health-rules.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.codescene/code-health-rules.json b/.codescene/code-health-rules.json index 22502de..ddf445f 100644 --- a/.codescene/code-health-rules.json +++ b/.codescene/code-health-rules.json @@ -6,6 +6,12 @@ { "name": "String Heavy Function Arguments", "weight": 0.0 }, { "name": "Primitive Obsession", "weight": 0.0 } ] + }, + { + "matching_content_path": "pluginkit/settings/parse.go", + "rules": [ + { "name": "String Heavy Function Arguments", "weight": 0.0 } + ] } ] }