Event Hooks Examples

Event hooks are outbound calls from Kong Gateway. With event hooks, the Kong Gateway can communicate with target services or resources, letting the target know that an event was triggered. When an event is triggered in Kong, it calls a URL with information about that event. Event hooks add a layer of configuration for subscribing to worker events using the admin interface. Worker events are integrated into Kong Gateway to communicate within the gateway context. For example, when an entity is created, the Kong Gateway fires an event with information about the entity. Parts of the Kong Gateway codebase can subscribe to these events, then process the events using callbacks.

In Kong Gateway, these callbacks can be defined using one fo the following “handlers”:

  • webhook: Makes a JSON POST request to a provided URL with the event data as a payload. Useful for building a middle tier integration (your own webhook that receives Kong hooks). Specific headers can be configured for the request.

  • webhook-custom: Fully configurable request. Useful for building a direct integration with a service (for example, a Slack webhook). Because it’s fully configurable, it’s more complex to configure. It supports templating on a configurable body, a configurable form payload, and headers.

  • log: This handler, which requires no configuration, logs the event and the content of the payload into the Kong Gateway logs. If using hybrid mode, the crud and dao:crud sources will log on the control plane logs and the balancer and rate-limiting-advanced sources will log on the data plane logs.

  • lambda: This handler runs specified Lua code after an event is triggered.

Webhook

Webhook event hooks make JSON POST requests to a provided URL with the event data as a payload. For this example, we will use a site that is helpful for testing webhooks: https://webhook.site.

To create a webhook event hook:

  1. Generate a URL by navigating to https://webhook.site in your web browser.
  2. Select Copy to clipboard next to Your unique URL.
  3. Create a webhook event hook on the consumers event (Kong entity the event hook will listen to for events), on the crud source (action that triggers logging), and the URL you copied from step 2 using the following HTTP request:

    cURL

    HTTPie

    1. curl -i -X POST http://{HOSTNAME}:8001/event-hooks \
    2. -d source=crud \
    3. -d event=consumers \
    4. -d handler=webhook \
    5. -d config.url={WEBHOOK_URL}
    1. http -f :8001/event-hooks \
    2. source=crud \
    3. event=consumers \
    4. handler=webhook \
    5. config.url={WEBHOOK_URL}
  4. Navigate to the URL from step 2. You should see a POST request, of type ping, notifying our webhook endpoint about the creation of this webhook.

  5. In Kong Manager or Kong Admin API, add a consumer from any workspace.

    Kong Manager

    Admin API

    1. Select the workspace.
    2. Select Consumers in the left navigation.
    3. Select the New Consumer button.
    4. Enter a Username.
    5. (Optional) Enter a Custom ID and any Tags.
    6. Select the Create button.

    Create a consumer, Ada Lovelace, by making the following HTTP request to your instance of the Kong Admin API:

    cURL

    HTTPie

    1. curl -i -X POST http://{HOSTNAME}:8001/consumers \
    2. -d username="Ada Lovelace"
    1. http -f :8001/consumers \
    2. username="Ada Lovelace"
  6. Check the URL from the https://webhook.site page. You should see an entry with data for the new consumer in its payload.

    1. {
    2. "source": "crud",
    3. "entity": {
    4. "created_at": 1627581878,
    5. "type": 0,
    6. "username": "Ada Lovelace",
    7. "id": "0fd2319f-13ea-4582-a448-8d11893026a8"
    8. },
    9. "event": "consumers",
    10. "operation": "create",
    11. "schema": "consumers"
    12. }

Custom webhook

Custom webhook event hooks are fully customizable requests. Custom webhooks are useful for building direct integration with a service. Because custom webhooks are fully configurable, they have more complex configurations. Custom webhooks support Lua templating on a configurable body, form payload, and headers. For a list of possible fields for templating, see the sources endpoint.

The following example sends a message to Slack any time a new administrator is invited to Kong Gateway. Slack allows for incoming webhooks and we can use these to build an integration with Kong’s event hooks features.

