Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

ndac (NextDNS-as-Code) manages NextDNS profiles declaratively. Desired state lives in TOML files, live state comes from the NextDNS API, and the difference between the two is the plan.

Start with Installation, then Configuration. The examples directory has complete configuration repositories: minimal (one profile), multi-profile (templates shared by several profiles) and paranoid (strict protection, no logs), plus the GitHub Actions workflow described in CI recipes.

Installation

Each GitHub release of ndac provides:

  • archives for Linux (x86_64 and aarch64, glibc and static musl) and macOS (x86_64 and Apple silicon), with shell completions, the man page and, on Linux, the systemd units;
  • .deb and .rpm packages of the static Linux binary;
  • a container image, ghcr.io/esl1h/ndac;
  • SHA256SUMS, signed with cosign, a CycloneDX SBOM, and build provenance attestations for every file.

Archives

version=0.1.0
target=x86_64-unknown-linux-musl
curl -fsSLO "https://github.com/Esl1h/ndac/releases/download/v$version/ndac-$version-$target.tar.gz"
gh attestation verify "ndac-$version-$target.tar.gz" --repo Esl1h/ndac
tar -xzf "ndac-$version-$target.tar.gz"
install -m 0755 "ndac-$version-$target/ndac" ~/.local/bin/

The musl builds are static and run on any Linux distribution. See Shell completions and man page for the extra files.

Packages

  • Debian and Ubuntu: sudo apt install ./ndac_0.1.0-1_amd64.deb
  • Fedora and RHEL: sudo dnf install ./ndac-0.1.0-1.x86_64.rpm, or from the COPR repository when it is enabled
  • Arch Linux: the AUR package ndac-bin, when it is published
  • From source: cargo install --locked ndac

Packages install the binary, completions, the man page and the systemd units; no unit is enabled.

Container

docker run --rm -v "$PWD:/work" -e NEXTDNS_API_KEY ghcr.io/esl1h/ndac:v0.1.0 plan

The image contains only the static binary and CA certificates, and runs as a non-root user in /work. Verify it with gh attestation verify oci://ghcr.io/esl1h/ndac:v0.1.0 --repo Esl1h/ndac or with cosign verify (see the maintainer guide).

Scheduled drift checks with systemd

ndac-drift.service and ndac-drift.timer run ndac drift --format prom every hour and write /var/lib/ndac/ndac_drift.prom for the node_exporter textfile collector (--collector.textfile.directory). The service runs as a dynamic user with a strict sandbox and reads the API key from an encrypted systemd credential:

sudo install -d /etc/credstore.encrypted
printf '%s' "$KEY" | sudo systemd-creds encrypt --name=nextdns-api-key - \
  /etc/credstore.encrypted/nextdns-api-key
sudo systemctl enable --now ndac-drift.timer

It expects the configuration repository in /etc/ndac, readable by any user. Drift is measured against the post-apply snapshots, so the snapshot directory must hold the snapshots of the machine or pipeline that applies the configuration, readable by the service.

Configuration

Files

  • ndac.toml is the root file. ndac uses --config PATH, then NDAC_CONFIG, then the nearest ndac.toml in the working directory or a parent directory.
  • include lists globs, relative to the root directory, of template and profile files. Matches are sorted. Absolute patterns, .. and files or symlinks resolving outside the root directory are rejected. Hidden directories and target/ are skipped.
  • Files under templates/ are templates; every other included file is a profile. The file stem is the key: profiles/casa.toml is profile casa. Keys must be unique among templates and among profiles.
  • ndac.local.toml, next to ndac.toml, is loaded automatically when it exists. It may only contain [provider], [auth] and [output], which override the root file. Keep it out of git; ndac init adds it to .gitignore.
  • The user file, $XDG_CONFIG_HOME/ndac/config.toml (or ~/.config/ndac/config.toml, on every platform), holds personal defaults for all configuration directories. It may only contain [auth] and [output]; ndac.local.toml and ndac.toml override it.

Editors get completion and validation from the JSON Schemas in schema/ (ndac.schema.json for the root file, ndac-profile.schema.json for profiles and templates). ndac schema --kind root|local|profile|user prints them.

Output

[output].color is auto (the default), always or never. --color overrides it; otherwise ndac.local.toml, ndac.toml and the user file are read in that order. In auto mode, NO_COLOR, CLICOLOR_FORCE and TERM=dumb are honored.

Profiles and templates

A profile or template file is the profile itself, using the API’s camelCase names:

id      = "abc123"            # empty or absent: created on apply
name    = "Casa"
extends = ["base", "paranoid"]
ignore  = ["parentalControl.services"]

[settings.logs]
retention = "90d"

[parentalControl]
safeSearch = true
categories = { gambling = true, porn = true }

[denylist]
mode = "authoritative"

[denylist.items]
"tiktokv.com" = true
"foo.example" = false   # present but inactive

Fields left out are not managed: ndac never changes them.

id, name, ignore, auth, endpoint and list mode are profile-only; a template that sets them is rejected. [endpoint] is never sent to NextDNS; it only feeds ndac endpoint render (see Endpoints and doctor).

How extends merges

A profile resolves by applying layers, in order, onto an empty profile:

  1. each template listed in extends, where a template’s own extends is applied just before it (recursively);
  2. the profile itself.

Each layer merges onto the result of the layers before it:

  • Tables merge recursively.
  • Scalars: the last layer that sets a value wins.
  • ID arrays (security.tlds, privacy.blocklists, privacy.natives) replace the inherited array. An entry "$inherit" expands to the inherited array at that position. Duplicates keep their first occurrence.
  • Item maps (denylist.items, allowlist.items, parentalControl.services, parentalControl.categories) merge by key. The value "$remove" deletes an inherited key.
  • id, name, ignore, auth, endpoint and list mode are never inherited.

