micobu/gitea.php

83 lines
2.0 KiB
PHP
Raw Normal View History

2022-01-18 21:04:35 +01:00
<?php
// Micobu Gitea Hook
$secret_key = 'mykey';
$micobu_pipe = '/var/tmp/micobu_pipe';
$micobu_key = "mykey";
// check for POST request
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
error_log('GITEA HOOK: FAILED - not POST - '. $_SERVER['REQUEST_METHOD']);
exit();
}
// get content type
$content_type = isset($_SERVER['CONTENT_TYPE']) ? strtolower(trim($_SERVER['CONTENT_TYPE'])) : '';
if ($content_type != 'application/json') {
error_log('GITEA HOOK: FAILED - not application/json - '. $content_type);
exit();
}
// get payload
$payload = trim(file_get_contents("php://input"));
if (empty($payload)) {
error_log('GITEA HOOK: FAILED - no payload');
exit();
}
// get header signature
$header_signature = isset($_SERVER['HTTP_X_GITEA_SIGNATURE']) ? $_SERVER['HTTP_X_GITEA_SIGNATURE'] : '';
if (empty($header_signature)) {
error_log('GITEA HOOK: FAILED - header signature missing');
exit();
}
// calculate payload signature
$payload_signature = hash_hmac('sha256', $payload, $secret_key, false);
// check payload signature against header signature
if ($header_signature !== $payload_signature) {
error_log('GITEA HOOK: FAILED - payload signature');
exit();
}
// convert json to array
$decoded = json_decode($payload);
// check for json decode errors
if (json_last_error() !== JSON_ERROR_NONE) {
error_log('GITEA HOOK: FAILED - json decode - '. json_last_error());
exit();
}
// success, do something
$name = $decoded->repository->name;
$url = $decoded->repository->html_url;
$hash = $decoded->after;
preg_match("/^[_\-A-Za-z0-9]{1,30}$/", $name, $matches);
if (!$matches) {
error_log('GITEA HOOK: FAILED - name verification');
exit();
}
preg_match("/^[_\-A-Za-z0-9:\/\.]{1,150}$/", $url, $matches);
if (!$matches) {
error_log('GITEA HOOK: FAILED - url verification');
exit();
}
preg_match("/^[A-Za-z0-9]{1,50}$/", $hash, $matches);
if (!$matches) {
error_log('GITEA HOOK: FAILED - hash verification');
exit();
}
file_put_contents($micobu_pipe, "$micobu_key $name $url $hash\n");
?>