본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

제네릭 Webhook Provider (Generic Webhook)

원문 보기 위키 갱신

External Secrets Operator가 단순한 웹 API와 통합할 수 있도록, 엔드포인트를 지정하는 방식의 제네릭 webhook provider를 살펴볼게요.

출처: External Secrets

본문

예시 (Example)

먼저 webhook 백엔드가 있는 SecretStore를 만드세요. 여기서는 정적 user/password test를 사용할게요:

apiVersion: external-secrets.io/v1
kind: SecretStore
metadata:
  name: webhook-backend
spec:
  provider:
    webhook:
      url: "http://httpbin.org/get?parameter={{ .remoteRef.key }}"
      result:
        jsonPath: "$.args.parameter"
      headers:
        Content-Type: application/json
        Authorization: Basic {{ print .auth.username ":" .auth.password | b64enc }}
      secrets:
      - name: auth
        secretRef:
          name: webhook-credentials
---
apiVersion: v1
kind: Secret
metadata:
  name: webhook-credentials
  labels:
    external-secrets.io/type: webhook # webhook이 이 secret을 쓰도록 허용하는 데 필요
data:
  username: dGVzdA== # "test"
  password: dGVzdA== # "test"

참고: 이것은 결과로 키를 그대로 돌려주는 것뿐이라 실용적이진 않지만, 어떻게 동작하는지 보여 줘요.

참고: ClusterSecretStore를 쓸 때는 모든 secrets 참조에 시크릿이 위치한 네임스페이스를 반드시 제공해 주세요.

이제 위 SecretStore를 사용하는 ExternalSecret을 만드세요:

apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
  name: webhook-example
spec:
  refreshInterval: "15s"
  secretStoreRef:
    name: webhook-backend
    kind: SecretStore
  target:
    name: example-sync
  data:
  - secretKey: foobar
    remoteRef:
      key: secret
---
# 이렇게 시크릿을 만들게 됨:
kind: Secret
metadata:
  name: example-sync
data:
  foobar: c2VjcmV0

Push secret

시크릿을 푸시하려면 다음 store를 만드세요:

apiVersion: external-secrets.io/v1
kind: SecretStore
metadata:
  name: webhook-backend
spec:
  provider:
    webhook:
      url: "http://httpbin.org/push?id={{ .remoteRef.remoteKey }}&secret={{ .remoteRef.secretKey }}"
      body: '{"secret-field": "{{ index .remoteRef .remoteRef.remoteKey }}"}'
      headers:
        Content-Type: application/json
        Authorization: Basic {{ print .auth.username ":" .auth.password | b64enc }}
      secrets:
      - name: auth
        secretRef:
          name: webhook-credentials

그 다음 push secret을 만드세요:

apiVersion: external-secrets.io/v1alpha1
kind: PushSecret
metadata:
  name: pushsecret-example # 사용자 지정 가능
spec:
  refreshInterval: 1h0m0s # push secret이 reconcile되는 간격
  secretStoreRefs: # 시크릿을 푸시할 secret store 목록
    - name: webhook-backend
      kind: SecretStore
  selector:
    secret:
      name: test-secret
  data:
    - conversionStrategy:
      match:
        secretKey: testsecret
        remoteRef:
          remoteKey: remotekey

secretKey가 제공되지 않으면 시크릿 전체가 JSON 인코딩되어 제공돼요.

시크릿은 remoteRef 객체에 추가되어 templating 엔진에서 가져올 수 있어요. provider의 body 필드가 비어 있으면 시크릿이 body로 전송돼요. body를 비워야 하는 드문 경우에는 provider의 body 값을 '{{ "" }}'로 설정하면 돼요.

인증 (Authentication)

Webhook은 인증에 NTLM도 지원해요:

apiVersion: external-secrets.io/v1
kind: SecretStore
metadata:
  name: webhook-backend
spec:
  provider:
    webhook:
      url: "http://httpbin.org/get?parameter={{ .remoteRef.key }}"
      result:
        jsonPath: "$.args.parameter"
      auth:
        ntlm:
            usernameSecret:
              name: webhook-credentials
              key: username
              namespace: externalsecrets
            passwordSecret:
              name: webhook-credentials
              key: password
              namespace: externalsecrets
---
apiVersion: v1
kind: Secret
metadata:
  name: webhook-credentials
  namespace: externalsecrets
  labels:
    external-secrets.io/type: webhook # auth.ntlm 시크릿에도 필요
data:
  username: dGVzdA== # "test"
  password: dGVzdA== # "test"

참고: 주어진 ExternalSecret에 대한 webhook 엔드포인트가 404 상태 코드를 반환하면, 시크릿이 삭제된 것으로 간주돼요. 그러면 ExternalSecret에 설정된 deletionPolicy가 실행돼요.

