seedling: Kairos config validator library (#798)

* Validate yaml

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* lint feedback

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Validate User name with JsonSchema

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* WIP users validation

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Add multiple examples for ssh keys

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Add example of complex validation with AnyOf

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Better business rule example with P2P

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Test with message for empty network_token

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Split into a file for each sub section

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Add install schema validations

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Add to main schema

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Add more tests for p2p

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Add install schema

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Validate fields between new and old schema

It also adds the missing ones

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Lint

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Remove temp debugging functions

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Add new fields in old schema

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Add documentation for all exported

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Move schemas into a directory of their own

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Add missing dot at end of comment

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

* Rebase master and add local_file to bundles

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>

---------

Signed-off-by: Mauro Morales <mauro.morales@spectrocloud.com>
This commit is contained in:
Mauro Morales 2023-02-08 11:02:13 +01:00 committed by Itxaka
parent 0a62e316e0
commit 84c68ff0b8
9 changed files with 788 additions and 0 deletions

View File

@ -0,0 +1,79 @@
package config
import (
jsonschemago "github.com/swaggest/jsonschema-go"
)
// InstallSchema represents the install block in the Kairos configuration. It is used to drive automatic installations without user interaction.
type InstallSchema struct {
_ struct{} `title:"Kairos Schema: Install block" description:"The install block is to drive automatic installations without user interaction."`
Auto bool `json:"auto,omitempty" description:"Set to true when installing without Pairing"`
BindMounts []string `json:"bind_mounts,omitempty"`
Bundles []BundleSchema `json:"bundles,omitempty" description:"Add bundles in runtime"`
Device string `json:"device,omitempty" pattern:"^(auto|/|(/[a-zA-Z0-9_-]+)+)$" description:"Device for automated installs" examples:"[\"auto\",\"/dev/sda\"]"`
EphemeralMounts []string `json:"ephemeral_mounts,omitempty"`
EncryptedPartitions []string `json:"encrypted_partitions,omitempty"`
Env []interface{} `json:"env,omitempty"`
GrubOptionsSchema `json:"grub_options,omitempty"`
Image string `json:"image,omitempty" description:"Use a different container image for the installation"`
PowerManagement
SkipEncryptCopyPlugins bool `json:"skip_copy_kcrypt_plugin,omitempty"`
}
// BundleSchema represents the bundle block which can be used in different places of the Kairos configuration. It is used to reference a bundle and its confguration.
type BundleSchema struct {
DB string `json:"db_path,omitempty"`
LocalFile bool `json:"local_file,omitempty"`
Repository string `json:"repository,omitempty"`
Rootfs string `json:"rootfs_path,omitempty"`
Targets []string `json:"targets,omitempty"`
}
// GrubOptionsSchema represents the grub options block which can be used in different places of the Kairos configuration. It is used to configure grub.
type GrubOptionsSchema struct {
DefaultFallback string `json:"default_fallback,omitempty" description:"Sets default fallback logic"`
DefaultMenuEntry string `json:"default_menu_entry,omitempty" description:"Change GRUB menu entry"`
ExtraActiveCmdline string `json:"extra_active_cmdline,omitempty" description:"Additional Kernel option cmdline to apply just for active"`
ExtraCmdline string `json:"extra_cmdline,omitempty" description:"Additional Kernel option cmdline to apply"`
ExtraPassiveCmdline string `json:"extra_passive_cmdline,omitempty" description:"Additional Kernel option cmdline to apply just for passive"`
ExtraRecoveryCmdline string `json:"extra_recovery_cmdline,omitempty" description:"Set additional boot commands when booting into recovery"`
NextEntry string `json:"next_entry,omitempty" description:"Set the next reboot entry."`
SavedEntry string `json:"saved_entry,omitempty" description:"Set the default boot entry."`
}
// PowerManagement is a meta structure to hold the different rules for managing power, which are not compatible between each other.
type PowerManagement struct {
}
// NoPowerManagement is a meta structure used when the user does not define any power management options or when the user does not want to reboot or poweroff the machine.
type NoPowerManagement struct {
Reboot bool `json:"reboot,omitempty" const:"false" default:"false" description:"Reboot after installation"`
Poweroff bool `json:"poweroff,omitempty" const:"false" default:"false" description:"Power off after installation"`
}
// RebootOnly is a meta structure used to enforce that when the reboot option is set, the poweroff option is not set.
type RebootOnly struct {
Reboot bool `json:"reboot,omitempty" const:"true" default:"false" required:"true" description:"Reboot after installation"`
Poweroff bool `json:"poweroff,omitempty" const:"false" default:"false" description:"Power off after installation"`
}
// PowerOffOnly is a meta structure used to enforce that when the poweroff option is set, the reboot option is not set.
type PowerOffOnly struct {
Reboot bool `json:"reboot,omitempty" const:"false" default:"false" description:"Reboot after installation"`
Poweroff bool `json:"poweroff,omitempty" const:"true" default:"false" required:"true" description:"Power off after installation"`
}
var _ jsonschemago.OneOfExposer = PowerManagement{}
// The OneOfModel interface is only needed for the tests that check the new schemas contain all needed fields
// it can be removed once the new schema is the single source of truth.
type OneOfModel interface {
JSONSchemaOneOf() []interface{}
}
// JSONSchemaOneOf defines that different which are the different valid power management rules and states that one and only one of them needs to be validated for the entire schema to be valid.
func (PowerManagement) JSONSchemaOneOf() []interface{} {
return []interface{}{
NoPowerManagement{}, RebootOnly{}, PowerOffOnly{},
}
}

View File

@ -0,0 +1,134 @@
package config_test
import (
"strings"
. "github.com/kairos-io/kairos/pkg/config/schemas"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Install Schema", func() {
var config *KConfig
var err error
var yaml string
JustBeforeEach(func() {
config, err = NewConfigFromYAML(yaml, "#cloud-config", InstallSchema{})
Expect(err).ToNot(HaveOccurred())
})
Context("when device is auto", func() {
BeforeEach(func() {
yaml = `#cloud-config
device: auto`
})
It("succeedes", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
Context("when device is a path", func() {
BeforeEach(func() {
yaml = `#cloud-config
device: /dev/sda`
})
It("succeedes", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
Context("when device is other than a path or auto", func() {
BeforeEach(func() {
yaml = `#cloud-config
device: foobar`
})
It("errors", func() {
Expect(config.IsValid()).NotTo(BeTrue())
Expect(
strings.Contains(config.ValidationError(),
"does not match pattern '^(auto|/|(/[a-zA-Z0-9_-]+)+)$'",
),
).To(BeTrue())
})
})
Context("when reboot and poweroff are true", func() {
BeforeEach(func() {
yaml = `#cloud-config
device: /dev/sda
reboot: true
poweroff: true`
})
It("errors", func() {
Expect(config.IsValid()).NotTo(BeTrue())
Expect(config.ValidationError()).To(MatchRegexp("value must be false"))
})
})
Context("when reboot is true and poweroff is false", func() {
BeforeEach(func() {
yaml = `#cloud-config
device: /dev/sda
reboot: true
poweroff: false`
})
It("succeedes", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
Context("when reboot is false and poweroff is true", func() {
BeforeEach(func() {
yaml = `#cloud-config
device: /dev/sda
reboot: false
poweroff: true`
})
It("succeedes", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
Context("with no power management set", func() {
BeforeEach(func() {
yaml = `#cloud-config
device: /dev/sda`
})
It("succeedes", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
Context("with all possible options", func() {
BeforeEach(func() {
yaml = `#cloud-config
device: "/dev/sda"
reboot: true
auto: true
image: "docker:.."
bundles:
- rootfs_path: /usr/local/lib/extensions/<name>
targets:
- container://<image>
grub_options:
extra_cmdline: "config_url=http://"
extra_active_cmdline: "config_url=http://"
extra_passive_cmdline: "config_url=http://"
default_menu_entry: "foobar"
env:
- foo=barevice: /dev/sda`
})
It("succeedes", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
})

View File

@ -0,0 +1,68 @@
package config
import (
jsonschemago "github.com/swaggest/jsonschema-go"
)
// P2PSchema represents the P2P block in the Kairos configuration. It is used to enables and configure the p2p full-mesh functionalities.
type P2PSchema struct {
_ struct{} `title:"Kairos Schema: P2P block" description:"The p2p block enables the p2p full-mesh functionalities."`
Role string `json:"role,omitempty" default:"none" enum:"[\"master\",\"worker\",\"none\"]"`
NetworkID string `json:"network_id,omitempty" description:"User defined network-id. Can be used to have multiple clusters in the same network"`
DNS bool `json:"dns,omitempty" description:"Enable embedded DNS See also: https://mudler.github.io/edgevpn/docs/concepts/overview/dns/"`
DisableDHT bool `json:"disable_dht,omitempty" default:"true" description:"Disabling DHT makes co-ordination to discover nodes only in the local network"`
P2PNetworkExtended
VPN `json:"vpn,omitempty"`
}
// KubeVIPSchema represents the kubevip block in the Kairos configuration. It sets the Elastic IP used in KubeVIP. Only valid with p2p.
type KubeVIPSchema struct {
_ struct{} `title:"Kairos Schema: KubeVIP block" description:"Sets the Elastic IP used in KubeVIP. Only valid with p2p"`
EIP string `json:"eip,omitempty" example:"192.168.1.110"`
ManifestURL string `json:"manifest_url,omitempty" description:"Specify a manifest URL for KubeVIP." default:""`
Enable bool `json:"enable,omitempty" description:"Enables KubeVIP"`
Interface bool `json:"interface,omitempty" description:"Specifies a KubeVIP Interface" example:"ens18"`
}
// P2PNetworkExtended is a meta structure to hold the different rules for managing the P2P network, which are not compatible between each other.
type P2PNetworkExtended struct {
}
// P2PAutoDisabled is used to validate that when p2p.auto is disabled, then neither p2p.auto.ha not p2p.network_token can be set.
type P2PAutoDisabled struct {
NetworkToken string `json:"network_token,omitempty" const:"" required:"true"`
Auto struct {
Enable bool `json:"enable" const:"false" required:"true"`
Ha struct {
Enable bool `json:"enable" const:"false"`
} `json:"ha"`
} `json:"auto"`
}
// P2PAutoEnabled is used to validate that when p2p.auto is set, p2p.network_token has to be set.
type P2PAutoEnabled struct {
NetworkToken string `json:"network_token" required:"true" minLength:"1" description:"network_token is the shared secret used by the nodes to co-ordinate with p2p"`
Auto struct {
Enable bool `json:"enable,omitempty" const:"true"`
Ha struct {
Enable bool `json:"enable" const:"true"`
MasterNodes int `json:"master_nodes,omitempty" minimum:"1" description:"Number of HA additional master nodes. A master node is always required for creating the cluster and is implied."`
} `json:"ha"`
} `json:"auto,omitempty"`
}
var _ jsonschemago.OneOfExposer = P2PNetworkExtended{}
// JSONSchemaOneOf defines that different which are the different valid p2p network rules and states that one and only one of them needs to be validated for the entire schema to be valid.
func (P2PNetworkExtended) JSONSchemaOneOf() []interface{} {
return []interface{}{
P2PAutoEnabled{}, P2PAutoDisabled{},
}
}
// VPN represents the vpn block in the Kairos configuration.
type VPN struct {
Create bool `json:"vpn,omitempty" default:"true"`
Use bool `json:"use,omitempty" default:"true"`
Envs []interface{} `json:"env,omitempty"`
}

View File

@ -0,0 +1,182 @@
package config_test
import (
"strings"
. "github.com/kairos-io/kairos/pkg/config"
. "github.com/kairos-io/kairos/pkg/config/schemas"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("P2P Schema", func() {
var config *KConfig
var err error
var yaml string
JustBeforeEach(func() {
config, err = NewConfigFromYAML(yaml, DefaultHeader, P2PSchema{})
Expect(err).ToNot(HaveOccurred())
})
Context("with role master", func() {
BeforeEach(func() {
yaml = `#cloud-config
role: master
network_token: "b3RwOgogIGRoYWdlX3NpemU6IDIwOTcxNTIwCg=="`
})
It("succeeds", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
Context("with role worker", func() {
BeforeEach(func() {
yaml = `#cloud-config
role: worker
network_token: "b3RwOgogIGRoYWdlX3NpemU6IDIwOTcxNTIwCg=="`
})
It("succeeds", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
Context("with role none", func() {
BeforeEach(func() {
yaml = `#cloud-config
role: none
network_token: "b3RwOgogIGRoYWdlX3NpemU6IDIwOTcxNTIwCg=="`
})
It("succeeds", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
Context("with other role", func() {
BeforeEach(func() {
yaml = `#cloud-config
role: foobar
network_token: "b3RwOgogIGRoYWdlX3NpemU6IDIwOTcxNTIwCg=="`
})
It("errors", func() {
Expect(config.ValidationError()).To(MatchRegexp(`value must be one of "master", "worker", "none"`))
Expect(config.IsValid()).NotTo(BeTrue())
})
})
Context("With a network_token and p2p.auto.enable = false", func() {
BeforeEach(func() {
yaml = `#cloud-config
network_token: "b3RwOgogIGRoYWdlX3NpemU6IDIwOTcxNTIwCg=="
auto:
enable: false`
})
It("errors", func() {
Expect(config.IsValid()).NotTo(BeTrue())
Expect(
strings.Contains(config.ValidationError(), `value must be true`),
).To(BeTrue())
})
})
Context("With an empty network_token and p2p.auto.enable = true", func() {
BeforeEach(func() {
yaml = `#cloud-config
network_token: ""
auto:
enable: true`
})
It("Fails", func() {
Expect(config.IsValid()).NotTo(BeTrue())
Expect(
strings.Contains(config.ValidationError(),
"length must be >= 1, but got 0",
),
).To(BeTrue())
})
})
Context("With a network_token and p2p.auto.enable = true", func() {
BeforeEach(func() {
yaml = `#cloud-config
network_token: "b3RwOgogIGRoYWdlX3NpemU6IDIwOTcxNTIwCg=="
auto:
enable: true`
})
It("succeeds", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
Context("With a p2p.auto.enable = false and ha.enable = true", func() {
BeforeEach(func() {
yaml = `#cloud-config
network_token: ""
auto:
enable: false
ha:
enable: true`
})
It("errors", func() {
Expect(config.IsValid()).NotTo(BeTrue())
Expect(config.ValidationError()).To(MatchRegexp("(length must be >= 1, but got 0|value must be true)"))
})
})
Context("HA with 0 master nodes", func() {
BeforeEach(func() {
yaml = `#cloud-config
network_token: "b3RwOgogIGRoYWdlX3NpemU6IDIwOTcxNTIwCg=="
auto:
enable: true
ha:
enable: true
master_nodes: 0`
})
It("fails", func() {
Expect(config.IsValid()).NotTo(BeTrue())
Expect(config.ValidationError()).To(MatchRegexp("must be >= 1 but found 0"))
})
})
Context("HA", func() {
BeforeEach(func() {
yaml = `#cloud-config
network_token: "b3RwOgogIGRoYWdlX3NpemU6IDIwOTcxNTIwCg=="
auto:
enable: true
ha:
enable: true
master_nodes: 2`
})
It("succeedes", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
Context("kubevip", func() {
BeforeEach(func() {
yaml = `#cloud-config
network_token: "b3RwOgogIGRoYWdlX3NpemU6IDIwOTcxNTIwCg=="
auto:
enable: true
ha:
enable: true
master_nodes: 2`
})
It("succeedes", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
})

View File

@ -0,0 +1,98 @@
package config
import (
"encoding/json"
"fmt"
"strings"
"github.com/santhosh-tekuri/jsonschema/v5"
jsonschemago "github.com/swaggest/jsonschema-go"
"gopkg.in/yaml.v3"
)
// RootSchema groups all the different schemas of the Kairos configuration together.
type RootSchema struct {
_ struct{} `title:"Kairos Schema" description:"Defines all valid Kairos configuration attributes."`
Bundles []BundleSchema `json:"bundles,omitempty" description:"Add bundles in runtime"`
ConfigURL string `json:"config_url,omitempty" description:"URL download configuration from."`
Env []string `json:"env,omitempty"`
FailOnBundleErrors bool `json:"fail_on_bundles_errors,omitempty"`
GrubOptionsSchema `json:"grub_options,omitempty"`
Install InstallSchema `json:"install,omitempty"`
Options []interface{} `json:"options,omitempty" description:"Various options."`
Users []UserSchema `json:"users,omitempty" minItems:"1" required:"true"`
P2P P2PSchema `json:"p2p,omitempty"`
}
// KConfig is used to parse and validate Kairos configuration files.
type KConfig struct {
source string
parsed interface{}
validationError error
schemaType interface{}
header string
}
func (kc *KConfig) validate() {
reflector := jsonschemago.Reflector{}
generatedSchema, err := reflector.Reflect(kc.schemaType)
if err != nil {
kc.validationError = err
}
generatedSchemaJSON, err := json.MarshalIndent(generatedSchema, "", " ")
if err != nil {
kc.validationError = err
}
sch, err := jsonschema.CompileString("schema.json", string(generatedSchemaJSON))
if err != nil {
kc.validationError = err
}
if err = sch.Validate(kc.parsed); err != nil {
kc.validationError = err
}
}
// IsValid returns true if the schema rules of the configuration are valid.
func (kc *KConfig) IsValid() bool {
kc.validate()
return kc.validationError == nil
}
// ValidationError returns one of the errors of an invalid schemam rule, when the configuration is valid, then it returns an empty string.
func (kc *KConfig) ValidationError() string {
kc.validate()
if kc.validationError != nil {
return kc.validationError.Error()
}
return ""
}
func (kc *KConfig) hasHeader() bool {
return strings.HasPrefix(kc.source, kc.header)
}
// NewConfigFromYAML is a constructor for KConfig instances. The source of the configuration is passed in YAML and if there are any issues unmarshaling it will return an error.
func NewConfigFromYAML(s, h string, st interface{}) (*KConfig, error) {
kc := &KConfig{
source: s,
header: h,
schemaType: st,
}
if !kc.hasHeader() {
return kc, fmt.Errorf("missing %s header", kc.header)
}
err := yaml.Unmarshal([]byte(s), &kc.parsed)
if err != nil {
return kc, err
}
return kc, nil
}

View File

@ -0,0 +1,126 @@
package config_test
import (
"fmt"
"reflect"
"strings"
. "github.com/kairos-io/kairos/pkg/config"
. "github.com/kairos-io/kairos/pkg/config/schemas"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func getTagName(s string) string {
if len(s) < 1 {
return ""
}
f := func(c rune) bool {
return c == '"' || c == ','
}
return s[:strings.IndexFunc(s, f)]
}
func structContainsField(f, t string, str interface{}) bool {
values := reflect.ValueOf(str)
types := values.Type()
for j := 0; j < values.NumField(); j++ {
tagName := getTagName(types.Field(j).Tag.Get("json"))
if types.Field(j).Name == f || tagName == t {
return true
} else {
if types.Field(j).Type.Kind() == reflect.Struct {
if types.Field(j).Type.Name() != "" {
model := reflect.New(types.Field(j).Type)
if instance, ok := model.Interface().(OneOfModel); ok {
for _, childSchema := range instance.JSONSchemaOneOf() {
if structContainsField(f, t, childSchema) {
return true
}
}
}
}
}
}
}
return false
}
func structFieldsContainedInOtherStruct(left, right interface{}) {
leftValues := reflect.ValueOf(left)
leftTypes := leftValues.Type()
for i := 0; i < leftValues.NumField(); i++ {
leftTagName := getTagName(leftTypes.Field(i).Tag.Get("yaml"))
leftFieldName := leftTypes.Field(i).Name
if leftTypes.Field(i).IsExported() {
It(fmt.Sprintf("Checks that the new schema contians the field %s", leftFieldName), func() {
Expect(
structContainsField(leftFieldName, leftTagName, right),
).To(BeTrue())
})
}
}
}
var _ = Describe("Schema", func() {
var config *KConfig
var err error
var yaml string
JustBeforeEach(func() {
config, err = NewConfigFromYAML(yaml, DefaultHeader, RootSchema{})
})
Context("While the new Schema is not the single source of truth", func() {
structFieldsContainedInOtherStruct(Config{}, RootSchema{})
})
Context("While the new InstallSchema is not the single source of truth", func() {
structFieldsContainedInOtherStruct(Install{}, InstallSchema{})
})
Context("While the new BundleSchema is not the single source of truth", func() {
structFieldsContainedInOtherStruct(Bundle{}, BundleSchema{})
})
Context("With invalid YAML syntax", func() {
BeforeEach(func() {
yaml = `#cloud-config
this is:
- invalid
yaml`
})
It("errors", func() {
Expect(err.Error()).To(MatchRegexp("yaml: line 4: could not find expected ':'"))
})
})
Context("With the wrong header", func() {
BeforeEach(func() {
yaml = `---
users:
- name: "kairos"
passwd: "kairos"`
})
It("errors", func() {
Expect(err.Error()).To(MatchRegexp("missing #cloud-config header"))
})
})
Context("When `users` is empty", func() {
BeforeEach(func() {
yaml = `#cloud-config
users: []`
})
It("errors", func() {
Expect(err).ToNot(HaveOccurred())
Expect(config.IsValid()).NotTo(BeTrue())
Expect(config.ValidationError()).To(MatchRegexp("minimum 1 items required, but found 0 items"))
})
})
})

View File

@ -0,0 +1,13 @@
package config_test
import (
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
func TestConfig(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Config Schemas Suite")
}

View File

@ -0,0 +1,11 @@
package config
// UserSchema represents the users block in the Kairos configuration. It allows the creation of users in the system.
type UserSchema struct {
_ struct{} `title:"Kairos Schema: Users block" description:"The users block allows you to create users in the system."`
Name string `json:"name,omitempty" pattern:"([a-z_][a-z0-9_]{0,30})" required:"true" example:"kairos"`
Passwd string `json:"passwd,omitempty" example:"kairos"`
LockPasswd bool `json:"lockPasswd,omitempty" example:"true"`
Groups string `json:"groups,omitempty" example:"admin"`
SSHAuthorizedKeys []string `json:"ssh_authorized_keys,omitempty" examples:"[\"github:USERNAME\",\"ssh-ed25519 AAAF00BA5\"]"`
}

View File

@ -0,0 +1,77 @@
package config_test
import (
"strings"
. "github.com/kairos-io/kairos/pkg/config"
. "github.com/kairos-io/kairos/pkg/config/schemas"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)
var _ = Describe("Users Schema", func() {
var config *KConfig
var err error
var yaml string
JustBeforeEach(func() {
config, err = NewConfigFromYAML(yaml, DefaultHeader, UserSchema{})
Expect(err).ToNot(HaveOccurred())
})
Context("When a user has no name", func() {
BeforeEach(func() {
yaml = `#cloud-config
passwd: foobar`
})
It("errors", func() {
Expect(config.IsValid()).NotTo(BeTrue())
Expect(config.ValidationError()).To(MatchRegexp("missing properties: 'name'"))
})
})
Context("When a user name doesn't fit the pattern", func() {
BeforeEach(func() {
yaml = `#cloud-config
name: "007"
passwd: "bond"`
})
It("errors", func() {
Expect(config.IsValid()).NotTo(BeTrue())
Expect(
strings.Contains(config.ValidationError(),
"does not match pattern '([a-z_][a-z0-9_]{0,30})'",
),
).To(BeTrue())
})
})
Context("With only the required attributes", func() {
BeforeEach(func() {
yaml = `#cloud-config
name: "kairos"`
})
It("succeeds", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
Context("With all possible attributes", func() {
BeforeEach(func() {
yaml = `#cloud-config
name: "kairos"
passwd: "kairos"
lock_passwd: true
groups: "admin"
ssh_authorized_keys:
- github:mudler`
})
It("succeeds", func() {
Expect(config.IsValid()).To(BeTrue())
})
})
})