Skip to content

feat(helm): add configurable policy CronJobs to the dirctl chart - #1994

Merged
akijakya merged 2 commits into
mainfrom
feat/policy-cronjob-helm
Aug 7, 2026
Merged

akijakya merged 2 commits into
mainfrom
feat/policy-cronjob-helm

Conversation

@akijakya

@akijakya akijakya commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

Closes #1977. Depends on #1987 (merged) for --trusted=false, and #1979 for a shell-capable image.

What

A node-level content policy — "sync every record in a given domain", "drop records that aren't signed" — previously meant a forked chart or hand-written manifests. The cronjobs map runs a single dirctl call per entry, and a policy is a pipeline: search, then act on the result.

policies declares that pipeline from values alone:

policies:
  sync-netsec:
    enabled: true
    schedule: "0 3 * * *"
    action: sync
    match:
      domain: [network_security]

  prune-untrusted:
    enabled: true
    schedule: "*/30 * * * *"
    action: prune
    match:
      trusted: false
      scan-severity: MEDIUM

Four actions, each pairing a search source with a --stdin sink:

Action Source Sink
sync dirctl routing search dirctl sync create --stdin
prune dirctl search dirctl delete --stdin
publish dirctl search dirctl routing publish --stdin
unpublish dirctl search dirctl routing unpublish --stdin

Rendered outcome

Both examples ship enabled: false. Enabling them produces exactly this — nothing elided:

prune-untrusted — full CronJob
apiVersion: batch/v1
kind: CronJob
metadata:
  name: dir-dirctl-policy-prune-untrusted
  labels:
    helm.sh/chart: dirctl-0.1.0
    app.kubernetes.io/name: dirctl
    app.kubernetes.io/instance: dir
    app.kubernetes.io/version: "1.16.0"
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/component: dir-dirctl-policy-prune-untrusted
spec:
  schedule: "*/30 * * * *"
  successfulJobsHistoryLimit: 10
  failedJobsHistoryLimit: 10
  concurrencyPolicy: "Forbid"
  jobTemplate:
    spec:
      template:
        metadata:
          labels:
            app.kubernetes.io/name: dirctl
            app.kubernetes.io/instance: dir
            app.kubernetes.io/component: dir-dirctl-policy-prune-untrusted
        spec:
          restartPolicy: OnFailure
          containers:
          - name: dirctl
            image: "ghcr.io/agntcy/dir-ctl:latest"
            imagePullPolicy: IfNotPresent
            securityContext:
              readOnlyRootFilesystem: true
              runAsNonRoot: true
              runAsUser: 65532
            command:
            - /bin/sh
            - -c
            - |-
              set -eu
              out="$(dirctl search --format cid --output json --limit 100 --scan-severity 'MEDIUM' --trusted=false)"
              if [ -z "$out" ]; then
                echo "[prune-untrusted] search returned no output" >&2
                exit 1
              fi
              count="$(printf '%s' "$out" | jq 'length')"
              echo "[prune-untrusted] matched ${count} record(s)"
              if [ "$count" -eq 0 ]; then
                exit 0
              fi
              printf '%s' "$out" | jq .
              printf '%s' "$out" | dirctl delete --stdin
            env:
            - name: DIRECTORY_CLIENT_SERVER_ADDRESS
              value: dir-apiserver.dir-server.svc.cluster.local:8888
            - name: DIRECTORY_CLIENT_AUTH_MODE
              value: ""
            - name: DIRECTORY_CLIENT_JWT_AUDIENCE
              value: ""
            - name: DIRECTORY_CLIENT_SPIFFE_TOKEN
              value: ""
            resources:
              limits:
                cpu: 100m
                memory: 128Mi
              requests:
                cpu: 50m
                memory: 64Mi
            volumeMounts:
              - name: home-dir
                mountPath: /home/nonroot
          volumes:
            # Writable home directory for config files when root filesystem is read-only
            # Required for applications that create config files (e.g., MCP host)
            - name: home-dir
              emptyDir: {}

sync-netsec, schedule 0 3 * * * — same resource shape, differing only in the script:

