Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ and container identity can use it.
- Network ACLs (with tag-based policy attachment, Hetzner-firewall style)
- Fleet-repo-only host aliases (`@name` expansion, cycle-detected)
- Per-instance eth0 device config: static IPs, attached ACLs, default actions
- Container creation with declared image + tags
- Container and virtual-machine creation with declared image + tags (`type: virtual-machine`)
- Backup selection for [incus-backup](https://github.com/unidoc/incus-backup): `backup: {policy: nightly}` sets the Incus key `user.backup.policy` (and `exclude: true` sets `user.backup.exclude`)

## What it deliberately does NOT manage

Expand Down Expand Up @@ -307,6 +308,11 @@ of these dangerous shapes:
- Instance eth0 `ingress-default` changing from `reject` or `drop` to
`allow` (world-open flip).
- Instance eth0 removing all attached ACLs.
- A live instance with `security.privileged=true` or
`security.idmap.isolated=false`. Nesting (`security.nesting=true`) is
allowed for unprivileged containers. `--force` lets the rest of the plan
proceed; sync never rewrites these keys, so the instance is left as it is
and has to be reset by hand (`incus config unset <instance> <key>`).

Emitted by `diff` in red with a `DANGER` prefix; emitted by `sync
--apply` output and required in a `--force` flag before proceeding.
Expand Down
2 changes: 1 addition & 1 deletion cmd/incus-sync/cmd_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ Safety:
cmd.Flags().StringVar(&socketPath, "socket", incus.DefaultSocket, "Incus unix socket path")
cmd.Flags().StringVar(&project, "project", "", "Incus project (default: fleet.yaml or `default`)")
cmd.Flags().BoolVar(&apply, "apply", false, "Actually apply changes (default: dry run)")
cmd.Flags().BoolVar(&force, "force", false, "Override refuse-worthy checks (empty ACL/set, widening ingress-default)")
cmd.Flags().BoolVar(&force, "force", false, "Override refuse-worthy checks (empty ACL/set, widening ingress-default, policy violations such as privileged instances, which are left as they are)")
cmd.Flags().BoolVar(&dirtyOK, "dirty-ok", false, "Proceed even when fleet repo is dirty or behind upstream")
return cmd
}
Expand Down
27 changes: 27 additions & 0 deletions docs/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,29 @@ of being reusable.
instance: <name>
description: <string>
original_image: images:<alias> # required if sync should create the container
type: container | virtual-machine # optional; default container. Only used on create: an existing
# instance keeps its type, so an existing VM is declared the same way
# (`import` writes `type: virtual-machine`). A virtual machine cannot have
# `provision:`, before.sh, after.sh or a non-empty files/ (they run
# inside the guest and need the Incus agent).
profiles: [<profile>...] # optional; default [default]
tags: [<tag>...] # match tag-based policies
start: true | false # optional; default true on first create

# Back this instance up with incus-backup (optional). Written as the Incus
# config key user.backup.policy / user.backup.exclude. An explicit key on the
# instance wins over the backup server's own assignments. When this block is
# absent sync never touches those keys, so a hand-set key survives.
backup:
policy: <name> # a policy defined on the backup server (or in client.yaml)
# exclude: true # alternatively: never back this instance up (exclusive with policy)
# `backup: {}` removes both keys from the instance. A bare `backup:` with nothing under it is
# YAML null and counts as an absent block (the keys are left alone), and an unknown key inside
# the block (a typo such as `polcy:`) is a load error. Sync compares against the effective
# config: when the instance declares a policy and a profile sets user.backup.exclude, the instance
# gets user.backup.exclude=false (an instance key cannot remove a profile key). `backup: {}`
# cannot remove a user.backup.policy that comes from a profile.

# eth0 device — all fields optional
ip4: <IPv4 address> # if set, ip4_prefix_length + ip4_gateway are REQUIRED
ip4_prefix_length: <int> # no safe default — IPv4 subnet size varies per deployment
Expand Down Expand Up @@ -277,6 +296,14 @@ not on the Incus device. Only the three keys shown above are
reconciled per device. Every other key on the
device — including profile-provided ones — is left alone.

## Instance isolation policy

A live instance with `security.privileged=true` or `security.idmap.isolated=false` is reported as
a policy violation, and `sync --apply` refuses without `--force`. With `--force` the rest of the
plan is applied and the instance is left as it is: sync never rewrites these keys, so reset them by
hand (`incus config unset <instance> <key>`). `security.nesting=true` is allowed for an
unprivileged container (Docker, Incus or LXC inside it).

## Reference syntax

| Prefix | Where it resolves | Example |
Expand Down
75 changes: 75 additions & 0 deletions internal/config/backup_strict_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package config

// What counts as an empty backup: block, and a VM next to the directory `incus-sync create` scaffolds.

import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"

"github.com/unidoc/incus-sync/internal/model"
)

