Skip to content

HTTPS receiver contract (PRO + ENTERPRISE)

PRO + ENTERPRISE Feature

Sync to self-hosted secret managers requires a PRO or ENTERPRISE tier licence.

An HTTPS receiver is a small service you run that takes copies of Azure Key Vault secrets and certificates from CertifyClouds and writes them into your own system. CertifyClouds sends it signed HTTPS messages and reads its answers. This page is the exact contract your receiver must keep. Setting up the configuration in CertifyClouds is on Sync to self-hosted secret managers.

A reference receiver at the end of this page keeps every rule here. Start from it and replace its in-memory store with writes into your own system.


What your receiver must do

These are requirements, not suggestions. CertifyClouds relies on each of them to never replace or remove something it did not write.

  1. Verify every signature. Check the signature over the exact bytes received, with a constant-time comparison, and answer 401 when a signature header is missing or wrong, or when the timestamp is more than five minutes from now. See Signing. The connection check in CertifyClouds cannot prove that your receiver does this: a receiver that answers 200 to everything passes the check. Verifying is your responsibility.
  2. Answer a repeated message once. A request whose webhook-id you already answered within the last five minutes gets that same answer again, and changes nothing. CertifyClouds sends a new webhook-id with every message, so only a retry by something in between, or a replay of a captured message, repeats one. If you run more than one instance of the receiver, or it can restart, keep the answered ids in a store every instance shares and that survives a restart, such as your database or Redis with a five-minute expiry.
  3. Never apply an unconditional write. A secret.upsert always carries either "createOnly": true or an expectedVersion, and a secret.delete always carries an expectedVersion. Answer 409 when createOnly is true and the name exists, or when expectedVersion is not the item's current version (including when the name does not exist). Refuse anything else with 400. If your system cannot make that check and the write happen as one step, put a lock around them.
  4. Give every write a new version. The version you return must change on every write, must never repeat for a name, even after a delete and a re-create, and must never be "0". It is printable text of 1 to 200 characters. A random UUID per write qualifies. See Versions.
  5. Accept only the names CertifyClouds sends. A name is one segment of letters, digits, ., _ and -, never . or .., at most 255 characters. Refuse any other name with 400 before it reaches your store, so a store keyed by file or URL path is safe.
  6. Answer quickly and plainly. Answer within 30 seconds of the connection starting, without compression, with a small JSON object. Do not redirect: CertifyClouds does not follow redirects. See Connections.
  7. Decide what a delete does. What your receiver does with a secret.delete is your choice, and CertifyClouds cannot undo it. Keeping a recoverable copy in your own store is recommended.

Connections

  • HTTPS only, to the Endpoint URL you enter in CertifyClouds. Every message is a POST to that URL.
  • Trusted certificate. The receiver's certificate must be signed by the CA certificate you enter in CertifyClouds, or by a public authority if you enter none, and must name the host in the URL. TLS 1.2 or later. There is no option to skip certificate checks.
  • Direct. CertifyClouds connects straight to the receiver's address, never through a proxy, and only at addresses your administrator allowed. See Network Requirements.
  • No redirects. A 3xx answer is not followed. It counts as a failure.
  • 30 seconds in total per message, from opening the connection to the last byte of your answer. Connecting must take no longer than 5 seconds of that.
  • Uncompressed answers. CertifyClouds sends Accept-Encoding: identity. An answer with any other Content-Encoding is refused unread.
  • Small answers. An answer larger than 1 MiB is refused unread.
  • Every message has a Content-Length header and a Content-Type of application/json.

Signing

Every message is signed as described by the Standard Webhooks specification, with the Signing secret you enter in CertifyClouds.

The signing secret

The signing secret is whsec_ followed by the standard base64 encoding (not the URL-safe one) of at least 24 random bytes. The whsec_ prefix is optional. To make one:

echo "whsec_$(openssl rand -base64 32)"

Enter the same secret in CertifyClouds and in your receiver. Anyone who has it can sign messages your receiver will accept, so store it as you would any other credential.

Headers

Header Value
webhook-id A new random UUID for every message
webhook-timestamp When the message was signed, in whole seconds since 1 January 1970 UTC
webhook-signature v1, followed by the base64 of the signature
Authorization Bearer <token>, only when you entered a Bearer token (optional)