set -eu
out="$(dirctl routing search --output json --limit 100 --domain 'network_security')"
if [ -z "$out" ]; then
  echo "[sync-netsec] search returned no output" >&2
  exit 1
fi
count="$(printf '%s' "$out" | jq 'length')"
echo "[sync-netsec] matched ${count} record(s)"
if [ "$count" -eq 0 ]; then
  exit 0
fi
printf '%s' "$out" | jq .
printf '%s' "$out" | dirctl sync create --stdin

With dryRun: true the sink line is replaced by echo "[prune-untrusted] dry run: not applying action 'prune'" — inside the loop, for the paginated actions, so a dry run still reports every page.

Design notes

match keys are dirctl flag names, passed through mechanically rather than mapped against a whitelist. List → flag repeated per item; bool → --flag=true|false; scalar → --flag 'value'. Any filter the CLI grows works with no chart change — including the --exclude-* flags from #1987, which did not exist when the template was written:

match:
  trusted: false
  exclude-name: ["cisco.com/*"]
# -> dirctl search ... --exclude-name 'cisco.com/*' --trusted=false

The trade is that an unrecognised-but-well-formed key surfaces at run time. Anything that would be silent-wrong rather than loudly-wrong is rejected at helm template time:

Rejected Why
limit/offset/format/output inside match the chart sets these; would emit a duplicate flag
an unknown action
a value containing ' would break out of the shell quoting
a key outside ^[a-z0-9][a-z0-9-]*$ keys are interpolated unquoted, so name; rm -rf / would be executable shell
a limit that is not a positive integer also interpolated unquoted
a sync policy with no skill/domain/locator/module dirctl routing search requires a criterion; without one it exits 0 printing nothing

Three details in the generated script are load-bearing:

  • The count guard. cli/util/cids.Collect returns "at least one CID is required" on empty stdin, so dirctl delete|routing publish|routing unpublish --stdin fail on an empty array. Without the guard, a policy matching nothing would fail on every run.
  • The empty-output guard, separate from the count. A search can exit 0 while printing nothing — dirctl routing search does exactly that with no criteria, reporting to stderr. That leaves count empty, and [ "" -eq 0 ] errors; because it is an if condition, set -e does not stop the script, so it would fall through to the sink with empty input. [ -z "$out" ] turns that into a clear failure.
  • No set -o pipefail. Capturing the search into a variable under set -eu surfaces a failing search without it, and yields the match count and dry-run dump for free. (busybox ash does support pipefail; this shape was preferred for the count, not out of necessity.)

Pagination differs by action, because only some of them change whether a record still matches:

Action Coverage
prune Deleting stops a record matching, so the set shrinks and offset 0 always sees the remaining work.
publish, unpublish The action does not change the record, so the same first page would be reprocessed forever. These loop over --offset until a short page comes back.
sync Cannot page — dirctl routing search has no --offset. Processes the first limit matches only; documented as a constraint on limit.

Policies render through the existing cronjobs loop as policy-<name> entries, inheriting the SPIRE, env, volume, resource and security wiring without duplicating the ~100-line pod spec. env, resources, volumes, volumeMounts, concurrencyPolicy and the history limits work per policy exactly as for a cronjobs entry. The policy- prefix keeps a policy and a cronjobs entry of the same name from colliding.

command: now renders via toYaml, giving the |- block above rather than one escaped line, so the script stays readable in kubectl get cronjob -o yaml. Verified byte-identical output for plain single-line command lists.

Notes for reviewers

  • sync reads the routing index, not the local store, so its usable match keys are only those dirctl routing search accepts: skill, domain, locator, module, min-score. The presence of at least one is enforced at template time; which other keys are valid is documented, not enforced, since enforcing that would mean the whitelist the passthrough design avoids.
  • Both examples ship disabled, departing from the existing cronjobs examples which are enabled: true. A default-on prune that deletes untrusted records is not a default worth having.
  • Overriding a shipped example's match merges rather than replaces it (Helm deep-merge). Setting match: {trusted: false} on prune-untrusted yields --scan-severity 'MEDIUM' --trusted=false. Use a new policy key to avoid this.
  • safe: false is not the complement of safe: true — it matches records with an explicit unsafe scan report, while never-scanned records match neither. A prune keyed on it silently spares unscanned records. Called out in a warning admonition in the docs, since it is the kind of thing that makes a destructive policy act on the wrong population.
  • limit: 0 is rejected rather than silently becoming 100. Sprig's default treats 0 as empty, so the obvious $policy.limit | default 100 would have swallowed it; the template uses hasKey instead.

