talos/pkg/machinery/resources/config/machine_config_test.go
Andrey Smirnov 2f4b9d8d6d
feat: make machine configuration read-only in Talos (almost)
Talos shouldn't try to re-encode the machine config it was provided
with.

So add a `ReadonlyWrapper` around `*v1alpha1.Config` which makes sure
that raw config object is not available anymore (it's a private field),
but config accessors are available for read-only access.

Another thing that `ReadonlyWrapper` does is that it preserves the
original `[]byte` encoding of the config keeping it exactly same way as
it was loaded from file or read over the network.

Improved `talosctl edit mc` to preserve the config as it was submitted,
and preserve the edits on error from Talos (previously edits were lost).

`ReadonlyWrapper` is not used on config generation path though - config
there is represented by `*v1alpha.Config` and can be freely modified.

Why almost? Some parts of Talos (platform code) patch the machine
configuration with new data. We need to fix platforms to provide
networking configuration in a different way, but this will come with
other PRs later.

Signed-off-by: Andrey Smirnov <andrey.smirnov@talos-systems.com>
2021-12-28 20:12:55 +03:00

44 lines
1.3 KiB
Go

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package config_test
import (
"regexp"
"testing"
"github.com/cosi-project/runtime/pkg/resource"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
"github.com/talos-systems/talos/pkg/machinery/config/configloader"
"github.com/talos-systems/talos/pkg/machinery/resources/config"
)
func TestMachineConfigMarshal(t *testing.T) {
cfg, err := configloader.NewFromBytes([]byte(`version: v1alpha1
persist: true # foo
debug: false
machine:
type: controlplane
`))
require.NoError(t, err)
r := config.NewMachineConfig(cfg)
m, err := resource.MarshalYAML(r)
require.NoError(t, err)
enc, err := yaml.Marshal(m)
require.NoError(t, err)
enc = regexp.MustCompile("(created|updated): [0-9-:TZ+]+").ReplaceAll(enc, nil)
assert.Equal(t,
"metadata:\n namespace: config\n type: MachineConfigs.config.talos.dev\n id: v1alpha1\n version: 1\n owner:\n phase: running\n \n \n"+
"spec:\n version: v1alpha1\n persist: true # foo\n debug: false\n machine:\n type: controlplane\n",
string(enc))
}