webhook

repository·master·Indexed 11 days ago

https://github.com/adnanh/webhook

A lightweight, configurable tool written in Go that allows you to create HTTP endpoints (hooks) to execute local commands. It integrates with services like GitHub, Bitbucket, Slack, or Mattermost by triggering scripts based on incoming HTTP requests, supporting JSON or YAML configuration, HMAC signature validation (SHA1, SHA256, SHA512), and complex trigger rules using logical operators.

Tokens
7.5K
Snippets
18
Records
37
Agent score
90%

What's inside webhook

  1. How systemd socket activation works with webhook

    master

    On systemd-based platforms, webhook supports socket activation. In this mode, systemd manages the listening socket and launches webhook only when the first request arrives.

    Advantages:

    • Privilege Escalation Avoidance: webhook can run as a normal user while binding to privileged ports (like 80 or 443) because systemd handles the initial bind.
    • Connection Resilience: If the webhook process restarts, pending connections are not dropped; they wait in the systemd socket until the process is ready.

    Behavior: webhook automatically detects socket activation via environment variables. When detected, it ignores the -port and -socket CLI options and uses the socket provided by systemd.

  2. Use logical operators (And, Or, Not) in hook rules

    master

    You can combine multiple rules using logical operators to create complex triggering conditions:

    • And: Evaluates to true only if all sub-rules are true.
    • Or: Evaluates to true if any sub-rule is true.
    • Not: Evaluates to true only if the sub-rule is false.

    You can nest these operators to create multi-level logic (e.g., an and rule containing an or rule).

    {
        "and": [
        {
            "match": {
                "parameter": {
                    "source": "header",
                    "name": "X-Hub-Signature"
                },
                "type": "payload-hmac-sha1",
                "secret": "mysecret"
            }
        },
        {
            "or": [
            {
                "match":
                {
                    "parameter":
                    {
                        "source": "payload",
                        "name": "ref"
                    },
                    "type": "value",
                    "value": "refs/heads/master"
                }
            },
            {
                "match":
                {
                    "parameter":
                    {
                        "source": "header",
                        "name": "X-GitHub-Event"
                    },
                    "type": "value",
                    "value": "ping"
                }
            }
            ]
        }
        ]
    }
  3. How webhook processes requests

    master

    The webhook tool follows a simple lifecycle for every incoming request:

    1. Receive the HTTP request.
    2. Parse the headers, payload, and query variables.
    3. Check if the specified trigger-rule properties for the hook are satisfied.
    4. Execute the specified command, passing arguments via command line arguments or environment variables.
  4. Define a webhook hook

    master
    Hooks are defined as objects within a JSON or YAML configuration file. To be considered valid, every hook object must contain the id and execute-command properties. All other properties are optional and allow you to customize the execution environment, response behavior, and trigger logic.
  5. Use template functions to inject secrets and environment variables

    master

    Webhook supports standard Go template features and provides three specific functions to help manage dynamic configuration and secrets: getenv, cat, and credential.

    When using these functions to inject strings into JSON or YAML, it is highly recommended to pipe the result through the built-in Go template function js (e.g., {{ getenv "VAR" | js }}). This ensures that the injected value is properly escaped and remains a well-formed string within your configuration file.

    {
      "secret": "{{ getenv "MY_VAR" | js }}"
    }
  6. Handle Multipart Form Data

    master

    webhook provides limited support for parsing multipart form data:

    • Form Values: All values are automatically added to the payload scope.
    • JSON Parsing: Use the parse-parameters-as-json setting to parse specific values or file parts as JSON. When a file part is parsed as JSON, it is added to the payload map.
    • Files: Files are ignored unless they have a Content-Type of application/json or are specified in the parse-parameters-as-json setting.
  7. Run webhook behind a reverse proxy

    master

    You can run webhook behind a reverse proxy like Nginx or Apache. The proxy forwards requests to webhook via a TCP port or a Unix domain socket (using the -socket flag).

    Important Security Note: When running behind a proxy, the ip-whitelist trigger rule will check the IP address of the proxy instead of the original client. You must enforce client IP restrictions within the proxy configuration itself.

  8. Install webhook

    master

    You can install webhook using several methods depending on your environment:

    Building from source

    Ensure you have Go 1.21 or newer installed, then run:

    go build github.com/adnanh/webhook

    Using package managers

    • Snap: Available via the Snap Store.
    • Ubuntu: sudo apt-get install webhook (requires 17.04 or later).
    • Debian: sudo apt-get install webhook (requires "stretch" or later).
    • FreeBSD: pkg install webhook.

    Prebuilt binaries

    Download binaries for various architectures from the GitHub Releases page.

    go build github.com/adnanh/webhook
  9. Configure HTTPS for webhook

    master

    By default, webhook serves requests over HTTP. To enable HTTPS, use the -secure flag and provide your certificate and private key using the -cert and -key flags.

    If using a CA-signed certificate, the certificate file should be a concatenation of the server's certificate followed by the CA's certificate.

    Available flags for TLS configuration:

    • -secure: Enables HTTPS.
    • -cert /path/to/cert.pem: Path to the certificate file.
    • -key /path/to/key.pem: Path to the private key file.
    • -tls-min-version: Sets the minimum TLS version.
    • -list-cipher-suites: Lists available cipher suites (can be used with -tls-min-version).
  10. Configure systemd socket activation for webhook

    master

    To use socket activation, you must create two matching unit files in your systemd directory (e.g., /etc/systemd/system/): webhook.socket and webhook.service.

    1. Create the Socket Unit (webhook.socket)

    The socket unit defines how systemd listens for incoming connections.

    Example: Listen on all interfaces, port 9000

    [Unit]
    Description=Webhook server socket
    
    [Socket]
    ListenStream=9000
    
    [Install]
    WantedBy=multi-user.target

    Configuration Options for [Socket]:

    • Specific Interface: Use ListenStream=10.0.0.1:9000 and set FreeBind=true to listen on a single interface.
    • Unix Domain Socket: Use ListenStream=/tmp/webhook.sock to use a file-based socket instead of a network port.

    2. Create the Service Unit (webhook.service)

    The service unit defines how webhook is executed. Note that Type=exec is used for socket activation.

    Example Service Configuration

    [Unit]
    Description=Webhook server
    
    [Service]
    Type=exec
    ExecStart=webhook -nopanic -hooks /etc/webhook/hooks.yml
    
    # Run as a non-privileged user
    User=nobody
    Group=nogroup

    3. Enable and Start

    Only the socket needs to be enabled and started. The service will start automatically upon the first request.

    sudo systemctl enable webhook.socket
    sudo systemctl start webhook.socket
    sudo systemctl enable webhook.socket
    sudo systemctl start webhook.socket
  11. Find webhook usage examples and guides

    master

    For complex hook configurations and real-world implementation patterns, refer to the following resources:

    • Hook Examples: Detailed examples of various hook configurations can be found in the docs/Hook-Examples.md file.
    • Community Guides: There is an extensive list of community-contributed guides covering use cases such as:
      • Deploying React apps with Slack integration.
      • Automating static site deployments (Salt, Git, Zola).
      • Triggering Ansible AWX jobs from SCM commits.
      • Integrating with Plex, JIRA, and GitHub.
    • Community Contributions: The webhook-contrib repository contains a collection of tools and helpers contributed by the community.