Because templates are layers, a template can use "$inherit" or "$remove" against whatever is stacked before it. With extends = ["base", "paranoid"] and blocklists = ["$inherit", "hagezi-pro"] in paranoid, the result is base’s blocklists plus hagezi-pro. A profile without extends cannot use the markers.

Cycles (a extends b extends a) and unknown templates are errors.

Normalization

ndac render <profile> prints the canonical desired state that plan compares with the live profile:

  • durations become seconds ("30d" is 2592000; units s, m, h, d, w and y = 365 days, combinable as in "1h30m");
  • domains become lowercase punycode without a trailing dot, so Example.com. and example.com are the same entry (and a duplicate if both are listed);
  • ID arrays become [{ id }] and item maps [{ id, active }], sorted by ID. List order is assumed not to matter to NextDNS.

List modes

denylist and allowlist take a mode:

  • authoritative (default): the configured items are the whole list; live items that are not configured are removed.
  • merge: only the configured items are managed; other live items are left alone.

ID arrays and the parental control maps are always authoritative. Use ignore to leave one of them unmanaged.

Formatting

ndac fmt sorts ID arrays (with "$inherit" first) and item maps, aligns = within each table, and ends files with one newline. It never changes values or drops comments, and keeps file permissions. ndac fmt --check lists files that need formatting and exits with 1.

Authentication

ndac needs a NextDNS API key, found at the bottom of the account page. The key gives access to the whole account, including DNS logs, so ndac never takes it as a command-line argument and never prints it.

Sources

[auth].sources lists where to look, in order; the first source that yields a key wins.

ReferenceReadsNotes
systemd-cred:NAME$CREDENTIALS_DIRECTORY/NAMEBest for services: LoadCredentialEncrypted= keeps the key encrypted at rest.
keyring:SERVICE/USEROS keyringSecret Service (GNOME Keyring, KWallet) or macOS Keychain. Store with ndac auth set --backend keyring.
cmd:PROGRAM ARGSfirst line of the program’s outputFor password managers: cmd:pass show nextdns/api-key, cmd:gopass show -o nextdns. Runs without a shell, with a cleared environment, inherited stdin (for pinentry or a security-key touch), and a timeout.
age:PATHfile decrypted with ageBuild feature age. Uses the age binary with NDAC_AGE_IDENTITY, so plugins such as age-plugin-yubikey work.
env-file:VARfile named by $VARDocker and Kubernetes secrets convention.
file:PATHa fileTrailing newline trimmed.
env:VARan environment variableConvenient in CI; visible to anything that can read the environment.
dotenv[:PATH]NEXTDNS_API_KEY in a .env fileDefault search: ./.env, then next to ndac.toml. Guardrails apply.
configapi_key in [auth]ndac.local.toml first, then ndac.toml, then the profile file, then the user file. Guardrails apply.

The table is roughly ordered from most to least protected at rest.

Resolution order

  1. --auth-source REF (repeatable or comma-separated), or NDAC_AUTH_SOURCE.
  2. The profile’s [auth].sources, for commands that act on that profile (for example a profile in a separate NextDNS account).
  3. [auth].sources from ndac.local.toml, then ndac.toml.
  4. [auth].sources from the user file (see Configuration).
  5. The default chain: systemd-cred:nextdns-api-key, env-file:NEXTDNS_API_KEY_FILE, env:NEXTDNS_API_KEY, dotenv, keyring:nextdns/default, config.

A source that is not present (unset variable, absent file, no keyring entry, no keyring service on the machine) is skipped. A source that exists but fails (unreadable file, command exiting non-zero, locked keyring) stops resolution with exit code 3, unless on_source_error = "skip".

Literal keys

A literal key in ndac.local.toml, ndac.toml, a profile file, the user file or .env is allowed, with guardrails:

  • the file must be readable only by its owner, who must be the current user. Fix with chmod 600. allow_insecure_permissions = true in ndac.local.toml or the user file (or NDAC_ALLOW_INSECURE_PERMISSIONS=1) turns the error into a warning;
  • the file must not be tracked by git, and inside a work tree it must be ignored. --allow-tracked-secret overrides this for one run;
  • a warning names the file on every run; quiet_literal = true silences it.

Commands

  • ndac auth check [--profile P] resolves the key, then lists the profiles it can reach. It prints the source, never the key.
  • ndac auth sources [--profile P] shows the chain, where it came from, and the status of each source.
  • ndac auth set --backend keyring|config|file stores a key typed at a hidden prompt, or read from stdin when it is not a terminal. config writes ndac.local.toml with mode 0600 and adds it to .gitignore.

Why there is no --api-key

Command-line arguments of every process are readable by other users through /proc/<pid>/cmdline and ps, and are saved in shell history. Environment variables and files with private permissions do not have these problems.

Plan and drift

ndac plan compares the desired state of each profile with its live state and prints what ndac apply would change. It never writes anything.

profile "casa" (abc123)
  ~ privacy.blocklists
      + hagezi-pro
  ~ settings.logs.retention: 7776000 → 2592000 (90d → 30d)
  ! denylist                                     [drift]
      - foo.example   (live only; authoritative → will be removed)

profile "trabalho" (def456): no changes

Plan: 1 to add, 1 to change, 1 to remove across 1 profile. Drift in 1 section.

Symbols: + add, - remove, ~ change, ! a section changed outside ndac.

What is compared

  • Only fields set in configuration are managed; others are left alone.
  • Paths in ignore are skipped on both sides.
  • Lists are compared by ID. In authoritative lists, live items that are not configured are removed; in merge lists they are left alone.
  • A profile without id is shown as (to be created).

