From bf6db58a7e6200a892dc94e619a8ff347133efb4 Mon Sep 17 00:00:00 2001 From: Blai Peidro Date: Wed, 2 Dec 2026 22:50:35 +0100 Subject: [PATCH] feat: a repository's folder is its root for the jobs that use it A repository may read one of its folders as its root (paths.folders in the run message, by repository name). With local files, the Runner resolves the job's playbooks and inventories under / of its own checkout, the whole checkout without one. The folder is checked as the controller checks it, and a job whose folder is not in the checkout ends with its error. Part of ansibleforms/ansibleforms#1634 --- CHANGELOG.md | 4 ++ internal/ansible/prepare.go | 80 ++++++++++++++++++++++++++++++++ internal/ansible/prepare_test.go | 48 +++++++++++++++++++ internal/runner/runner.go | 61 +++++++++++++++++++----- internal/runner/runner_test.go | 48 +++++++++++++++++-- 5 files changed, 227 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35edb87..2101e74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ The changes made to the Runner between two releases wait under Unreleased and go ## Unreleased +### Added + +- **A repository's folder:** a repository's own checkout is read from the folder the controller names as its root + ## 7.9.0 The RTE Runner of [AnsibleForms 7.9.0](https://github.com/ansibleforms/ansibleforms/releases/tag/7.9.0). diff --git a/internal/ansible/prepare.go b/internal/ansible/prepare.go index 93a93b9..f49d95d 100644 --- a/internal/ansible/prepare.go +++ b/internal/ansible/prepare.go @@ -174,6 +174,86 @@ func RepoFolder(repoPath, name string) (string, error) { return filepath.Join(repoPath, name), nil } +// maxRepoPathLength is the longest folder a repository reads as its root, as the controller keeps it. +const maxRepoPathLength = 250 + +// NormalizeRepoPath checks the folder a repository reads as its root, as the controller does +// (Repo.normalizeRepoPath in the application): relative to its checkout, each folder a plain name +// (no leading /, no . nor .., no empty folder, no hidden one), its trailing slashes dropped. +// +// Args: +// +// value: the folder given ("" : the whole checkout). +// +// Returns: +// +// The folder, normalised ("" : none). +// +// Errors: +// +// When it is not a folder inside the repository, saying why. +func NormalizeRepoPath(value string) (string, error) { + // step 1 : trimmed, its trailing slashes dropped (prod/ is prod) + text := strings.TrimRight(strings.TrimSpace(value), "/") + if text == "" { + return "", nil + } + // step 2 : relative, each folder a plain name + if strings.HasPrefix(text, "/") { + return "", fmt.Errorf("Invalid repository folder: %s. It is relative to the repository: no leading /.", text) + } + if len(text) > maxRepoPathLength { + return "", fmt.Errorf("Invalid repository folder: it is longer than %d characters.", maxRepoPathLength) + } + for _, part := range strings.Split(text, "/") { + switch { + case part == "": + return "", fmt.Errorf("Invalid repository folder: %s. It has an empty folder (//).", text) + case part == "." || part == "..": + return "", fmt.Errorf("Invalid repository folder: %s. It must stay inside the repository: no . nor .. in it.", text) + case !ValidRepoName(part): + return "", fmt.Errorf("Invalid repository folder: %s. Each folder has letters, digits, dots, dashes and underscores only, not starting with a dot.", text) + } + } + return text, nil +} + +// ContentFolder is a repository's root: its checkout under the repositories folder, or the folder +// of it the controller reads as its root. A folder the checkout does not have refuses the job, +// never read as the whole checkout or an empty one. +// +// Args: +// +// repoPath: the repositories folder (REPO_PATH). +// name: the repository. +// sub: the folder it reads as its root ("" : the whole checkout). +// +// Returns: +// +// The folder. +// +// Errors: +// +// When the name or the folder is not valid, or the folder is not in the checkout. +func ContentFolder(repoPath, name, sub string) (string, error) { + checkout, err := RepoFolder(repoPath, name) + if err != nil { + return "", err + } + rel, err := NormalizeRepoPath(sub) + if err != nil { + return "", err + } + if rel == "" { + return checkout, nil + } + folder := filepath.Join(checkout, filepath.FromSlash(rel)) + if !isDir(folder) { + return "", fmt.Errorf("Repository '%s' reads its folder '%s', which is not in its checkout on this Runner. Add the folder in git, or change the repository's folder.", name, rel) + } + return folder, nil +} + // exists tells whether a path exists. // // Args: diff --git a/internal/ansible/prepare_test.go b/internal/ansible/prepare_test.go index 6586adf..318185f 100644 --- a/internal/ansible/prepare_test.go +++ b/internal/ansible/prepare_test.go @@ -48,6 +48,54 @@ func TestRepoFolder(t *testing.T) { } } +// TestNormalizeRepoPath checks the folder a repository reads as its root, as the controller +// checks it: relative, each folder a plain name, its trailing slashes dropped. +func TestNormalizeRepoPath(t *testing.T) { + for in, want := range map[string]string{"": "", " ": "", "/": "", "dev": "dev", " envs/prod/ ": "envs/prod", "a.b/c_d-1": "a.b/c_d-1"} { + if got, err := NormalizeRepoPath(in); err != nil || got != want { + t.Errorf("%q: %q %v", in, got, err) + } + } + for in, why := range map[string]string{ + "/etc": "no leading /", + strings.Repeat("a", 251): "longer than 250", + "a//b": "an empty folder", + "a/../b": "no . nor ..", + "./a": "no . nor ..", + "a/.git": "letters, digits", + "a b": "letters, digits", + "a/b..c": "letters, digits", + } { + if _, err := NormalizeRepoPath(in); err == nil || !strings.Contains(err.Error(), why) { + t.Errorf("%q: %v", in, err) + } + } +} + +// TestContentFolder checks a repository's root: its checkout, or its folder in it ; a bad name, a +// bad folder or one the checkout does not have refused. +func TestContentFolder(t *testing.T) { + repos := t.TempDir() + _ = os.MkdirAll(filepath.Join(repos, "r", "envs", "prod"), 0o700) + _ = os.WriteFile(filepath.Join(repos, "r", "file"), nil, 0o600) + if f, err := ContentFolder(repos, "r", ""); err != nil || f != filepath.Join(repos, "r") { + t.Errorf("the checkout %s %v", f, err) + } + if f, err := ContentFolder(repos, "r", "envs/prod/"); err != nil || f != filepath.Join(repos, "r", "envs", "prod") { + t.Errorf("its folder %s %v", f, err) + } + for _, c := range []struct{ name, sub, why string }{ + {"../r", "", "Invalid repository name"}, + {"r", "../x", "no . nor .."}, + {"r", "dev", "reads its folder 'dev', which is not in its checkout"}, + {"r", "file", "reads its folder 'file', which is not in its checkout"}, + } { + if _, err := ContentFolder(repos, c.name, c.sub); err == nil || !strings.Contains(err.Error(), c.why) { + t.Errorf("%s %s: %v", c.name, c.sub, err) + } + } +} + // TestPlaybookFile checks the playbook's file: as named, else with .yml or .yaml when only that // one is there. func TestPlaybookFile(t *testing.T) { diff --git a/internal/runner/runner.go b/internal/runner/runner.go index 1b0cd6b..ab94d3b 100644 --- a/internal/runner/runner.go +++ b/internal/runner/runner.go @@ -745,7 +745,12 @@ func (r *Runner) run(j *job, h jobstream.Header, paths, given map[string]any, tr h.Playbook = "playbook" } if len(h.Inventories) == 0 { - for i, inv := range inventoryRoots(paths) { + roots, err := inventoryRoots(paths) + if err != nil { + fail("[ERROR]: " + err.Error()) + return + } + for i, inv := range roots { name := fmt.Sprintf("inventory-%d", i) folders[name] = inv.Dir h.Inventories = append(h.Inventories, jobstream.Inventory{Repository: inv.Repository, Folder: name}) @@ -913,14 +918,37 @@ func asList(v any) []any { return l } +// repoRoot is a repository's root on this Runner (its own checkout under REPO_PATH): the folder +// of it the controller reads as its root (the run message's paths.folders), its whole checkout +// without one. +// +// Args: +// +// paths: the run message's paths. +// name: the repository. +// +// Returns: +// +// The folder. +// +// Errors: +// +// When the name or its folder is not valid, or the folder is not in its checkout. +func repoRoot(paths map[string]any, name string) (string, error) { + folders, _ := paths["folders"].(map[string]any) + sub, _ := folders[name].(string) + return ansible.ContentFolder(settings.RepoPath(), name, sub) +} + // playbookDir resolves a job's playbook folder, as the controller's own Runner does: the // playbooks the controller sent when it sent them ; else, with local files, its repository's root // (playbookRoot), its repository's playbooks folder when it has one, the repository, or -// ANSIBLE_PATH ; the sub folder under it. +// ANSIBLE_PATH ; the sub folder under it. A repository's root is the folder of it the controller +// reads as its root, when it names one. // // Args: // -// paths: the run message's paths ({ playbookRepo, inventoryRepos, playbookRoot }). +// paths: the run message's paths ({ playbookRepo, inventoryRepos, folders, playbookRoot }). // sent: the folder of the playbooks the controller sent, empty when it sent none. // transferred: tells the job's files were sent (its repository is then not on this Runner). // @@ -932,13 +960,15 @@ func playbookDir(paths map[string]any, sent string, transferred bool) func(strin repo, _ := paths["playbookRepo"].(string) root := sent if b, _ := paths["playbookRoot"].(bool); b && root == "" { - folder, err := ansible.RepoFolder(settings.RepoPath(), repo) - if transferred || err != nil || !exists(folder) { + checkout, err := ansible.RepoFolder(settings.RepoPath(), repo) + if transferred || err != nil || !exists(checkout) { return "", fmt.Errorf("playbookRepository '%s' is not a repository used for playbooks", repo) } - root = folder + if root, err = repoRoot(paths, repo); err != nil { + return "", err + } } else if root == "" && repo != "" { - folder, err := ansible.RepoFolder(settings.RepoPath(), repo) + folder, err := repoRoot(paths, repo) if err != nil { return "", err } @@ -971,7 +1001,8 @@ func exists(p string) bool { } // inventoryRoots are the folders a job's inventories are in: the local inventories folder, then -// each repository its paths name for inventories. +// each repository its paths name for inventories, from the folder of it the controller reads as +// its root. // // Args: // @@ -980,14 +1011,22 @@ func exists(p string) bool { // Returns: // // The folders. -func inventoryRoots(paths map[string]any) []ansible.Root { +// +// Errors: +// +// When a repository's folder is not valid, or not in its checkout. +func inventoryRoots(paths map[string]any) ([]ansible.Root, error) { roots := []ansible.Root{{Dir: settings.InventoryPath()}} for _, v := range asList(paths["inventoryRepos"]) { if name, ok := v.(string); ok && ansible.ValidRepoName(name) { - roots = append(roots, ansible.Root{Repository: name, Dir: filepath.Join(settings.RepoPath(), name)}) + dir, err := repoRoot(paths, name) + if err != nil { + return nil, err + } + roots = append(roots, ansible.Root{Repository: name, Dir: dir}) } } - return roots + return roots, nil } // onCancel stops a job: its playbook's process group signalled at once ; a job not handed over diff --git a/internal/runner/runner_test.go b/internal/runner/runner_test.go index 96053d3..e53dd55 100644 --- a/internal/runner/runner_test.go +++ b/internal/runner/runner_test.go @@ -729,6 +729,14 @@ func TestRunJobContainer(t *testing.T) { if m := end(56)["message"].(string); !strings.Contains(m, "Invalid repository name") { t.Errorf("a playbook folder that is not one: %s", m) } + repos := t.TempDir() + t.Setenv("REPO_PATH", repos) + _ = os.MkdirAll(filepath.Join(repos, "inv"), 0o700) + send(t, conn, socket.Message{"t": "run", "jobId": 57, "contract": socket.SocketContract, "sealed": sealed(t, 57, map[string]any{}), + "paths": map[string]any{"inventoryRepos": []any{"inv"}, "folders": map[string]any{"inv": "prod"}}}) + if m := end(57)["message"].(string); !strings.Contains(m, "Repository 'inv' reads its folder 'prod', which is not in its checkout") { + t.Errorf("an inventory repository's folder not in its checkout: %s", m) + } } // TestRunJobAckedFirst checks a job whose items were all acked before its run let go: removed @@ -980,9 +988,43 @@ func TestPaths(t *testing.T) { if _, err := playbookDir(map[string]any{"playbookRepo": "plain", "playbookRoot": true}, "", true)(""); err == nil { t.Error("a repository's root, its files sent without playbooks") } - roots := inventoryRoots(map[string]any{"inventoryRepos": []any{"a", 1.0, "../b"}}) - if len(roots) != 2 || roots[0].Dir != "/inv" || roots[1].Repository != "a" { - t.Errorf("roots %v", roots) + roots, err := inventoryRoots(map[string]any{"inventoryRepos": []any{"a", 1.0, "../b"}}) + if err != nil || len(roots) != 2 || roots[0].Dir != "/inv" || roots[1].Repository != "a" || roots[1].Dir != filepath.Join(repos, "a") { + t.Errorf("roots %v %v", roots, err) + } + // a repository's folder read as its root (paths.folders): its playbooks and inventories there + _ = os.MkdirAll(filepath.Join(repos, "sub", "envs", "prod", "playbooks"), 0o700) + _ = os.MkdirAll(filepath.Join(repos, "sub", "dev"), 0o700) + folders := map[string]any{"sub": "envs/prod/", "plain": "", "other": 1.0} + for _, c := range []struct { + paths map[string]any + want string + }{ + {map[string]any{"playbookRepo": "sub", "folders": folders}, filepath.Join(repos, "sub", "envs", "prod", "playbooks")}, + {map[string]any{"playbookRepo": "sub", "playbookRoot": true, "folders": folders}, filepath.Join(repos, "sub", "envs", "prod")}, + {map[string]any{"playbookRepo": "sub", "folders": map[string]any{"sub": "dev"}}, filepath.Join(repos, "sub", "dev")}, + {map[string]any{"playbookRepo": "plain", "folders": folders}, filepath.Join(repos, "plain")}, + {map[string]any{"playbookRepo": "plain", "folders": "bad"}, filepath.Join(repos, "plain")}, + } { + if got, err := playbookDir(c.paths, "", false)(""); err != nil || got != c.want { + t.Errorf("%v: %s %v", c.paths, got, err) + } + } + for _, paths := range []map[string]any{ + {"playbookRepo": "sub", "folders": map[string]any{"sub": "gone"}}, + {"playbookRepo": "sub", "playbookRoot": true, "folders": map[string]any{"sub": "gone"}}, + {"playbookRepo": "sub", "folders": map[string]any{"sub": "../x"}}, + } { + if _, err := playbookDir(paths, "", false)(""); err == nil { + t.Errorf("%v: no error", paths) + } + } + roots, err = inventoryRoots(map[string]any{"inventoryRepos": []any{"sub", "plain"}, "folders": map[string]any{"sub": "dev"}}) + if err != nil || len(roots) != 3 || roots[1].Dir != filepath.Join(repos, "sub", "dev") || roots[2].Dir != filepath.Join(repos, "plain") { + t.Errorf("roots in a folder %v %v", roots, err) + } + if _, err := inventoryRoots(map[string]any{"inventoryRepos": []any{"sub"}, "folders": map[string]any{"sub": "/abs"}}); err == nil { + t.Error("an inventory repository's folder that is not one") } if len(extravarsOf(map[string]any{"b": 2.0})) != 1 || len(extravarsOf(`{"a":1}`)) != 1 || len(extravarsOf("null")) != 0 || len(extravarsOf("bad")) != 0 || len(extravarsOf(nil)) != 0 || asList("x") != nil { t.Error("readers")