← Back to Pull requests

Replace secrets helper with secret-generic-connector in /readsecret.sh #3685

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Oct 28, 2026 19:33 UTC
Author

What does this PR do?

CONTP-2242

/readsecret.sh now reads secrets with the secret-generic-connector (SGC) that already ships in the operator image, instead of the /helpers binary. /helpers is removed from the image.

Nothing changes for users. They keep the same configuration:

  • secretBackend.command=/readsecret.sh

  • secretBackend.arguments=<directory>

  • a Secret mounted at that directory

  • ENC[<key>] references
  • How it works. SGC doesn't take the directory as a command-line argument. It reads its backend settings from the JSON the operator writes to stdin. The script adds the k8s.file backend and the directory to that JSON, then runs SGC.

    The script also keeps the old helper's rules:

  • exactly one argument, and a trailing space in arguments still works

  • 8 KiB maximum file size (SGC's own default is 10 MiB)

  • the same checks on the input (protocol version, non-empty secret list)
  • Motivation

    One binary for secret resolution in the operator image instead of two.

    Additional Notes

    Compatibility. The documented setup works the same as before. I compared this branch with the current image on:

  • a Secret mounted as a volume, including the kubelet's ..data symlink layout

  • items/path remapping and projected volumes

  • key names containing ., - and uppercase letters

  • the operator's own apiKey/appKey: ENC[...]

  • DatadogAgent spec.global.credentials ENC[...]

  • rotation with secretBackend.refreshInterval

  • the FIPS image
  • Breaking changes. Both affect undocumented behaviour:

  • ENC[../x], a reference that leaves the configured directory, is now rejected. The old helper allowed it, which was a path-traversal hole. docs/secret_management.md now says references must stay inside the directory.

  • The /helpers binary and its source (cmd/helpers/) are removed, so anyone calling it directly (instead of /readsecret.sh) breaks.
  • Security note. SGC follows a symlink inside the directory that points outside it; the old helper refused. Kubernetes Secret volumes never create such links. The proper fix belongs in SGC.

    Not tested: arm64 at runtime (the SGC image is published for arm64), OpenShift with random UIDs, readOnlyRootFilesystem.

    Minimum Agent Versions

    N/A (operator-only change).

    Describe your test plan

    This procedure was run verbatim on a fresh kind cluster against this branch before it was posted. Every step has a command and its expected output, so a human or an agent can follow it as written.

    Goal. Check that the documented usage of the operator's secret helper (secretBackend.command=/readsecret.sh, secretBackend.arguments=<dir>, a mounted Secret, ENC[<key>]) works exactly as before, now that the script calls SGC instead of the /helpers binary.

    Runs on Linux or macOS with docker, kind (v0.20+), kubectl and helm (v3). It takes about 20 minutes. Every step lists the command and the expected result; a step fails if its output doesn't match.

    The API and app keys are fake. 403 responses from Datadog in the operator logs are expected: they prove a resolved key was sent.

    0. Setup

    # From a checkout of the PR branch (levan-m/sgc-migration)
    export IMG=datadog-operator:qa-sgc        # image under test
    export CTX=kind-sgc-qa
    export NS=datadog
    export CHART_VERSION=2.31.0               # published datadog/datadog-operator chart
    k() { kubectl --context "$CTX" "$@"; }
    opLogs() { k -n "$NS" logs deploy/dd-operator-datadog-operator; }
    

    1. Unit tests, build the image, check its contents

    go test ./pkg/secrets/ -run TestReadSecretScript -v
    

    Expected: --- PASS: TestReadSecretScript_payload and --- PASS: TestReadSecretScript_rejectsInvalidInput, with every subtest passing.

    # SGC_VERSION has no default in the Dockerfile; the Makefile derives it from pkg/images/images.go
    export SGC_VERSION=$(awk -F '"' '/^[[:space:]]*AgentLatestVersion =/ {print $2}' pkg/images/images.go)
    echo "SGC_VERSION=$SGC_VERSION"
    docker build --build-arg SGC_VERSION="$SGC_VERSION" -t "$IMG" .
    docker run --rm --entrypoint /bin/bash "$IMG" -c '
      test ! -e /helpers && echo "PASS: /helpers removed" || echo "FAIL: /helpers present"
      /usr/local/bin/secret-generic-connector -version
      ls -l /readsecret.sh
      [[ $(< /readsecret.sh) == *secret-generic-connector* ]] && echo "PASS: script calls SGC" || echo "FAIL: script does not call SGC"'
    

    Expected:

  • PASS: /helpers removed

  • secret-generic-connector <SGC_VERSION> (7.85.4 at the time of writing)

  • a docker build warning InvalidDefaultArgInFrom for the SGC base image is expected and harmless: SGC_VERSION is passed explicitly

  • /readsecret.sh with mode -r-xr-x---

  • PASS: script calls SGC
  • 2. Cluster, Secret, operator

    kind create cluster --name sgc-qa
    kind load docker-image "$IMG" --name sgc-qa
    k create namespace "$NS"
    
    # Secret mounted into the operator. Includes edge-case keys used in step 4.
    head -c 8192 /dev/zero | tr '\0' a > /tmp/qa-exact8192
    head -c 8193 /dev/zero | tr '\0' a > /tmp/qa-over8192
    k -n "$NS" create secret generic operator-backend-secrets \
      --from-literal=api_key=fake-api-key-v1 \
      --from-literal=app_key=fake-app-key-v1 \
      --from-literal=app.key-Mixed_1=dotted-value \
      --from-file=exact8192=/tmp/qa-exact8192 \
      --from-file=over8192=/tmp/qa-over8192
    
    cat > /tmp/qa-values.yaml <<EOF
    image:
      repository: ${IMG%:*}
      tag: ${IMG##*:}
      doNotCheckTag: true
      pullPolicy: Never
    apiKey: ENC[api_key]
    appKey: ENC[app_key]
    logLevel: debug
    secretBackend:
      command: /readsecret.sh
      # trailing space is intentional: the operator splits on " ", which yields an empty extra argument
      arguments: "/etc/secret-volume "
      refreshInterval: 20s
    volumes:
      - name: secret-volume
        secret:
          secretName: operator-backend-secrets
    volumeMounts:
      - name: secret-volume
        mountPath: /etc/secret-volume
        readOnly: true
    EOF
    
    helm repo add datadog https://helm.datadoghq.com && helm repo update datadog
    helm --kube-context "$CTX" install dd-operator datadog/datadog-operator --version "$CHART_VERSION" \
      -n "$NS" -f /tmp/qa-values.yaml
    k -n "$NS" rollout status deploy/dd-operator-datadog-operator --timeout=180s
    sleep 20
    

    2a. Operator is configured and running

    k -n "$NS" get deploy dd-operator-datadog-operator -o jsonpath='{.spec.template.spec.containers[0].args}' | tr ',' '\n' | grep -E 'secretBackend|secretRefresh'
    k -n "$NS" get pods
    opLogs | grep -c 'Unable to get credentials'
    opLogs | grep -o '"msg":"Starting secret refresh routine"[^}]*'
    

    Expected:

  • the args include -secretBackendCommand=/readsecret.sh, -secretBackendArgs=/etc/secret-volume and -secretRefreshInterval=20s

  • the pod is 1/1 Running with 0 restarts

  • the Unable to get credentials count is 0, meaning the operator resolved ENC[api_key]/ENC[app_key] through /readsecret.sh at startup

  • a Starting secret refresh routine line with "interval":20
  • 3. Operator credentials (end to end)

    3a. Negative control: an unknown handle is reported

    helm --kube-context "$CTX" upgrade dd-operator datadog/datadog-operator --version "$CHART_VERSION" \
      -n "$NS" -f /tmp/qa-values.yaml --set 'apiKey=ENC[does_not_exist]'
    k -n "$NS" rollout status deploy/dd-operator-datadog-operator --timeout=180s; sleep 15
    opLogs | grep 'Unable to get credentials' | grep -o '"error":"[^"]*'
    

    Expected: an error occurred while decrypting 'does_not_exist': failed to stat secret file 'does_not_exist': stat /etc/secret-volume/does_not_exist: no such file or directory. The failed to stat secret file part is SGC's own wording, which shows SGC handled the request.

    3b. Restore

    helm --kube-context "$CTX" upgrade dd-operator datadog/datadog-operator --version "$CHART_VERSION" -n "$NS" -f /tmp/qa-values.yaml
    k -n "$NS" rollout status deploy/dd-operator-datadog-operator --timeout=180s; sleep 15
    opLogs | grep -c 'Unable to get credentials'     # expected: 0
    

    4. Script behaviour inside the operator pod

    Each check sends the same payload the operator sends. r <dir> '<json secrets list>' [extra args...] prints the script's stdout and exit code. The image has no grep/sed, so output is filtered on the host.

    k -n "$NS" exec deploy/dd-operator-datadog-operator -- bash -c '
    r(){ d=$1; s=$2; shift 2; printf "%s" "{\"version\":\"1.0\",\"secrets\":[$s]}" | /readsecret.sh "$d" "$@"; echo "  [rc=$?]"; }
    echo "T1 kubelet layout:"; ls -la /etc/secret-volume
    echo "T2 both keys:";       r /etc/secret-volume "\"api_key\",\"app_key\""
    echo "T3 empty extra arg:"; r /etc/secret-volume "\"api_key\"" ""
    echo "T4 trailing slash:";  r /etc/secret-volume/ "\"api_key\""
    echo "T5 dotted key name:"; r /etc/secret-volume "\"app.key-Mixed_1\""
    echo "T6 exactly 8192 B:";  r /etc/secret-volume "\"exact8192\""
    echo "T7 8193 B:";          r /etc/secret-volume "\"over8192\""
    echo "T8 missing key:";     r /etc/secret-volume "\"nope\""
    echo "T9 ../ traversal:";   r /etc/secret-volume "\"../hostname\""
    echo "T10 no args:";        printf "{\"version\":\"1.0\",\"secrets\":[\"api_key\"]}" | /readsecret.sh; echo "  [rc=$?]"
    echo "T11 two real args:";  r /etc/secret-volume "\"api_key\"" extra
    echo "T12 version 2.0:";    printf "{\"version\":\"2.0\",\"secrets\":[\"api_key\"]}" | /readsecret.sh /etc/secret-volume; echo "  [rc=$?]"
    echo "T13 empty secrets:";  printf "{\"version\":\"1.0\",\"secrets\":[]}" | /readsecret.sh /etc/secret-volume; echo "  [rc=$?]"
    echo "T14 invalid json:";   printf "not json" | /readsecret.sh /etc/secret-volume; echo "  [rc=$?]"
    echo "T15 leading whitespace:"; printf " \n\t{\"version\":\"1.0\",\"secrets\":[\"api_key\"]}" | /readsecret.sh /etc/secret-volume; echo "  [rc=$?]"' 2>&1 \
      | sed -E 's/a{20,}/<8192 a>/'
    

    Expected:

    | ID | Expected output | Meaning |
    |---|---|---|
    | T1 | listing includes ..data -> ..<timestamp> and api_key -> ..data/api_key | real kubelet atomic layout |
    | T2 | {"api_key":{"value":"fake-api-key-v1","error":null},"app_key":{"value":"fake-app-key-v1","error":null}} [rc=0] | documented usage |
    | T3 | api_key → fake-api-key-v1, [rc=0] | a trailing space in arguments keeps working |
    | T4 | api_key → fake-api-key-v1, [rc=0] | |
    | T5 | app.key-Mixed_1 → dotted-value, [rc=0] | |
    | T6 | exact8192 → <8192 a>, "error":null, [rc=0] | at the size limit |
    | T7 | "value":null,"error":"secret file 'over8192' exceeds maximum size limit of 8192 bytes ...", [rc=0] | 8 KiB limit kept |
    | T8 | "value":null,"error":"failed to stat secret file 'nope': ...", [rc=0] | per-secret error, as before |
    | T9 | "value":null,"error":"path outside allowed directory", [rc=0] | intentional change: the old helper returned the content of /etc/hostname |
    | T10 | Error: expected exactly 1 argument (secrets directory), got 0, [rc=1] | |
    | T11 | Error: expected exactly 1 argument (secrets directory), got 2, [rc=1] | |
    | T12 | Error: incompatible protocol version, [rc=1] | |
    | T13 | Error: no secrets listed in input, [rc=1] | |
    | T14 | Error: failed to unmarshal json input, [rc=1] | |
    | T15 | api_key → fake-api-key-v1, [rc=0] | valid JSON with leading whitespace is accepted, as before |

    5. Secret rotation with refreshInterval

    k -n "$NS" create secret generic operator-backend-secrets \
      --from-literal=api_key=fake-api-key-v2 --from-literal=app_key=fake-app-key-v1 \
      --from-literal=app.key-Mixed_1=dotted-value --from-file=exact8192=/tmp/qa-exact8192 --from-file=over8192=/tmp/qa-over8192 \
      --dry-run=client -o yaml | k apply -f -
    for i in $(seq 1 36); do opLogs | grep -q 'Credentials have changed, cache updated' && break; sleep 5; done
    opLogs | grep -o '"msg":"Credentials have changed, cache updated"' | head -1
    

    Expected: "msg":"Credentials have changed, cache updated" within 3 minutes (kubelet sync plus a 20s refresh).

    5b. Negative: the key is removed from the Secret

    k -n "$NS" create secret generic operator-backend-secrets --from-literal=app_key=fake-app-key-v1 \
      --dry-run=client -o yaml | k apply -f -
    for i in $(seq 1 36); do opLogs | grep -q 'Failed to refresh credentials' && break; sleep 5; done
    opLogs | grep 'Failed to refresh credentials' | grep -o '"error":"[^"]*' | head -1
    

    Expected: an error occurred while decrypting 'api_key': failed to stat secret file 'api_key': .... The operator stays Running.

    6. Other documented Secret mount layouts

    k -n "$NS" create secret generic layout-a --from-literal=api_key=val-a --from-literal=app.key=val-dot
    k -n "$NS" create secret generic layout-b --from-literal=other=val-b
    cat <<EOF | k apply -f -
    apiVersion: v1
    kind: Pod
    metadata: {name: qa-layouts, namespace: $NS}
    spec:
      securityContext: {runAsUser: 1001, runAsGroup: 0}
      containers:
      - name: c
        image: $IMG
        imagePullPolicy: Never
        command: ["/bin/bash","-c","sleep 3600"]
        volumeMounts:
        - {name: remap, mountPath: /etc/remap, readOnly: true}
        - {name: proj, mountPath: /etc/proj, readOnly: true}
      volumes:
      - name: remap
        secret:
          secretName: layout-a
          items: [{key: api_key, path: dd/api}, {key: app.key, path: app_key}]
      - name: proj
        projected:
          sources:
          - secret: {name: layout-a, items: [{key: api_key, path: api_key}]}
          - secret: {name: layout-b}
    EOF
    k -n "$NS" wait --for=condition=Ready pod/qa-layouts --timeout=120s
    k -n "$NS" exec qa-layouts -- bash -c '
    r(){ printf "%s" "{\"version\":\"1.0\",\"secrets\":[$2]}" | /readsecret.sh "$1"; echo "  [rc=$?]"; }
    echo "L1 items/path remap:"; r /etc/remap "\"dd/api\",\"app_key\""
    echo "L2 projected volume:"; r /etc/proj "\"api_key\",\"other\""'
    k -n "$NS" delete pod qa-layouts --wait=false
    

    Expected:

  • L1: dd/api → val-a and app_key → val-dot, both "error":null, [rc=0]

  • L2: api_key → val-a and other → val-b, [rc=0]
  • 7. DatadogAgent ENC[...] credentials (operator without its own keys)

    When the operator has no apiKey/appKey, it resolves spec.global.credentials from the DatadogAgent through the same secret backend.

    # restore the full Secret
    k -n "$NS" create secret generic operator-backend-secrets \
      --from-literal=api_key=fake-api-key-v2 --from-literal=app_key=fake-app-key-v1 \
      --dry-run=client -o yaml | k apply -f -
    grep -v -E '^(apiKey|appKey):' /tmp/qa-values.yaml > /tmp/qa-values-nokeys.yaml
    helm --kube-context "$CTX" upgrade dd-operator datadog/datadog-operator --version "$CHART_VERSION" -n "$NS" -f /tmp/qa-values-nokeys.yaml
    cat <<EOF | k apply -f -
    apiVersion: datadoghq.com/v2alpha1
    kind: DatadogAgent
    metadata: {name: datadog, namespace: $NS}
    spec:
      global:
        credentials: {apiKey: "ENC[api_key]", appKey: "ENC[app_key]"}
    EOF
    k -n "$NS" rollout restart deploy/dd-operator-datadog-operator
    k -n "$NS" rollout status deploy/dd-operator-datadog-operator --timeout=180s; sleep 90
    opLogs | grep -c 'decrypting'                                        # expected: 0
    opLogs | grep '"logger":"metadata' | grep -o '"error":"received error status code 403[^"]*' | head -1
    

    Expected:

  • decrypting count is 0

  • at least one received error status code 403 from a metadata.* logger, meaning the key resolved from the DatadogAgent was sent
  • 7b. Negative

    k -n "$NS" patch datadogagent datadog --type merge -p '{"spec":{"global":{"credentials":{"apiKey":"ENC[nope]"}}}}'
    k -n "$NS" rollout restart deploy/dd-operator-datadog-operator
    k -n "$NS" rollout status deploy/dd-operator-datadog-operator --timeout=180s; sleep 90
    opLogs | grep -o "an error occurred while decrypting 'nope'[^\"]*" | sort -u | head -2
    

    Expected: an error occurred while decrypting 'nope': failed to stat secret file 'nope': ...

    8. Optional: compare with the released operator

    To confirm parity, rerun step 4 against the last release, which still uses /helpers:

    docker pull registry.datadoghq.com/operator:1.31.2
    docker run --rm --entrypoint /bin/bash registry.datadoghq.com/operator:1.31.2 -c 'ls -l /helpers /readsecret.sh'
    

    Deploy it the same way, with image.repository=registry.datadoghq.com/operator, image.tag=1.31.2 and pullPolicy=IfNotPresent, then run step 4. Expected differences:

  • T2–T6: same values. The old output omits "error":null.

  • T7, T8: still errors, worded differently (secret exceeds max allowed size, secret does not exist).

  • T9 resolves on the old image. This is the one intentional change.

  • T10–T14: same exit code 1. The old error message is followed by cobra's usage text.

  • T15: same value.
  • 9. Cleanup

    kind delete cluster --name sgc-qa
    rm -f /tmp/qa-values.yaml /tmp/qa-values-nokeys.yaml /tmp/qa-exact8192 /tmp/qa-over8192
    

    Pass criteria

    All of steps 1–7 match their expected output. The intended behaviour changes are:

  • T9: ../ handles are rejected

  • /helpers is gone from the image

  • error message wording differs
  • Anything else that differs is a failure.

    Checklist

  • PR has at least one valid label: bug, enhancement, refactoring, documentation, tooling, and/or dependencies

  • PR has a milestone or the qa/skip-qa label

  • All commits are signed (see: [signing commits][1])
  • [1]: https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits

    🤖 Generated with Claude Code

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: levan-m Review duration: 51141m
    All Vouch review confidence checks passed
    Residual risk 0.45 = Change Risk (0.82) × (1 − Review Confidence (0.45)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.82 · 650 lines diff across 8 files
    0.82
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    44%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Sensitive Paths sensitive_paths
    0.082
    Real PR Conversation Timeline
    1 comments
    "Review active on #3685"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: medium confidence: 44.7% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 82.2% (HIGH) · Higher = larger blast radius
    82.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 44.7% · Lower = rushed or shallow review
    44.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 45.5% · Moderate risk
    45.5%