The bearer token is for an API gateway in front of your receiver. It does not replace checking the signature.

Verifying a message

  1. Read the three webhook- headers. If one is missing, answer 401.
  2. If webhook-timestamp is not a whole number, or is more than 300 seconds before or after your clock, answer 401.
  3. Decode the signing secret: remove whsec_ and base64-decode the rest. That is the key.
  4. Compute HMAC-SHA256 with that key over webhook-id, a full stop, webhook-timestamp, a full stop, then the request body exactly as received. Do not parse and re-serialise the body first.
  5. Build the expected value v1, followed by the base64 of the result.
  6. The webhook-signature header may hold several space-separated signatures. Compare each with the expected value using a constant-time comparison. If none matches, answer 401.

Only then parse the body. CertifyClouds sends one signature. A 401 is read as "the credential was refused": CertifyClouds stops that configuration for the rest of its run and shows that the target did not accept the credential.


Messages

Every body is a JSON object with three fields:

Field Meaning
type The event: connection.test, secret.describe, secret.upsert or secret.delete
runId A UUID naming the CertifyClouds operation that sent the message. The messages sent for one item's sync share it. Log it, so your records can be matched to a CertifyClouds run
data The event's fields, below

Secrets and certificates both use the secret. events. data.name is the copy's name, made from the configuration's Naming pattern.

connection.test

Sent by Check connection. data is {}. Answer 200. The body of the answer is not read.

{"type": "connection.test", "runId": "6f1c0a52-3b8e-4f7d-9a2e-1c5d8b7e4a90", "data": {}}

secret.describe

Sent at the start of every sync of an item, before every delete, and when an admin opens or acknowledges a conflict. It asks what you hold under a name. data is {"name": "<name>"}.

Answer When
200 {"exists": false} You hold nothing under the name. Do not answer 404
200 {"exists": true, "version": "<version>", "updatedAt": "<time>", "stamps": {...}} You hold an item under the name
  • exists must be the JSON value true or false.
  • version is required when exists is true: the item's current version.
  • updatedAt is optional: when the current version was written, as an ISO 8601 time. It is shown to admins when an item is in conflict.
  • stamps is optional: the stamps object of the item's last write, returned unchanged. See Stamps.

Never put the value in this answer.

secret.upsert

Writes a copy. data holds:

Field Meaning
name The copy's name
itemType secret or certificate
value A secret's value, as text. Secrets only
certificate The certificate, as PEM text. Certificates only
privateKey The certificate's private key, as unencrypted PEM text. Certificates only
chain The rest of the certificate chain, as PEM text. Certificates only, and only when the certificate has a chain. Absent otherwise
stamps An object of text values that says where the copy came from. Store it with the item. See Stamps
expiresOn When the Key Vault item expires, as an ISO 8601 time in UTC, or null when it has no expiry date in Key Vault. It is the expiry date when this copy was written. Changing only the expiry date in Key Vault sends no new message; the next write, such as the one for the item's next version, carries the new date
source {"vault", "item", "tenant"}: the Key Vault name, the Key Vault item's address without a version, and the tenant, home or a Microsoft Entra tenant ID
createOnly true when your last secret.describe answer said nothing is there: refuse with 409 if the name exists
expectedVersion Present when createOnly is false: the version your last secret.describe answer gave. Refuse with 409 unless it is still the item's current version
{
  "type": "secret.upsert",
  "runId": "6f1c0a52-3b8e-4f7d-9a2e-1c5d8b7e4a90",
  "data": {
    "name": "kv-prod-eu-db-password",
    "itemType": "secret",
    "value": "<the secret value>",
    "stamps": {
      "vault": "kv-prod-eu",
      "source": "automation-sync",
      "tenant": "home",
      "cc-source-version": "<Key Vault version id>",
      "cc-source-id": "https://kv-prod-eu.vault.azure.net/secrets/db-password"
    },
    "expiresOn": "2027-03-31T23:59:59+00:00",
    "source": {
      "vault": "kv-prod-eu",
      "item": "https://kv-prod-eu.vault.azure.net/secrets/db-password",
      "tenant": "home"
    },
    "createOnly": true
  }
}
Answer When
200 {"version": "<new version>"} The write was applied. Any 2xx status counts, but the body must be this JSON object
409 createOnly is true and the name exists, or expectedVersion is not the current version
400 Neither createOnly: true nor an expectedVersion was sent, or the name or body is not valid