To create a custom webhook event hook:

  1. Create an app in Slack.
  2. Activate incoming webhooks in the settings for your new app.
  3. Select to Add New Webhook to Workspace, select the channel where you wish to receive notices, and select Allow.
  4. Copy the Webhook URL, for example https://hooks.slack.com/services/foo/bar/baz.
  5. Create a webhook event hook on the admins event (Kong entity the event hook will listen to for events), and the crud source (action that triggers logging), and format the payload as, “Admin account `{{ entity.username }}` {{ operation }}d; e-mail address set to `{{ entity.email }}`”, using the following HTTP request:

    cURL

    HTTPie

    1. curl -i -X POST http://{HOSTNAME}:8001/event-hooks \
    2. -d source=crud \
    3. -d event=admins \
    4. -d handler=webhook-custom \
    5. -d config.method=POST \
    6. -d config.url={WEBHOOK_URL} \
    7. -d config.headers.content-type="application/json" \
    8. -d config.payload.text="Admin account \`{{ entity.username }}\` {{ operation}}d; email address set to \`{{ entity.email }}\`"
    1. http -f :8001/event-hooks \
    2. source=crud \
    3. event=admins \
    4. handler=webhook-custom \
    5. config.method=POST \
    6. config.url={WEBHOOK_URL} \
    7. config.headers.content-type="application/json" \
    8. config.payload.text="Admin account \`{{ entity.username }}\` {{ operation}}d; email address set to \`{{ entity.email }}\`"
  6. Turn on RBAC.

    To enable RBAC, you will need the initial KONG_PASSWORD that was used when you first installed Kong Gateway and ran migrations. This is also the default password for the Super Admin, and will be required once RBAC is on.

    UNIX-based system or Windows

    Docker

    1. Modify configuration settings below in your kong.conf file. Navigate to the file at /etc/kong/kong.conf:

      1. cd /etc/kong/
    2. Copy the kong.conf.default file so you know you have a working copy to fall back to.

      1. cp kong.conf.default kong.conf
    3. Now, edit the following settings in kong.conf:

      1. echo >> enforce_rbac = on >> /etc/kong/kong.confecho >> admin_gui_auth = basic-auth >> /etc/kong.confecho >> admin_gui_session_conf = {"secret":"secret","storage":"kong","cookie_secure":false}”

      This will turn on RBAC, tell Kong Gateway to use basic authentication (username/password), and tell the Sessions Plugin how to create a session cookie.

      The cookie is used for all subsequent requests to authenticate the user until it expires. The session has a limited duration and renews at a configurable interval, which helps prevent an attacker from obtaining and using a stale cookie after the session has ended.

    4. Restart Kong Gateway and point to the new config file:

      1. kong restart -c /etc/kong/kong.conf

    If you have a Docker installation, run the following command to set the needed environment variables and reload the gateway’s configuration.

    Note: make sure to replace <kong-container-id> with the ID of your container.

    1. echo "KONG_ENFORCE_RBAC=on
    2. KONG_ADMIN_GUI_AUTH=basic-auth
    3. KONG_ADMIN_GUI_SESSION_CONF='{\"secret\":\"secret\",\"storage\":\"kong\",\"cookie_secure\":false}'
    4. kong reload exit" | docker exec -i {KONG_CONTAINER_ID} /bin/sh

    This will turn on RBAC, tell Kong Gateway to use basic authentication (username/password), and tell the Sessions Plugin how to create a session cookie.

    The cookie is used for all subsequent requests to authenticate the user, until it expires. The session has a limited duration and renews at a configurable interval, which helps prevent an attacker from obtaining and using a stale cookie after the session has ended.

    Outside of this guide, you will likely want to modify these settings differently, depending on your installation. You can read more about these settings here: Basic Auth for Kong Manager.

  7. Invite an Admin using Kong Manager or the Kong Admin API.

    Kong Manager

    Admin API

    1. Go to Kong Manager, or reload the page if you already have it open and you will see a login screen.
    2. Log in to Kong Manager with the built-in Super Admin account, kong_admin, and its password. This is the initial KONG_PASSWORD you used when you ran migrations during installation.
    3. From the Teams > Admins tab, click Invite Admin.
    4. Enter the new administrator’s Email address and Username.
    5. Click Invite Admin to send the invite. At this point in the getting started guide, you likely haven’t set up SMTP yet, so no email will be sent.

    Create an admin, Arya Stark, by making the following HTTP request to your instance of the Kong Admin API:

    Note: Replace {KONG_ADMIN_PASSWORD} with your kong_admin password. This is the initial KONG_PASSWORD you used when you ran migrations during installation.

    cURL

    HTTPie

    1. curl -i -X POST http://{HOSTNAME}:8001/admins \
    2. -d username="Arya Stark" \
    3. -d email=arya@gameofthrones.com \
    4. -H Kong-Admin-Token:{KONG_ADMIN_PASSWORD}
    1. http -f :8001/admins \
    2. username="Arya Stark" \
    3. email=arya@gameofthrones.com \
    4. Kong-Admin-Token={KONG_ADMIN_PASSWORD}

Afterwards, you should receive a message in the Slack channel you selected with the message you included as the config.payload.text.

Log

Log event hooks log the specified event and content of the payload into the Kong Gateway logs.