Drift

After every verified apply, and after ndac import (which makes the files equal to the live profile), ndac stores a post-apply snapshot of the live profile. plan compares each change against it:

  • pending: the configuration changed since the last apply;
  • drift: the live profile changed (for example in the dashboard);
  • conflict: both changed the same field or item.

Without a snapshot every change is pending. ndac drift reports drift for scheduled checks, and ndac reconcile resolves it; see Drift and reconcile.

Options

  • --target PATH limits the plan to a profile (casa), a section (casa.denylist) or a section in every profile (*.privacy.blocklists). Repeatable. A target whose profile part matches no profile is a configuration error (exit 4), not an empty plan.
  • --detailed-exitcode exits with 2 when there are changes, 0 when none.
  • --format text|json|markdown.

A profile whose file was removed but that has snapshots is reported; only ndac apply --allow-destroy deletes it.

JSON format

--format json prints a stable document. Fields are only added within a format_version; any other change bumps it.

{
  "format_version": 1,
  "summary": { "add": 1, "change": 1, "remove": 1, "profiles": 1, "drift_sections": 1 },
  "profiles": [
    {
      "key": "casa",
      "id": "abc123",
      "create": false,
      "list_modes": { "denylist": "authoritative" },
      "changes": [
        { "op": "add_item", "list": "privacy.blocklists", "id": "hagezi-pro", "active": null, "origin": "pending" },
        { "op": "set_field", "path": "settings.logs.retention", "from": 7776000, "to": 2592000, "origin": "pending" },
        { "op": "remove_item", "list": "denylist", "id": "foo.example", "origin": "drift" }
      ]
    }
  ],
  "removed": []
}
  • op is one of set_field, add_item, remove_item, set_item_active.
  • origin is pending, drift or conflict.
  • active is null for lists without an active flag (TLDs, blocklists, natives).

Markdown format

--format markdown is meant for pull request comments: a summary line and one collapsible block per profile, truncated at 60000 characters.

Snapshots

Snapshots live in .ndac/snapshots/<profile>/ (configurable with provider.snapshot_dir), one JSON file per snapshot, mode 0600, and the newest provider.snapshot_keep (default 50) are kept per profile.

  • ndac snapshot list [--profile P]
  • ndac snapshot show <id>: the full JSON. IDs can be shortened to a unique prefix.
  • ndac snapshot diff <a> <b>: the changes that turn snapshot a into b.

Drift and reconcile

Drift is a change made outside ndac, for example in the NextDNS dashboard, since the last apply. It is found by comparing each difference with the post-apply snapshot (see Plan and drift). Profiles without a snapshot, profiles to be created and removed profiles have no drift.

ndac drift

ndac drift                          # text, like `plan` but drift only
ndac drift --format json            # the plan JSON format, drift only
ndac drift --format github          # workflow annotations
ndac drift --format prom --textfile-dir /var/lib/node_exporter/textfile

drift exits with 0 when there is no drift and 2 when there is, so a scheduled job can open an issue or alert on exit code 2. Changes made only in the configuration (pending) are not drift and are not reported.

--format github prints one ::warning per drifted section, pointing at the file and line that set it: the profile, or the last template in extends that sets it. Paths are relative to the working directory, so run it from the repository root.

--format prom prints, or with --textfile-dir writes atomically to ndac_drift.prom for the node_exporter textfile collector:

# HELP ndac_drift Section changed outside ndac since the last apply (1).
# TYPE ndac_drift gauge
ndac_drift{profile="casa",section="denylist"} 1
# HELP ndac_drift_last_run_timestamp_seconds When the drift check last completed.
# TYPE ndac_drift_last_run_timestamp_seconds gauge
ndac_drift_last_run_timestamp_seconds 1792600000

Only drifted sections get a series. Alert on ndac_drift == 1, and on an old ndac_drift_last_run_timestamp_seconds to catch a check that stopped running.

ndac reconcile

reconcile shows the drift and asks, item by item:

profile "casa": denylist: bar.example is in NextDNS, not in the configuration [drift]
[o]verwrite live  [i]mport into code  [s]kip  [O]/[I] all remaining:
  • overwrite live applies the configuration’s value to NextDNS, with the same snapshot and verification steps as apply;
  • import into code writes the live value into the configuration;
  • skip leaves both sides as they are (an empty answer also skips).

O and I apply the same answer to every remaining item.

For automation, --non-interactive --prefer live imports everything and --non-interactive --prefer code overwrites everything. Without a terminal, --prefer is required. --target limits reconcile like plan.

Overwriting goes through the same guard as apply: if it would remove every item of an authoritative list, for example an item added in the dashboard to a list the configuration keeps empty, reconcile stops and nothing is changed. Pass --allow-destroy if that is intended.

Writing into the configuration

Imports edit one key, array element or item at a time with toml_edit, so comments, key order and whitespace are kept. A file that ndac fmt had already formatted is formatted again after the edit, so ndac fmt --check keeps passing; other files keep their layout. Each edited line gets a trailing comment such as # imported 2026-10-21 (drift), unless the line already has a comment or --no-comment is given. Comments cannot go inside inline tables, so values there are written without one.

When the value comes from a template, interactive runs ask where to write it: into the profile, as an override (the default), or into the template, which also changes every profile listed as using it. Non-interactive runs always write into the profile.

How each kind of change is written into the profile:

  • a field: the live value replaces the configured one (durations are written as strings such as "30d");
  • an item added in NextDNS: added to the item map, or to the ID array (as ["$inherit", "id"] when the array is otherwise inherited);
  • an item removed in NextDNS: removed from the profile; if a template still provides it, item maps get "id" = "$remove" and ID arrays are written out in full without $inherit;
  • an item’s active flag: the live flag is written.

