feat(web-app-kix): lock the LDAP auth settings natively through meta/forms.yml

Requirement 072, settings inventory row 397 of web-app-kix, operator
pick A (2026-11-13 ~19:20): the LDAP SysConfig options were only an XML
default, so an agent edit in the SysConfig admin survived every deploy
(kix-backend Kernel/System/SysConfig.pm Rebuild keeps the stored Value,
ValueGetAll prefers it).

- meta/forms.yml declares the native form ldap (path /admin, the
  sysconfig admin module) with host, port, base_dn, search_user_dn,
  uid, access_attr, administrator_group_dn and user_group_dn, enforced
  while services.ldap is on. Their values are the computed keys
  services.kix.ldap of meta/services.yml; the bind password stays out
  of the form and the sink, as in the Matomo form.
- KIX_LDAP_SETTINGS reads the form through lookup('form_values', ...).
  KIX_LDAP_AUTHENTICATION builds both Authentication options from it,
  and both the XML default and the new templates/auth_ldap.conf.j2
  render that one structure.
- auth_ldap.conf.j2 is a KIX local config file, mounted as the config
  volume auth_ldap_lock at /opt/kix/config/zzz_infinito_auth_ldap.conf.
  KIX reads every file there before the database and marks each of its
  keys read-only (Kernel/Config.pm GetLocalConfig, GetSysConfig merges
  the file over SysConfig); the API reports ReadOnly
  (Kernel/API/Operation/V1/SysConfig/SysConfigOptionGet.pm:147) and the
  agent portal renders the value read-only (SysConfigFormService.ts
  handleSingleSysconfigKey, text-area-input/index.marko readonly). The
  file carries the JSON base64 encoded, so no value needs escaping.
- Before the render, tasks/00_core.yml slurps the previous file on the
  stack host (masked, without become), the role filter kix_ldap_lock_fields returns its
  managed fields without the bind password, and
  tasks/utils/forms/drift.yml reports what the write reverts. No KIX
  boot or container exec is needed; a first deploy reads nothing.
- KIX_LDAP_UID_ATTR and both group DNs read the same computed keys.

Proof:
- tests/unit/python/roles/web-app-kix/test_ldap_lock_form.py: 10 OK
  (logs/kix-ldap-lock-form-3.log), including a real perl eval of the
  rendered file the way GetLocalConfig reads it, with a bind password
  holding a quote, a backslash and a dollar, and the round trip
  write-then-read; all 10 fail against the base role files
  (logs/kix-ldap-lock-form-negative-1.log).
- Green: forms lint (logs/kix-forms-lint-1.log), sso profile lock (14),
  vars used, vars usage in yaml, comments, project root import,
  credential tasks masked (logs/kix-*-1.log); ruff check and format
  clean.

Residual: live proof in the final roundtrip of the single-file mount
inside the kix_config volume path in compose and swarm, JSON::PP and
MIME::Base64 in the backend image's perl (both core modules), the
read-only value in the SysConfig dialog (a JSON value may open the
CodeMirror editor, whose read-only state is unverified), and the drift
line. The contact, role and usage-context sync maps stay locked inside
the file but are not declared as fields. The agent portal logo and icon
are marker-gated (written only when the design image changes), so they
stay undeclared. The new file holds the bind password base64 encoded with
mode 0644, the same exposure as the existing zzz_auth_ldap.xml; tightening
both needs the backend uid and is a follow-up.

Cost: one slurp on the stack host and one more replicated config file
per deploy; no runtime cost.

🎯 Fix: 90 %
💥 Break: 5 %
💸 Cost: 100 %
⏱️ Time: 100 %
🛡️ Security: ~100 %
🏆 Score: 86
🚦 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-13 19:56:43 +00:00
1 parent 7a36f99f19
commit 652e590d54
10 files changed
+426 -67

No files matched your search