템플레이팅 (Templating)

제네릭 WebHook provider는 templating 엔진을 사용해 API 호출을 생성해요. url, headers, body, result.jsonPath 필드에서 쓸 수 있어요.

provider는 가져올 시크릿을 remoteRef라는 객체에 넣어요.

추가로, 시크릿을 이름이 있는 객체(named objects)로 추가할 수 있어요. 예를 들어 인증 헤더에 쓰기 위해서요. 각 시크릿은 templating 엔진에서 객체의 이름을 결정하는 name 속성을 가져요.

모든 파라미터 (All Parameters)

apiVersion: external-secrets.io/v1
kind: ClusterSecretStore
metadata:
  name: statervault
spec:
  provider:
    webhook:
      # 호출할 Url. 요청 파라미터를 채우려면 templating 엔진 사용.
      url: <url>
      # http 메서드, 기본값 GET
      method: <method>
      # 타임아웃(1s, 1m 등)
      timeout: 1s
      result:
        # [jsonPath](https://jsonpath.com) 문법, 템플레이팅도 가능
        jsonPath: <jsonPath>
      # 헤더 맵, 템플레이팅 가능
      headers:
        <Header-Name>: <header contents>
      # 요청으로 보낼 Body, 템플레이팅 가능 (선택)
      body: <body>
      # templating 엔진에 노출할 시크릿 목록
      secrets:
      # 위 템플레이팅에서 이 시크릿을 참조할 이름
      - name: <name>
        secretRef:
          namespace: <namespace> # ClusterSecretStores에서만 사용
          name: <name>
      # TLS 핸드셰이크를 위한 CA 추가
      caBundle: <base64 encoded cabundle>
      caProvider:
        type: Secret or ConfigMap
        name: <name of secret or configmap>
        namespace: <namespace> # ClusterSecretStores에서만 사용
        key: <key inside secret>

generator로서의 Webhook

webhook을 generator로도 활용할 수 있어요. 문법은 동일해요. 자세한 내용은 generator-webhook 문서를 참조하세요.

secretstore와 generator 모두에서 소스 시크릿에 라벨을 붙여야 하므로, 아래 참조되는 시크릿에는 라벨이 필요를 참조하세요.

디버깅 (Debugging)

store 상태와 이벤트부터 시작하기

대부분의 webhook 문제는 로그보다는 SecretStore 자체에 드러나요:

kubectl describe secretstore <name> -n <namespace>
# 또는, 클러스터 범위 store의 경우
kubectl describe clustersecretstore <name>

Ready 상태가 False이고 reason이 InvalidProviderConfig라면, 클라이언트를 만들 수 없거나 store 검증이 실패했을 수 있어요. 함께 발생한 이벤트에 밑바탕 오류가 담겨 있는데, 보통 상태 메시지보다 더 구체적이에요.

ProviderNotFound reason은 더 좁아요. spec.provider에 지정된 provider를 전혀 해석(resolve)하지 못해서 provider 코드가 실행되지 못한 거예요. 이 경우 상태 메시지가 백엔드를 명시하고 이벤트만큼 구체적이에요.

시크릿별 실패는 ExternalSecret을 대신 확인하세요:

kubectl describe externalsecret <name> -n <namespace>

오퍼레이터 로그 레벨 높이기

컨트롤러를 --loglevel debug로 실행하면 각 객체에 대한 reconcile 결정을 볼 수 있어요. 오퍼레이터가 무엇을 그리고 왜 했는지 로그로 남기지만, HTTP 요청/응답 내용은 의도적으로 로그로 남기지 않아요(아래 참조).

내장 요청/응답 덤프가 없는 이유

webhook provider는 url, headers, body를 templating 엔진을 통해 렌더링하는데, 그 템플릿에는 보통 참조된 시크릿에서 가져온 자격 증명이 포함돼요. 요청이나 응답을 덤프하면 그 자격 증명이 오퍼레이터 로그에 기록되고, 로그 접근 권한이 있는 사람이라면 누구든 읽을 수 있게 돼요. 그래서 trace나 wire-dump 옵션을 제공하지 않고, 추가될 가능성도 낮아요.

경고: 오퍼레이터에서 GODEBUG=http2debug=2를 설정하면 인증 헤더와 전체 body를 포함해 완전히 마스킹되지 않은 HTTP/2 프레임 덤프가 생성돼요. HTTP/2만 다루고, 지원되는 디버깅 경로가 아니며, 프로덕션 인스턴스에서는 절대 켜면 안 돼요.

로깅 프록시로 트래픽 검사하기