func tDecode(t *testing.T, body string) string {
path := filepath.Join(t.TempDir(), "instance.yaml")
if err := os.WriteFile(path, []byte("instance: web\nproject: default\n"+body), 0o644); err != nil {
t.Fatal(err)
}
var inst model.Instance
if err := readYAMLFile(path, &inst); err != nil {
return "decode-error"
}
set, unset, managed := inst.BackupConfig()
return fmt.Sprintf("managed=%v|set=%v|unset=%v", managed, set, unset)
}

// docs/schema.md line 224 (head): "An empty `backup:` block (no policy, no exclude) removes both keys."
func TestEmptyBackupBlockSpellings(t *testing.T) {
for _, tc := range []struct{ name, body, want string }{
{"flow mapping {}", "backup: {}\n",
"managed=true|set=map[]|unset=[user.backup.policy user.backup.exclude]"},
// YAML null: the pointer stays nil, so this is "absent" (keys kept), whatever the docs say.
{"bare key", "backup:\n",
"managed=false|set=map[]|unset=[]"},
{"policy line commented out", "backup:\n # policy: nightly\n",
"managed=false|set=map[]|unset=[]"},
// A misspelt key must not silently turn into "remove both keys".
{"misspelt key", "backup:\n polcy: nightly\n",
"decode-error"},
} {
got := tDecode(t, tc.body)
t.Logf("%-28s %s", tc.name+":", got)
if got != tc.want {
t.Errorf("%s:\n got %s\n want %s", tc.name, got, tc.want)
}
}
}

