基于 OpenResty + GitHub WebHook 的代码自动更新

OpenResty

OpenResty 是一个基于 Nginx 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。

安装及使用请参阅OpenResty官网

Nginx配置

1
2
3
4
5
6
7
8
9
server {
listen 80;
server_name yourdomain;

location /webhook {
default_type 'text/plain';
content_by_lua_file /your/lua/path/webhook.lua;
}
}

webhook.lua 源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
local GITHUB_WEBHOOK_SECRET = "your github webhook secret"

local request_method = ngx.var.request_method
if "POST" ~= request_method then
ngx.exit(404)
end

local signature = ngx.req.get_headers()["X-Hub-Signature"]
if signature == nil then
return ngx.exit(404)
end

ngx.req.read_body()
local req_body = ngx.req.get_body_data()
if not req_body then
return ngx.exit(404)
end

local dt = {}
for k, v in string.gmatch(signature, "(%w+)=(%w+)") do
dt[k] = v
end

local str = require "resty.string"

local digest = ngx.hmac_sha1(GITHUB_WEBHOOK_SECRET, req_body)

if str.to_hex(digest) ~= dt["sha1"] then
ngx.log(ngx.ERR, "signature error")
return ngx.exit(404)
end

os.execute("cd /your/blog/repositorie/path/ && git pull");
ngx.say("OK")

签名校验务必写成 ~=

Lua 中 not 是一元运算符,优先级高于 ==。若写成 if not str.to_hex(digest) == dt["sha1"] then,实际会被解析为 if (not str.to_hex(digest)) == dt["sha1"] then

str.to_hex(digest) 返回非空字符串(真值),not 之后恒为 false,再与十六进制签名串比较永远不相等——该分支永不执行,HMAC 校验形同虚设,任何人知道 URL 即可触发部署。