트래픽을 보려면 지원되는 방식은 오퍼레이터와 대상 서비스 사이에 프록시를 두고 프록시 로그를 읽는 거예요. webhook url이 평문 HTTP로 프록시를 가리키게 해서 요청이 거기서 읽히게 하고, 프록시가 실제 엔드포인트 방향으로 TLS를 종료하게 하세요. 사이드카로 실행하면 평문 구간(hop)을 pod 안에 두게 돼요.

external-secrets 배포에 사이드카와 그 설정 볼륨을 추가하세요. 프록시와 관련된 필드만 표시했고, pod 스펙의 나머지는 유지하세요.

# spec.template.spec.containers
- name: debug-proxy
  image: nginx:alpine
  ports:
    - containerPort: 8080
  volumeMounts:
    - name: debug-proxy-config
      mountPath: /etc/nginx/conf.d
# spec.template.spec.volumes
- name: debug-proxy-config
  configMap:
    name: debug-proxy-config

키는 .conf로 끝나야 해요. 기본 nginx 설정이 /etc/nginx/conf.d/*.conf만 포함하기 때문이에요. 다른 키로는 사이드카가 프록시 대신 기본 nginx 페이지를 서비스해요.

apiVersion: v1
kind: ConfigMap
metadata:
  name: debug-proxy-config
data:
  debug-proxy.conf: |
    log_format dump escape=none '$request_method $uri $args -> $upstream_status'
                                ' authorization="$http_authorization"';

    server {
      listen 8080;
      access_log /dev/stdout dump;
      location / {
        proxy_pass https://secrets.example.com;
        proxy_set_header Host secrets.example.com;
        # nginx는 기본적으로 SNI를 보내지 않아, 서버 이름으로 인증서를
        # 선택하는 엔드포인트를 깨뜨립니다.
        proxy_ssl_server_name on;
      }
    }

그러면 요청 메서드, 경로와 쿼리, 업스트림 상태, Authorization 헤더가 로그로 남아요. 다른 헤더가 필요하면 log_format에 $http_<header> 변수를 더 추가하세요. 요청과 응답 body는 캡처되지 않아요. 필요하다면 mirror나 전용 캡처 프록시를 사용하세요.

디버깅하는 동안 store에 url: "http://localhost:8080/..."를 설정하세요. 이제 프록시 로그에 오퍼레이터가 로그로 남기길 거부하는 것과 같은 자격 증명이 포함되므로 민감하게 취급하고, 작업이 끝나면 사이드카를 제거하세요.

경고: nginx는 proxy_ssl_verify on과 proxy_ssl_trusted_certificate가 설정되지 않으면 업스트림 인증서를 검증하지 않아요. 그래서 이 프록시는 의도적으로 오퍼레이터보다 관대해요. TLS 신뢰 문제를 진단하는 데 쓰지 마세요. caProvider나 인증서 오류는 프록시가 경로에 들어오는 순간 해결된 것처럼 보일 거예요.

참조되는 시크릿에는 라벨이 필요 (Referenced secrets must be labeled)

webhook이 읽는 모든 Secret에는 external-secrets.io/type: webhook 라벨이 있어야 해요.

그 라벨은 SecretStore 또는 ClusterSecretStore의 spec.provider.webhook.secrets, Webhook generator의 spec.secrets, 그리고 auth.ntlm의 usernameSecret과 passwordSecret(같은 코드 경로로 해석됨)을 모두 포함해요. 없으면 조회가 다음과 같이 실패해요:

secret does not contain needed label 'external-secrets.io/type: webhook'. Update secret label to use it with webhook

템플릿 값은 두 단계 깊이

secrets 아래에 나열된 시크릿은 .<name>.<keyInSecret>로 노출되고 .<name>이 아니에요. 예를 들어:

secrets:
  - name: creds
    secretRef:
      name: webhook-credentials

값은 {{ .creds.username }}와 {{ .creds.password }}예요. {{ .creds }}를 참조하면 값이 아니라 Go map을 렌더링해요. 또한 참조된 시크릿의 모든 키가 노출된다는 점에 주의하세요. secretRef의 key 필드가 그것을 좁혀 주지 않아요.

템플레이팅된 url은 템플레이팅 전에 검증됨

store 검증은 templating 엔진이 실행되기 전에 spec.provider.webhook.url을 있는 그대로 사용해 연결 가능성(reachability) 검사를 수행해요. 따라서 호스트가 템플릿에서 오는 url은, 템플레이팅된 요청 자체가 성공하더라도 다음과 같은 메시지로 검증에 실패해요:

error accessing external store: dial tcp :443: connect: connection refused

호스트는 리터럴로 두고 경로나 쿼리 문자열만 템플레이팅하세요.

더 알아보기 (Learn more)