To create a log event hook:

  1. Create a log event hook on the consumers event (Kong entity the event hook will listen to for events) and on the crud source (action that triggers logging) using the following HTTP request:

    cURL

    HTTPie

    1. curl -i -X POST http://{HOSTNAME}:8001/event-hooks \
    2. -d source=crud \
    3. -d event=consumers \
    4. -d handler=log
    1. http -f :8001/event-hooks \
    2. source=crud \
    3. event=consumers \
    4. handler=log
  2. In Kong Manager or Kong Admin API, add a consumer from any workspace.

    Kong Manager

    Admin API

    1. Select the workspace.
    2. Select Consumers in the left navigation.
    3. Select the New Consumer button.
    4. Enter a Username.
    5. (Optional) Enter a Custom ID and any Tags.
    6. Select the Create button.

    Create a consumer, Elizabeth Bennet, by making the following HTTP request to your instance of the Kong Admin API:

    cURL

    HTTPie

    1. curl -i -X POST http://{HOSTNAME}:8001/consumers \
    2. -d username="Elizabeth Bennet"
    1. http -f :8001/consumers \
    2. username="Elizabeth Bennet"
  3. You should see an entry with data for the new consumer in the payload in Kong’s error log, which is typically accessible at /usr/local/kong/logs/error.log.

    1. 172.19.0.1 - - [29/Jul/2021:15:57:15 +0000] "POST /consumers HTTP/1.1" 409 147 "-" "HTTPie/2.4.0"
    2. 2021/07/29 15:57:26 [notice] 68854#0: *819021 +--------------------------------------------------+, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    3. 2021/07/29 15:57:26 [notice] 68854#0: *819021 |[kong] event_hooks.lua:?:452 "log callback: " { "consumers", "crud", {|, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    4. 2021/07/29 15:57:26 [notice] 68854#0: *819021 | entity = { |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    5. 2021/07/29 15:57:26 [notice] 68854#0: *819021 | created_at = 1627574246, |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    6. 2021/07/29 15:57:26 [notice] 68854#0: *819021 | id = "4757bd6b-8d54-4b08-bf24-01e346a9323e",|, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    7. 2021/07/29 15:57:26 [notice] 68854#0: *819021 | type = 0, |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    8. 2021/07/29 15:57:26 [notice] 68854#0: *819021 | username = "Elizabeth Bennet" |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    9. 2021/07/29 15:57:26 [notice] 68854#0: *819021 | }, |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    10. 2021/07/29 15:57:26 [notice] 68854#0: *819021 | operation = "create", |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    11. 2021/07/29 15:57:26 [notice] 68854#0: *819021 | schema = "consumers" |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    12. 2021/07/29 15:57:26 [notice] 68854#0: *819021 | }, 68854 } |, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001
    13. 2021/07/29 15:57:26 [notice] 68854#0: *819021 +--------------------------------------------------+, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001

Lambda

The lambda event hook allows you to write completely custom logic in Lua code and hook it into a variety of Kong events. The following example writes a log entry any time a consumer changes, but conditionally and with custom formatting.

To create a lambda event hook:

  1. Create a Lua script to load into the lambda event hook and save it to a file named lambda.lua on your home directory.

    1. return function (data, event, source, pid)
    2. local user = data.entity.username
    3. error("Event hook on consumer " .. user .. "")
    4. end
  2. Create a lambda event hook on the consumers event (Kong entity the event hook will listen to for events) and on the crud source (action that triggers logging) using the following HTTP request:

    cURL

    HTTPie

    1. curl -i -X POST http://{HOSTNAME}:8001/event-hooks \
    2. -d source=crud \
    3. -d event=consumers \
    4. -d handler=lambda \
    5. -F config.functions='return function (data, event, source, pid) local user = data.entity.username error("Event hook on consumer " .. user .. "")end'
    1. http -f :8001/event-hooks \
    2. source=crud \
    3. event=consumers \
    4. handler=lambda \
    5. config.functions[]=@~/lambda.lua
  3. In Kong Manager or Kong Admin API, add a consumer to any workspace.

    Kong Manager

    Admin API

    1. Select the workspace.
    2. Select Consumers in the left navigation.
    3. Select the New Consumer button.
    4. Enter a Username.
    5. (Optional) Enter a Custom ID and any Tags.
    6. Select the Create button.

    Create a consumer, Lois Lane, by making the following HTTP request to your instance of the Kong Admin API:

    cURL

    HTTPie

    1. curl -i -X POST http://{HOSTNAME}:8001/consumers \
    2. -d username="Lois Lane"
    1. http -f :8001/consumers \
    2. username="Lois Lane"
  4. You should see an entry “Event hook on consumer Lois Lane” in Kong’s error log, which is typically accessible at /usr/local/kong/logs/error.log.

    1. 2021/07/29 21:52:54 [error] 114#0: *153047 [kong] event_hooks.lua:190 [string "return function (data, event, source, pid)..."]:3: Event hook on consumer Lois Lane, context: ngx.timer, client: 172.19.0.1, server: 0.0.0.0:8001