[projects/pld-builder.new] request_handler: answer with a status code that tells what went wrong
arekm
arekm at pld-linux.org
Mon Oct 26 17:17:26 CET 2026
commit 32115f141527e3dcd9c42167d4c73f097bbd277d
Author: Arkadiusz Miśkiewicz <arekm at maven.pl>
Date: Sat Oct 24 13:59:26 2026 +0200
request_handler: answer with a status code that tells what went wrong
Every rejection was a 500, so make-request.sh retried bad signatures.
Now malformed requests get 400, refusals 403, a missing length 411,
GET 405, and only builder failures 500.
PLD_Builder/request_handler.py | 99 +++++++++++++++++------------------
PLD_Builder/request_handler_server.py | 41 ++++++++++-----
2 files changed, 77 insertions(+), 63 deletions(-)
---
diff --git a/PLD_Builder/request_handler.py b/PLD_Builder/request_handler.py
index 8a3381d..314ce71 100644
--- a/PLD_Builder/request_handler.py
+++ b/PLD_Builder/request_handler.py
@@ -2,6 +2,8 @@
import time
import sys
+from http import HTTPStatus
+from xml.parsers.expat import ExpatError
import gpg
import request
import log
@@ -35,7 +37,7 @@ def check_double_id(id):
def handle_group(r, user):
lockf = None
- def fail_mail(msg):
+ def refuse(status, msg):
if len(r.batches) >= 1:
spec = r.batches[0].spec
else:
@@ -46,11 +48,14 @@ def handle_group(r, user):
m.set_headers(subject = "building %s failed" % spec)
m.write_line(msg)
m.send()
+ lockf.close()
+ return status
lockf = lock("request")
if check_double_id(r.id):
+ # resent after it was queued
lockf.close()
- return
+ return HTTPStatus.OK
try:
if (user.change_requester and r.requester):
@@ -64,21 +69,15 @@ def handle_group(r, user):
for batch in r.batches:
if not user.can_do("src", config.builder, batch.branch):
- fail_mail("user %s is not allowed to src:%s:%s" \
+ return refuse(HTTPStatus.FORBIDDEN, "user %s is not allowed to src:%s:%s" \
% (user.get_login(), config.builder, batch.branch))
- lockf.close()
- return
if 'test-build' in r.flags and 'upgrade' in r.flags:
- fail_mail("it's forbidden to upgrade from a test build")
- lockf.close()
- return
+ return refuse(HTTPStatus.BAD_REQUEST, "it's forbidden to upgrade from a test build")
if "upgrade" in r.flags and not user.can_do("upgrade", config.builder, batch.branch):
- fail_mail("user %s is not allowed to upgrade:%s:%s" \
+ return refuse(HTTPStatus.FORBIDDEN, "user %s is not allowed to upgrade:%s:%s" \
% (user.get_login(), config.builder, batch.branch))
- lockf.close()
- return
# src builder handles only special commands
if batch.is_command() and (batch.command in ["git pull"] or batch.command[:5] == "skip:" or config.builder in batch.builders):
@@ -93,44 +92,32 @@ def handle_group(r, user):
batch.builders_status[bld] = '?'
batch.builders_status_time[bld] = time.time()
if bld not in config.binary_builders and bld != config.builder:
- fail_mail("I (src rpm builder '%s') do not handle binary builder '%s', only '%s'" % \
+ return refuse(HTTPStatus.BAD_REQUEST, "I (src rpm builder '%s') do not handle binary builder '%s', only '%s'" % \
(config.builder, bld, ' '.join(config.binary_builders)))
- lockf.close()
- return
if batch.is_command():
if "no-chroot" in batch.command_flags:
if not user.can_do("command-no-chroot", bld):
- fail_mail("user %s is not allowed to command-no-chroot:%s" \
+ return refuse(HTTPStatus.FORBIDDEN, "user %s is not allowed to command-no-chroot:%s" \
% (user.get_login(), bld))
- lockf.close()
- return
if not user.can_do("command", bld):
- fail_mail("user %s is not allowed to command:%s" \
+ return refuse(HTTPStatus.FORBIDDEN, "user %s is not allowed to command:%s" \
% (user.get_login(), bld))
- lockf.close()
- return
elif not user.can_do("binary", bld, batch.branch):
pkg = batch.spec
if pkg.endswith(".spec"):
pkg = pkg[:-5]
if not user.can_do("binary-" + pkg, bld, batch.branch):
- fail_mail("user %s is not allowed to binary-%s:%s:%s" \
+ return refuse(HTTPStatus.FORBIDDEN, "user %s is not allowed to binary-%s:%s:%s" \
% (user.get_login(), pkg, bld, batch.branch))
- lockf.close()
- return
if not "test-build" in r.flags and not user.can_do("ready", bld, batch.branch):
- fail_mail("user %s is not allowed to send ready builds (ready:%s:%s)" \
+ return refuse(HTTPStatus.FORBIDDEN, "user %s is not allowed to send ready builds (ready:%s:%s)" \
% (user.get_login(), bld, batch.branch))
- lockf.close()
- return
pkg = batch.spec
if pkg.endswith(".spec"):
pkg = pkg[:-5]
if not "test-build" in r.flags and blacklist.package(pkg):
- fail_mail("package '%s' is blacklisted, only test-builds allowed" % pkg)
- lockf.close()
- return
+ return refuse(HTTPStatus.FORBIDDEN, "package '%s' is blacklisted, only test-builds allowed" % pkg)
r.priority = user.check_priority(r.priority,config.builder)
r.time = time.time()
@@ -142,12 +129,13 @@ def handle_group(r, user):
q.write()
q.unlock()
lockf.close()
+ return HTTPStatus.OK
def handle_notification(r, user):
if not user.can_do("notify", r.builder):
# fail the request: the sender keeps retrying and mails about it
log.alert("user %s is not allowed to notify:%s" % (user.login, r.builder))
- return False
+ return HTTPStatus.FORBIDDEN
q = B_Queue(path.req_queue_file)
q.lock(0)
q.read()
@@ -172,42 +160,53 @@ def handle_notification(r, user):
q.dump_html(path.queue_html_stats_file)
q.write_signed(path.req_queue_signed_file)
q.unlock()
- return True
+ return HTTPStatus.OK
+
+def reject_request(user, msg):
+ log.alert(msg)
+ m = user.message_to()
+ m.set_headers(subject = "invalid request")
+ m.write_line(msg)
+ m.send()
+ return HTTPStatus.BAD_REQUEST
def handle_request(req, filename = None):
- if req == '':
+ """Verify and handle a signed request, return the HTTP status for it.
+
+ Failures on the builder's side raise instead.
+ """
+ if not req:
log.alert('Empty body received. Filename: %s' % filename)
- return False
+ return HTTPStatus.BAD_REQUEST
keys = gpg.get_keys(req)
(em, body) = gpg.verify_sig(req)
if not em:
log.alert("Invalid signature, missing/untrusted key. Keys in gpg batch: '%s'" % keys)
- return False
+ return HTTPStatus.FORBIDDEN
user = acl.user_by_email(em)
if user == None:
# FIXME: security email here
log.alert("'%s' not in acl. Keys in gpg batch: '%s'" % (em, keys))
- return False
+ return HTTPStatus.FORBIDDEN
acl.set_current_user(user)
status.push("request from %s" % user.login)
- r = request.parse_request(body)
- ok = True
- if r.kind == 'group':
- handle_group(r, user)
- elif r.kind == 'notification':
- ok = handle_notification(r, user)
+ try:
+ r = request.parse_request(body)
+ # a missing attribute is a KeyError, a bad number a ValueError
+ except (ExpatError, log.Panic, KeyError, ValueError) as e:
+ ret = reject_request(user, f"{user.get_login()}: invalid request: {e}")
else:
- msg = "%s: don't know how to handle requests of this kind '%s'" \
- % (user.get_login(), r.kind)
- log.alert(msg)
- m = user.message_to()
- m.set_headers(subject = "unknown request")
- m.write_line(msg)
- m.send()
+ if r.kind == 'group':
+ ret = handle_group(r, user)
+ elif r.kind == 'notification':
+ ret = handle_notification(r, user)
+ else:
+ ret = reject_request(user, "%s: don't know how to handle requests of this kind '%s'" \
+ % (user.get_login(), r.kind))
status.pop()
- return ok
+ return ret
def handle_request_main(req, filename = None):
acl.try_reload()
@@ -219,7 +218,7 @@ def handle_request_main(req, filename = None):
return ret
def main():
- sys.exit(not handle_request_main(sys.stdin.read()))
+ sys.exit(handle_request_main(sys.stdin.read()) != HTTPStatus.OK)
if __name__ == '__main__':
wrap.wrap(main)
diff --git a/PLD_Builder/request_handler_server.py b/PLD_Builder/request_handler_server.py
index 4aa9cbf..2430684 100644
--- a/PLD_Builder/request_handler_server.py
+++ b/PLD_Builder/request_handler_server.py
@@ -1,5 +1,6 @@
#!/usr/bin/python3
+import re
import socket
import log
import signal
@@ -9,6 +10,7 @@ import traceback
import os
from config import config, init_conf
+from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ForkingMixIn
@@ -37,37 +39,50 @@ class ForkingHTTPServer(ForkingMixIn, HTTPServer):
signal.signal(signal.SIGINT, signal.SIG_DFL)
super().finish_request(request, client_address)
+def status_text(s):
+ # the reason phrase is one latin-1 line; make-request shows it to the user
+ return re.sub(r'[^\x20-\x7e]', '?', s)
+
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
- self.send_error(401);
+ self.send_response(HTTPStatus.METHOD_NOT_ALLOWED)
+ self.send_header('Allow', 'POST')
+ self.send_header('Content-Length', '0')
+ self.end_headers()
def do_POST(self):
filename = None
try:
- length = int(self.headers.get('content-length'))
filename = self.headers.get('x-filename')
- if not length:
- log.error("request_handler_server: [%s]: 401 Unauthorized" % self.client_address[0])
- self.send_error(401)
- self.end_headers()
+ if self.headers.get('content-length') is None:
+ log.error("request_handler_server: [%s]: 411 Length Required" % self.client_address[0])
+ self.send_error(HTTPStatus.LENGTH_REQUIRED)
+ return
+ try:
+ length = int(self.headers.get('content-length'))
+ except ValueError:
+ length = 0
+ if length <= 0:
+ log.error("request_handler_server: [%s]: 400 Bad Request: no body" % self.client_address[0])
+ self.send_error(HTTPStatus.BAD_REQUEST, "no request body")
return
query = self.rfile.read(length)
- if not request_handler.handle_request_main(query, filename = filename):
+ status = request_handler.handle_request_main(query, filename = filename)
+ if status != HTTPStatus.OK:
error = log.last_log();
- log.error("request_handler_server: [%s]: handle_request_main(..., %s) failed" % (self.client_address[0], filename))
- self.send_error(500, "%s: request failed. %s" % (filename, error))
- self.end_headers()
+ log.error("request_handler_server: [%s]: handle_request_main(..., %s) failed: %d %s" % (self.client_address[0], filename, status.value, status.phrase))
+ # send_error() ends the headers itself
+ self.send_error(status, status_text("%s: request failed. %s" % (filename, error)))
return
- self.send_response(200)
+ self.send_response(HTTPStatus.OK)
self.end_headers()
except Exception as e:
- self.send_error(500, "%s: %s" % (filename, e))
- self.end_headers()
+ self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR, status_text("%s: %s" % (filename, e)))
log.error("request_handler_server: [%s]: exception: %s\n%s" % (self.client_address[0], e, traceback.format_exc()))
raise
pass
================================================================
---- gitweb:
http://git.pld-linux.org/gitweb.cgi/projects/pld-builder.new.git/commitdiff/ce9feb3c796ed049b6dd260a50d94d80feb1656d
More information about the pld-cvs-commit
mailing list