The new version must follow the version rules and must differ from the expectedVersion sent.

On a 409, CertifyClouds asks again with secret.describe. If an item is there, the item is marked Conflict and waits for an admin, unless an admin already allowed overwriting that exact version. Otherwise the sync fails and is tried again on its next run. Nothing is overwritten.

If your answer to an applied write cannot be read (not JSON, no valid version, or late), CertifyClouds does not know what happened. The sync fails, and the next secret.describe finds a version CertifyClouds did not record, so the item stops at Conflict until an admin acknowledges it. See Conflicts.

secret.delete

Sent only when Delete on remove is on and an item is removed from the queue, or its configuration is deleted, and only after secret.describe showed that the copy is still the version CertifyClouds wrote. data is {"name": "<name>", "expectedVersion": "<version>"}.

Answer When
200 The item was deleted. Any 2xx counts. The body is not read
404 You hold nothing under the name. CertifyClouds reports the copy as already gone
409 expectedVersion is not the current version. CertifyClouds leaves the copy alone and reports that it was kept
400 No expectedVersion was sent, or the name is not valid

What the delete does in your system is your choice, and CertifyClouds cannot undo it. A recoverable delete, such as moving the item to a deleted state your own team can restore, is recommended. If the same name is written again later, its new version must still differ from every version it had before.


Versions

version is your receiver's own text. CertifyClouds never interprets it: it stores it, shows it to admins, and sends it back as expectedVersion.

  • Printable text, 1 to 200 characters. It is shown on CertifyClouds' screens, so never put a secret in it.
  • New on every write.
  • Never repeated for a name, even after a delete and a re-create. CertifyClouds treats an item at the version it last wrote as its own copy, so a repeated version could make CertifyClouds replace or delete an item someone else wrote.
  • Never "0". CertifyClouds reserves it. An answer with "0" is not read.

Stamps

stamps is an object of text values CertifyClouds sends with every write. Store it with the item and return it unchanged in secret.describe.

Key Value
vault The Key Vault name
source Always automation-sync
tenant home, or the Microsoft Entra tenant ID of the Key Vault
cc-source-id The Key Vault item's address without a version
cc-source-version The Key Vault version that was copied. Secrets only

When a first write finds an item already at the name, CertifyClouds reads cc-source-id from the stamps you return. If it names the same Key Vault item, the admin is told that the item may be CertifyClouds' own write whose answer was lost, rather than something unrelated.

The same stamp is read after the configuration's credential or CA certificate is replaced. An item still at the version CertifyClouds last wrote, whose cc-source-id names the same Key Vault item, is treated as the copy CertifyClouds wrote and syncs as before. If you do not return stamps, each item stops as a conflict once after such a change and an admin allows the overwrite.

Nothing else is read from the stamps, and on their own they never make CertifyClouds overwrite an item without an admin.


Status codes

Only a 2xx answer is success.

Answer What CertifyClouds does
2xx Success
3xx Not followed. The sync fails
400 The sync fails: the target rejected the item's name or format
401 The credential was refused. The connection check fails at Sign-in, and during a sync the configuration's other items are skipped for that run and stay due
403 The sync fails: the credential has no access where the copies go, or, on secret.delete, is not allowed to delete. On connection.test, the check fails at Sign-in
404 On secret.delete, the copy is already gone. On any other event, the sync fails
409 On secret.upsert and secret.delete, as described above
410 The sync fails, saying the receiver no longer accepts this copy
413 The sync fails as for 400. Answer it when the item is too large for your receiver
429 The sync fails and is tried again on its next run
502, 503, 504 The target is treated as unavailable: the configuration's other items are skipped for that run and stay due
Any other The sync fails

A failed sync is tried again on its next scheduled run. CertifyClouds does not read a Retry-After header.


Reference receiver

The reference receiver keeps every rule on this page. It uses only the Python standard library (Python 3.11 or later) and stores items in memory, so a restart loses them. Copy it and replace the store with writes into your own system.