After writing, the configuration is loaded again; if it no longer loads, the files are restored and the error is shown. Right after reconcile --non-interactive --prefer live, plan shows no changes.

Apply, import and rollback

Getting started

ndac init                     # ndac.toml, templates/base.toml, .taplo.toml, .gitignore
ndac auth set --backend keyring
ndac import --all             # one file per live profile under profiles/
ndac plan                     # empty right after an import

ndac import writes each profile in the canonical layout, with every documented field and authoritative lists, so plan right after it shows no changes. It never overwrites a file unless --force is given, and it records the imported state as the drift baseline.

Apply

ndac apply computes the plan, prints it, and asks for confirmation (type yes). Without a terminal it refuses to run unless --auto-approve is given.

For each profile with changes, it:

  1. saves a pre-apply snapshot of the live profile;
  2. sends the smallest set of calls, in this order: profile name, security, privacy, parental control, denylist, allowlist, settings. Field changes in one object become one PATCH; an authoritative list with more than one change becomes one PUT of the whole list; single item changes and merge-mode lists use per-item POST, PATCH and DELETE;
  3. writes the new id into the profile file after creating a profile (comments and layout are kept);
  4. reads the profile back and compares it with the configuration. A remaining difference is an error (“apply verification failed”) and the state is saved as a failed-apply snapshot; otherwise it is saved as the post-apply snapshot that plan uses to detect drift.

Profiles are applied concurrently; calls within a profile are sequential.

Safety

  • Destroy guard: emptying an authoritative list, and deleting a profile whose file was removed, require --allow-destroy (also accepted by reconcile, which overwrites through the same steps).
  • Lock: .ndac/snapshots/.lock prevents two applies from the same checkout at once.
  • Ctrl-C: the request in flight finishes, no new request starts, the report shows what was and was not applied, and the exit code is 130.
  • Retries: only idempotent requests are retried blindly. Adding a list item re-reads the list before trying again.

Rollback

ndac snapshot list --profile casa
ndac rollback 20261021T155535123Z-1a2b3c4d

rollback treats the snapshot as the complete desired state of its profile (all lists authoritative), shows the plan, asks for confirmation and applies it like apply. Like apply, it refuses to leave a list empty unless you pass --allow-destroy. The configuration files are not changed, so the next plan shows the configuration’s changes as pending again.

Exit codes

CodeMeaning
0Success, or no changes
1Error, cancelled confirmation, or verification failure
2Changes pending (plan --detailed-exitcode, drift)
3Authentication error
4Configuration error, including a --target that matches no profile
5API error after retries
130Interrupted by Ctrl-C

Endpoints and doctor

ndac endpoint render

ndac endpoint render casa --target nextdns-cli
ndac endpoint render casa --target resolved --device "Office PC"
ndac endpoint render casa --target networkmanager --device Laptop
ndac endpoint render casa --target android --device "Pixel 8"
ndac endpoint render casa --target doh-url --device "Pixel 8"

endpoint render prints configuration text for a profile to stdout. It never writes system files and never runs commands: review the output, then install it yourself. The profile needs an id, so apply new profiles first.

Targets

  • nextdns-cli: /etc/nextdns.conf for the nextdns client, one key value line per option, in the format the client itself writes. Options come from the profile’s [endpoint] table:

    [endpoint]
    cacheSize        = "10MB"   # cache-size
    reportClientInfo = true     # report-client-info
    
    [endpoint.conditional]       # one `profile <selector>=<id>` line each
    "10.0.3.0/24"       = "kids"     # a profile key...
    "00:1c:42:2e:60:4a" = "def456"   # ...or a NextDNS profile ID
    

    Selectors are what the client accepts before =: an IPv4 or IPv6 CIDR, a MAC address, an interface name or @user. Conditional lines come before the default profile because the client uses the first match. --device does not apply: the client sends device names itself when reportClientInfo is on.

  • resolved: a systemd-resolved drop-in using DNS over TLS, with the NextDNS IPv4 anycast addresses 45.90.28.0 and 45.90.30.0 and the profile hostname as TLS server name. The profile’s IPv6 addresses are only added with --api-ipv6, in builds with the unstable-endpoints feature (see Undocumented endpoints).

  • networkmanager: a POSIX shell script with nmcli commands that set the same servers on one connection (CONNECTION=... sh script.sh). DNS over TLS in NetworkManager requires systemd-resolved as its DNS backend.

  • android: the Private DNS hostname.

  • doh-url: the DNS-over-HTTPS URL.

Device names

With --device, queries appear under that name in the NextDNS logs:

  • DNS over TLS (resolved, networkmanager, android) puts the name in the hostname: <device>-<id>.dns.nextdns.io, where spaces become -- (Office PC gives Office--PC-abc123.dns.nextdns.io). Only ASCII letters, digits, - and spaces are allowed, and the label must fit in 63 characters.
  • DNS over HTTPS appends the URL-encoded name: https://dns.nextdns.io/abc123/Pixel%208.

ndac doctor

ndac doctor
ndac doctor --expect-profile casa --expect-device Laptop

doctor asks https://test.nextdns.io how this host’s queries reach NextDNS and prints a checklist:

✓ queries reach NextDNS (protocol DOT, server example-1)
✓ profile abc123
✓ device name "Laptop"

It exits with 0 when every check passes, 2 on a mismatch (queries not reaching NextDNS, another profile or device name, or an expected profile that cannot be compared) and 5 when the test service cannot be reached. Unencrypted queries (UDP) are reported with ! but do not fail the check.