// cmd/incus-sync/cmd_create.go:52 always creates an empty files/ next to instance.yaml.
func TestScaffoldedDirectoryForAVM(t *testing.T) {
validate := func(dir string) string {
f := &Fleet{Instances: map[string]model.Instance{"web": {Name: "web", Type: model.InstanceTypeVM, SourceDir: dir}}}
if err := f.validateInstances(); err != nil {
return "refused"
}
return "ok"
}
scaffold := t.TempDir()
if err := os.MkdirAll(filepath.Join(scaffold, "files"), 0o755); err != nil {
t.Fatal(err)
}
populated := t.TempDir()
if err := os.MkdirAll(filepath.Join(populated, "files", "etc"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(populated, "files", "etc", "motd"), []byte("hi\n"), 0o644); err != nil {
t.Fatal(err)
}
got := strings.Join([]string{"empty-files=" + validate(scaffold), "populated-files=" + validate(populated)}, "|")
t.Logf("%s", got)
if want := "empty-files=ok|populated-files=refused"; got != want {
t.Errorf("got %s\nwant %s", got, want)
}
}
32 changes: 32 additions & 0 deletions internal/config/backup_validate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package config

import (
"strings"
"testing"

"github.com/unidoc/incus-sync/internal/model"
)

func TestBackupBlockValidation(t *testing.T) {
cases := map[string]struct {
b *model.InstanceBackup
wantErr string
}{
"ok policy": {&model.InstanceBackup{Policy: "nightly"}, ""},
"ok exclude": {&model.InstanceBackup{Exclude: true}, ""},
"ok absent": {nil, ""},
"both": {&model.InstanceBackup{Policy: "x", Exclude: true}, "mutually exclusive"},
"bad name": {&model.InstanceBackup{Policy: "has space"}, "invalid backup.policy"},
"bad name sym": {&model.InstanceBackup{Policy: "a/b"}, "invalid backup.policy"},
}
for name, c := range cases {
f := &Fleet{Instances: map[string]model.Instance{"web": {Name: "web", Backup: c.b}}}
err := f.validateInstances()
switch {
case c.wantErr == "" && err != nil:
t.Errorf("%s: unexpected error %v", name, err)
case c.wantErr != "" && (err == nil || !strings.Contains(err.Error(), c.wantErr)):
t.Errorf("%s: want error containing %q, got %v", name, c.wantErr, err)
}
}
}
83 changes: 83 additions & 0 deletions internal/config/instance_type_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package config

import (
"os"
"path/filepath"
"strings"
"testing"

"github.com/unidoc/incus-sync/internal/model"
)

func TestInstanceTypeValidation(t *testing.T) {
cases := map[string]struct {
inst model.Instance
wantErr string
}{
"default is a container": {model.Instance{Name: "web"}, ""},
"container": {model.Instance{Name: "web", Type: "container"}, ""},
"vm": {model.Instance{Name: "web", Type: "virtual-machine"}, ""},
"vm with a backup block": {model.Instance{Name: "web", Type: "virtual-machine", Backup: &model.InstanceBackup{Policy: "nightly"}}, ""},
"unknown type": {model.Instance{Name: "web", Type: "vm"}, "invalid type"},
"vm provision": {model.Instance{Name: "web", Type: "virtual-machine", Provision: &model.ProvisionSpec{}}, "not supported for virtual machines"},
"container provision": {model.Instance{Name: "web", Provision: &model.ProvisionSpec{}}, ""},
}
for name, c := range cases {
f := &Fleet{Instances: map[string]model.Instance{"web": c.inst}}
err := f.validateInstances()
switch {
case c.wantErr == "" && err != nil:
t.Errorf("%s: unexpected error %v", name, err)
case c.wantErr != "" && (err == nil || !strings.Contains(err.Error(), c.wantErr)):
t.Errorf("%s: want error containing %q, got %v", name, c.wantErr, err)
}
}
}

// before.sh, after.sh and files/ next to instance.yaml run inside the guest at create time; a VM has no agent yet.
func TestVMRefusesProvisioningFilesInItsDirectory(t *testing.T) {
for _, f := range []string{"before.sh", "after.sh", "files"} {
dir := t.TempDir()
p := filepath.Join(dir, f)
if f == "files" {
if err := os.MkdirAll(p, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(p, "motd"), []byte("hi\n"), 0o644); err != nil {
t.Fatal(err)
}
} else if err := os.WriteFile(p, []byte("true\n"), 0o644); err != nil {
t.Fatal(err)
}
vm := &Fleet{Instances: map[string]model.Instance{"web": {Name: "web", Type: "virtual-machine", SourceDir: dir}}}
if err := vm.validateInstances(); err == nil || !strings.Contains(err.Error(), f) {
t.Errorf("%s next to a VM: %v", f, err)
}
ct := &Fleet{Instances: map[string]model.Instance{"web": {Name: "web", SourceDir: dir}}}
if err := ct.validateInstances(); err != nil {
t.Errorf("%s next to a container must stay allowed: %v", f, err)
}
}
vm := &Fleet{Instances: map[string]model.Instance{"web": {Name: "web", Type: "virtual-machine", SourceDir: t.TempDir()}}}
if err := vm.validateInstances(); err != nil {
t.Errorf("an empty instance directory is fine for a VM: %v", err)
}
}

// An empty files/ (what `incus-sync create` scaffolds) or one holding only a placeholder pushes nothing.
func TestVMAllowsAnEmptyFilesDirectory(t *testing.T) {
dir := t.TempDir()
if err := os.Mkdir(filepath.Join(dir, "files"), 0o755); err != nil {
t.Fatal(err)
}
vm := &Fleet{Instances: map[string]model.Instance{"web": {Name: "web", Type: "virtual-machine", SourceDir: dir}}}
if err := vm.validateInstances(); err != nil {
t.Errorf("empty files/: %v", err)
}
if err := os.WriteFile(filepath.Join(dir, "files", ".gitkeep"), nil, 0o644); err != nil {
t.Fatal(err)
}
if err := vm.validateInstances(); err != nil {
t.Errorf("files/ with only .gitkeep: %v", err)
}
}
47 changes: 47 additions & 0 deletions internal/config/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package config
import (
"fmt"
"net/netip"
"os"
"path/filepath"
"regexp"
"strings"

Expand Down Expand Up @@ -323,6 +325,37 @@ func (f *Fleet) validateInstances() error {
return fmt.Errorf("instance %q: invalid ip6 %q", name, inst.IP6)
}
}
if !model.ValidInstanceType(inst.Type) {
return fmt.Errorf("instance %q: invalid type %q (container or virtual-machine)", name, inst.Type)
}
if inst.IsVM() {
if inst.Provision != nil {
return fmt.Errorf("instance %q: provision is not supported for virtual machines (it runs commands inside the guest, which needs the Incus agent there)", name)
}
// the instance directory is applied at create time too: before.sh, files/ and after.sh.
// An empty files/ (as `incus-sync create` scaffolds it) pushes nothing and is fine; so is a
// placeholder such as .gitkeep.
if inst.SourceDir != "" {
for _, f := range []string{"before.sh", "after.sh", "files"} {
p := filepath.Join(inst.SourceDir, f)
if _, err := os.Stat(p); err != nil {
continue
}
if f == "files" && !hasVisibleEntries(p) {
continue
}
return fmt.Errorf("instance %q: %s next to instance.yaml is not supported for virtual machines (it runs inside the guest, which needs the Incus agent there)", name, f)
}
}
}
if b := inst.Backup; b != nil {
if b.Exclude && b.Policy != "" {
return fmt.Errorf("instance %q: backup.policy and backup.exclude are mutually exclusive", name)
}
if b.Policy != "" && !model.ValidBackupPolicyName(b.Policy) {
return fmt.Errorf("instance %q: invalid backup.policy %q (letters, digits, - _ . only)", name, b.Policy)
}
}
for devName, dev := range inst.EffectiveDevices() {
if dev == nil {
continue
Expand Down Expand Up @@ -353,3 +386,17 @@ func checkAddress(s string) error {
// Ensure the model import stays live once we lean on it more heavily
// (e.g. tags, additional resolvers).
var _ = model.AliasRef

// hasVisibleEntries reports whether dir holds anything besides dotfiles (.gitkeep and the like).
func hasVisibleEntries(dir string) bool {
entries, err := os.ReadDir(dir)
if err != nil {
return true // unreadable: do not guess that it is empty
}
for _, e := range entries {
if !strings.HasPrefix(e.Name(), ".") {
return true
}
}
return false
}
Loading
Loading