This repository was archived by the owner on Jun 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathconfigure.py
More file actions
executable file
·659 lines (604 loc) · 20.4 KB
/
configure.py
File metadata and controls
executable file
·659 lines (604 loc) · 20.4 KB
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
"""Configuration management for IDP"""
import copy
import importlib
import json
import logging
import os
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
from oidcop.logging import configure_logging
from oidcop.scopes import SCOPE2CLAIMS
from oidcop.utils import load_yaml_config
logger = logging.getLogger(__name__)
DEFAULT_FILE_ATTRIBUTE_NAMES = [
"server_key",
"server_cert",
"filename",
"template_dir",
"private_path",
"public_path",
"db_file",
"jwks_file",
]
OP_DEFAULT_CONFIG = {
"capabilities": {
"subject_types_supported": ["public", "pairwise"],
"grant_types_supported": [
"authorization_code",
"implicit",
"urn:ietf:params:oauth:grant-type:jwt-bearer",
"refresh_token",
],
},
"cookie_handler": {
"class": "oidcop.cookie_handler.CookieHandler",
"kwargs": {
"keys": {
"private_path": "private/cookie_jwks.json",
"key_defs": [
{"type": "OCT", "use": ["enc"], "kid": "enc"},
{"type": "OCT", "use": ["sig"], "kid": "sig"},
],
"read_only": False,
},
"name": {
"session": "oidc_op",
"register": "oidc_op_rp",
"session_management": "sman",
},
},
},
"claims_interface": {"class": "oidcop.session.claims.ClaimsInterface", "kwargs": {}},
"authz": {
"class": "oidcop.authz.AuthzHandling",
"kwargs": {
"grant_config": {
"usage_rules": {
"authorization_code": {
"supports_minting": [
"access_token",
"refresh_token",
"id_token",
],
"max_usage": 1,
},
"access_token": {},
"refresh_token": {
"supports_minting": ["access_token", "refresh_token"],
"expires_in": -1,
},
},
"expires_in": 43200,
}
},
},
"httpc_params": {"verify": False, "timeout": 4},
"issuer": "https://{domain}:{port}",
"template_dir": "templates",
"token_handler_args": {
"jwks_file": "private/token_jwks.json",
"code": {"kwargs": {"lifetime": 600}},
"token": {
"class": "oidcop.token.jwt_token.JWTToken",
"kwargs": {"lifetime": 3600},
},
"refresh": {
"class": "oidcop.token.jwt_token.JWTToken",
"kwargs": {"lifetime": 86400},
},
"id_token": {"class": "oidcop.token.id_token.IDToken", "kwargs": {}},
},
"scopes_to_claims": SCOPE2CLAIMS,
}
AS_DEFAULT_CONFIG = copy.deepcopy(OP_DEFAULT_CONFIG)
AS_DEFAULT_CONFIG["claims_interface"] = {
"class": "oidcop.session.claims.OAuth2ClaimsInterface",
"kwargs": {},
}
def add_base_path(conf: Union[dict, str], base_path: str, file_attributes: List[str]):
if isinstance(conf, str):
if conf.startswith("/"):
pass
elif conf == "":
conf = "./" + conf
else:
conf = os.path.join(base_path, conf)
elif isinstance(conf, dict):
for key, val in conf.items():
if key in file_attributes:
if val.startswith("/"):
continue
elif val == "":
conf[key] = "./" + val
else:
conf[key] = os.path.join(base_path, val)
if isinstance(val, dict):
conf[key] = add_base_path(val, base_path, file_attributes)
return conf
def set_domain_and_port(conf: dict, uris: List[str], domain: str, port: int):
for key, val in conf.items():
if key in uris:
if isinstance(val, list):
_new = [v.format(domain=domain, port=port) for v in val]
else:
_new = val.format(domain=domain, port=port)
conf[key] = _new
elif isinstance(val, dict):
conf[key] = set_domain_and_port(val, uris, domain, port)
return conf
def create_from_config_file(
cls,
filename: str,
base_path: str = "",
entity_conf: Optional[List[dict]] = None,
file_attributes: Optional[List[str]] = None,
domain: Optional[str] = "",
port: Optional[int] = 0,
):
if filename.endswith(".yaml"):
"""Load configuration as YAML"""
_conf = load_yaml_config(filename)
elif filename.endswith(".json"):
_str = open(filename).read()
_conf = json.loads(_str)
elif filename.endswith(".py"):
head, tail = os.path.split(filename)
tail = tail[:-3]
module = importlib.import_module(tail)
_conf = getattr(module, "OIDCOP_CONFIG")
else:
raise ValueError("Unknown file type")
return cls(
_conf,
entity_conf=entity_conf,
base_path=base_path,
file_attributes=file_attributes,
domain=domain,
port=port,
)
class Base(dict):
""" Configuration base class """
parameter = {}
def __init__(
self,
conf: Dict,
base_path: str = "",
file_attributes: Optional[List[str]] = None,
):
dict.__init__(self)
if file_attributes is None:
file_attributes = DEFAULT_FILE_ATTRIBUTE_NAMES
if base_path and file_attributes:
# this adds a base path to all paths in the configuration
add_base_path(conf, base_path, file_attributes)
def __getattr__(self, item):
return self[item]
def __setattr__(self, key, value):
if key in self:
raise KeyError("{} has already been set".format(key))
super(Base, self).__setitem__(key, value)
def __setitem__(self, key, value):
if key in self:
raise KeyError("{} has already been set".format(key))
super(Base, self).__setitem__(key, value)
class EntityConfiguration(Base):
default_config = AS_DEFAULT_CONFIG
uris = ["issuer", "base_url"]
parameter = {
"add_on": None,
"authz": None,
"authentication": None,
"base_url": "",
"capabilities": None,
"claims_interface": None,
"client_db": None,
"cookie_handler": None,
"endpoint": {},
"httpc_params": {},
"issuer": "",
"keys": None,
"session_params": None,
"template_dir": None,
"token_handler_args": {},
"userinfo": None,
}
def __init__(
self,
conf: Dict,
base_path: Optional[str] = "",
entity_conf: Optional[List[dict]] = None,
domain: Optional[str] = "",
port: Optional[int] = 0,
file_attributes: Optional[List[str]] = None,
):
conf = copy.deepcopy(conf)
Base.__init__(self, conf, base_path, file_attributes)
if file_attributes is None:
file_attributes = DEFAULT_FILE_ATTRIBUTE_NAMES
if not domain:
domain = conf.get("domain", "127.0.0.1")
if not port:
port = conf.get("port", 80)
for key in self.parameter.keys():
_val = conf.get(key)
if not _val:
if key in self.default_config:
_val = copy.deepcopy(self.default_config[key])
self.format(
_val,
base_path=base_path,
file_attributes=file_attributes,
domain=domain,
port=port,
)
else:
continue
if key not in DEFAULT_EXTENDED_CONF:
logger.warning(f"{key} not seems to be a valid configuration parameter")
elif not _val:
logger.warning(f"{key} not configured, using default configuration values")
if key == "template_dir":
_val = os.path.abspath(_val)
setattr(self, key, _val)
# try:
# _dir = self.template_dir
# except AttributeError:
# self.template_dir = os.path.abspath("templates")
# else:
# self.template_dir =
def format(self, conf, base_path, file_attributes, domain, port):
"""
Formats parts of the configuration. That includes replacing the strings {domain} and {port}
with the used domain and port and making references to files and directories absolute
rather then relative. The formatting is done in place.
:param conf: The configuration part
:param base_path: The base path used to make file/directory refrences absolute
:param file_attributes: Attribute names that refer to files or directories.
:param domain: The domain name
:param port: The port used
"""
add_base_path(conf, base_path, file_attributes)
if isinstance(conf, dict):
set_domain_and_port(conf, self.uris, domain=domain, port=port)
class OPConfiguration(EntityConfiguration):
"Provider configuration"
default_config = OP_DEFAULT_CONFIG
parameter = EntityConfiguration.parameter.copy()
parameter.update(
{
"id_token": None,
"login_hint2acrs": {},
"login_hint_lookup": None,
"sub_func": {},
"scopes_to_claims": {},
}
)
def __init__(
self,
conf: Dict,
base_path: Optional[str] = "",
entity_conf: Optional[List[dict]] = None,
domain: Optional[str] = "",
port: Optional[int] = 0,
file_attributes: Optional[List[str]] = None,
):
super().__init__(
conf=conf,
base_path=base_path,
entity_conf=entity_conf,
domain=domain,
port=port,
file_attributes=file_attributes,
)
self.scopes_to_claims
class ASConfiguration(EntityConfiguration):
"Authorization server configuration"
def __init__(
self,
conf: Dict,
base_path: Optional[str] = "",
entity_conf: Optional[List[dict]] = None,
domain: Optional[str] = "",
port: Optional[int] = 0,
file_attributes: Optional[List[str]] = None,
):
EntityConfiguration.__init__(
self,
conf=conf,
base_path=base_path,
entity_conf=entity_conf,
domain=domain,
port=port,
file_attributes=file_attributes,
)
class Configuration(Base):
"""Server Configuration"""
uris = ["issuer", "base_url"]
def __init__(
self,
conf: Dict,
entity_conf: Optional[List[dict]] = None,
base_path: str = "",
file_attributes: Optional[List[str]] = None,
domain: Optional[str] = "",
port: Optional[int] = 0,
):
Base.__init__(self, conf, base_path, file_attributes)
log_conf = conf.get("logging")
if log_conf:
self.logger = configure_logging(config=log_conf).getChild(__name__)
else:
self.logger = logging.getLogger("oidcop")
self.webserver = conf.get("webserver", {})
if not domain:
domain = conf.get("domain", "127.0.0.1")
if not port:
port = conf.get("port", 80)
set_domain_and_port(conf, self.uris, domain=domain, port=port)
if entity_conf:
for econf in entity_conf:
_path = econf.get("path")
_cnf = conf
if _path:
for step in _path:
_cnf = _cnf[step]
_attr = econf["attr"]
_cls = econf["class"]
setattr(
self,
_attr,
_cls(
_cnf,
base_path=base_path,
file_attributes=file_attributes,
domain=domain,
port=port,
),
)
DEFAULT_EXTENDED_CONF = {
"add_on": {
"pkce": {
"function": "oidcop.oidc.add_on.pkce.add_pkce_support",
"kwargs": {"essential": False, "code_challenge_method": "S256 S384 S512"},
},
"claims": {
"function": "oidcop.oidc.add_on.custom_scopes.add_custom_scopes",
"kwargs": {
"research_and_scholarship": [
"name",
"given_name",
"family_name",
"email",
"email_verified",
"sub",
"iss",
"eduperson_scoped_affiliation",
]
},
},
},
"authz": {
"class": "oidcop.authz.AuthzHandling",
"kwargs": {
"grant_config": {
"usage_rules": {
"authorization_code": {
"supports_minting": [
"access_token",
"refresh_token",
"id_token",
],
"max_usage": 1,
},
"access_token": {},
"refresh_token": {
"supports_minting": ["access_token", "refresh_token"],
"expires_in": -1,
},
},
"expires_in": 43200,
}
},
},
"authentication": {
"user": {
"acr": "urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocolPassword",
"class": "oidcop.user_authn.user.UserPassJinja2",
"kwargs": {
"verify_endpoint": "verify/user",
"template": "user_pass.jinja2",
"db": {
"class": "oidcop.util.JSONDictDB",
"kwargs": {"filename": "passwd.json"},
},
"page_header": "Testing log in",
"submit_btn": "Get me in!",
"user_label": "Nickname",
"passwd_label": "Secret sauce",
},
}
},
"capabilities": {
"subject_types_supported": ["public", "pairwise"],
"grant_types_supported": [
"authorization_code",
"implicit",
"urn:ietf:params:oauth:grant-type:jwt-bearer",
"refresh_token",
],
},
"cookie_handler": {
"class": "oidcop.cookie_handler.CookieHandler",
"kwargs": {
"keys": {
"private_path": "private/cookie_jwks.json",
"key_defs": [
{"type": "OCT", "use": ["enc"], "kid": "enc"},
{"type": "OCT", "use": ["sig"], "kid": "sig"},
],
"read_only": False,
},
"name": {
"session": "oidc_op",
"register": "oidc_op_rp",
"session_management": "sman",
},
},
},
"endpoint": {
"webfinger": {
"path": ".well-known/webfinger",
"class": "oidcop.oidc.discovery.Discovery",
"kwargs": {"client_authn_method": None},
},
"provider_info": {
"path": ".well-known/openid-configuration",
"class": "oidcop.oidc.provider_config.ProviderConfiguration",
"kwargs": {"client_authn_method": None},
},
"registration": {
"path": "registration",
"class": "oidcop.oidc.registration.Registration",
"kwargs": {
"client_authn_method": None,
"client_secret_expiration_time": 432000,
},
},
"registration_api": {
"path": "registration_api",
"class": "oidcop.oidc.read_registration.RegistrationRead",
"kwargs": {"client_authn_method": ["bearer_header"]},
},
"introspection": {
"path": "introspection",
"class": "oidcop.oauth2.introspection.Introspection",
"kwargs": {
"client_authn_method": ["client_secret_post"],
"release": ["username"],
},
},
"authorization": {
"path": "authorization",
"class": "oidcop.oidc.authorization.Authorization",
"kwargs": {
"client_authn_method": None,
"claims_parameter_supported": True,
"request_parameter_supported": True,
"request_uri_parameter_supported": True,
"response_types_supported": [
"code",
"token",
"id_token",
"code token",
"code id_token",
"id_token token",
"code id_token token",
# "none"
],
"response_modes_supported": ["query", "fragment", "form_post"],
},
},
"token": {
"path": "token",
"class": "oidcop.oidc.token.Token",
"kwargs": {
"client_authn_method": [
"client_secret_post",
"client_secret_basic",
"client_secret_jwt",
"private_key_jwt",
],
},
},
"userinfo": {
"path": "userinfo",
"class": "oidcop.oidc.userinfo.UserInfo",
"kwargs": {"claim_types_supported": ["normal", "aggregated", "distributed"]},
},
"end_session": {
"path": "session",
"class": "oidcop.oidc.session.Session",
"kwargs": {
"logout_verify_url": "verify_logout",
"post_logout_uri_path": "post_logout",
"signing_alg": "ES256",
"frontchannel_logout_supported": True,
"frontchannel_logout_session_supported": True,
"backchannel_logout_supported": True,
"backchannel_logout_session_supported": True,
"check_session_iframe": "check_session_iframe",
},
},
},
"httpc_params": {"verify": False, "timeout": 4},
"issuer": "https://{domain}:{port}",
"keys": {
"private_path": "private/jwks.json",
"key_defs": [
{"type": "RSA", "use": ["sig"]},
{"type": "EC", "crv": "P-256", "use": ["sig"]},
],
"public_path": "static/jwks.json",
"read_only": False,
"uri_path": "static/jwks.json",
},
"login_hint2acrs": {
"class": "oidcop.login_hint.LoginHint2Acrs",
"kwargs": {
"scheme_map": {
"email": ["urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocolPassword"]
}
},
},
"template_dir": "templates",
"token_handler_args": {
"jwks_def": {
"private_path": "private/token_jwks.json",
"read_only": False,
"key_defs": [{"type": "oct", "bytes": "24", "use": ["enc"], "kid": "code"}],
},
"code": {"kwargs": {"lifetime": 600}},
"token": {
"class": "oidcop.token.jwt_token.JWTToken",
"kwargs": {
"lifetime": 3600,
"add_claims_by_scope": True,
"aud": ["https://example.org/appl"],
},
},
"refresh": {
"class": "oidcop.token.jwt_token.JWTToken",
"kwargs": {
"lifetime": 3600,
"aud": ["https://example.org/appl"],
},
},
"id_token": {
"class": "oidcop.token.id_token.IDToken",
"kwargs": {
"base_claims": {
"email": {"essential": True},
"email_verified": {"essential": True},
}
},
},
},
"userinfo": {
"class": "oidcop.user_info.UserInfo",
"kwargs": {"db_file": "users.json"},
},
"scopes_to_claims": SCOPE2CLAIMS,
"session_params": {
"password": "ses_key",
"salt": "ses_salt",
"sub_func": {
"public": {"class": "oidcop.session.manager.PublicID", "kwargs": {"salt": "mysalt"}},
"pairwise": {
"class": "oidcop.session.manager.PairWiseID",
"kwargs": {"salt": "mysalt"},
},
},
},
}