feat(roles): record the source semver and add the role_version lookup

Cherry-pick of f5cb1d15a7 and a86b31d696 from feature/iam-profile-rbac into production, so the custom roles web-app-cst-store and web-app-cst-security-check pin their images through lookup('role_version', ...) instead of a hand-set version per release.

The pull records the semver of Cargo.toml, else pyproject.toml, else package.json at the pinned commit (or in a local checkout) in the role marker; the lookup returns it. The lookup usage lint accepts lookups whose callers live in pulled roles through a reasoned nocheck marker.

Conflict in docs/requirements/046-custom-roles.md resolved by keeping the new criterion and production's open INFINITO_EXTRA_MOUNTS checkbox. test_marker passes VERSION to write_marker in the owner-only test production already carries (8c199a915d), as IAM did in 1bde39c2b1.

(cherry picked from commit f5cb1d15a7216831513b7c695a6cbd0e6770afcd)
(cherry picked from commit a86b31d696fb532830feb1ba6eadbc5ff9e90cbf)

🎯 Fix: 95 %
💥 Break: 5 %
💸 Cost: –
⏱️ Time: –
🛡️ Security: 100 %
🏆 Score: 90
🚦 Gate: ✅ 90/5, cost and time <= 100, security 100 %

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
kevinveenbirkenbachandClaude Opus 5.5 committed 2026-11-10 10:32:48 +00:00
1 parent 4289effbef
commit e615f5fa22
15 files changed
+445 -47

No files matched your search