--expect-profile takes a profile key from the configuration, if there is one, or a NextDNS profile ID. The test service sometimes shows the profile as a fingerprint (fp…) instead of its ID; then the profile cannot be compared, is reported with ? and counts as a failed check, because the expectation could not be confirmed.

doctor does not use the API key and does not need a configuration file. Each run asks a fresh random subdomain of test.nextdns.io, so the answer cannot come from a DNS cache.

Undocumented endpoints

The NextDNS API documentation does not describe DNS rewrites or the setup information of a profile (its IPv6 addresses). ndac supports both behind the unstable-endpoints build feature, which release binaries and packages do not include:

cargo install --locked ndac --features unstable-endpoints

The paths and shapes follow the nextdns-go client (rewrites.go, setup.go), which the Terraform provider uses, not the API documentation. NextDNS can change or remove them without notice, and the live end-to-end test does not cover them.

Rewrites

[rewrites]
mode = "authoritative"        # or "merge", as for denylist

[rewrites.items]
"router.lan" = "192.168.1.1"  # an IP address...
"nas.lan"    = "nas.example"  # ...or a hostname
  • Names are domains, normalized like denylist entries. Answers are IP addresses or hostnames.
  • Templates merge rewrites.items by name; "$remove" as the answer drops an inherited rewrite. rewrites.mode is profile-only.
  • A rewrite is identified by name and answer, so plans show a changed answer as a removal and an addition (- router.lan → 192.168.1.1, + router.lan → 192.168.1.2). apply deletes before it adds, because the API keeps one rewrite per name.
  • import writes [rewrites] in authoritative mode, and drift covers rewrites like any list. reconcile --prefer live cannot write rewrites back into the files; edit [rewrites.items] by hand.
  • A new profile is created first, then its rewrites are added.
  • rewrites can be used in ignore and --target.

IPv6 servers

ndac endpoint render casa --target resolved --api-ipv6
ndac endpoint render casa --target networkmanager --api-ipv6

--api-ipv6 reads the profile’s IPv6 addresses from the setup endpoint and adds them to the resolved and networkmanager output, which otherwise only have the IPv4 anycast addresses. It needs the API key. Each address is parsed, and anything that is not an IPv6 address is an error, because the networkmanager output is a shell script.

Not supported

  • Linked IP: its settings include an update token, which is a credential; ndac drops it from the setup response instead of storing it.
  • Catalogs of blocklists, natives, services and categories: no source describes them.

Shell completions and man page

ndac completions bash > ~/.local/share/bash-completion/completions/ndac
ndac completions zsh  > "${fpath[1]}/_ndac"
ndac completions fish > ~/.config/fish/completions/ndac.fish
ndac man > ndac.1 && man ./ndac.1

completions supports bash, zsh, fish, elvish and powershell. Release archives and packages include both, generated the same way.

CI recipes

A configuration repository usually runs three jobs:

  • on a pull request, ndac plan posted as a comment, so reviewers see what the change does to the live profiles;
  • on a merge to main, ndac apply --auto-approve, behind an approval;
  • on a schedule, ndac drift, which opens an issue when someone changed a profile outside ndac.

GitHub Actions

ndac init --github-actions writes .github/workflows/nextdns-gitops.yml, the same file as examples/github-actions/nextdns-gitops.yml. It needs two environments, each with the secret NEXTDNS_API_KEY:

  • nextdns-plan, for the plan and drift jobs. Fork pull requests never get the key and are not planned.
  • nextdns, for the apply job. Add required reviewers so every apply is approved, and limit deployments to main.

The workflow downloads a pinned release (NDAC_VERSION), checks it against SHA256SUMS and with gh attestation verify before running it.

The API key in CI

The key can read and change the whole account, DNS logs included, so keep it in environment secrets rather than repository secrets, and give it only to the jobs that need it. env:NEXTDNS_API_KEY is in the default source chain. To avoid a long-lived secret in GitHub, fetch the key at run time with OIDC from a secrets manager and point ndac at the file:

- uses: aws-actions/configure-aws-credentials@<sha> # pin it
  with:
    role-to-assume: arn:aws:iam::123456789012:role/nextdns-ci
    aws-region: eu-west-1
- run: |
    (umask 077 && aws secretsmanager get-secret-value --secret-id nextdns \
      --query SecretString --output text > "$RUNNER_TEMP/nextdns-key")
- run: ndac plan
  env:
    NDAC_AUTH_SOURCE: file:${{ runner.temp }}/nextdns-key

hashicorp/vault-action with JWT authentication works the same way.

Snapshots in CI

Drift is found by comparing the live profile with the snapshot ndac takes after each verified apply (see Plan and drift). A CI runner starts empty, so the workflow keeps .ndac/snapshots as the artifact ndac-snapshots after each apply and downloads the newest one before the next apply or drift check. Without a snapshot every difference is reported as pending and ndac drift finds nothing.

Exit codes in scripts

  • ndac plan --detailed-exitcode exits 0 without changes and 2 with changes.
  • ndac drift exits 0 without drift and 2 with drift.
  • Anything else is an error; see Exit codes.
rc=0
ndac drift --format github || rc=$?
case $rc in
  0) echo "no drift" ;;
  2) echo "drift found" ;;
  *) exit "$rc" ;;
esac

--format github prints workflow annotations, --format prom writes a Prometheus textfile; see Drift and reconcile.

Without CI

On a server, the systemd timer shipped with the packages runs ndac drift every hour and exports metrics for the node exporter; see Installation.

FAQ and troubleshooting

FAQ

Is there a state file? No. The desired state is in the TOML files and the live state comes from the API on every run. Snapshots under .ndac/ are only used to tell drift from pending changes and to roll back.

