29
30
31:- module(webhook,
32 [ webhook_authorized/1 33 ]). 34:- use_module(library(settings)). 35:- use_module(library(sha)). 36:- use_module(library(lists)). 37:- use_module(library(apply)). 38:- use_module(library(debug)). 39:- use_module(openid). 40:- use_module(csrf).
60:- setting(secret, atom, '',
61 'Shared secret for GitHub webhooks (/blog/pull, /examples/pull)'). 62
63max_body_size(1_000_000).
70webhook_authorized(Request) :-
71 memberchk(x_hub_signature_256(Signature), Request),
72 !,
73 ( setting(secret, Secret),
74 Secret \== '',
75 read_body(Request, Body),
76 hmac_sha(Secret, Body, HMAC, [ algorithm(sha256),
77 encoding(octet)
78 ]),
79 hash_atom(HMAC, Hex),
80 atom_concat('sha256=', Hex, Expected),
81 same_string(Expected, Signature)
82 -> debug(webhook, 'Valid webhook signature', [])
83 ; refuse(Request)
84 ).
85webhook_authorized(Request) :-
86 site_user_logged_in(User),
87 site_user_property(User, granted(admin)),
88 !,
89 csrf_check(Request).
90webhook_authorized(Request) :-
91 refuse(Request).
92
93refuse(Request) :-
94 memberchk(path(Path), Request),
95 throw(http_reply(forbidden(Path))).
101read_body(Request, Body) :-
102 memberchk(content_length(Len), Request),
103 max_body_size(Max),
104 Len =< Max,
105 memberchk(input(In), Request),
106 ( stream_property(In, encoding(octet))
107 -> true
108 ; set_stream(In, encoding(octet))
109 ),
110 read_string(In, Len, Body),
111 string_length(Body, Len).
118same_string(A, B) :-
119 atom_codes(A, CA),
120 atom_codes(B, CB),
121 length(CA, Len),
122 length(CB, Len),
123 foldl(xor_or, CA, CB, 0, Diff),
124 Diff == 0.
125
126xor_or(A, B, D0, D) :-
127 D is D0 \/ (A xor B)
Authorize GitHub webhook requests
Handlers such as /blog/pull and /examples/pull run `git pull`, rebuild indexes and purge the CDN. They may only be triggered by
X-Hub-Signature-256header: an HMAC-SHA256 of the request body using the secret. The secret is the settingwebhook:secret, set indata/private/plweb.confasand in the GitHub webhook configuration (Settings/Webhooks/Secret).
Anything else is refused with 403 (Forbidden).