CertifyClouds sends only to https URLs, so run it behind a reverse proxy on the same machine that terminates TLS with a certificate CertifyClouds trusts:

export PUSH_RECEIVER_SECRET='<the signing secret you entered in CertifyClouds>'
python3 push_receiver.py

It listens on 127.0.0.1:8080 unless you set PUSH_RECEIVER_HOST and PUSH_RECEIVER_PORT.

"""Reference receiver for CertifyClouds HTTP push sync.

Copy this file and replace the in-memory store with writes into your own secret manager. It uses only the
Python standard library (3.11 or later). CertifyClouds sends only to https URLs, so run it behind a
TLS-terminating reverse proxy on the same machine: values cross the hop from the proxy in clear, so the receiver
listens only on the loopback interface unless you say otherwise.

Environment:
    PUSH_RECEIVER_SECRET  the signing secret you entered for the configuration in CertifyClouds (required):
                          ``whsec_`` followed by the base64 of at least 24 random bytes
    PUSH_RECEIVER_HOST    the interface to listen on (default 127.0.0.1); 0.0.0.0 in a container whose proxy runs
                          in another container
    PUSH_RECEIVER_PORT    the port to listen on (default 8080)

Every request is a POST (any path) whose JSON body is ``{"type": <event>, "runId": <string>, "data": {...}}``,
signed with the Standard Webhooks headers ``webhook-id``, ``webhook-timestamp`` and ``webhook-signature``
(https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md). ``runId`` is
the sync run's id, for your logs.

Events and answers (every answer is a JSON object):
    connection.test   {}                                   -> 200 {}
    secret.describe   {name}                               -> 200 {"exists": false}
                                                              200 {"exists": true, "version", "updatedAt", "stamps"}
    secret.upsert     {name, itemType, value or the certificate parts, stamps, expiresOn, source,
                       createOnly, expectedVersion?}       -> 200 {"version"}
                                                              400 unless createOnly is true or expectedVersion is
                                                                  given: a write is never unconditional
                                                              409 when createOnly is true and the name exists,
                                                                  or expectedVersion is not the current version
    secret.delete     {name, expectedVersion}              -> 200 {}
                                                              404 when the name does not exist
                                                              409 when expectedVersion is not the current version

``name`` is one segment of letters, digits, ``.``, ``_`` and ``-`` (never ``.`` or ``..``), at most 255
characters: anything else is a 400 before it reaches your store, so a store keyed by file or URL path is safe.

``version`` is a new random UUID on every write, so it never repeats for a name, even after a delete and a
re-create. It must never be ``"0"``, which CertifyClouds reserves. ``updatedAt`` is an ISO 8601 UTC time. A
delete here cannot be undone; your own store may keep a recoverable copy instead.

Any request: 401 when a signature header is missing or wrong, or the timestamp is more than five minutes from
now; 400 for a body that is not an event above; 411 without a Content-Length; 413 for a body over 1 MiB, refused
before it is read. A connection silent for 30 seconds is closed, and at most 32 requests are handled at once. A
sender that keeps trickling bytes is not cut off here: set a request timeout on the reverse proxy in front, which
on the loopback interface is the only thing that can connect.

A request whose ``webhook-id`` was already answered within the five minutes gets that same answer again and
changes nothing: CertifyClouds sends a new id with every message, so only a retry or a replay repeats one. Those
answers are kept in this process's memory, so a restart forgets them and a second instance never sees them: a
message captured between the proxy and the receiver could then be replayed within its five minutes. If you run
more than one instance, or it can restart, keep the answered ids in a store every instance shares and that
survives a restart (your database, or Redis with a five-minute expiry), keyed by ``webhook-id``.
"""

from __future__ import annotations

import base64
import hashlib
import hmac
import json
import os
import re
import socket
import sys
import threading
import time
import uuid
from collections.abc import Mapping
from dataclasses import dataclass
from datetime import UTC, datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

SECRET_PREFIX = "whsec_"
MIN_SECRET_BYTES = 24
REPLAY_WINDOW_SECONDS = 5 * 60
MAX_BODY_BYTES = 1024 * 1024
# A silent sender gives up its thread after this long, and no more than this many requests run at once.
SOCKET_TIMEOUT_SECONDS = 30
MAX_CONCURRENT_REQUESTS = 32
# The names CertifyClouds sends: one segment, so no name can climb out of a store keyed by path.
NAME = re.compile(r"[A-Za-z0-9._-]{1,255}")