Will ndac change settings I did not write down? No. Fields that are not set in configuration are not managed. Lists are different: in authoritative mode (the default, and what import writes) live items that are not configured are removed; use mode = "merge" to leave them alone, or list the path in ignore.

Can I start from the profiles I already have? Yes: ndac import --all writes one file per profile, and ndac plan right after it is empty.

Can one repository manage profiles in several NextDNS accounts? Yes. A profile can set its own [auth].sources; see Authentication.

Why is there no --api-key flag? Command-line arguments are visible to other users through the process list and stay in shell history. See Authentication.

Does ndac configure my devices? No. ndac endpoint render prints configuration for the NextDNS CLI, systemd-resolved, NetworkManager and Android, and never installs anything.

Is this an official NextDNS tool? No. ndac is an independent project that uses the public NextDNS API.

Troubleshooting

Exit codes say which part failed; see Exit codes. -v, -vv or NDAC_LOG=debug add logging on stderr, and --log-format json makes it machine-readable. Logs never contain the key.

Authentication (exit code 3)

  • ndac auth sources shows the source chain in use, where it came from, and the status of each source; ndac auth check shows which source answered. Neither prints the key.
  • “readable by other users”: a file with a literal key must be private. Run chmod 600 on it.
  • “is tracked by git” or “is not ignored by git”: move the key out of the repository, or add the file to .gitignore. ndac init already ignores ndac.local.toml and .env.
  • “keyring is locked or access was denied”: unlock the keyring, or use another source on machines without a desktop session (servers, CI).

Configuration (exit code 4)

ndac validate lists every problem with file, line and a hint. Unknown keys are usually typos; the error suggests the closest valid name. The JSON Schemas in schema/ give the same checks in editors (ndac init writes a .taplo.toml for them).

API errors (exit code 5)

The client retries rate limits and server errors with backoff (provider.retries, default 5). -v logs each retry and its reason, -vv every API call with its method, endpoint template, status and duration.

A plan that never becomes empty

After apply, ndac reads the profile back and checks that the plan is empty; a field that NextDNS changes or rejects silently fails that check. Add the path to ignore and open an issue with ndac plan --format json output.

ndac doctor says queries do not reach NextDNS

This device does not use NextDNS for DNS, or uses it without a profile. Use ndac endpoint render for the device, then run ndac doctor again; see Endpoints and doctor.

Threat model

Assets

  • The NextDNS API key. It grants full access to the NextDNS account: every profile, its settings, and its query logs, which are a record of the browsing history of every device using those profiles. The API documentation describes a single key per account, shown on the account page, and no scopes or read-only keys. A leaked key must be treated as a full account compromise and rotated in the dashboard.
  • Snapshots (.ndac/snapshots/): full profile JSON taken before each apply. They contain configuration, not logs, but reveal allow and deny lists. A setup object in the profile response is never stored, since it may hold the linked IP update token.
  • Configuration: the TOML files. Normally public-safe; they become sensitive only if they hold a literal key.

Actors

  • The local user running ndac.
  • Other local users on the same machine.
  • CI systems running ndac plan, apply or drift.
  • Contributors and fork pull requests.
  • The NextDNS API (trusted for correctness of its own data, not for shaping what ndac executes).

Trust boundaries and mitigations

Command line and process

ThreatMitigation
Key visible in /proc/<pid>/cmdline, ps and shell historyNo --api-key flag; --auth-source accepts references only, and a value that looks like a pasted key is rejected without being echoed.
Key read from a core dump or by ptrace from a same-user processprctl(PR_SET_DUMPABLE, 0) at startup on Linux.
Key in logs, errors, plan output or panic messagesThe key type prints **** plus at most the last four characters; it only reaches the X-Api-Key header, marked sensitive; error types never carry it; every resolved key is registered and masked by the log writer as a last line of defense. Release builds abort on panic.
Key forwarded to another hostThe HTTP client refuses plain http (except loopback for tests) and never follows redirects.
env: variable inherited by child processescmd:, age: and git children run with a cleared environment plus a short allow list. The variable is not removed from ndac’s own environment: in Rust 2024 that requires unsafe, and ndac never spawns children that inherit its environment.

Key sources

ThreatMitigation
Literal key in a file readable by other usersFiles holding a literal key (ndac.local.toml, ndac.toml, profile files, .env) must be mode 0600-like and owned by the current user, or resolution fails with exit code 3. The override allow_insecure_permissions is only honored from ndac.local.toml or NDAC_ALLOW_INSECURE_PERMISSIONS=1, so a committed file cannot weaken it.
Literal key committed to gitA literal key in a file that git tracks, or that is in a work tree and not ignored, fails resolution. --allow-tracked-secret overrides it for one run, with a loud warning. ndac init and ndac auth set --backend config add ndac.local.toml and .env to .gitignore. gitleaks runs in pre-commit and CI.
Shell injection through cmd: sourcesCommands are split with shell-words rules and executed directly, never through a shell. Shell syntax is passed as literal arguments.
A cmd: source hanging or prompting foreverauth.cmd_timeout (default 30s) kills the child.
.env parsing changing the process environment.env files are parsed without being loaded into the environment.
A source failing silently and a different key being usedA source that exists but fails is an error by default; on_source_error = "skip" must be chosen explicitly, and never skips guardrail violations.

CI and repository