+10 -27
View File
@@ -12,31 +12,29 @@ import shutil
import stat
from typing import TYPE_CHECKING
from utils.roles.custom import PREFIX
from utils.roles.custom import MARKER_FILE, MARKER_HEADER, PREFIX, marker_fields
if TYPE_CHECKING:
from pathlib import Path
MARKER_FILE = ".infinito-custom-role"
MARKER_HEADER = "# infinito-nexus custom role"
_MARKER_LIMIT = 4096
def marker_text(directory: str, group: str, provenance: str) -> str:
def marker_text(directory: str, group: str, provenance: str, version: str) -> str:
"""Return the content of the marker file.
Args:
directory: the name the role directory is placed as under ``roles/``.
group: the inventory group the role was pulled for.
provenance: the source and resolved commit the role was placed from.
version: the semver the source's manifests declare; empty for none.
"""
return (
text = (
f"{MARKER_HEADER}\ndirectory: {directory}\ngroup: {group}\n"
f"source: {provenance}\n"
)
return f"{text}version: {version}\n" if version else text
def write_marker(role: Path, group: str, provenance: str) -> None:
def write_marker(role: Path, group: str, provenance: str, version: str) -> None:
"""Write the marker into a staged role, replacing whatever entry holds its name.
The entry is removed without following it and the marker is created
@@ -47,6 +45,7 @@ def write_marker(role: Path, group: str, provenance: str) -> None:
role: the staged role directory, named as it is placed.
group: the inventory group the role was pulled for.
provenance: the source and resolved commit the role was placed from.
version: the semver the source's manifests declare; empty for none.
"""
marker = role / MARKER_FILE
try:
@@ -61,7 +60,7 @@ def write_marker(role: Path, group: str, provenance: str) -> None:
marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600
)
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
handle.write(marker_text(role.name, group, provenance))
handle.write(marker_text(role.name, group, provenance, version))
def is_placed(path: Path) -> bool:
@@ -70,7 +69,7 @@ def is_placed(path: Path) -> bool:
Args:
path: an entry of the role search directory.
"""
return not path.is_symlink() and _fields(path).get("directory") == path.name
return not path.is_symlink() and marker_fields(path).get("directory") == path.name
def provenance(path: Path) -> str:
@@ -79,7 +78,7 @@ def provenance(path: Path) -> str:
Args:
path: a role directory :func:`is_placed` accepts.
"""
return _fields(path).get("source", "")
return marker_fields(path).get("source", "")
def custom_entries(roles_dir: Path) -> list[Path]:
@@ -98,19 +97,3 @@ def placed_roles(roles_dir: Path) -> list[Path]:
roles_dir: the role search directory.
"""
return [entry for entry in custom_entries(roles_dir) if is_placed(entry)]
def _fields(role: Path) -> dict[str, str]:
try:
descriptor = os.open(
role / MARKER_FILE, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
)
except OSError:
return {}
with os.fdopen(descriptor, encoding="utf-8", errors="replace") as handle:
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
return {}
lines = handle.read(_MARKER_LIMIT).splitlines()
if not lines or lines[0] != MARKER_HEADER:
return {}
return dict(line.split(": ", 1) for line in lines[1:] if ": " in line)
+2 -2
View File
@@ -115,9 +115,9 @@ def _place(declared: dict[str, Source], roles_dir: Path, work_dir: Path) -> list
staging = _holder(work_dir, group, holders) / group
origin = stage(group, source, staging)
_check_role(group, staging)
write_marker(staging, group, origin)
write_marker(staging, group, origin.provenance, origin.version)
staged.append((staging, roles_dir / group))
lines.append(f"{group}: {origin}")
lines.append(f"{group}: {origin.provenance}")
for _staging, target in staged:
_check_target(target)
dropped = [entry for entry in undeclared if is_placed(entry)]
+43 -6
View File
@@ -9,13 +9,28 @@ import subprocess
import tarfile
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, NamedTuple
from utils.roles.custom import CustomRoleError
from utils.cache.files import read_text
from utils.roles.custom import CustomRoleError, manifest_version
if TYPE_CHECKING:
from .declaration import Source
class Staged(NamedTuple):
"""What :func:`stage` copied.
Args:
provenance: the source and, for a pinned version, the resolved commit.
version: the semver the source repository's manifests declare at
that commit (or in the local checkout); empty for none.
"""
provenance: str
version: str
_COPY_IGNORE = shutil.ignore_patterns(".git", ".claude", "__pycache__")
_DROPPED_ENV = frozenset(
{
@@ -67,7 +82,7 @@ def check(group: str, source: Source, placements: list[Path], roles_dir: Path) -
)
def stage(group: str, source: Source, target: Path) -> str:
def stage(group: str, source: Source, target: Path) -> Staged:
"""Copy the role of ``source`` into ``target`` and describe what was copied.
Args:
@@ -76,7 +91,8 @@ def stage(group: str, source: Source, target: Path) -> str:
target: a path that does not exist yet; it becomes the role directory.
Returns:
The source and, for a pinned version, the resolved commit.
The source with, for a pinned version, the resolved commit, and the
semver the repository root's manifests declare.
Raises:
CustomRoleError: the source cannot be read, or it holds an entry,
@@ -89,7 +105,10 @@ def stage(group: str, source: Source, target: Path) -> str:
f"{group}: source.path is not a directory in the source"
)
shutil.copytree(content, target, symlinks=True, ignore=_COPY_IGNORE)
return source.describe()
return Staged(
source.describe(),
manifest_version(lambda name: _local_text(Path(source.url) / name)),
)
with tempfile.TemporaryDirectory(prefix="infinito-custom-role-") as scratch:
_git(scratch, ["init", "--quiet", "--bare"], f"{group}: git init failed")
_git(
@@ -130,6 +149,7 @@ def stage(group: str, source: Source, target: Path) -> str:
["archive", "--format=tar", tree],
f"{group}: git archive of source.path failed",
)
version = manifest_version(lambda name: _blob_text(scratch, commit, name))
target.mkdir()
try:
with tarfile.open(fileobj=io.BytesIO(archive)) as tar:
@@ -138,7 +158,24 @@ def stage(group: str, source: Source, target: Path) -> str:
raise CustomRoleError(
f"{group}: source.path holds an entry the pull refuses to unpack: {exc}"
) from exc
return f"{source.describe()} (commit {commit})"
return Staged(f"{source.describe()} (commit {commit})", version)
def _local_text(path: Path) -> str | None:
if path.is_symlink() or not path.is_file():
return None
try:
return read_text(str(path))
except UnicodeDecodeError:
return None
def _blob_text(scratch: str, commit: str, name: str) -> str | None:
try:
blob = _git(scratch, ["show", f"{commit}:{name}"], f"no {name} at {commit}")
except CustomRoleError:
return None
return blob.decode(errors="replace")
def _check_local(
+8
View File
@@ -75,6 +75,14 @@ make roles-clean
A pull stages every role outside `roles/` and changes `roles/` only when all of them passed, so a refused pull leaves it as it was. It replaces or removes only the directories it placed itself, whose marker names them, and refuses a declared name that meets a symbolic link, a hand-placed directory or a copy of a placed role. `make roles-clean` removes every `roles/web-app-cst-*` directory the pull placed and reports every other one it leaves in place. Git ignores `roles/web-app-cst-*`, so a pulled role never enters a core commit.
The pull also records the version the source repository declares at the pinned commit, or in a local checkout: `Cargo.toml`, else `pyproject.toml`, else `package.json`. A role pins the images its own repository publishes with it, so no release has to bump them by hand:
```yaml
security-check:
image: ghcr.io/infinito-nexus/security/web
version: "{{ lookup('role_version', 'web-app-cst-security-check') }}"
```
For the local compose stack, `INFINITO_EXTRA_MOUNTS=<dir>[,<dir>]` mounts each directory read-only at the same path into the `infinito` container, so a local `url` resolves inside it.
### Private Repositories 🔐
@@ -65,6 +65,7 @@ The placement rule is per check. The catalog "Position" column uses these labels
| `dashboard` | line above | [test_logout_dashboard.py](../../../../tests/lint/ansible/roles/web-app/integration/test_logout_dashboard.py) | Opts a `web-app-*` role out of the dashboard tile integration. Same shape as `logout`. |
| `sso` | line above | [test_sso.py](../../../../tests/lint/ansible/roles/web-app/integration/test_sso.py) | Opts the role's unified `services.sso` block out. Declares "no login flow"; paired with `enabled: false` + `shared: false`. |
| `file-size` | head (first 30 lines) | [test_python_file_size.py](../../../../tests/lint/repository/structure/test_python_file_size.py) | Opts the entire `.py` file out of the 500-line cap. |
| `lookup-external-consumer` | head of the lookup plugin (first 30 lines) | [test_usage.py](../../../../tests/integration/ansible/lookups/test_usage.py) | Accepts a `plugins/lookup/` plugin that nothing in this repository calls outside `tests/`, because its callers are custom roles pulled from their own repositories (such as `role_version` for `web-app-cst-*`). Write it as `# nocheck: lookup-external-consumer -- <who calls it>`; a bare marker grants nothing and is reported. |
| `comments-valid` | head (first 30 lines) | [test_comments_valid.py](../../../../tests/lint/repository/test_comments_valid.py) | Opts the entire file out of the useful-comment check. Reserved for vendored / upstream config templates (e.g. Discourse `app.yml`) whose inline documentation is all intentional. |
| `info-media` | head of `meta/main.yml` (first 30 lines) | [test_info_homepage_video.py](../../../../tests/lint/ansible/roles/meta/test_info_homepage_video.py) | Opts an invokable role out of the required `meta/info.yml` `homepage` + `video` entries. Marker lives in `meta/main.yml` (a comment-only `info.yml` would fail the info schema lint). Reserved for fully self-written roles (backups, host plumbing) that have no upstream product page or demo video. |
| `credential-masking` | same or above | [test_credential_tasks_are_masked.py](../../../../tests/lint/ansible/modules/test_credential_tasks_are_masked.py) | Allows the marked task to carry a credential without `no_log` on itself or a parent. Marker goes on or directly above the task's `- name:`. |
+1
View File
@@ -33,6 +33,7 @@ As an operator, I want to declare application roles that live in their own repos
- [x] A pull that stops leaves `roles/` unchanged, and no staging or leftover directory of a pull appears under `roles/`.
- [x] A declared name that meets a symbolic link under `roles/`, or a directory the pull did not place, stops the run with a message naming it, and the pull never replaces or removes such a directory.
- [x] A command lists the placed custom roles with their source and resolved commit, and a `make` target removes every `roles/web-app-cst-*` directory the pull placed and nothing else.
- [x] The pull records the semver the source repository declares at the pinned commit, or in a local checkout, in the role's marker: `[package].version` of `Cargo.toml` (or `[workspace.package].version`), else `[project].version` of `pyproject.toml`, else `version` of `package.json`. `lookup('role_version', 'web-app-cst-<name>')` returns it and fails when the source declares none, so a role pins the images its own repository publishes as `version: "{{ lookup('role_version', 'web-app-cst-<name>') }}"` in `meta/services.yml` and a release never needs a hand-set image version.
- [ ] `INFINITO_EXTRA_MOUNTS=<dir>[,<dir>]` mounts each directory read-only at the same path into the `infinito` container when the stack is created, so a local `source.url` resolves inside the container; an entry that is not an existing absolute directory stops the stack start with an error naming it.
- [x] `roles/web-app-cst-*` is ignored by Git in core, so a pulled role never enters a core commit.
- [x] The `web-app-cst-` prefix is reserved: a lint fails on an in-tree role whose name starts with it.
+53
View File
@@ -0,0 +1,53 @@
"""lookup('role_version', 'web-app-cst-<name>')
Args:
application_id: a custom role the pull placed under ``roles/``.
Returns:
The version the pull read from ``Cargo.toml``, ``pyproject.toml`` or
``package.json`` at the source's pinned commit, or in its local checkout,
as recorded in the role's pull marker, e.g. ``0.4.3``.
"""
# nocheck: lookup-external-consumer -- called by pulled web-app-cst-* roles
from __future__ import annotations
from pathlib import Path
from typing import Any
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
from utils.roles.custom import VERSION_MANIFESTS, is_custom, marker_fields
class LookupModule(LookupBase):
def run(
self, terms: list[Any], variables: dict[str, Any] | None = None, **kwargs: Any
) -> list[str]:
if len(terms) != 1:
raise AnsibleError(
"lookup('role_version', application_id) takes exactly one term"
)
application_id = str(terms[0])
if not is_custom(application_id):
raise AnsibleError(
f"lookup('role_version'): {application_id!r} is no custom role; "
"only a role the pull places records a source version"
)
base = (variables or {}).get("playbook_dir")
if not base:
raise AnsibleError("lookup('role_version'): 'playbook_dir' is unavailable.")
fields = marker_fields(Path(str(base)) / "roles" / application_id)
if fields.get("directory") != application_id:
raise AnsibleError(
f"lookup('role_version'): roles/{application_id} was not placed by a pull"
)
version = fields.get("version", "")
if not version:
raise AnsibleError(
f"lookup('role_version'): the source of {application_id} declares no "
f"semver in {', '.join(VERSION_MANIFESTS)} at its repository root"
)
return [version]
@@ -31,6 +31,7 @@ import re
import unittest
from typing import TYPE_CHECKING
from utils.annotations.suppress import marker_reason
from utils.cache.files import iter_project_files, read_text
from . import PROJECT_ROOT
@@ -42,6 +43,26 @@ LOOKUP_PLUGINS_DIR = PROJECT_ROOT / "plugins" / "lookup"
USAGE_EXTS = (".yml", ".yaml", ".j2", ".jinja2", ".tmpl", ".py")
EXTERNAL_CONSUMER_RULE = "lookup-external-consumer"
HEAD_LINES = 30
def external_consumer_reason(path: Path) -> str | None:
"""Return the reason of the plugin's ``lookup-external-consumer`` marker.
Args:
path: the lookup plugin file.
Returns:
The reason stated by the first marker in the file's head, an empty
string for a bare marker, or None when the head carries no marker.
"""
for line in read_text(str(path)).splitlines()[:HEAD_LINES]:
reason = marker_reason(line, EXTERNAL_CONSUMER_RULE)
if reason is not None:
return reason
return None
def _defines_lookup_module(path: Path) -> bool:
"""Return True if the module defines ``class LookupModule`` at top level.
@@ -146,9 +167,18 @@ class TestLookupDefinitionsAreUsed(unittest.TestCase):
unused: list[tuple[str, Path, str]] = []
for name in sorted(defined):
s = state[name]
if not s["used_any"]:
if s["used_outside"]:
continue
reason = external_consumer_reason(defined[name])
if reason:
continue
if reason == "":
unused.append(
(name, defined[name], f"bare `{EXTERNAL_CONSUMER_RULE}` marker")
)
elif not s["used_any"]:
unused.append((name, defined[name], "not used anywhere"))
elif not s["used_outside"]:
else:
unused.append((name, defined[name], "only used in tests"))
if unused:
@@ -68,12 +68,15 @@ def write(path: Path, text: str) -> Path:
def role_repo(root: Path, application_id: str = ROLE) -> Path:
"""A repository whose tag ``v1.0.0`` holds the role and whose branch ``feature`` moved on.
The repository root declares ``version = "1.0.0"`` in ``Cargo.toml``.
Args:
root: directory the repository is created in.
application_id: the ``vars/main.yml`` application_id of the role.
"""
repo = root / "repo"
write(repo / "README.md", "repository root\n")
write(repo / "Cargo.toml", '[package]\nname = "demo"\nversion = "1.0.0"\n')
write(repo / ROLE_PATH / ROLE_FILE_META_MAIN, "galaxy_info: {}\n")
write(repo / ROLE_PATH / ROLE_FILE_VARS_MAIN, f"application_id: {application_id}\n")
write(repo / ROLE_PATH / ROLE_FILE_TASKS_MAIN, "release: v1\n")
@@ -20,7 +20,8 @@ class TestListMain(unittest.TestCase):
marker = roles / "web-app-cst-a" / MARKER_FILE
marker.parent.mkdir()
marker.write_text(
marker_text("web-app-cst-a", "web-app-cst-a", ORIGIN), encoding="utf-8"
marker_text("web-app-cst-a", "web-app-cst-a", ORIGIN, "1.0.0"),
encoding="utf-8",
)
(roles / "web-app-cst-hand").mkdir()
(roles / "web-app-nextcloud").mkdir()
@@ -16,11 +16,13 @@ from cli.administration.roles.marker import (
provenance,
write_marker,
)
from utils.roles.custom import marker_fields
from ._fixtures import write
ORIGIN = "https://example.invalid/w.git ansible/roles/web-app-cst-a @ v1 (commit abc)"
PLACED = "web-app-cst-a"
VERSION = "1.4.2"
class TestMarker(unittest.TestCase):
@@ -28,7 +30,10 @@ class TestMarker(unittest.TestCase):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.roles = Path(tmp.name) / "roles"
write(self.roles / PLACED / MARKER_FILE, marker_text(PLACED, PLACED, ORIGIN))
write(
self.roles / PLACED / MARKER_FILE,
marker_text(PLACED, PLACED, ORIGIN, VERSION),
)
write(self.roles / "web-app-cst-hand" / "mine.yml", "mine: true\n")
write(self.roles / "web-app-cst-forged" / MARKER_FILE, "something else\n")
shutil.copytree(self.roles / PLACED, self.roles / "web-app-cst-copy")
@@ -38,7 +43,7 @@ class TestMarker(unittest.TestCase):
)
write(
self.roles / "web-app-nextcloud" / MARKER_FILE,
marker_text("web-app-nextcloud", "web-app-nextcloud", ORIGIN),
marker_text("web-app-nextcloud", "web-app-nextcloud", ORIGIN, ""),
)
(self.roles / "web-app-cst-link").symlink_to(self.roles / PLACED)
@@ -65,6 +70,12 @@ class TestMarker(unittest.TestCase):
def test_provenance_reads_back_what_the_pull_recorded(self):
self.assertEqual(ORIGIN, provenance(self.roles / PLACED))
def test_the_version_the_pull_recorded_reads_back(self):
self.assertEqual(VERSION, marker_fields(self.roles / PLACED)["version"])
def test_a_marker_without_a_version_has_no_version_field(self):
self.assertNotIn("version", marker_fields(self.roles / "web-app-nextcloud"))
def test_custom_entries_are_every_prefixed_entry(self):
self.assertEqual(
[
@@ -91,14 +102,15 @@ class TestWriteMarker(unittest.TestCase):
self.role.mkdir()
def test_marker_names_the_directory_and_the_group(self):
write_marker(self.role, PLACED, ORIGIN)
write_marker(self.role, PLACED, ORIGIN, VERSION)
self.assertTrue(is_placed(self.role))
self.assertEqual(ORIGIN, provenance(self.role))
self.assertEqual(VERSION, marker_fields(self.role)["version"])
def test_a_symbolic_link_under_the_marker_name_is_replaced_not_followed(self):
victim = write(self.root / "victim.yml", "victim: true\n")
(self.role / MARKER_FILE).symlink_to(victim)
write_marker(self.role, PLACED, ORIGIN)
write_marker(self.role, PLACED, ORIGIN, VERSION)
text = victim.read_text(encoding="utf-8") # nocheck: cache-read tempdir
self.assertEqual("victim: true\n", text)
self.assertFalse((self.role / MARKER_FILE).is_symlink())
@@ -106,13 +118,13 @@ class TestWriteMarker(unittest.TestCase):
def test_a_directory_under_the_marker_name_is_replaced(self):
write(self.role / MARKER_FILE / "nested.yml", "nested: true\n")
write_marker(self.role, PLACED, ORIGIN)
write_marker(self.role, PLACED, ORIGIN, VERSION)
self.assertTrue((self.role / MARKER_FILE).is_file())
self.assertTrue(is_placed(self.role))
def test_the_marker_is_readable_by_its_owner_only_whatever_the_umask(self):
self.addCleanup(os.umask, os.umask(0))
write_marker(self.role, PLACED, ORIGIN)
write_marker(self.role, PLACED, ORIGIN, VERSION)
mode = (self.role / MARKER_FILE).stat().st_mode
self.assertEqual(0o600, stat.S_IMODE(mode))
self.assertTrue(is_placed(self.role))
@@ -108,7 +108,25 @@ class TestStage(_SourceFixture, unittest.TestCase):
sha = git(self.repo, "rev-parse", "v1.0.0^{commit}").strip()
self.assertEqual("release: v1\n", read_text(str(target / ROLE_FILE_TASKS_MAIN)))
self.assertFalse((target / "README.md").exists())
self.assertIn(f"(commit {sha})", origin)
self.assertFalse((target / "Cargo.toml").exists())
self.assertIn(f"(commit {sha})", origin.provenance)
self.assertEqual("1.0.0", origin.version)
def test_tag_reads_the_version_its_own_commit_declares(self):
write(self.repo / "Cargo.toml", '[package]\nname = "demo"\nversion = "2.0.0"\n')
git(self.repo, "commit", "-q", "-am", "bump")
git(self.repo, "tag", "v2.0.0")
target = self.root / "staged"
origin = stage(ROLE, Source(str(self.repo), "v1.0.0", ROLE_PATH), target)
self.assertEqual("1.0.0", origin.version)
def test_tag_without_a_version_manifest_records_none(self):
git(self.repo, "rm", "-q", "Cargo.toml")
git(self.repo, "commit", "-q", "-m", "drop manifest")
git(self.repo, "tag", "v3.0.0")
target = self.root / "staged"
origin = stage(ROLE, Source(str(self.repo), "v3.0.0", ROLE_PATH), target)
self.assertEqual("", origin.version)
def test_full_commit_sha_is_staged(self):
sha = git(self.repo, "rev-parse", "v1.0.0^{commit}").strip()
@@ -125,7 +143,17 @@ class TestStage(_SourceFixture, unittest.TestCase):
"release: uncommitted\n", read_text(str(target / ROLE_FILE_TASKS_MAIN))
)
self.assertFalse((target / "__pycache__").exists())
self.assertIn("(working tree)", origin)
self.assertIn("(working tree)", origin.provenance)
self.assertEqual("1.0.0", origin.version)
def test_local_directory_reads_the_version_of_its_working_tree(self):
write(
self.repo / "Cargo.toml",
'[package]\nname = "demo"\nversion = "1.1.0-rc.1"\n',
)
target = self.root / "staged"
origin = stage(ROLE, Source(str(self.repo), None, ROLE_PATH), target)
self.assertEqual("1.1.0-rc.1", origin.version)
def test_local_directory_skips_unreadable_agent_harness_state(self):
harness = self.repo / ROLE_PATH / ".claude" / ".cc-writes"
@@ -0,0 +1,67 @@
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from ansible.errors import AnsibleError
from cli.administration.roles.marker import MARKER_FILE, marker_text
from plugins.lookup.role_version import LookupModule
ROLE = "web-app-cst-demo"
ORIGIN = "https://example.invalid/demo.git ansible/roles/web-app-cst-demo @ v0.4.3 (commit abc)"
class TestRoleVersion(unittest.TestCase):
def setUp(self) -> None:
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = Path(tmp.name)
self.variables = {"playbook_dir": str(self.root)}
def _place(self, directory: str, version: str) -> None:
role = self.root / "roles" / directory
role.mkdir(parents=True)
(role / MARKER_FILE).write_text(
marker_text(directory, directory, ORIGIN, version), encoding="utf-8"
)
def _lookup(self, application_id: str) -> list[str]:
return LookupModule().run([application_id], variables=self.variables)
def test_returns_the_version_the_pull_recorded(self):
self._place(ROLE, "0.4.3")
self.assertEqual(["0.4.3"], self._lookup(ROLE))
def test_a_pull_without_a_version_fails_naming_the_manifests(self):
self._place(ROLE, "")
with self.assertRaisesRegex(AnsibleError, "Cargo.toml, pyproject.toml"):
self._lookup(ROLE)
def test_a_role_the_pull_did_not_place_fails(self):
(self.root / "roles" / ROLE).mkdir(parents=True)
with self.assertRaisesRegex(AnsibleError, "was not placed by a pull"):
self._lookup(ROLE)
def test_a_marker_naming_another_directory_fails(self):
self._place("web-app-cst-other", "0.4.3")
(self.root / "roles" / "web-app-cst-other").rename(self.root / "roles" / ROLE)
with self.assertRaisesRegex(AnsibleError, "was not placed by a pull"):
self._lookup(ROLE)
def test_an_in_tree_role_is_refused(self):
with self.assertRaisesRegex(AnsibleError, "is no custom role"):
self._lookup("web-app-nextcloud")
def test_exactly_one_term_is_required(self):
with self.assertRaises(AnsibleError):
LookupModule().run([], variables=self.variables)
def test_playbook_dir_is_required(self):
with self.assertRaisesRegex(AnsibleError, "playbook_dir"):
LookupModule().run([ROLE], variables={})
if __name__ == "__main__":
unittest.main()
+85 -1
View File
@@ -2,9 +2,93 @@ from __future__ import annotations
import unittest
from utils.roles.custom import is_custom, is_custom_path
from utils.roles.custom import is_custom, is_custom_path, manifest_version
from utils.roles.mapping import ROLE_FILE_TASKS_MAIN
CARGO = '[package]\nname = "x"\nversion = "0.4.3"\n'
PYPROJECT = '[project]\nname = "x"\nversion = "7.2.0"\n'
PACKAGE_JSON = '{"name": "x", "version": "2.3.0"}'
def _repo(**files: str):
return files.get
class TestManifestVersion(unittest.TestCase):
def test_cargo_package_version(self):
self.assertEqual("0.4.3", manifest_version(_repo(**{"Cargo.toml": CARGO})))
def test_cargo_workspace_package_version(self):
text = '[workspace.package]\nversion = "1.2.3"\n'
self.assertEqual("1.2.3", manifest_version(_repo(**{"Cargo.toml": text})))
def test_pyproject_project_version(self):
self.assertEqual(
"7.2.0", manifest_version(_repo(**{"pyproject.toml": PYPROJECT}))
)
def test_package_json_version(self):
self.assertEqual(
"2.3.0", manifest_version(_repo(**{"package.json": PACKAGE_JSON}))
)
def test_cargo_wins_over_pyproject_and_package_json(self):
files = {
"Cargo.toml": CARGO,
"pyproject.toml": PYPROJECT,
"package.json": PACKAGE_JSON,
}
self.assertEqual("0.4.3", manifest_version(_repo(**files)))
def test_a_workspace_inherited_cargo_version_falls_through(self):
files = {
"Cargo.toml": "[package]\nversion.workspace = true\n",
"pyproject.toml": PYPROJECT,
}
self.assertEqual("7.2.0", manifest_version(_repo(**files)))
def test_a_dynamic_pyproject_version_declares_none(self):
text = '[project]\nname = "x"\ndynamic = ["version"]\n'
self.assertEqual("", manifest_version(_repo(**{"pyproject.toml": text})))
def test_a_value_that_is_no_semver_is_passed_over(self):
files = {
"Cargo.toml": '[package]\nversion = "latest"\n',
"package.json": PACKAGE_JSON,
}
self.assertEqual("2.3.0", manifest_version(_repo(**files)))
def test_a_prerelease_semver_counts(self):
text = '[package]\nversion = "1.0.0-rc.1+build.5"\n'
self.assertEqual(
"1.0.0-rc.1+build.5", manifest_version(_repo(**{"Cargo.toml": text}))
)
def test_a_version_with_a_trailing_newline_is_passed_over(self):
files = {
"Cargo.toml": '[package]\nversion = "1.0.0\\n"\n',
"package.json": PACKAGE_JSON,
}
self.assertEqual("2.3.0", manifest_version(_repo(**files)))
def test_a_version_of_non_ascii_digits_is_passed_over(self):
files = {
"Cargo.toml": '[package]\nversion = "١.٢.٣"\n',
"package.json": PACKAGE_JSON,
}
self.assertEqual("2.3.0", manifest_version(_repo(**files)))
def test_a_too_deeply_nested_manifest_declares_none(self):
files = {"package.json": "[" * 100000 + "]" * 100000}
self.assertEqual("", manifest_version(_repo(**files)))
def test_unparsable_manifests_declare_none(self):
files = {"Cargo.toml": "[package\n", "package.json": "{not json"}
self.assertEqual("", manifest_version(_repo(**files)))
def test_a_repository_without_manifests_declares_none(self):
self.assertEqual("", manifest_version(_repo()))
class TestIsCustom(unittest.TestCase):
def test_reserved_prefix_is_custom(self):
+90
View File
@@ -11,10 +11,27 @@ project-tree scan helpers in :mod:`utils.cache` read it.
from __future__ import annotations
import json
import os
import re
import stat
import tomllib
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable
from pathlib import Path
PREFIX: str = "web-app-cst-"
ROLES_GLOB: str = f"roles/{PREFIX}*"
CUSTOM_KEY: str = "custom"
SOURCE_KEY: str = "source"
MARKER_FILE: str = ".infinito-custom-role"
MARKER_HEADER: str = "# infinito-nexus custom role"
VERSION_MANIFESTS: tuple[str, ...] = ("Cargo.toml", "pyproject.toml", "package.json")
_MARKER_LIMIT = 4096
_SEMVER = re.compile(r"\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?", re.ASCII)
class CustomRoleError(Exception):
@@ -38,3 +55,76 @@ def is_custom_path(rel_path: str) -> bool:
"""
parts = rel_path.split("/")
return len(parts) > 1 and parts[0] == "roles" and is_custom(parts[1])
def marker_fields(role: Path) -> dict[str, str]:
"""Return the fields of a role's pull marker, read without following a link.
Args:
role: a role directory under ``roles/``.
Returns:
``directory``, ``group``, ``source`` and, when the pull found one,
``version``; empty when the role carries no readable marker.
"""
try:
descriptor = os.open(
role / MARKER_FILE, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK
)
except OSError:
return {}
with os.fdopen(descriptor, encoding="utf-8", errors="replace") as handle:
if not stat.S_ISREG(os.fstat(descriptor).st_mode):
return {}
lines = handle.read(_MARKER_LIMIT).splitlines()
if not lines or lines[0] != MARKER_HEADER:
return {}
return dict(line.split(": ", 1) for line in lines[1:] if ": " in line)
def manifest_version(read: Callable[[str], str | None]) -> str:
"""Return the semver the first version manifest of a repository declares.
Args:
read: returns the text of a file at the repository root by name, or
None when the repository has no such file.
Returns:
``[package].version`` of ``Cargo.toml`` (or its
``[workspace.package].version``), ``[project].version`` of
``pyproject.toml`` or ``version`` of ``package.json``, tried in
that order; a value that is no semver is passed over. Empty when
none declares one.
"""
for name in VERSION_MANIFESTS:
text = read(name)
if text is None:
continue
version = _declared_version(name, text)
if _SEMVER.fullmatch(version):
return version
return ""
def _declared_version(name: str, text: str) -> str:
try:
data = json.loads(text) if name == "package.json" else tomllib.loads(text)
except (ValueError, RecursionError):
return ""
if not isinstance(data, dict):
return ""
if name == "package.json":
candidates = [data]
elif name == "Cargo.toml":
workspace = data.get("workspace")
candidates = [
data.get("package"),
workspace.get("package") if isinstance(workspace, dict) else None,
]
else:
candidates = [data.get("project")]
for table in candidates:
value = table.get("version") if isinstance(table, dict) else None
if isinstance(value, str):
return value
return ""