Testing

install/charts/dirctl/ci/test-policies.sh + task test:helm: 25 assertions over helm template output covering every action, every match value kind, per-action pagination, the dry-run path, the disabled path, both guards, the absence of pipefail, and all six template-time rejections. helm lint cannot check any of this — it only verifies the chart renders. Wired into the Lint CI job, which the path filter runs for chart changes. Mutation-tested: breaking dirctl delete --stdin in the template makes the suite fail and exit 1.

Beyond that:

  • Default helm template output is byte-identical to before this PR.
  • All four rendered dirctl invocations were extracted from the manifests and run against the CLI on this branch; each parses and fails only on TCP connect, confirming no unknown flags.
  • The generated scripts were run inside a faithful replica of the build(cli): make the dirctl image shell-capable #1979 alpine runtime image under the chart's own securityContext (runAsUser: 65532, readOnlyRootFilesystem: true, emptyDir at /home/nonroot): /bin/sh and jq present, dirctl resolves on PATH after the ENTRYPOINT override, empty match set exits 0, non-empty reaches the sink.
  • The pagination loop was exercised in busybox ash against a stub returning two full pages then a short one: it iterates, stops on the short page, and reports the correct total.

Not verified: no live-cluster run. Everything above is rendering plus container-level execution, not a CronJob observed firing in a cluster. sync is the least covered — it reads the routing index, so a single-node environment can never make it match.

Docs

docs/content/dir/dir-deployment-kubernetes.md gains a Content Policies section: the action table, match value kinds, the exclude- example, the sync caveat, the field reference, the per-action pagination table, a warning that safe: false is not the complement of safe: true, and a dry-run admonition showing real log output.

@akijakya akijakya self-assigned this Aug 7, 2026
@akijakya
akijakya requested a review from a team as a code owner August 7, 2026 10:45
@github-actions github-actions Bot added the size/M Denotes a PR that changes 200-999 lines label Aug 7, 2026
@akijakya
akijakya requested a balanced review from Copilot August 7, 2026 10:51

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds configurable Helm-managed policy CronJobs that search for records and then sync, prune, publish, or unpublish them.

Changes:

  • Generates policy shell pipelines through the existing CronJob template.
  • Adds policy examples, documentation, and rendering tests.
  • Adds a Taskfile command for Helm policy tests.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
Taskfile.yml Adds the Helm test task.
install/charts/dirctl/values.yaml Defines example policies and configuration guidance.
install/charts/dirctl/templates/cronjob.yaml Integrates policies into CronJob rendering.
install/charts/dirctl/templates/_policies.tpl Generates policy flags and shell pipelines.
install/charts/dirctl/ci/test-policies.sh Tests rendered policy behavior.
install/charts/dirctl/ci/policies-values.yaml Supplies policy test fixtures.
install/charts/dirctl/.helmignore Excludes test fixtures from chart packages.
docs/content/dir/dir-deployment-kubernetes.md Documents content policies and actions.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread Taskfile.yml Resolved
@codecov

codecov Bot commented Aug 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@tkircsi tkircsi left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@akijakya
akijakya force-pushed the feat/policy-cronjob-helm branch from 37633ea to 520f57c Compare August 7, 2026 11:39
@akijakya
akijakya merged commit 9012e01 into main Aug 7, 2026
37 checks passed
@akijakya
akijakya deleted the feat/policy-cronjob-helm branch August 7, 2026 12:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/M Denotes a PR that changes 200-999 lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Add configurable policy CronJob helm templates to the dirctl chart

4 participants