comparison 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
comparison
equal deleted inserted replaced
43:6854efe15210 44:576f4b1ec79f
35 #include "page-api-workers.h" 35 #include "page-api-workers.h"
36 #include "page-index.h" 36 #include "page-index.h"
37 #include "page-jobresults.h" 37 #include "page-jobresults.h"
38 #include "page-static.h" 38 #include "page-static.h"
39 #include "pageutil.h" 39 #include "pageutil.h"
40 #include "scid.h"
40 41
41 enum page { 42 enum page {
42 PAGE_INDEX, /* Job results at index. */ 43 PAGE_INDEX, /* Job results at index. */
43 PAGE_JOBRESULTS, /* List of jobresult for one job. */ 44 PAGE_JOBRESULTS, /* List of jobresult for one job. */
44 PAGE_API, 45 PAGE_API,
45 PAGE_STATIC, 46 PAGE_STATIC,
46 PAGE_LAST /* Not used. */ 47 PAGE_LAST /* Not used. */
47 }; 48 };
49
50 static int
51 allowed(const struct kreq *req)
52 {
53 for (size_t i = 0; i < req->reqsz; ++i)
54 if (strcmp(req->reqs[i].key, "X-Api-Key") == 0 &&
55 strcmp(req->reqs[i].val, scid.apikey) == 0)
56 return 1;
57
58 return 0;
59 }
48 60
49 static void 61 static void
50 dispatch_api(struct kreq *req) 62 dispatch_api(struct kreq *req)
51 { 63 {
52 static const struct { 64 static const struct {
59 { "v1/todo", page_api_v1_todo }, 71 { "v1/todo", page_api_v1_todo },
60 { "v1/workers", page_api_v1_workers }, 72 { "v1/workers", page_api_v1_workers },
61 { NULL, NULL } 73 { NULL, NULL }
62 }; 74 };
63 75
64 for (size_t i = 0; apis[i].prefix; ++i) 76 /* Any API page requires authentication key. */
65 if (strncmp(req->path, apis[i].prefix, strlen(apis[i].prefix)) == 0) 77 if (req->method == KMETHOD_POST && !allowed(req)) {
66 return apis[i].handler(req); 78 log_warn("http: client not allowed");
79 pageutil_status(req, KHTTP_401);
80 } else {
81 for (size_t i = 0; apis[i].prefix; ++i)
82 if (strncmp(req->path, apis[i].prefix, strlen(apis[i].prefix)) == 0)
83 return apis[i].handler(req);
67 84
68 pageutil_status(req, KHTTP_404); 85 pageutil_status(req, KHTTP_404);
86 }
69 } 87 }
70 88
71 static const char *pages[] = { 89 static const char *pages[] = {
72 [PAGE_INDEX] = "", 90 [PAGE_INDEX] = "",
73 [PAGE_JOBRESULTS] = "jobresults", 91 [PAGE_JOBRESULTS] = "jobresults",
85 static void 103 static void
86 process(struct kreq *req) 104 process(struct kreq *req)
87 { 105 {
88 assert(req); 106 assert(req);
89 107
90 log_debug("http: accessing page '%s'", req->fullpath); 108 log_debug("http: accessing page '%s' method %d", req->fullpath, req->method);
91 109
92 if (req->page == PAGE_LAST) 110 if (req->page == PAGE_LAST)
93 pageutil_status(req, KHTTP_404); 111 pageutil_status(req, KHTTP_404);
94 else 112 else
95 handlers[req->page](req); 113 handlers[req->page](req);