@@ -0,0 +1,76 @@
from __future__ import annotations
import base64
import binascii
import json
import re
from collections.abc import Mapping
ADMINISTRATOR = "Authentication###100-Infinito-LDAP"
USER = "Authentication###200-Infinito-LDAP-User"
PAYLOAD = re.compile(r"decode_base64\('([A-Za-z0-9+/=]*)'\)")
FIELDS = {
"host": (ADMINISTRATOR, "Host"),
"port": (ADMINISTRATOR, "Params", "port"),
"base_dn": (ADMINISTRATOR, "BaseDN"),
"search_user_dn": (ADMINISTRATOR, "SearchUserDN"),
"uid": (ADMINISTRATOR, "UID"),
"access_attr": (ADMINISTRATOR, "AccessAttr"),
"administrator_group_dn": (ADMINISTRATOR, "GroupDN"),
"user_group_dn": (USER, "GroupDN"),
}
MISSING = object()
def _payload(slurped) -> Mapping:
content = slurped.get("content") if isinstance(slurped, Mapping) else None
if not isinstance(content, str) or not content:
return {}
try:
match = PAYLOAD.search(base64.b64decode(content).decode("utf-8"))
held = json.loads(base64.b64decode(match.group(1))) if match else {}
except (binascii.Error, UnicodeDecodeError, ValueError):
return {}
return held if isinstance(held, Mapping) else {}
def _config(held: Mapping, option: str) -> Mapping:
backends = held.get(option)
backend = backends[0] if isinstance(backends, list) and backends else None
config = backend.get("Config") if isinstance(backend, Mapping) else None
return config if isinstance(config, Mapping) else {}
def _walk(node, keys):
for key in keys:
if not isinstance(node, Mapping) or key not in node:
return MISSING
node = node[key]
return node
def kix_ldap_lock_fields(slurped) -> dict:
"""Return the managed LDAP fields the locked KIX config file holds.
Args:
slurped: the registered ``slurp`` result of the file
``templates/auth_ldap.conf.j2`` renders; a failed read, a
missing payload or a malformed one yields no field.
Returns:
Each field of the ``ldap`` form of ``meta/forms.yml`` the file holds,
mapped to its value; a field the file lacks is left out, and the
bind password never appears.
"""
held = _payload(slurped)
fields = {}
for field, (option, *keys) in FIELDS.items():
value = _walk(_config(held, option), keys)
if value is not MISSING:
fields[field] = value
return fields
class FilterModule:
def filters(self):
return {"kix_ldap_lock_fields": kix_ldap_lock_fields}
+62
View File
@@ -0,0 +1,62 @@
---
ldap:
path: /admin
native: true
sinks: [KIX_LDAP_SETTINGS]
fields:
host:
source: services.kix.ldap.host
when: services.ldap.enabled
mode: enforced
selector: textarea.input-style
type: text
label: LDAP host
port:
source: services.kix.ldap.port
when: services.ldap.enabled
mode: enforced
selector: textarea.input-style
type: number
label: LDAP port
base_dn:
source: services.kix.ldap.base_dn
when: services.ldap.enabled
mode: enforced
selector: textarea.input-style
type: text
label: Base DN
search_user_dn:
source: services.kix.ldap.search_user_dn
when: services.ldap.enabled
mode: enforced
selector: textarea.input-style
type: text
label: Search user DN
uid:
source: services.kix.ldap.uid
when: services.ldap.enabled
mode: enforced
selector: textarea.input-style
type: text
label: UID attribute
access_attr:
source: services.kix.ldap.access_attr
when: services.ldap.enabled
mode: enforced
selector: textarea.input-style
type: text
label: Group member attribute
administrator_group_dn:
source: services.kix.ldap.administrator_group_dn
when: services.ldap.enabled
mode: enforced
selector: textarea.input-style
type: text
label: Administrator group DN
user_group_dn:
source: services.kix.ldap.user_group_dn
when: services.ldap.enabled
mode: enforced
selector: textarea.input-style
type: text
label: User group DN
+9
View File
@@ -87,6 +87,15 @@ kix:
http: 8083
sso: 16500
sso_onion: 16532
ldap:
host: "{{ LDAP.SERVER.DOMAIN }}"
port: "{{ LDAP.SERVER.PORT | int }}"
base_dn: "{{ LDAP.DN.OU.USERS }}"
search_user_dn: "{{ LDAP.DN.ADMINISTRATOR.DATA }}"
uid: "{{ LDAP.USER.ATTRIBUTES.ID }}"
access_attr: "{{ LDAP.RBAC.MEMBER_ATTRIBUTE }}"
administrator_group_dn: "cn=web-app-kix-administrator,{{ LDAP.DN.OU.ROLES }}"
user_group_dn: "cn=web-app-kix-user,{{ LDAP.DN.OU.ROLES }}"
run_after:
- web-app-keycloak
lifecycle: beta
+9
View File
@@ -54,6 +54,15 @@ auth_ldap:
target: /opt/kix/Kernel/Config/Files/zzz_auth_ldap.xml
when: "{{ lookup('config', 'web-app-kix', 'services.ldap.enabled') | bool }}"
auth_ldap_lock:
type: config
source: "{{ [lookup('container', 'web-app-kix', 'directories.volumes'), 'auth_ldap.conf'] | path_join }}"
mode: "0444"
mounts:
- service: backend
target: /opt/kix/config/zzz_infinito_auth_ldap.conf
when: "{{ lookup('config', 'web-app-kix', 'services.ldap.enabled') | bool }}"
proxy_nginx_conf:
type: config
source: "{{ [lookup('container', 'web-app-kix', 'directories.volumes'), 'kix-proxy.default.conf'] | path_join }}"
+22
View File
@@ -6,6 +6,24 @@
name: svc-stack
tasks_from: consumer.yml
- name: "⬇️ Read the LDAP settings the locked KIX config file holds"
ansible.builtin.slurp:
src: "{{ KIX_AUTH_LDAP_LOCK_HOST_PATH }}"
register: kix_ldap_lock_stored
failed_when: false
become: false
delegate_to: "{{ STACK_HOST }}"
run_once: true
no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"
when: KIX_LDAP_ENABLED | bool
- name: "📣 Report the LDAP settings the write reverts"
ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'tasks/utils/forms/drift.yml') }}"
vars:
forms_drift_current:
ldap: "{{ kix_ldap_lock_stored | kix_ldap_lock_fields }}"
when: KIX_LDAP_ENABLED | bool
- name: "📄 Render KIX host-side config files (local + swarm peers)"
ansible.builtin.include_tasks:
file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}"
@@ -15,6 +33,10 @@
dest: "{{ KIX_AUTH_LDAP_HOST_PATH }}"
mode: "0644"
condition: "{{ KIX_LDAP_ENABLED | bool }}"
- src: "auth_ldap.conf.j2"
dest: "{{ KIX_AUTH_LDAP_LOCK_HOST_PATH }}"
mode: "0644"
condition: "{{ KIX_LDAP_ENABLED | bool }}"
- src: "kix-proxy.default.conf.j2"
dest: "{{ KIX_PROXY_NGINX_HOST_PATH }}"
mode: "0644"
@@ -0,0 +1 @@
do { require JSON::PP; require MIME::Base64; %{ JSON::PP::decode_json(MIME::Base64::decode_base64('{{ KIX_LDAP_AUTHENTICATION | to_json | b64encode }}')) } }
@@ -4,72 +4,14 @@
<Description Translatable="1">{{ SOFTWARE_NAME }} LDAP backend (svc-db-openldap) for the web-app-kix-administrator role group. Authenticates KIX agents via Auth::LDAP and provisions the contact, its profile fields and the KIX roles of both role groups via Auth::Sync::LDAP.</Description>
<Group>Framework</Group>
<Setting>
<Object>[
{
"Name": "{{ SOFTWARE_NAME }} svc-db-openldap (Agent, web-app-kix-administrator)",
"Enabled": 1,
"UsageContext": "Agent",
"Module": "Kernel::System::Auth::LDAP",
"Config": {
"Host": "{{ KIX_LDAP_HOST }}",
"Params": {
"async": 0,
"port": {{ KIX_LDAP_PORT }},
"timeout": 10,
"version": 3
},
"BaseDN": "{{ KIX_LDAP_BASE_DN }}",
"AlwaysFilter": "(objectclass=inetOrgPerson)",
"Charset": "utf-8",
"SearchUserDN": "{{ KIX_LDAP_BIND_DN }}",
"SearchUserPw": "{{ KIX_LDAP_BIND_PW }}",
"GroupDN": "{{ KIX_LDAP_ADMINISTRATOR_GROUP_DN }}",
"AccessAttr": "{{ LDAP.RBAC.MEMBER_ATTRIBUTE }}",
"UID": "{{ KIX_LDAP_UID_ATTR }}",
"UserAttr": "DN",
"AuthAttr": "{{ KIX_LDAP_UID_ATTR }}",
"UserSuffix": "",
"Debug": 1
},
"Sync": {{ KIX_LDAP_SYNC | to_json }}
}
]</Object>
<Object>{{ KIX_LDAP_AUTHENTICATION['Authentication###100-Infinito-LDAP'] | to_json }}</Object>
</Setting>
</ConfigItem>
<ConfigItem AccessLevel="confidential" Name="Authentication###200-Infinito-LDAP-User" Required="1" Valid="1" ConfigLevel="200">
<Description Translatable="1">Second {{ SOFTWARE_NAME }} LDAP backend for the web-app-kix-user role group. KIX iterates over Authentication entries; if the administrator backend (###100) refuses (user not in admin group), this one tries the user group. The OAuth2-proxy `allowed_groups` filter still lets only members of either group through, so this backend never sees a user without an {{ SOFTWARE_NAME }} role. Both backends share one sync, so the KIX roles always follow every role group the user holds.</Description>
<Group>Framework</Group>
<Setting>
<Object>[
{
"Name": "{{ SOFTWARE_NAME }} svc-db-openldap (Agent, web-app-kix-user)",
"Enabled": 1,
"UsageContext": "Agent",
"Module": "Kernel::System::Auth::LDAP",
"Config": {
"Host": "{{ KIX_LDAP_HOST }}",
"Params": {
"async": 0,
"port": {{ KIX_LDAP_PORT }},
"timeout": 10,
"version": 3
},
"BaseDN": "{{ KIX_LDAP_BASE_DN }}",
"AlwaysFilter": "(objectclass=inetOrgPerson)",
"Charset": "utf-8",
"SearchUserDN": "{{ KIX_LDAP_BIND_DN }}",
"SearchUserPw": "{{ KIX_LDAP_BIND_PW }}",
"GroupDN": "{{ KIX_LDAP_USER_GROUP_DN }}",
"AccessAttr": "{{ LDAP.RBAC.MEMBER_ATTRIBUTE }}",
"UID": "{{ KIX_LDAP_UID_ATTR }}",
"UserAttr": "DN",
"AuthAttr": "{{ KIX_LDAP_UID_ATTR }}",
"UserSuffix": "",
"Debug": 1
},
"Sync": {{ KIX_LDAP_SYNC | to_json }}
}
]</Object>
<Object>{{ KIX_LDAP_AUTHENTICATION['Authentication###200-Infinito-LDAP-User'] | to_json }}</Object>
</Setting>
</ConfigItem>
</kix_config>
+38 -7
View File
@@ -37,14 +37,11 @@ KIX_DESIGN_ICONS:
builtin: "/opt/kix/static/img/kix_start_icon.png"
KIX_LDAP_ENABLED: "{{ lookup('config', application_id, 'services.ldap.enabled') | bool }}"
KIX_LDAP_HOST: "{{ LDAP.SERVER.DOMAIN }}"
KIX_LDAP_PORT: "{{ LDAP.SERVER.PORT }}"
KIX_LDAP_BASE_DN: "{{ LDAP.DN.OU.USERS }}"
KIX_LDAP_BIND_DN: "{{ LDAP.DN.ADMINISTRATOR.DATA }}"
KIX_LDAP_SETTINGS: "{{ lookup('form_values', application_id, 'ldap') }}"
KIX_LDAP_BIND_PW: "{{ LDAP.BIND_CREDENTIAL }}"
KIX_LDAP_UID_ATTR: "{{ LDAP.USER.ATTRIBUTES.ID }}"
KIX_LDAP_ADMINISTRATOR_GROUP_DN: "cn={{ application_id }}-administrator,{{ LDAP.DN.OU.ROLES }}"
KIX_LDAP_USER_GROUP_DN: "cn={{ application_id }}-user,{{ LDAP.DN.OU.ROLES }}"
KIX_LDAP_UID_ATTR: "{{ lookup('config', application_id, 'services.kix.ldap.uid') }}"
KIX_LDAP_ADMINISTRATOR_GROUP_DN: "{{ lookup('config', application_id, 'services.kix.ldap.administrator_group_dn') }}"
KIX_LDAP_USER_GROUP_DN: "{{ lookup('config', application_id, 'services.kix.ldap.user_group_dn') }}"
KIX_ROLE_SUPERUSER: "Superuser"
KIX_ROLE_AGENT: "Ticket Agent"
KIX_LDAP_CONTACT_SYNC:
@@ -82,7 +79,41 @@ KIX_LDAP_SYNC:
ContactUserSync: "{{ KIX_LDAP_CONTACT_SYNC }}"
GroupDNBasedRoleSync: "{{ KIX_LDAP_ROLE_SYNC }}"
GroupDNBasedUsageContextSync: "{{ KIX_LDAP_USAGE_CONTEXT_SYNC }}"
KIX_LDAP_BACKEND_CONFIG:
Host: "{{ KIX_LDAP_SETTINGS.host }}"
Params:
async: 0
port: "{{ KIX_LDAP_SETTINGS.port | int }}"
timeout: 10
version: 3
BaseDN: "{{ KIX_LDAP_SETTINGS.base_dn }}"
AlwaysFilter: "(objectclass=inetOrgPerson)"
Charset: "utf-8"
SearchUserDN: "{{ KIX_LDAP_SETTINGS.search_user_dn }}"
SearchUserPw: "{{ KIX_LDAP_BIND_PW }}"
AccessAttr: "{{ KIX_LDAP_SETTINGS.access_attr }}"
UID: "{{ KIX_LDAP_SETTINGS.uid }}"
UserAttr: "DN"
AuthAttr: "{{ KIX_LDAP_SETTINGS.uid }}"
UserSuffix: ""
Debug: 1
KIX_LDAP_AUTHENTICATION:
"Authentication###100-Infinito-LDAP":
- Name: "{{ SOFTWARE_NAME }} svc-db-openldap (Agent, web-app-kix-administrator)"
Enabled: 1
UsageContext: "Agent"
Module: "Kernel::System::Auth::LDAP"
Config: "{{ KIX_LDAP_BACKEND_CONFIG | combine({'GroupDN': KIX_LDAP_SETTINGS.administrator_group_dn}) }}"
Sync: "{{ KIX_LDAP_SYNC }}"
"Authentication###200-Infinito-LDAP-User":
- Name: "{{ SOFTWARE_NAME }} svc-db-openldap (Agent, web-app-kix-user)"
Enabled: 1
UsageContext: "Agent"
Module: "Kernel::System::Auth::LDAP"
Config: "{{ KIX_LDAP_BACKEND_CONFIG | combine({'GroupDN': KIX_LDAP_SETTINGS.user_group_dn}) }}"
Sync: "{{ KIX_LDAP_SYNC }}"
KIX_AUTH_LDAP_HOST_PATH: "{{ lookup('container', application_id, 'directories.volumes') }}auth_ldap.xml"
KIX_AUTH_LDAP_LOCK_HOST_PATH: "{{ lookup('container', application_id, 'directories.volumes') }}auth_ldap.conf"
KIX_PROXY_NGINX_HOST_PATH: "{{ lookup('container', application_id, 'directories.volumes') }}kix-proxy.default.conf"
@@ -0,0 +1,5 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]
__all__ = ["PROJECT_ROOT"]
@@ -0,0 +1,202 @@
from __future__ import annotations
import base64
import importlib.util
import json
import shutil
import subprocess
import unittest
import xml.etree.ElementTree as ET
from pathlib import PurePosixPath
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar
from utils.cache.yaml import load_yaml_any
from utils.templating.ansible import _trust_as_template
from . import PROJECT_ROOT
ROLE = PROJECT_ROOT / "roles" / "web-app-kix"
FORMS = ROLE / "meta" / "forms.yml"
VOLUMES = ROLE / "meta" / "volumes.yml"
VARS = ROLE / "vars" / "main.yml"
TASKS = ROLE / "tasks" / "00_core.yml"
LOCK_TEMPLATE = ROLE / "templates" / "auth_ldap.conf.j2"
XML_TEMPLATE = ROLE / "templates" / "zzz_auth_ldap.xml.j2"
FILTER = ROLE / "filter_plugins" / "kix_ldap_lock.py"
SINK = "KIX_LDAP_SETTINGS"
DRIFT = "tasks/utils/forms/drift.yml"
ADMINISTRATOR = "Authentication###100-Infinito-LDAP"
USER = "Authentication###200-Infinito-LDAP-User"
KIX_LOCAL_CONFIG_DIR = PurePosixPath("/opt/kix/config")
PROBE_SECRET = "probe'pw\\with$specials"
SETTINGS = {
"host": "ldap.example",
"port": 636,
"base_dn": "ou=users,dc=example",
"search_user_dn": "cn=administrator,dc=example",
"uid": "uid",
"access_attr": "member",
"administrator_group_dn": "cn=web-app-kix-administrator,ou=roles,dc=example",
"user_group_dn": "cn=web-app-kix-user,ou=roles,dc=example",
}
SYNC = [{"Enabled": 1, "Module": "Kernel::System::Auth::Sync::LDAP", "Config": {}}]
GETLOCALCONFIG = (
"my $Content = do { local $/; <STDIN> };"
' my %Hash = eval "($Content)"; die $@ if $@;'
" print JSON::PP->new->canonical->encode(\\%Hash);"
)
def _filter():
spec = importlib.util.spec_from_file_location("kix_ldap_lock", FILTER)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module.kix_ldap_lock_fields
def _render(path) -> str:
variables = DataLoader().load_from_file(str(VARS), trusted_as_template=True)
variables.update(
{
SINK: SETTINGS,
"KIX_LDAP_BIND_PW": PROBE_SECRET,
"KIX_LDAP_SYNC": SYNC,
"SOFTWARE_NAME": "Infinito.Nexus",
}
)
templar = Templar(loader=DataLoader(), variables=variables)
return templar.template(_trust_as_template(path.read_text(encoding="utf-8")))
def _tasks() -> list[dict]:
return DataLoader().load_from_file(str(TASKS), trusted_as_template=True)
def _index(tasks: list[dict], predicate) -> int:
return next(index for index, task in enumerate(tasks) if predicate(task))
class TestTheLockedFileCarriesTheSink(unittest.TestCase):
def test_each_backend_takes_its_managed_fields_from_the_sink(self) -> None:
held = json.loads(
base64.b64decode(
_render(LOCK_TEMPLATE).split("decode_base64('")[1].split("'")[0]
)
)
administrator = held[ADMINISTRATOR][0]["Config"]
self.assertEqual(SETTINGS["host"], administrator["Host"])
self.assertEqual(SETTINGS["port"], administrator["Params"]["port"])
self.assertEqual(SETTINGS["uid"], administrator["AuthAttr"])
self.assertEqual(SETTINGS["administrator_group_dn"], administrator["GroupDN"])
self.assertEqual(SETTINGS["user_group_dn"], held[USER][0]["Config"]["GroupDN"])
self.assertEqual(PROBE_SECRET, administrator["SearchUserPw"])
def test_the_read_returns_exactly_what_the_write_put_in(self) -> None:
rendered = _render(LOCK_TEMPLATE).encode("utf-8")
fields = _filter()({"content": base64.b64encode(rendered).decode("ascii")})
self.assertEqual(SETTINGS, fields)
self.assertNotIn(PROBE_SECRET, json.dumps(fields))
def test_a_missing_or_foreign_file_reports_no_field(self) -> None:
read = _filter()
foreign = base64.b64encode(b"('Foo' => 1)").decode("ascii")
for slurped in ({"failed": True}, {"content": ""}, {"content": foreign}):
with self.subTest(slurped=slurped):
self.assertEqual({}, read(slurped))
@unittest.skipIf(shutil.which("perl") is None, "perl is not installed")
def test_kix_reads_the_file_as_its_local_config(self) -> None:
result = subprocess.run(
["perl", "-MJSON::PP", "-e", GETLOCALCONFIG],
input=_render(LOCK_TEMPLATE),
capture_output=True,
text=True,
check=False,
)
self.assertEqual(0, result.returncode, result.stderr)
held = json.loads(result.stdout)
self.assertEqual({ADMINISTRATOR, USER}, set(held))
self.assertEqual(PROBE_SECRET, held[ADMINISTRATOR][0]["Config"]["SearchUserPw"])
self.assertEqual(
SETTINGS["port"], held[ADMINISTRATOR][0]["Config"]["Params"]["port"]
)
def test_the_xml_default_holds_the_same_backends(self) -> None:
root = ET.fromstring(_render(XML_TEMPLATE)) # noqa: S314 - parses the role's own template rendered from test values, no untrusted input
locked = json.loads(
base64.b64decode(
_render(LOCK_TEMPLATE).split("decode_base64('")[1].split("'")[0]
)
)
for item in root.iter("ConfigItem"):
with self.subTest(option=item.get("Name")):
self.assertEqual(
locked[item.get("Name")],
json.loads(item.find("Setting/Object").text),
)
class TestTheFormIsLockedByKix(unittest.TestCase):
def test_the_form_is_native_and_names_every_field_the_read_returns(self) -> None:
form = load_yaml_any(str(FORMS))["ldap"]
self.assertIs(True, form["native"])
self.assertEqual([SINK], form["sinks"])
self.assertEqual(set(SETTINGS), set(form["fields"]))
for field, spec in form["fields"].items():
with self.subTest(field=field):
self.assertEqual("services.ldap.enabled", spec["when"])
def test_the_sink_reads_only_its_form(self) -> None:
self.assertEqual(
"{{ lookup('form_values', application_id, 'ldap') }}",
load_yaml_any(str(VARS))[SINK],
)
def test_the_file_lands_in_the_local_config_kix_marks_read_only(self) -> None:
lock = load_yaml_any(str(VOLUMES))["auth_ldap_lock"]
(mount,) = lock["mounts"]
self.assertEqual("backend", mount["service"])
self.assertEqual(KIX_LOCAL_CONFIG_DIR, PurePosixPath(mount["target"]).parent)
self.assertIn("'auth_ldap.conf'", lock["source"])
class TestTheDeployReportsBeforeItWrites(unittest.TestCase):
def test_the_file_is_read_and_reported_before_it_is_rendered(self) -> None:
tasks = _tasks()
read = _index(
tasks,
lambda task: (
"KIX_AUTH_LDAP_LOCK_HOST_PATH"
in str(task.get("ansible.builtin.slurp", {}))
),
)
report = _index(
tasks,
lambda task: DRIFT in str(task.get("ansible.builtin.include_tasks", "")),
)
render = _index(
tasks,
lambda task: any(
entry.get("src") == LOCK_TEMPLATE.name
for entry in task.get("vars", {}).get("role_templates", [])
),
)
self.assertLess(read, report)
self.assertLess(report, render)
def test_the_report_reads_the_fields_of_the_locked_file(self) -> None:
report = next(
task
for task in _tasks()
if DRIFT in str(task.get("ansible.builtin.include_tasks", ""))
)
self.assertEqual(
"{{ kix_ldap_lock_stored | kix_ldap_lock_fields }}",
report["vars"]["forms_drift_current"]["ldap"],
)
if __name__ == "__main__":
unittest.main()