Files
core/solutions/engine/values.go
T

306 lines
7.8 KiB
Go
Raw Normal View History

package engine
import (
"fmt"
"net"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"yetano.dev/yetano/core/secretref"
"yetano.dev/yetano/core/solutions/catalog"
)
// MaxAnswerLen bounds a single text answer (SEC-03).
const MaxAnswerLen = 64 << 10
var (
hostnameRE = regexp.MustCompile(`^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`)
emailRE = regexp.MustCompile(`^[^@\s]+@[^@\s]+$`)
dateRE = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
)
// TypeValidator checks and normalizes one scalar answer of a type. New
// question types are added with RegisterType (WIZ-04).
type TypeValidator func(v any) (any, error)
var extraTypes = map[string]TypeValidator{}
// RegisterType adds a question type. It must be called before catalogs
// using the type are validated; built-in types cannot be replaced.
func RegisterType(name string, fn TypeValidator) error {
if catalog.QuestionTypes[name] {
return fmt.Errorf("type %q is built in", name)
}
extraTypes[name] = fn
catalog.QuestionTypes[name] = true
return nil
}
// Normalize converts an answer given as text (CLI --set, interactive
// input) or as decoded YAML/JSON into the canonical value for the
// question and validates it. It does not check option enablement.
func Normalize(q *catalog.Question, v any) (any, error) {
switch q.Type {
case "multiselect", "list":
items := listOf(v)
out := make([]any, 0, len(items))
seen := map[string]bool{}
for _, it := range items {
var n any
var err error
if q.Type == "multiselect" {
n, err = optionValue(q, it)
} else {
n, err = scalar(q.Item, it)
}
if err != nil {
return nil, err
}
k := catalog.Scalar(n)
if seen[k] {
continue
}
seen[k] = true
out = append(out, n)
}
if err := checkCount(q.Validation, len(out)); err != nil {
return nil, err
}
return out, nil
case "select":
return optionValue(q, v)
case "keyvalue":
m, ok := v.(map[string]any)
if !ok {
s, isStr := v.(string)
if !isStr {
return nil, fmt.Errorf("want key=value pairs")
}
m = map[string]any{}
for _, part := range splitList(s) {
k, val, ok := strings.Cut(part, "=")
if !ok || strings.TrimSpace(k) == "" {
return nil, fmt.Errorf("%q: want key=value", part)
}
m[strings.TrimSpace(k)] = strings.TrimSpace(val)
}
}
return m, nil
}
n, err := scalar(q.Type, v)
if err != nil {
return nil, err
}
return n, checkValue(q.Validation, n)
}
func optionValue(q *catalog.Question, v any) (any, error) {
s := strings.TrimSpace(catalog.Scalar(v))
for _, o := range q.Options {
if o.ID == s {
return o.ID, nil
}
}
// a number picks the n-th option (interactive CLI)
if n, err := strconv.Atoi(s); err == nil && n >= 1 && n <= len(q.Options) {
return q.Options[n-1].ID, nil
}
ids := make([]string, len(q.Options))
for i, o := range q.Options {
ids[i] = o.ID
}
return nil, fmt.Errorf("%q is not one of %s", s, strings.Join(ids, ", "))
}
func listOf(v any) []any {
switch x := v.(type) {
case []any:
return x
case []string:
out := make([]any, len(x))
for i, s := range x {
out[i] = s
}
return out
case string:
var out []any
for _, p := range splitList(x) {
out = append(out, p)
}
return out
case nil:
return nil
}
return []any{v}
}
func splitList(s string) []string {
var out []string
for _, p := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == '\n' || r == ' ' || r == ';' }) {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
// scalar validates one value of a scalar type.
func scalar(typ string, v any) (any, error) {
if fn, ok := extraTypes[typ]; ok {
return fn(v)
}
if b, ok := v.(bool); ok && typ == "boolean" {
return b, nil
}
s := strings.TrimSpace(catalog.Scalar(v))
if len(s) > MaxAnswerLen || !utf8.ValidString(s) {
return nil, fmt.Errorf("value too long or not UTF-8")
}
switch typ {
case "boolean":
switch strings.ToLower(s) {
case "true", "yes", "y", "on", "1", "ja", "j":
return true, nil
case "false", "no", "n", "off", "0", "nein":
return false, nil
}
return nil, fmt.Errorf("%q: want yes or no", s)
case "integer":
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return nil, fmt.Errorf("%q: want a whole number", s)
}
return int(n), nil
case "decimal":
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return nil, fmt.Errorf("%q: want a number", s)
}
return f, nil
case "port":
n, err := strconv.Atoi(s)
if err != nil || n < 1 || n > 65535 {
return nil, fmt.Errorf("%q: want a port 1-65535", s)
}
return n, nil
case "hostname", "domain":
s = strings.ToLower(strings.TrimSuffix(s, "."))
if !hostnameRE.MatchString(s) || len(s) > 253 {
return nil, fmt.Errorf("%q: not a valid %s", s, typ)
}
if typ == "domain" && !strings.Contains(s, ".") {
return nil, fmt.Errorf("%q: a domain needs a dot (example.org)", s)
}
return s, nil
case "email":
if !emailRE.MatchString(s) {
return nil, fmt.Errorf("%q: not an e-mail address", s)
}
return s, nil
case "ip":
if net.ParseIP(s) == nil {
return nil, fmt.Errorf("%q: not an IP address", s)
}
return s, nil
case "cidr":
if _, _, err := net.ParseCIDR(s); err != nil {
if net.ParseIP(s) == nil {
return nil, fmt.Errorf("%q: not a network (CIDR) or address", s)
}
}
return s, nil
case "url":
u, err := url.Parse(s)
if err != nil || u.Scheme == "" || u.Host == "" {
return nil, fmt.Errorf("%q: not a URL", s)
}
return s, nil
case "duration":
if _, err := time.ParseDuration(s); err != nil {
return nil, fmt.Errorf("%q: want a duration like 30s, 5m, 4h", s)
}
return s, nil
case "date":
if !dateRE.MatchString(s) {
return nil, fmt.Errorf("%q: want YYYY-MM-DD", s)
}
if _, err := time.Parse("2006-01-02", s); err != nil {
return nil, fmt.Errorf("%q: not a date", s)
}
return s, nil
case "path", "dir":
if s == "" || strings.ContainsRune(s, 0) {
return nil, fmt.Errorf("want a path")
}
return s, nil
case "secret":
// SEC-01/WIZ-07: only references, never the secret itself.
if err := secretref.Validate(s); err != nil || s == "" {
return nil, fmt.Errorf("give a reference (secret://name, env:VAR, file:path), never the secret itself")
}
return s, nil
case "string", "text", "package", "profile", "capability", "provider", "target":
return s, nil
}
return nil, fmt.Errorf("unknown type %q", typ)
}
func checkValue(val catalog.Validation, v any) error {
msg := func(err string) error {
if val.Message != "" {
return fmt.Errorf("%s", val.Message)
}
return fmt.Errorf("%s", err)
}
if f, ok := v.(float64); ok {
return checkRange(val, f, msg)
}
if n, ok := v.(int); ok {
return checkRange(val, float64(n), msg)
}
if s, ok := v.(string); ok {
if val.MinLength > 0 && len(s) < val.MinLength {
return msg(fmt.Sprintf("at least %d characters", val.MinLength))
}
if val.MaxLength > 0 && len(s) > val.MaxLength {
return msg(fmt.Sprintf("at most %d characters", val.MaxLength))
}
if val.Pattern != "" {
re, err := regexp.Compile(val.Pattern)
if err != nil {
return fmt.Errorf("bad pattern in catalog: %v", err)
}
if !re.MatchString(s) {
return msg(fmt.Sprintf("%q does not match %s", s, val.Pattern))
}
}
}
return nil
}
func checkRange(val catalog.Validation, f float64, msg func(string) error) error {
if val.Min != nil && f < *val.Min {
return msg(fmt.Sprintf("at least %v", *val.Min))
}
if val.Max != nil && f > *val.Max {
return msg(fmt.Sprintf("at most %v", *val.Max))
}
return nil
}
func checkCount(val catalog.Validation, n int) error {
if val.MinItems > 0 && n < val.MinItems {
if val.Message != "" {
return fmt.Errorf("%s", val.Message)
}
return fmt.Errorf("at least %d item(s)", val.MinItems)
}
if val.MaxItems > 0 && n > val.MaxItems {
return fmt.Errorf("at most %d item(s)", val.MaxItems)
}
return nil
}