ThreatMitigation
Fork pull requests exfiltrating secretsNo pull_request_target; workflows triggered by pull requests get no secrets and read-only tokens. Live end-to-end tests run only from a protected environment with required reviewers.
Compromised third-party actionsEvery action is pinned to a commit SHA, persist-credentials: false, minimal permissions, harden-runner egress auditing, and zizmor/actionlint in CI.
Malicious or vulnerable dependenciescargo deny (RustSec advisories, license allow list, crates.io only, openssl banned), dependency review on pull requests, Dependabot with a cooldown, Cargo.lock committed and --locked builds.
Tampered release artifactsPlanned in the release phase: build provenance attestations, signed checksums, SBOMs.

The NextDNS API

ThreatMitigation
API returns unexpected fieldsUnknown fields are preserved and ignored, never interpreted.
API reports errors with HTTP 200Any response with an errors array is a failure.
Partial apply after a failureA snapshot is taken before every apply and the result is verified afterwards (apply phase).

Out of scope

  • A compromised local user account: it can read the keyring session, the private files and the process memory of its own processes.
  • The security of the NextDNS service itself.
  • Endpoint configuration that ndac endpoint render prints and the user installs manually.

Known limitations

Items here are assumptions that could not be verified against an official source. Each one is revisited when the related feature is implemented. The reference is the NextDNS API documentation, which is labeled beta.

NextDNS API key format

The custom gitleaks rule in .gitleaks.toml assumes keys are 40 lowercase hexadecimal characters. The API documentation shows an example key in that format, but does not specify it. If real keys differ, secret scanning still relies on the default gitleaks rules and on the generic api_key = ... patterns.

Endpoints

  • GET /profiles (list profiles) is not described in the documentation text, which only covers POST /profiles and GET/PATCH/DELETE on /profiles/:profile. It is widely used by other NextDNS tools and is assumed to return { id, name } entries, paginated like other arrays.
  • Nested arrays inside GET /profiles/:profile are assumed to be complete; only array child endpoints (for example /denylist) are paginated.
  • PUT on an array endpoint is assumed to take the full JSON array as body, and POST a single item object.
  • Rewrites and setup information (feature unstable-endpoints) are not documented at all; see Undocumented endpoints.

Responses

  • The documentation describes response bodies for 200 and 400 only. Other statuses are handled by code: 401/403 are authentication errors, 404 is “not found”, 429 and 5xx are retried. Any errors array is reported when present.
  • Rate limits are not documented. The client retries 429 and 5xx with exponential backoff and full jitter, honoring Retry-After.
  • List items with an active flag are assumed to be active when the flag is missing.

Configuration

  • NextDNS is assumed to ignore list order, so lists are compared and rendered sorted by ID.
  • Domains are validated locally (lowercase punycode, at least two labels, no wildcards). NextDNS may accept or reject a slightly different set.
  • It is not documented whether the API returns domains and TLDs exactly as stored. Live entries are matched by their normalized form, so Example.COM in the live profile is the same item as example.com in configuration; removals and updates use the ID as the API returned it.
  • Blocklist, native, service and category IDs are not checked against a catalog: the catalog endpoints are not documented.
  • There are two JSON Schemas (root file and profile/template files) instead of one, because the two kinds of files have different shapes.

Authentication

  • The API documentation describes one key per account and no scopes; the threat model assumes a key grants full account access.
  • On a machine without a keyring service (servers, CI), a keyring: source is treated as missing rather than failed, so the default chain keeps working there. A locked keyring is a failure.
  • env: variables are not removed from the process environment after being read: doing so requires unsafe in Rust 2024, and ndac starts children only with a cleared environment.
  • The age: source shells out to the age binary instead of using the age crate, so identities from plugins work the same way as with the command-line tool.
  • The user file is looked up under XDG_CONFIG_HOME on every platform, not in the macOS or Windows configuration directories. ndac keeps no per-user state, so XDG_STATE_HOME is not used.

Apply

  • The lock is advisory and per checkout: two checkouts of the same repository can still apply concurrently. Within one checkout it is taken before the live state is read, so a confirmed plan cannot be overtaken by another apply.
  • The workflow written by ndac init --github-actions keeps snapshots as workflow artifacts, which expire (90 days by default). With no apply in that time, drift is no longer detected until the next apply.
  • After a partial apply (--target, or reconcile overwriting only some items), the post-apply snapshot records the whole live profile. Drift left untouched then shows as pending instead of drift, until the next full apply or import.

Reconcile

  • Interactive prompts are not covered by automated tests; the non-interactive paths are.
  • Importing a field that NextDNS no longer returns removes it from the profile. If a template sets it, the import fails with a message instead, because a profile cannot unset an inherited field.

Endpoints and doctor

  • The IPv4 anycast addresses (45.90.28.0, 45.90.30.0), the DNS-over-TLS hostname format and the DNS-over-HTTPS URL format come from the NextDNS setup instructions, not from the API. IPv6 addresses are left out of the resolved and networkmanager output because they are specific to each profile and not available from the documented API, unless --api-ipv6 reads them from the undocumented setup endpoint.
  • The nextdns.conf format and option names (profile, cache-size, report-client-info) were checked against the nextdns client source.
  • The minimum NetworkManager version that accepts IP#server-name in ipv4.dns was not confirmed.
  • test.nextdns.io is not documented. Its fields (status, protocol, profile, client, srcIP, destIP, anycast, server, clientName) were checked against live responses only. The values ok and unconfigured were observed; any value other than ok is treated as “queries do not reach NextDNS”. The bare host answers some clients with a script page instead of JSON, so doctor queries a random subdomain directly.

Release and packaging

  • The .deb, .rpm, AUR and COPR packages repackage the static musl binary instead of building from source; rpmlint reports statically-linked-binary, which is expected. They are not meant for the official Debian or Fedora repositories.
  • The x86_64 macOS binary is cross-compiled on an Apple silicon runner and is not executed during the build.
  • The .deb maintainer field has no email address, which Debian policy expects; dpkg accepts it.
  • ndac-drift.service cannot create the snapshots it compares with; they come from wherever apply runs (see Installation).