Response = tuple[int, dict[str, object]]
_Request = socket.socket | tuple[bytes, socket.socket]


def decode_secret(secret: str) -> bytes:
    """The HMAC key a signing secret carries. The ``whsec_`` prefix is optional."""
    try:
        key = base64.b64decode(secret.removeprefix(SECRET_PREFIX), validate=True)
    except ValueError:
        raise ValueError("The signing secret is not valid base64.") from None
    if len(key) < MIN_SECRET_BYTES:
        raise ValueError(f"The signing secret must hold at least {MIN_SECRET_BYTES} bytes.")
    return key


def signature(key: bytes, msg_id: str, timestamp: int, body: bytes) -> bytes:
    """The ``v1,<base64>`` signature of ``msg_id.timestamp.body``."""
    digest = hmac.new(key, f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256).digest()
    return b"v1," + base64.b64encode(digest)


class _Unauthorized(Exception):
    pass


@dataclass
class _Stored:
    version: str
    updated_at: str
    item: dict[str, object]


class PushReceiver:
    """Verifies, de-duplicates and applies the events. Safe to call from several threads."""

    def __init__(self, secret: str) -> None:
        self._key = decode_secret(secret)
        # One lock over de-duplication, the version check and the write, so createOnly and expectedVersion
        # stay atomic when two requests for the same name arrive together.
        self._lock = threading.Lock()
        self._store: dict[str, _Stored] = {}
        self._answered: dict[str, tuple[int, Response]] = {}

    def handle(self, headers: Mapping[str, str], body: bytes, now: int | None = None) -> Response:
        current = int(time.time()) if now is None else now
        try:
            msg_id, timestamp = self._verify(headers, body, current)
        except _Unauthorized as error:
            return 401, {"error": str(error)}
        with self._lock:
            # A repeat of an id older than the window is already refused by its signed timestamp.
            self._answered = {
                key: entry for key, entry in self._answered.items() if current - entry[0] <= REPLAY_WINDOW_SECONDS
            }
            answered = self._answered.get(msg_id)
            if answered is not None:
                return answered[1]
            response = self._apply(body, current)
            self._answered[msg_id] = (timestamp, response)
            return response

    def _verify(self, headers: Mapping[str, str], body: bytes, now: int) -> tuple[str, int]:
        lowered = {name.lower(): value for name, value in headers.items()}
        msg_id = lowered.get("webhook-id")
        raw_timestamp = lowered.get("webhook-timestamp")
        signatures = lowered.get("webhook-signature")
        if not msg_id or not raw_timestamp or not signatures:
            raise _Unauthorized("A Standard Webhooks header is missing.")
        try:
            timestamp = int(raw_timestamp)
        except ValueError:
            raise _Unauthorized("webhook-timestamp is not a whole number of seconds.") from None
        if abs(now - timestamp) > REPLAY_WINDOW_SECONDS:
            raise _Unauthorized("webhook-timestamp is more than five minutes from now.")
        expected = signature(self._key, msg_id, timestamp, body)
        # Several space-separated signatures may arrive while a secret is being rotated; any match counts.
        # compare_digest takes as long whatever the bytes, so the timing gives nothing away.
        if not any(hmac.compare_digest(candidate.encode(), expected) for candidate in signatures.split()):
            raise _Unauthorized("The signature does not match.")
        return msg_id, timestamp

    def _apply(self, body: bytes, now: int) -> Response:
        try:
            message = json.loads(body)
        except ValueError:
            return 400, {"error": "The body is not JSON."}
        if not isinstance(message, dict) or not isinstance(message.get("data"), dict):
            return 400, {"error": "The body must be an object with a data object."}
        event, data = message.get("type"), message["data"]
        if event == "connection.test":
            return 200, {}
        name = data.get("name")
        if not isinstance(name, str) or not NAME.fullmatch(name) or name in (".", ".."):
            return 400, {"error": "data.name must be one segment of letters, digits, '.', '_' and '-'."}
        if event == "secret.describe":
            return self._describe(name)
        if event == "secret.upsert":
            return self._upsert(name, data, now)
        if event == "secret.delete":
            return self._delete(name, data)
        return 400, {"error": "Unknown event type."}

    def _describe(self, name: str) -> Response:
        stored = self._store.get(name)
        if stored is None:
            return 200, {"exists": False}
        return 200, {
            "exists": True,
            "version": stored.version,
            "updatedAt": stored.updated_at,
            "stamps": stored.item.get("stamps", {}),
        }

    def _upsert(self, name: str, data: dict[str, object], now: int) -> Response:
        stored = self._store.get(name)
        expected_version = data.get("expectedVersion")
        create_only = data.get("createOnly") is True
        # An unconditional write could replace an item someone else changed, so it is never applied.
        if not create_only and not isinstance(expected_version, str):
            return 400, {"error": "An upsert needs createOnly true or a string expectedVersion."}
        if create_only and stored is not None:
            return 409, {"error": "The name already exists."}
        if expected_version is not None and (stored is None or stored.version != expected_version):
            return 409, {"error": "expectedVersion is not the current version."}
        item = {key: value for key, value in data.items() if key not in ("createOnly", "expectedVersion")}
        version = str(uuid.uuid4())
        self._store[name] = _Stored(version, datetime.fromtimestamp(now, UTC).isoformat(), item)
        return 200, {"version": version}

    def _delete(self, name: str, data: dict[str, object]) -> Response:
        expected_version = data.get("expectedVersion")
        if not isinstance(expected_version, str):
            return 400, {"error": "data.expectedVersion must be a string."}
        stored = self._store.get(name)
        if stored is None:
            return 404, {"error": "The name does not exist."}
        if stored.version != expected_version:
            return 409, {"error": "expectedVersion is not the current version."}
        del self._store[name]
        return 200, {}


