forked from iudx/iudx-auth-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
https.js
2839 lines (2276 loc) · 57.8 KB
/
https.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vim: set ts=8 sw=4 tw=0 noet : */
/*
* Copyright (c) 2019
* Arun Babu {arun <dot> hbni <at> gmail}
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
"use strict";
const fs = require("fs");
const os = require("os");
const dns = require("dns");
const url = require("url");
const cors = require("cors");
const ocsp = require("ocsp");
const Pool = require("pg").Pool;
const https = require("https");
const chroot = require("chroot");
const crypto = require("crypto");
const logger = require("node-color-log");
const cluster = require("cluster");
const express = require("express");
const aperture = require("./node-aperture");
const immutable = require("immutable");
const geoip_lite = require("geoip-lite");
const bodyParser = require("body-parser");
const http_request = require("request");
const pgNativeClient = require("pg-native");
const pg = new pgNativeClient();
const TOKEN_LEN = 16;
const TOKEN_LEN_HEX = 2 * TOKEN_LEN;
const EUID = process.geteuid();
const is_openbsd = os.type() === "OpenBSD";
const pledge = is_openbsd ? require("node-pledge") : null;
const unveil = is_openbsd ? require("openbsd-unveil"): null;
const SUCCESS = '{"success":true}';
const NUM_CPUS = os.cpus().length;
const SERVER_NAME = "auth.iudx.org.in";
const MAX_TOKEN_TIME = 31536000; // in seconds (1 year)
const MIN_TOKEN_HASH_LEN = 64;
const MAX_TOKEN_HASH_LEN = 64;
const MAX_SAFE_STRING_LEN = 512;
const MIN_CERTIFICATE_CLASS_REQUIRED = immutable.Map({
"/auth/v1/token/introspect" : 1,
"/auth/v1/certificate-info" : 2,
"/auth/v1/token" : 2,
"/auth/v1/token/confirm-payment" : 2,
"/auth/v1/credit" : 2,
"/auth/v1/credit/topup" : 2,
"/auth/v1/audit/credits" : 2,
"/auth/v1/audit/tokens" : 3,
"/auth/v1/token/revoke" : 3,
"/auth/v1/token/revoke-all" : 3,
"/auth/v1/acl" : 3,
"/auth/v1/acl/set" : 3,
"/auth/v1/acl/append" : 3,
"/auth/v1/group/add" : 3,
"/auth/v1/group/delete" : 3,
"/auth/v1/group/list" : 3,
});
let has_started_serving_apis = false;
/* --- dns --- */
dns.setServers ([
"1.1.1.1",
"4.4.4.4",
"8.8.8.8",
"[2001:4860:4860::8888]",
"[2001:4860:4860::8844]",
]);
/* --- telegram --- */
const telegram_apikey = fs.readFileSync ("telegram.apikey","ascii").trim();
const telegram_chat_id = fs.readFileSync ("telegram.chatid","ascii").trim();
const telegram_url = "https://api.telegram.org/bot" + telegram_apikey +
"/sendMessage?chat_id=" + telegram_chat_id +
"&text=";
/* --- postgres --- */
const DB_SERVER = "127.0.0.1";
const password = {
"DB" : fs.readFileSync ("passwords/auth.db.password","ascii").trim(),
};
// async postgres connection
const pool = new Pool ({
host : DB_SERVER,
port : 5432,
user : "auth",
database : "postgres",
password : password.DB,
});
pool.connect();
// sync postgres connection
pg.connectSync (
"postgresql://auth:"+ password.DB + "@" + DB_SERVER + ":5432/postgres",
function(err)
{
if(err) {
throw err;
}
}
);
/* --- express --- */
const app = express();
app.use (
cors ({
methods : ["POST"],
credentials : true,
origin : function (origin, callback)
{
callback(null, origin ? true : false);
}
})
);
app.use(bodyParser.raw({type:"*/*"}));
app.use(security);
app.disable("x-powered-by");
/* --- aperture --- */
const apertureOpts = {
types : aperture.types,
typeTable : {
ip : "ip",
time : "time",
tokens_per_day : "number", // tokens issued today
api : "string", // the API to be called
method : "string", // the method for API
"cert.class" : "number", // the certificate class
"cert.cn" : "string",
"cert.o" : "string",
"cert.ou" : "string",
"cert.c" : "string",
"cert.st" : "string",
"cert.gn" : "string",
"cert.sn" : "string",
"cert.title" : "string",
"cert.issuer.cn" : "string",
"cert.issuer.email" : "string",
"cert.issuer.o" : "string",
"cert.issuer.ou" : "string",
"cert.issuer.c" : "string",
"cert.issuer.st" : "string",
groups : "string", // CSV actually
country : "string",
region : "string",
timezone : "string",
city : "string",
latitude : "number",
longitude : "number",
}
};
const parser = aperture.createParser (apertureOpts);
const evaluator = aperture.createEvaluator (apertureOpts);
/* --- https --- */
const trusted_CAs = [
fs.readFileSync("ca.iudx.org.in.crt"),
fs.readFileSync("/etc/ssl/cert.pem"),
fs.readFileSync("CCAIndia2015.cer"),
fs.readFileSync("CCAIndia2014.cer"),
];
const https_options = {
key : fs.readFileSync("https-key.pem"),
cert : fs.readFileSync("https-certificate.pem"),
ca : trusted_CAs,
requestCert : true,
rejectUnauthorized : true,
};
/* --- functions --- */
function sha1 (string)
{
return crypto
.createHash("sha1")
.update(string)
.digest("hex");
}
function sha256 (string)
{
return crypto
.createHash("sha256")
.update(string)
.digest("hex");
}
function base64 (string)
{
return Buffer
.from(string)
.toString("base64");
}
function log(color, msg)
{
const message = new Date() + " | " + msg;
if (color === "red") {
send_telegram(message);
}
logger.color(color).log(message);
}
function send_telegram (message)
{
http_request ( telegram_url + "[ AUTH ] : " + message,
function (error, response, body)
{
if (error)
{
log ("yellow",
"Telegram failed ! response = " +
String(response) +
" body = " +
String(body)
);
}
}
);
}
function END_SUCCESS (res, http_status, msg)
{
res.setHeader("Content-Type", "application/json");
res.status(http_status).end(msg + "\n");
}
function END_ERROR (res, http_status, msg, exception = null)
{
if (exception)
log("red", String(exception).replace(/\n/g," "));
res.setHeader("Content-Type", "application/json");
res.setHeader("Connection", "close");
res.status(http_status).end('{"error":"' + msg + '"}\n');
res.socket.end();
res.socket.destroy();
}
function is_valid_email (email)
{
if (! email || typeof email !== "string")
return false;
if (email.length < 5 || email.length > 64)
return false;
let num_ats = 0;
let num_dots = 0;
for (const chr of email)
{
if (
(chr >= "a" && chr <= "z") ||
(chr >= "A" && chr <= "Z") ||
(chr >= "0" && chr <= "9")
)
{
// ok;
}
else
{
switch (chr)
{
case "-":
case "_":
break;
case "@":
++num_ats;
break;
case ".":
++num_dots;
break;
default:
return false;
}
}
}
if (num_ats !== 1 || num_dots < 1)
return false;
return true;
}
function is_certificate_ok (req, cert, validate_email)
{
if ((! cert) || (! cert.subject))
return "Invalid certificate. No subject found";
if (validate_email)
{
if (! is_valid_email(cert.subject.emailAddress))
return "Invalid emailAddress field in the certificate";
}
if ((! cert.issuer) || (! cert.issuer.emailAddress))
return "Certificate issuer has no emailAddress field";
const issuer_email = cert.issuer.emailAddress.toLowerCase();
if (! is_valid_email(issuer_email))
return "Certificate issuer's emailAddress is invalid";
if (issuer_email.startsWith("iudx.sub.ca@"))
{
const issued_to_domain = cert.subject.emailAddress
.toLowerCase()
.split("@")[1];
const issuer_domain = issuer_email
.toLowerCase()
.split("@")[1];
if (issuer_domain !== issued_to_domain)
{
log ("red",
"Invalid certificate: issuer = "+
issuer_domain +
" and issued to = " +
cert.subject.emailAddress
);
return "Invalid certificate issuer";
}
}
return "OK";
}
function is_secure (req, res, cert, validate_email = true)
{
if (req.headers.origin)
{
const origin = req.headers.origin.toLowerCase();
// e.g Origin = https://www.iudx.org.in:8443/
if (! origin.startsWith("https://"))
return "Insecure 'origin' field";
if ((origin.match(/\//g) || []).length < 2)
return "Invalid 'origin' field";
const origin_domain = String (
origin
.split("/")[2] // remove protocol
.split(":")[0] // remove port number
);
if (! origin_domain.endsWith(".iudx.org.in"))
return "Invalid 'origin' field in the header";
res.header("X-XSS-Protection", "1; mode=block");
res.header("X-Frame-Options", "deny");
res.header("X-Content-Type-Options","nosniff");
res.header("Referrer-Policy","no-referrer-when-downgrade");
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Methods", "POST");
}
const error = is_certificate_ok (req,cert,validate_email);
if (error !== "OK")
return "Invalid certificate. " + error;
return "OK";
}
function has_certificate_been_revoked (socket, cert, CRL)
{
const cert_fingerprint = cert.fingerprint
.replace(/:/g,"")
.toLowerCase();
const cert_serial = cert.serialNumber
.toLowerCase()
.replace(/^0+/,"");
const cert_issuer = cert.issuer.emailAddress.toLowerCase();
for (const c of CRL)
{
c.issuer = c.issuer.toLowerCase();
c.serial = c.serial.toLowerCase().replace(/^0+/,"");
c.fingerprint = c.fingerprint.toLowerCase().replace(/:/g,"");
if (
(c.issuer === cert_issuer) &&
(c.serial === cert_serial) &&
(c.fingerprint === cert_fingerprint)
)
{
return true;
}
}
// If it was issued by a sub-CA then check the sub-CA's cert too
// Assuming depth is <= 3. ca@iudx.org.in -> sub-CA -> user
if (cert_issuer !== "ca@iudx.org.in")
{
const ISSUERS = [];
if (cert.issuerCertificate)
{
// both CA and sub-CA are the issuers
ISSUERS.push(cert.issuerCertificate);
if (cert.issuerCertificate.issuerCertificate)
{
ISSUERS.push (
cert.issuerCertificate.issuerCertificate
);
}
}
else
{
/*
if the issuerCertificate is empty,
then the session must have been reused
by the browser.
*/
if (! socket.isSessionReused())
return true;
}
for (const issuer of ISSUERS)
{
if (issuer.fingerprint && issuer.serialNumber)
{
issuer.fingerprint = issuer
.fingerprint
.replace(/:/g,"")
.toLowerCase();
issuer.serialNumber = issuer
.serialNumber
.toLowerCase();
for (const c of CRL)
{
if (c.issuer === "ca@iudx.org.in")
{
const crl_serial = c.serial
.toLowerCase()
.replace(/^0+/,"");
const crl_fingerprint = c.fingerprint
.replace(/:/g,"")
.toLowerCase();
if (crl_serial === issuer.serial && crl_fingerprint === issuer.fingerprint)
return true;
}
}
}
else
{
/*
if fingerprint OR serial is undefined,
then the session must have been reused
by the browser.
*/
if (! socket.isSessionReused())
return true;
}
}
}
return false;
}
function is_string_safe (str, exceptions = "")
{
if (! str || typeof str !== "string")
return false;
if (str.length === 0 || str.length > MAX_SAFE_STRING_LEN)
return false;
exceptions = exceptions + "-/.@";
for (const ch of str)
{
if (
(ch >= "a" && ch <= "z") ||
(ch >= "A" && ch <= "Z") ||
(ch >= "0" && ch <= "9")
)
{
// ok
}
else
{
if (exceptions.indexOf(ch) === -1)
return false;
}
}
return true;
}
function is_iudx_certificate(cert)
{
if (! cert.issuer.emailAddress)
return false;
const email = cert
.issuer
.emailAddress
.toLowerCase();
// certificate issuer should be IUDX CA or a IUDX sub-CA
return (email ==="ca@iudx.org.in" || email.startsWith("iudx.sub.ca@"));
}
function body_to_json (body)
{
if (! body)
return {};
let string_body;
try
{
string_body = Buffer
.from(body,"utf-8")
.toString("ascii")
.trim();
if (string_body.length === 0)
return {};
}
catch (x)
{
return {};
}
try
{
const json_body = JSON.parse (string_body);
if (json_body)
return json_body;
else
return {};
}
catch (x)
{
return null;
}
}
function security (req, res, next)
{
if (! has_started_serving_apis)
{
if (is_openbsd) // drop "rpath"
pledge.init("error stdio tty prot_exec inet dns recvfd");
has_started_serving_apis = true;
}
req.setTimeout(5000);
const api = url.parse(req.url).pathname;
// Not an API !
if ((! api.startsWith("/auth/v1/")))
return next();
const cert = req.socket.getPeerCertificate(true);
const min_class_required = MIN_CERTIFICATE_CLASS_REQUIRED.get(api);
if (! min_class_required)
{
return END_ERROR (
res, 404,
"No such API. Please visit: " +
"<http://auth.iudx.org.in> for documentation."
);
}
cert.serialNumber = cert.serialNumber.toLowerCase();
cert.fingerprint = cert.fingerprint.toLowerCase();
if (is_iudx_certificate(cert))
{
let integer_cert_class = 0;
const cert_class = cert.subject["id-qt-unotice"];
if (cert_class)
{
integer_cert_class = parseInt(
cert_class.split(":")[1],10
) || 0;
}
if (integer_cert_class < 1)
return END_ERROR(res, 403, "Invalid certificate class");
if (integer_cert_class < min_class_required)
{
return END_ERROR (
res, 403,
"A class-" + min_class_required +
" or above certificate " +
"is required to call this API"
);
}
if (api.endsWith("/introspect") && integer_cert_class !== 1)
{
return END_ERROR (
res, 403,
"A class-1 certificate is required " +
"to call this API"
);
}
const error = is_secure(req,res,cert);
if (error !== "OK")
return END_ERROR (res, 403, error);
pool.query("SELECT crl FROM crl LIMIT 1", [], (error,results) =>
{
if (error || results.rows.length === 0)
{
return END_ERROR (
res, 500,
"Internal error!", error
);
}
const CRL = results.rows[0].crl;
if (has_certificate_been_revoked(req.socket,cert,CRL))
{
return END_ERROR (
res, 403,
"Certificate has been revoked"
);
}
if (! (res.locals.body = body_to_json(req.body)))
{
return END_ERROR (
res, 400,
"Body is not a valid JSON"
);
}
res.locals.cert = cert;
res.locals.cert_class = integer_cert_class;
res.locals.email = cert
.subject
.emailAddress
.toLowerCase();
return next();
});
}
else
{
ocsp.check({cert:cert.raw, issuer:cert.issuerCertificate.raw},
function (err, ocsp_response)
{
if (err)
{
return END_ERROR (
res, 403,
"Your certificate issuer did " +
"NOT respond to an OCSP request"
);
}
if (ocsp_response.type !== "good")
{
return END_ERROR (
res, 403,
"Your certificate has been " +
"revoked by your certificate issuer"
);
}
// certificate may not have a "emailAddress" field
const error = is_secure(req,res,cert,false);
if (error !== "OK")
return END_ERROR (res, 403, error);
res.locals.cert_class = 1;
res.locals.email = "";
if (is_valid_email(cert.subject.emailAddress))
{
res.locals.cert_class = 2;
res.locals.email = cert
.subject
.emailAddress
.toLowerCase();
}
if (res.locals.cert_class < min_class_required)
{
return END_ERROR (
res, 403,
"A class-" + min_class_required +
" or above certificate is" +
" required to call this API"
);
}
if (! (res.locals.body = body_to_json(req.body)))
{
return END_ERROR (
res, 400,
"Body is not a valid JSON"
);
}
res.locals.cert = cert;
return next();
});
}
}
function object_to_array (o)
{
if (o instanceof Object)
{
if (o instanceof Array)
return o;
else
return [o];
}
return null;
}
/* --- APIs --- */
app.post("/auth/v1/token", function (req, res) {
const cert = res.locals.cert;
const cert_class = res.locals.cert_class;
const body = res.locals.body;
const consumer_id = res.locals.email;
const response_array = [];
const resource_id_dict = {};
const resource_server_token = {};
const sha256_of_resource_server_token = {};
const request_array = object_to_array(body.request);
if ((! request_array) || request_array.length < 1)
{
return END_ERROR (
res, 400,
"'request' field must be a valid JSON array " +
"with at least 1 element"
);
}
const token_rows = pg.querySync (
"SELECT COUNT(*)/60.0 " +
"AS rate " +
"FROM token " +
"WHERE id = $1::text " +
"AND issued_at >= (NOW() - interval '60 seconds')",
[
consumer_id, // 1
],
);
// in last 1 minute
const tokens_rate_per_second = parseFloat (token_rows[0].rate);
if (tokens_rate_per_second > 1) // tokens per second
{
log ("red",
"Too many requests from user : " + consumer_id +
", from ip : " + String (req.connection.remoteAddress)
);
return END_ERROR (res, 429, "Too many requests");
}
const ip = req.connection.remoteAddress;
const geo = geoip_lite.lookup(ip) || {ll:[]};
const issuer = cert.issuer;
const context = {
principal : consumer_id,
action : "access",
conditions : {
ip : ip,
time : new Date(),
"cert.class" : cert_class,
"cert.cn" : cert.subject.CN || "",
"cert.o" : cert.subject.O || "",
"cert.ou" : cert.subject.OU || "",
"cert.c" : cert.subject.C || "",
"cert.st" : cert.subject.ST || "",
"cert.gn" : cert.subject.GN || "",
"cert.sn" : cert.subject.SN || "",
"cert.title" : cert.subject.title || "",
"cert.issuer.cn" : issuer.CN || "",
"cert.issuer.email" : issuer.emailAddress || "",
"cert.issuer.o" : issuer.O || "",
"cert.issuer.ou" : issuer.OU || "",
"cert.issuer.c" : issuer.C || "",
"cert.issuer.st" : issuer.ST || "",
country : geo.country || "",
region : geo.region || "",
timezone : geo.timezone || "",
city : geo.city || "",
latitude : geo.ll[0] || 0,
longitude : geo.ll[1] || 0,
}
};
let requested_token_time; // as specified by the consumer
let token_time = MAX_TOKEN_TIME; // to be sent along with token
if (body["token-time"])
{
requested_token_time = parseInt(body["token-time"],10);
if (
isNaN(requested_token_time) ||
requested_token_time < 1 ||
requested_token_time > MAX_TOKEN_TIME
)
{
return END_ERROR (
res, 400,
"'token-time' field should be > 0 and < " +
MAX_TOKEN_TIME
);
}
}
const existing_token = body["existing-token"];
const providers = {};
let num_rules_passed = 0;
let total_data_cost_per_second = 0.0;
const payment_info = {};
for (const row of request_array)
{
let resource = row["resource-id"];
if (! is_string_safe(resource, "*_")) // allow some chars
{
return END_ERROR (
res, 400,
"Invalid 'resource-id " +
"(contains unsafe chars)' : " + resource
);
}
if (typeof row.method === "string")
row.methods = [row.method];
if (! row.methods)
row.methods = ["*"];
if ( ! (row.methods instanceof Array))
{
return END_ERROR (res, 400,
"Invalid 'methods' for resource id:" +
resource
);
}
if (row.api && typeof row.api === "string")
row.apis = [row.api];
if (! row.apis)
row.apis = ["/*"];
if ( ! (row.apis instanceof Array))
{
return END_ERROR (res, 400,
"Invalid 'apis' for resource id:" +
resource
);
}
if (row.provider) // the resource-id is not in the catalog ?
{
if (typeof row.provider !== "string")
{
return END_ERROR (res, 400,
"Invalid 'provider': " + row.provider
);
}
if (! is_valid_email(row.provider))
{
return END_ERROR (res, 400,
"Invalid provider email: " +
row.provider
);
}
row.provider = row.provider.toLowerCase();
const provider_email_domain = row
.provider
.split("@")[1];
const sha1_of_provider_email = sha1(row.provider);
resource = provider_email_domain +
"/" +
sha1_of_provider_email +
"/" +
resource;
}
if ((resource.match(/\//g) || []).length < 3)
{
return END_ERROR (res, 400,
"Invalid 'resource-id' " +
"(it must have at least 3 '/' chars): " +
resource
);