diff scid/http.c @ 44:576f4b1ec79f

scid: implement API authentication
author David Demelier <markand@malikania.fr>
date Thu, 11 Aug 2022 21:24:07 +0200
parents 00b9af607524
children e8f24896b484
line wrap: on
line diff
--- a/scid/http.c	Thu Aug 11 11:34:32 2022 +0200
+++ b/scid/http.c	Thu Aug 11 21:24:07 2022 +0200
@@ -37,6 +37,7 @@
 #include "page-jobresults.h"
 #include "page-static.h"
 #include "pageutil.h"
+#include "scid.h"
 
 enum page {
 	PAGE_INDEX,             /* Job results at index. */
@@ -46,6 +47,17 @@
 	PAGE_LAST               /* Not used. */
 };
 
+static int
+allowed(const struct kreq *req)
+{
+	for (size_t i = 0; i < req->reqsz; ++i)
+		if (strcmp(req->reqs[i].key, "X-Api-Key") == 0 &&
+		    strcmp(req->reqs[i].val, scid.apikey) == 0)
+			return 1;
+
+	return 0;
+}
+
 static void
 dispatch_api(struct kreq *req)
 {
@@ -61,11 +73,17 @@
 		{ NULL,                 NULL                    }
 	};
 
-	for (size_t i = 0; apis[i].prefix; ++i)
-		if (strncmp(req->path, apis[i].prefix, strlen(apis[i].prefix)) == 0)
-			return apis[i].handler(req);
+	/* Any API page requires authentication key. */
+	if (req->method == KMETHOD_POST && !allowed(req)) {
+		log_warn("http: client not allowed");
+		pageutil_status(req, KHTTP_401);
+	} else {
+		for (size_t i = 0; apis[i].prefix; ++i)
+			if (strncmp(req->path, apis[i].prefix, strlen(apis[i].prefix)) == 0)
+				return apis[i].handler(req);
 
-	pageutil_status(req, KHTTP_404);
+		pageutil_status(req, KHTTP_404);
+	}
 }
 
 static const char *pages[] = {
@@ -87,7 +105,7 @@
 {
 	assert(req);
 
-	log_debug("http: accessing page '%s'", req->fullpath);
+	log_debug("http: accessing page '%s' method %d", req->fullpath, req->method);
 
 	if (req->page == PAGE_LAST)
 		pageutil_status(req, KHTTP_404);