class _BoundedServer(ThreadingHTTPServer):
    """A thread per request, at most ``MAX_CONCURRENT_REQUESTS`` at once: a further connection waits to be accepted."""

    def __init__(self, address: tuple[str, int], handler: type[BaseHTTPRequestHandler]) -> None:
        super().__init__(address, handler)
        self._slots = threading.BoundedSemaphore(MAX_CONCURRENT_REQUESTS)

    def process_request(self, request: _Request, client_address: tuple[str, int]) -> None:
        self._slots.acquire()
        try:
            super().process_request(request, client_address)
        except BaseException:
            self._slots.release()
            raise

    def process_request_thread(self, request: _Request, client_address: tuple[str, int]) -> None:
        try:
            super().process_request_thread(request, client_address)
        finally:
            self._slots.release()


def make_server(receiver: PushReceiver, host: str, port: int) -> ThreadingHTTPServer:
    class Handler(BaseHTTPRequestHandler):
        # Each read and write gives up after this long without progress. A sender that keeps trickling is the
        # reverse proxy's to cut off.
        timeout = SOCKET_TIMEOUT_SECONDS

        def do_POST(self) -> None:
            try:
                length = int(self.headers["Content-Length"])
            except (TypeError, ValueError):
                self._reply(411, {"error": "A Content-Length header is required."})
                return
            if not 0 <= length <= MAX_BODY_BYTES:
                # Refused before reading, so an oversized body is never held in memory.
                self._reply(413, {"error": f"The body must be at most {MAX_BODY_BYTES} bytes."})
                return
            try:
                body = self.rfile.read(length)
            except TimeoutError:
                self.close_connection = True
                return
            self._reply(*receiver.handle(self.headers, body))

        def _reply(self, status: int, payload: dict[str, object]) -> None:
            body = json.dumps(payload).encode()
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

    return _BoundedServer((host, port), Handler)


def main() -> None:
    secret = os.environ.get("PUSH_RECEIVER_SECRET")
    if not secret:
        sys.exit("Set PUSH_RECEIVER_SECRET to the signing secret you entered for the configuration in CertifyClouds.")
    receiver = PushReceiver(secret)
    host = os.environ.get("PUSH_RECEIVER_HOST", "127.0.0.1")
    server = make_server(receiver, host, int(os.environ.get("PUSH_RECEIVER_PORT", "8080")))
    server.serve_forever()


if __name__ == "__main__":
    main()