diff --git a/ansible/host/roles/netbird/defaults/main.yml b/ansible/host/roles/netbird/defaults/main.yml index 1a270cc9..fcdc216f 100644 --- a/ansible/host/roles/netbird/defaults/main.yml +++ b/ansible/host/roles/netbird/defaults/main.yml @@ -19,5 +19,12 @@ netbird_management_url: "" # the peer re-ups from its stored config, no setup key involved. netbird_unattended_upgrades: true +# NetBird's interface, whose name its daemon registers the overlay's resolver +# under with resolvconf, and which the role ranks first where resolvconf +# writes /etc/resolv.conf (tasks/resolvconf.yml). NetBird's own default; the +# role does not change it, and a host on which `netbird up --interface-name` +# did sets the same name here. +netbird_interface: wt0 + # Opt-in: the shipped playbooks run this role only where it is true. netbird_enabled: false diff --git a/ansible/host/roles/netbird/tasks/main.yml b/ansible/host/roles/netbird/tasks/main.yml index 66ce73f3..65a4301c 100644 --- a/ansible/host/roles/netbird/tasks/main.yml +++ b/ansible/host/roles/netbird/tasks/main.yml @@ -30,6 +30,11 @@ }; when: netbird_unattended_upgrades +# Before the daemon starts, so that a host that joins below registers its +# resolver into the order already. +- name: Put the overlay's resolver ahead of the provider's where resolvconf writes resolv.conf + ansible.builtin.import_tasks: resolvconf.yml + - name: Enable and start the NetBird daemon ansible.builtin.systemd_service: name: netbird diff --git a/ansible/host/roles/netbird/tasks/resolvconf.yml b/ansible/host/roles/netbird/tasks/resolvconf.yml new file mode 100644 index 00000000..b76ea180 --- /dev/null +++ b/ansible/host/roles/netbird/tasks/resolvconf.yml @@ -0,0 +1,52 @@ +--- +# The overlay's resolver first, where Debian's resolvconf writes +# /etc/resolv.conf. NetBird's daemon registers its resolver and the overlay's +# search domain as the record of its interface; resolvconf writes at most +# three nameservers, in the order of /etc/resolvconf/interface-order, whose +# patterns name br*, en*, eth*, wl* and others but not NetBird's interface, +# which only the last line, *, matches. A provider whose interface brings +# three or more nameservers therefore cuts the overlay's resolver off, and no +# overlay name resolves. Ranked first, the resolver answers the overlay's +# zones and forwards every other name to the nameservers /etc/resolv.conf +# held when the daemon started; a daemon that stops takes its record with it. +# +# resolvconf writes the file where /etc/resolv.conf links to its own, as its +# package links it on installation; anywhere else, systemd-resolved's stub, +# NetworkManager's file, a file by hand, nothing here runs. Without +# interface-order resolvconf takes a built-in list, which the role does not +# write out, and nothing here runs either. +# +# interface-order is a conffile of resolvconf, so the role adds its line +# above the package's and leaves the rest as it is: an upgrade keeps the +# file, and where a new version of the package changes it, dpkg asks, and +# unattended-upgrades holds the package back for a person. A person who takes +# the package's file drops the line until the next run writes it again. +- name: Find whether resolvconf writes /etc/resolv.conf + ansible.builtin.stat: + path: /etc/resolv.conf + register: netbird_resolv_conf + +- name: Find resolvconf's interface order + ansible.builtin.stat: + path: /etc/resolvconf/interface-order + register: netbird_interface_order + +- name: Rank the overlay's resolver first + ansible.builtin.blockinfile: + path: /etc/resolvconf/interface-order + insertbefore: BOF + marker: "# {mark} plexus.host.netbird: the overlay's resolver first" + block: "{{ netbird_interface }}" + when: + - netbird_resolv_conf.stat.lnk_source | default('') == '/run/resolvconf/resolv.conf' + - netbird_interface_order.stat.exists + register: netbird_ranked + +# A task, not a handler: a record already registered moves within this run, +# before the play's next task, and the flush a handler would need here, this +# early in the play, would run every other role's pending handler with it. +- name: Have resolvconf write resolv.conf in the new order + ansible.builtin.command: + cmd: resolvconf -u + when: netbird_ranked is changed # noqa: no-handler + changed_when: true diff --git a/newborns/netbird-resolvconf.test.ts b/newborns/netbird-resolvconf.test.ts new file mode 100644 index 00000000..6f9cae84 --- /dev/null +++ b/newborns/netbird-resolvconf.test.ts @@ -0,0 +1,317 @@ +// Where Debian's resolvconf writes /etc/resolv.conf, the netbird role of +// plexus.host ranks the overlay's resolver first. The host is a container of +// the stock Debian image with Debian's resolvconf installed as a machine +// image has it, /etc/resolv.conf its link; its interface eth0 registers four +// nameservers, two per address family, as a provider's does, and NetBird's +// record wt0 holds the overlay's resolver and its search domain, as the +// daemon registers them. Without the role, resolvconf writes three +// nameservers, all of them the provider's, and no overlay name resolves. +// +// The role's task file runs on the host as the role runs it, and the role +// runs it before it starts NetBird's daemon. After a run the overlay's +// resolver is the first nameserver and its domain the first of the search +// list, whether NetBird registered before the run or registers after it, +// under the interface the role is told; the rest of interface-order is the +// package's, and a second run changes nothing. The file is written again +// within the run, before the play's next task, and no handler another role +// notified earlier in the play runs for it. Where +// the package's interface-order comes back, as when a person takes the file of +// a new version, the next run ranks the overlay's resolver first again. Where +// /etc/resolv.conf is not resolvconf's, a link to systemd-resolved's stub or a +// file of its own as NetworkManager writes one, and where interface-order is +// missing, a run passes and changes nothing. Needs Docker and the network to +// build the host's image, as the newborns do; nothing reaches a real overlay. +import assert from 'node:assert/strict'; +import { join } from 'node:path'; +import { after, before, describe, test } from 'node:test'; +import { close, open, put, sh, tryRun } from './helpers.ts'; + +const WORKSPACE = join(import.meta.dirname, '..'); +/** Debian with Ansible from Debian, and resolvconf's package at hand: installed in a build, it cannot link a file Docker mounts. */ +const IMAGE = 'plx-newborn-netbird-resolvconf:trixie'; +const DOCKERFILE = `FROM debian:trixie +RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ansible \\ + && cd /root && apt-get download resolvconf && rm -rf /var/lib/apt/lists/* +`; +/** The role's task file, as its main file runs it. */ +const PLAY = `- name: The overlay's resolver + hosts: localhost + connection: local + gather_facts: false + tasks: + - name: The netbird role's ranking + ansible.builtin.include_role: + name: plexus.host.netbird + tasks_from: resolvconf +`; +/** + * The task file between a task of an earlier role that notifies a handler + * and tasks that read what the ranking left: the overlay's resolver leads at + * once, and the earlier role's handler has not run. + */ +const WITHIN = `- name: The overlay's resolver within one play + hosts: localhost + connection: local + gather_facts: false + handlers: + - name: Mark that the earlier role's handler ran + ansible.builtin.file: + path: /root/handler-ran + state: touch + mode: "0644" + tasks: + - name: A task of an earlier role that notifies its handler + ansible.builtin.command: "true" + changed_when: true + notify: Mark that the earlier role's handler ran + - name: The netbird role's ranking + ansible.builtin.include_role: + name: plexus.host.netbird + tasks_from: resolvconf + - name: Read resolv.conf + ansible.builtin.command: cat /etc/resolv.conf + register: read + changed_when: false + - name: The overlay's resolver leads already + ansible.builtin.assert: + that: (read.stdout_lines | select('match', '^nameserver') | first).split()[1] == overlay + fail_msg: resolv.conf is not written again within the run + - name: Find whether the earlier role's handler ran + ansible.builtin.stat: + path: /root/handler-ran + register: mark + - name: The earlier role's handler has not run + ansible.builtin.assert: + that: not mark.stat.exists + fail_msg: a handler of another role ran at the netbird role +`; +/** The whole role, to list what it runs. */ +const ROLE = `- name: The netbird role + hosts: localhost + connection: local + gather_facts: false + roles: + - plexus.host.netbird +`; +const OVERLAY = '100.64.0.53'; +const DOMAIN = 'example.internal'; +/** The provider's nameservers, by the record resolvconf keeps them under. */ +const PROVIDER: Record = { + 'eth0.inet6': ['2001:db8::1', '2001:db8::2'], + 'eth0.dhcp': ['192.0.2.1', '192.0.2.2'], +}; +const ORDER = '/etc/resolvconf/interface-order'; +/** The package's interface-order, kept before any run. */ +const PACKAGED = '/root/interface-order.packaged'; + +let here = ''; +let host = ''; + +const onHost = (...command: string[]) => sh('docker', ['exec', host, ...command], here); +const shellOnHost = (line: string) => onHost('sh', '-c', line); + +/** Registers a record with resolvconf, as a DHCP client or NetBird's daemon does. */ +const register = (record: string, lines: string[]) => + shellOnHost(`printf '%s\\n' ${lines.map((line) => `'${line}'`).join(' ')} | resolvconf -a ${record}`); +const registerOverlay = (record = 'wt0') => register(record, [`search ${DOMAIN}`, `nameserver ${OVERLAY}`]); + +/** One run of a play on the host; unfailing. */ +function play(file: string, extra: Record = {}, args: string[] = []) { + return tryRun( + 'docker', + [ + 'exec', + host, + 'env', + 'ANSIBLE_COLLECTIONS_PATH=/collections', + 'ANSIBLE_NOCOLOR=1', + 'ansible-playbook', + '-i', + 'localhost,', + `/play/${file}`, + '-e', + JSON.stringify(extra), + ...args, + ], + here, + ); +} +/** The count of changed tasks in a run's recap. */ +const changed = (output: string) => Number(/^localhost\s+:.*\bchanged=(\d+)/m.exec(output)?.[1] ?? Number.NaN); + +/** The nameservers and the search list of /etc/resolv.conf, in order. */ +async function resolver(): Promise<{ nameservers: string[]; search: string[] }> { + const lines = (await onHost('cat', '/etc/resolv.conf')).split('\n'); + return { + nameservers: lines.flatMap((line) => /^nameserver\s+(\S+)/.exec(line)?.[1] ?? []), + search: + lines + .find((line) => /^search\s/.test(line)) + ?.split(/\s+/) + .slice(1) ?? [], + }; +} + +before(async () => { + here = await open('netbird-resolvconf', { registry: false }); + put(here, { + 'image/Dockerfile': DOCKERFILE, + 'play/resolvconf.yml': PLAY, + 'play/within.yml': WITHIN, + 'play/role.yml': ROLE, + }); + await sh('docker', ['build', '-q', '-t', IMAGE, join(here, 'image')], here); + const started = ( + await sh( + 'docker', + [ + 'run', + '-d', + '--rm', + '--name', + `plx-newborn-${process.pid}-netbird-resolvconf`, + // To unmount the resolv.conf Docker mounts, so that resolvconf's package can link its own; nothing else. + '--cap-add', + 'SYS_ADMIN', + '-v', + `${join(WORKSPACE, 'ansible')}:/collections/ansible_collections/plexus:ro`, + '-v', + `${join(here, 'play')}:/play:ro`, + IMAGE, + 'sleep', + 'infinity', + ], + here, + ) + ).match(/^[0-9a-f]{64}$/m); + host = started?.[0] ?? ''; + if (!host) throw new Error('docker run printed no container id'); + await shellOnHost( + `umount /etc/resolv.conf && DEBIAN_FRONTEND=noninteractive dpkg -i /root/resolvconf_*.deb && cp ${ORDER} ${PACKAGED}`, + ); + // The package keeps the file it replaced as a record of its own; a machine image has none. + await onHost('resolvconf', '-d', 'original.resolvconf'); + for (const [record, nameservers] of Object.entries(PROVIDER)) + await register( + record, + nameservers.map((address) => `nameserver ${address}`), + ); +}); + +after(async () => { + if (host) await tryRun('docker', ['rm', '-f', '-v', host], here); + await close(); +}); + +describe('the netbird role ranks the overlay’s resolver first where resolvconf writes resolv.conf', () => { + test('the host as found: resolvconf writes the provider’s three, and the overlay’s resolver is cut off', async () => { + assert.match(await onHost('readlink', '-f', '/etc/resolv.conf'), /^\/run\/resolvconf\/resolv\.conf$/m); + await registerOverlay(); + const found = await resolver(); + assert.equal(found.nameservers.length, 3); + assert.equal(found.nameservers.includes(OVERLAY), false); + }); + + test('the role runs the ranking, before it starts NetBird’s daemon', async () => { + const listed = await play('role.yml', {}, ['--list-tasks']); + assert.equal(listed.ok, true, listed.output.slice(-6000)); + const tasks = listed.output.split('\n'); + const at = (name: string) => + tasks.findIndex((line) => new RegExp(`plexus\\.host\\.netbird : ${name}\\s+TAGS:`).test(line)); + const ranking = at("Rank the overlay's resolver first"); + const daemon = at('Enable and start the NetBird daemon'); + assert.ok(ranking >= 0, `the ranking is not listed:\n${listed.output}`); + assert.ok(daemon >= 0, `the daemon's start is not listed:\n${listed.output}`); + assert.ok(ranking < daemon, `the ranking is listed after the daemon's start:\n${listed.output}`); + }); + + test('a run ranks a record NetBird registered before it first: its resolver and its domain lead, and the rest of interface-order is the package’s', async () => { + const ran = await play('resolvconf.yml'); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + const found = await resolver(); + assert.equal(found.nameservers[0], OVERLAY); + assert.deepEqual(found.nameservers.slice(1), (PROVIDER['eth0.inet6'] ?? []).slice(0, 2)); + assert.equal(found.search[0], DOMAIN); + const order = await onHost('cat', ORDER); + const packaged = await onHost('cat', PACKAGED); + assert.ok(order.endsWith(packaged), 'the package’s lines follow, unchanged'); + const added = order + .slice(0, order.length - packaged.length) + .split('\n') + .filter(Boolean); + assert.deepEqual( + added.filter((line) => !line.startsWith('#')), + ['wt0'], + ); + }); + + test('a second run changes nothing', async () => { + const ran = await play('resolvconf.yml'); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal(changed(ran.output), 0, ran.output.slice(-3000)); + }); + + test('within the run: the file is written again before the play’s next task, and no handler of another role runs early', async () => { + await shellOnHost(`cp ${PACKAGED} ${ORDER} && resolvconf -u && rm -f /root/handler-ran`); + assert.equal((await resolver()).nameservers.includes(OVERLAY), false); + const ran = await play('within.yml', { overlay: OVERLAY }); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal((await resolver()).nameservers[0], OVERLAY); + }); + + test('a record NetBird registers after the run leads too', async () => { + await onHost('resolvconf', '-d', 'wt0'); + assert.equal((await resolver()).nameservers.includes(OVERLAY), false); + await registerOverlay(); + assert.equal((await resolver()).nameservers[0], OVERLAY); + }); + + test('the interface the role is told is the one ranked', async () => { + await onHost('resolvconf', '-d', 'wt0'); + await registerOverlay('nb7'); + try { + assert.equal((await resolver()).nameservers.includes(OVERLAY), false); + const ran = await play('resolvconf.yml', { netbird_interface: 'nb7' }); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal((await resolver()).nameservers[0], OVERLAY); + } finally { + await onHost('resolvconf', '-d', 'nb7'); + await play('resolvconf.yml'); + await registerOverlay(); + } + }); + + test('where the package’s interface-order comes back, the next run ranks the overlay’s resolver first again', async () => { + await shellOnHost(`cp ${PACKAGED} ${ORDER} && resolvconf -u`); + assert.equal((await resolver()).nameservers.includes(OVERLAY), false); + const ran = await play('resolvconf.yml'); + assert.equal(ran.ok, true, ran.output.slice(-6000)); + assert.equal((await resolver()).nameservers[0], OVERLAY); + }); + + test('where resolv.conf is not resolvconf’s, or interface-order is missing, a run passes and changes nothing', async () => { + /** What a run could change: where resolv.conf links to, what it holds, and interface-order. */ + const state = () => + shellOnHost( + `readlink /etc/resolv.conf; cat /etc/resolv.conf; cat ${ORDER} 2>/dev/null || echo no interface-order`, + ); + const hosts: Record = { + 'systemd-resolved’s stub': `mkdir -p /run/systemd/resolve && printf 'nameserver 127.0.0.53\\n' >/run/systemd/resolve/stub-resolv.conf && ln -sfn ../run/systemd/resolve/stub-resolv.conf /etc/resolv.conf`, + 'a file of its own, as NetworkManager writes one': `rm /etc/resolv.conf && printf '# Generated by NetworkManager\\nnameserver 192.0.2.53\\n' >/etc/resolv.conf`, + 'resolvconf’s link, and no interface-order': `mv ${ORDER} /root/interface-order.away`, + }; + const link = 'ln -sfn ../run/resolvconf/resolv.conf /etc/resolv.conf'; + try { + for (const [name, setUp] of Object.entries(hosts)) { + await shellOnHost(`${link} && cp ${PACKAGED} ${ORDER} && ${setUp}`); + const before = await state(); + const ran = await play('resolvconf.yml'); + assert.equal(ran.ok, true, `${name}: ${ran.output.slice(-6000)}`); + assert.equal(changed(ran.output), 0, `${name}: ${ran.output.slice(-3000)}`); + assert.equal(await state(), before, name); + } + } finally { + await shellOnHost(`${link} && cp ${PACKAGED} ${ORDER}`); + } + }); +});