Repository navigation
Expand file tree
/
Copy pathdb_utils.py
More file actions
168 lines (138 loc) · 5.57 KB
/
Copy pathdb_utils.py
File metadata and controls
168 lines (138 loc) · 5.57 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
from typing import Dict, List, Optional
from CTFd.models import db
from .models import OAUTHConfig
class DBUtils:
"""Database utility class for OAuth configuration management."""
DEFAULT_CONFIG = [
{"key": "oauth_plugin_enabled", "value": "off"},
{"key": "oauth_client_id", "value": ""},
{"key": "oauth_client_secret", "value": ""},
{"key": "oauth_authorization_endpoint", "value": ""},
{"key": "oauth_token_endpoint", "value": ""},
{"key": "oauth_userinfo_url", "value": ""},
{"key": "oauth_profile_url", "value": ""},
{"key": "oauth_logout_url", "value": ""},
{"key": "oauth_scope", "value": ""},
{"key": "oauth_admin_group", "value": "CTFd Admins"},
{"key": "oauth_sync_teams", "value": "off"},
{"key": "oauth_enable_pkce", "value": "off"},
# OIDC Discovery
{"key": "oauth_discovery_url", "value": ""},
# Claim mappings (for non-standard claim names)
{"key": "oauth_claim_preferred_username", "value": "preferred_username"},
{"key": "oauth_claim_email", "value": "email"},
{"key": "oauth_claim_affiliation", "value": "affiliation"},
]
@staticmethod
def get(key: str) -> Optional[OAUTHConfig]:
"""Get a single OAuth configuration by key."""
return OAUTHConfig.query.filter_by(key=key).first()
@staticmethod
def get_config() -> Dict[str, str]:
"""Get all OAuth configuration as a dictionary."""
configs = OAUTHConfig.query.all()
result = {}
for c in configs:
result[str(c.key)] = str(c.value)
return result
@staticmethod
def save_config(config: List[tuple[str, str]]) -> None:
"""Save OAuth configuration from a list of key-value tuples."""
for key, value in config:
record = (
db.session.query(OAUTHConfig)
.filter(OAUTHConfig.key == key)
.one_or_none()
)
if record:
record.value = value
else:
new_config = OAUTHConfig(key=key, value=value)
db.session.add(new_config)
db.session.commit()
db.session.close()
@staticmethod
def load_default() -> None:
"""Load default configuration values for keys that don't exist."""
for config_item in DBUtils.DEFAULT_CONFIG:
existing = DBUtils.get(config_item["key"])
if not existing:
new_config = OAUTHConfig(
key=config_item["key"], value=config_item["value"]
)
db.session.add(new_config)
db.session.commit()
@staticmethod
def validate_config() -> tuple[bool, List[str]]:
"""
Validate OAuth configuration.
Returns:
tuple: (is_valid, list_of_errors)
"""
config = DBUtils.get_config()
errors = []
if config.get("oauth_plugin_enabled") != "on":
return True, []
# Check required fields
required_fields = {
"oauth_client_id": "Client ID",
"oauth_client_secret": "Client Secret",
}
# Check if using OIDC discovery or manual configuration
if config.get("oauth_discovery_url"):
# OIDC discovery mode
if not config.get("oauth_discovery_url").startswith(
("http://", "https://")
):
errors.append("Discovery URL must be a valid HTTP(S) URL")
else:
# Manual configuration mode
required_fields.update(
{
"oauth_authorization_endpoint": "Authorization Endpoint",
"oauth_token_endpoint": "Token Endpoint",
"oauth_userinfo_url": "UserInfo URL",
}
)
for field, label in required_fields.items():
if not config.get(field):
errors.append(f"{label} is required")
# Validate URLs
url_fields = [
"oauth_authorization_endpoint",
"oauth_token_endpoint",
"oauth_userinfo_url",
"oauth_profile_url",
"oauth_logout_url",
]
for field in url_fields:
value = config.get(field)
if value and not value.startswith(("http://", "https://")):
field_name = field.replace("oauth_", "").replace("_", " ").title()
errors.append(f"{field_name} must be a valid HTTP(S) URL")
return len(errors) == 0, errors
@staticmethod
def discover_oidc_endpoints(discovery_url: str) -> Optional[Dict[str, str]]:
"""
Discover OAuth endpoints using OIDC discovery.
Args:
discovery_url: The OIDC discovery URL (e.g., https://idp.example.com/.well-known/openid-configuration)
Returns:
Dictionary with discovered endpoints or None on failure
"""
import requests
try:
response = requests.get(discovery_url, timeout=10)
if response.status_code != 200:
return None
discovery_doc = response.json()
return {
"oauth_authorization_endpoint": discovery_doc.get(
"authorization_endpoint", ""
),
"oauth_token_endpoint": discovery_doc.get("token_endpoint", ""),
"oauth_userinfo_url": discovery_doc.get("userinfo_endpoint", ""),
"oauth_logout_url": discovery_doc.get("end_session_endpoint", ""),
}
except Exception:
return None