Github AWS 的 Webhooks 秘密 API 网关

Github Webhooks secret with AWS API Gateway

我正在尝试让 Github Webhook 启动我拥有的 AWS Lambda。 我能弄清楚如何做到这一点的最好方法是使用 AWS API 网关,问题是安全性。

Github Webhook 只会通过 POST 调用发送秘密。

我找不到任何方法让 AWS API 网关验证此签名。 或者我可以在哪里添加此功能。

我想我可以写一篇 AWS Lambda Authorizer。 但这是很多代码在不同的地方,开始看到需要serverless框架。

我不知道在 AWS 中有没有更简单的设置?

我找不到使用 API 网关执行此操作的方法。我使用 (Python) 在 LAMBDA 中进行了验证。

高级概述:使用 GITHUB_SECRET 计算 HMAC 签名,然后与从 Github 传递的签名进行比较。

您显然可以简化,为了便于阅读而故意冗长。可能有更好的方法,但我找不到。

确保为 application/json 配置了 Webhook。希望这对其他人有帮助。

import logging
import json
import hmac
import hashlib
import re
from urllib.parse import unquote

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

GITHUB_SECRET = 'SECRET FROM GITHUB CONSOLE'


def lambda_handler(event, context):
    logger.info("Lambda execution starting up...")

    incoming_signature = re.sub(r'^sha1=', '', event['headers']['X-Hub-Signature'])
    incoming_payload = unquote(re.sub(r'^payload=', '', event['body']))
    calculated_signature = calculate_signature(GITHUB_SECRET, incoming_payload.encode('utf-8'))

    if incoming_signature != calculated_signature:
        logger.error('Unauthorized attempt')
        return {
            'statusCode': 403,
            'body': json.dumps('Forbidden')
        }

    logger.info('Request successfully authorized')

    # do stuff in Lambda

    return {
        'statusCode': 200,
        'body': json.dumps(f'Work in progress')
    }


def calculate_signature(github_signature, githhub_payload):
    signature_bytes = bytes(github_signature, 'utf-8')
    digest = hmac.new(key=signature_bytes, msg=githhub_payload, digestmod=hashlib.sha1)
    signature = digest.hexdigest()
    return signature

来到这里是因为我试图将 Github webhook 与 AWS lambda 和 运行 集成到与 OP 相同的问题中。在撰写本文时,我认为最好的解决方案是在主 lambda 中包含验证代码,正如其他人所建议的那样。

在 2017 年 9 月的 AWS 计算机博客上:

Enhanced request authorizer Lambda functions receive an event object that is similar to proxy integrations. It contains all of the information about a request, excluding the body.

来源: Using Enhanced Request Authorizers in Amazon API Gateway (amazon.com)

您无法按照 Github 的建议执行 HMAC,因为 AWS 授权方 lambda 不允许您访问 HTTP 请求的 body,而您需要使用它来比较摘要.

这很遗憾,因为 HMAC 似乎是保护响应 webhook 的端点的一种非常标准的方法。例如,请参阅此博客 post、Webhooks do’s and dont’s: what we learned after integrating +100 APIs (restful.io)。 Twitter 和 Stripe 做了类似的事情:

要使上述方法起作用,如果您使用的是 API 网关,则需要确保包含哈希签名的 header 作为 event lambda 的参数。为此,请按照以下说明操作:How do I pass custom headers through Amazon API Gateway to an AWS Lambda function using custom Lambda integration for further processing? (amazon.com)