Fake API

ndac-testkit follows the documented semantics. Where the documentation is silent, it assumes the following, and tests depend on these assumptions:

  • Successful PATCH, PUT, DELETE and item POST return 204 with no body.
  • Adding an item that already exists is a user error (200 with errors[].code = "duplicate").
  • PATCH with a key that does not exist in the target object is rejected with 400.
  • Domains in the denylist and allowlist must be lowercase ASCII (punycode) with at least two labels.

Maintainer guide

Repository settings checklist

These settings cannot be expressed as files in the repository and must be configured in the GitHub UI or API.

  • Branch ruleset on main: require a pull request, 1 approving review from CODEOWNERS, required status checks (all ci.yml and security.yml jobs), linear history, signed commits, block force pushes and deletion.
  • Tag ruleset for v*: only maintainers and the release GitHub App (see below) may create tags; block updates and deletion.
  • Secret scanning and push protection enabled.
  • Private vulnerability reporting enabled (used by SECURITY.md).
  • Dependabot alerts and security updates enabled.
  • Code scanning enabled (receives CodeQL and Scorecard SARIF).
  • Environment release with required reviewers, deployments limited to main (crates.io publishing) and tags v* (binaries, image, packages).
  • Environment release-plz without reviewers, deployments limited to main (opens the release pull request).
  • Environment nextdns-e2e with required reviewers, holding NEXTDNS_E2E_API_KEY and NEXTDNS_E2E_PROFILE_ID.
  • GitHub Pages source set to GitHub Actions (docs.yml deploys the book on every push to main that changes docs/).
  • After the first crates.io release, set the repository variable SEMVER_CHECKS_ENABLED to true to run cargo semver-checks on pull requests.
  • Immutable releases enabled, if available for the account.
  • Codecov: repository activated, OIDC upload allowed.
  • Actions settings: “Read repository contents” as default GITHUB_TOKEN permission; Actions may not create or approve pull requests (release-plz uses its GitHub App instead).

Releases

Releases are cut by merging the pull request that release-plz keeps open on main (chore: release vX.Y.Z):

Before merging it, run the E2E workflow by hand (Actions, Run workflow) and approve the nextdns-e2e environment. It does not run on a schedule.

  1. release-plz.yml opens or updates that pull request on every push to main: version bump of ndac, ndac-core and ndac-api (one version for all three) and the new CHANGELOG.md section.
  2. Merging it runs the publish job in the release environment: it publishes the three crates to crates.io with trusted publishing, creates the tag vX.Y.Z and a draft GitHub release.
  3. The tag starts release.yml: binaries for six targets built with cargo auditable, archives with completions, the man page and the systemd units, .deb and .rpm packages, a CycloneDX SBOM, SHA256SUMS signed with cosign, build provenance attestations (also attached as ndac-X.Y.Z.intoto.jsonl), and the image ghcr.io/esl1h/ndac (signed, with SBOM and provenance). The draft release is published once every asset is uploaded, so it also works with immutable releases.
  4. Publishing the release starts packaging.yml, which updates the AUR package ndac-bin and triggers the COPR build, when enabled.

just release-dry builds this host’s archive and SHA256SUMS into target/dist the same way, without publishing anything.

One-time setup

  • GitHub App for release-plz, installed on this repository only, with repository permissions Contents and Pull requests set to read and write. Pull requests and tags created with GITHUB_TOKEN would not start workflows. Store its client ID as the variable RELEASE_APP_CLIENT_ID and a private key as the secret RELEASE_APP_PRIVATE_KEY in both the release-plz and release environments.
  • crates.io: trusted publishing cannot create a crate, so the first version is published by hand. Set the workspace version (for example 0.1.0), then cargo publish -p ndac-api, -p ndac-core and -p ndac with a short-lived token, in that order. Then, for each crate, add a trusted publisher: repository Esl1h/ndac, workflow release-plz.yml, environment release. Revoke the token. Push the tag v0.1.0 by hand for the first binary release.
  • Enable release-plz: once the App and the crates exist, set the repository variable RELEASE_PLZ_ENABLED to true. Until then release-plz.yml skips its jobs.
  • GHCR: after the first image push, make the package ghcr.io/esl1h/ndac public and link it to this repository.
  • AUR (optional): create the package ndac-bin on the AUR with a dedicated SSH key. Store the private key as the secret AUR_SSH_PRIVATE_KEY in the release environment, the commit identity as the variables AUR_GIT_NAME and AUR_GIT_EMAIL, and set the variable AUR_ENABLED to true.
  • COPR (optional): create a COPR project with a package ndac using the SCM source, the “make srpm” method, this repository and spec packaging/rpm/ndac.spec; chroots for Fedora on x86_64 and aarch64. Store its custom webhook URL as the secret COPR_WEBHOOK_URL in the release environment and set the variable COPR_ENABLED to true.

Verifying a release

gh attestation verify ndac-0.1.0-x86_64-unknown-linux-musl.tar.gz --repo Esl1h/ndac
cosign verify-blob SHA256SUMS --bundle SHA256SUMS.sigstore.json \
  --certificate-identity "https://github.com/Esl1h/ndac/.github/workflows/release.yml@refs/tags/v0.1.0" \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com
sha256sum -c --ignore-missing SHA256SUMS
cosign verify ghcr.io/esl1h/ndac:v0.1.0 \
  --certificate-identity "https://github.com/Esl1h/ndac/.github/workflows/release.yml@refs/tags/v0.1.0" \
  --certificate-oidc-issuer https://token.actions.githubusercontent.com