dserver-token-generator-plugin-oauth2 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dserver_token_generator_plugin_oauth2/__init__.py +36 -0
- dserver_token_generator_plugin_oauth2/blueprint.py +493 -0
- dserver_token_generator_plugin_oauth2/cli.py +228 -0
- dserver_token_generator_plugin_oauth2/config.py +274 -0
- dserver_token_generator_plugin_oauth2/device_flow.py +279 -0
- dserver_token_generator_plugin_oauth2/jwt_utils.py +189 -0
- dserver_token_generator_plugin_oauth2/plugin.py +131 -0
- dserver_token_generator_plugin_oauth2/sql_models.py +37 -0
- dserver_token_generator_plugin_oauth2/user_provisioning.py +97 -0
- dserver_token_generator_plugin_oauth2/version.py +24 -0
- dserver_token_generator_plugin_oauth2-0.1.0.dist-info/METADATA +351 -0
- dserver_token_generator_plugin_oauth2-0.1.0.dist-info/RECORD +14 -0
- dserver_token_generator_plugin_oauth2-0.1.0.dist-info/WHEEL +4 -0
- dserver_token_generator_plugin_oauth2-0.1.0.dist-info/entry_points.txt +6 -0
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""
|
|
2
|
+
OAuth 2.0 device authorization flow (RFC 8628) for command-line clients.
|
|
3
|
+
|
|
4
|
+
A command-line client (e.g. ``dtool dserver login``) cannot receive the
|
|
5
|
+
browser redirect of the regular login. Instead:
|
|
6
|
+
|
|
7
|
+
1. The client requests a device code: ``POST /auth/oauth2/device``. It gets
|
|
8
|
+
a secret ``device_code`` and a short ``user_code`` with a verification URL
|
|
9
|
+
(the webapp by default), which it shows to the user.
|
|
10
|
+
2. The user opens the verification URL in any browser (also on another
|
|
11
|
+
machine), logs in as usual and approves the user code. The webapp calls
|
|
12
|
+
``GET /auth/oauth2/device/<user_code>`` and
|
|
13
|
+
``POST /auth/oauth2/device/<user_code>/approve`` (or ``/deny``),
|
|
14
|
+
authenticated with the user's dserver token (Bearer).
|
|
15
|
+
3. Meanwhile the client polls ``POST /auth/oauth2/device/token`` with its
|
|
16
|
+
device code and receives a dserver token once the request is approved.
|
|
17
|
+
|
|
18
|
+
The client's token inherits the login time (``auth_time``) of the approving
|
|
19
|
+
session, so a client session cannot outlive the browser session that
|
|
20
|
+
approved it, and cannot be used to extend a stale session.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import hashlib
|
|
24
|
+
import logging
|
|
25
|
+
import secrets
|
|
26
|
+
from datetime import datetime, timedelta, timezone
|
|
27
|
+
|
|
28
|
+
from flask import jsonify, request
|
|
29
|
+
|
|
30
|
+
from .blueprint import get_config, get_jwt_generator, oauth2_bp
|
|
31
|
+
# Imported at startup so that database migrations create the table.
|
|
32
|
+
from .sql_models import DeviceAuthorization
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"
|
|
37
|
+
|
|
38
|
+
# Consonants only: no vowels (no accidental words), no ambiguous characters
|
|
39
|
+
# such as 0/O or 1/I (RFC 8628, section 6.1).
|
|
40
|
+
USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ"
|
|
41
|
+
USER_CODE_LENGTH = 8
|
|
42
|
+
|
|
43
|
+
# Increase of the polling interval on "slow_down" (RFC 8628, section 3.5)
|
|
44
|
+
SLOW_DOWN_SECONDS = 5
|
|
45
|
+
|
|
46
|
+
# Claims of the approving session passed on to the client's token
|
|
47
|
+
INHERITED_CLAIMS = ("email", "name", "provider", "provider_user_id")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _now():
|
|
51
|
+
"""Return the current time as naive UTC, as stored in the database."""
|
|
52
|
+
return datetime.now(timezone.utc).replace(tzinfo=None)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _hash_device_code(device_code):
|
|
56
|
+
return hashlib.sha256(device_code.encode()).hexdigest()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _normalize_user_code(user_code):
|
|
60
|
+
return user_code.replace("-", "").replace(" ", "").upper()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _format_user_code(user_code):
|
|
64
|
+
half = len(user_code) // 2
|
|
65
|
+
return f"{user_code[:half]}-{user_code[half:]}"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _generate_user_code():
|
|
69
|
+
return "".join(secrets.choice(USER_CODE_ALPHABET)
|
|
70
|
+
for _ in range(USER_CODE_LENGTH))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _error(error, description, status=400):
|
|
74
|
+
"""Return an OAuth 2.0 error response (RFC 6749, section 5.2)."""
|
|
75
|
+
return jsonify({"error": error, "error_description": description}), status
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _session_from_bearer():
|
|
79
|
+
"""Return the verified claims of the request's Bearer token, or None."""
|
|
80
|
+
header = request.headers.get("Authorization", "")
|
|
81
|
+
if not header.startswith("Bearer "):
|
|
82
|
+
return None
|
|
83
|
+
return get_jwt_generator().verify_token(header[len("Bearer "):].strip())
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _session_auth_time(claims):
|
|
87
|
+
return int(claims.get("auth_time", claims["iat"]))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _find_pending(user_code):
|
|
91
|
+
"""Return the unexpired request for a user code, or None."""
|
|
92
|
+
|
|
93
|
+
row = DeviceAuthorization.query.filter_by(
|
|
94
|
+
user_code=_normalize_user_code(user_code)).first()
|
|
95
|
+
if row is None or row.expires_at <= _now():
|
|
96
|
+
return None
|
|
97
|
+
return row
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@oauth2_bp.route("/device", methods=["POST"])
|
|
101
|
+
def device_authorization():
|
|
102
|
+
"""Start a device login and return the device and user codes."""
|
|
103
|
+
from dservercore import sql_db
|
|
104
|
+
|
|
105
|
+
config = get_config()
|
|
106
|
+
data = request.get_json(silent=True) or request.form or {}
|
|
107
|
+
client_name = (data.get("client_name") or "").strip()[:80] or None
|
|
108
|
+
|
|
109
|
+
device_code = secrets.token_urlsafe(32)
|
|
110
|
+
while True:
|
|
111
|
+
user_code = _generate_user_code()
|
|
112
|
+
if DeviceAuthorization.query.filter_by(
|
|
113
|
+
user_code=user_code).first() is None:
|
|
114
|
+
break
|
|
115
|
+
|
|
116
|
+
now = _now()
|
|
117
|
+
sql_db.session.add(DeviceAuthorization(
|
|
118
|
+
device_code_hash=_hash_device_code(device_code),
|
|
119
|
+
user_code=user_code,
|
|
120
|
+
client_name=client_name,
|
|
121
|
+
created_at=now,
|
|
122
|
+
expires_at=now + timedelta(
|
|
123
|
+
seconds=config.device_code_lifetime_seconds),
|
|
124
|
+
interval=config.device_poll_interval,
|
|
125
|
+
status="pending",
|
|
126
|
+
))
|
|
127
|
+
sql_db.session.commit()
|
|
128
|
+
|
|
129
|
+
verification_uri = config.get_device_verification_url()
|
|
130
|
+
formatted = _format_user_code(user_code)
|
|
131
|
+
separator = "&" if "?" in verification_uri else "?"
|
|
132
|
+
logger.info(f"Started device login {formatted} for {client_name!r}")
|
|
133
|
+
return jsonify({
|
|
134
|
+
"device_code": device_code,
|
|
135
|
+
"user_code": formatted,
|
|
136
|
+
"verification_uri": verification_uri,
|
|
137
|
+
"verification_uri_complete":
|
|
138
|
+
f"{verification_uri}{separator}user_code={formatted}",
|
|
139
|
+
"expires_in": config.device_code_lifetime_seconds,
|
|
140
|
+
"interval": config.device_poll_interval,
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@oauth2_bp.route("/device/token", methods=["POST"])
|
|
145
|
+
def device_token():
|
|
146
|
+
"""Return the token for an approved device code (polled by clients)."""
|
|
147
|
+
from dservercore import sql_db
|
|
148
|
+
|
|
149
|
+
data = request.get_json(silent=True) or request.form or {}
|
|
150
|
+
if data.get("grant_type", DEVICE_CODE_GRANT_TYPE) != \
|
|
151
|
+
DEVICE_CODE_GRANT_TYPE:
|
|
152
|
+
return _error("unsupported_grant_type",
|
|
153
|
+
f"Expected grant_type {DEVICE_CODE_GRANT_TYPE}")
|
|
154
|
+
device_code = data.get("device_code")
|
|
155
|
+
if not device_code:
|
|
156
|
+
return _error("invalid_request", "Missing device_code")
|
|
157
|
+
|
|
158
|
+
row = DeviceAuthorization.query.filter_by(
|
|
159
|
+
device_code_hash=_hash_device_code(device_code)).first()
|
|
160
|
+
if row is None:
|
|
161
|
+
return _error("invalid_grant", "Unknown or already used device code")
|
|
162
|
+
|
|
163
|
+
now = _now()
|
|
164
|
+
if row.expires_at <= now:
|
|
165
|
+
sql_db.session.delete(row)
|
|
166
|
+
sql_db.session.commit()
|
|
167
|
+
return _error("expired_token", "The device code has expired")
|
|
168
|
+
|
|
169
|
+
if row.status == "denied":
|
|
170
|
+
sql_db.session.delete(row)
|
|
171
|
+
sql_db.session.commit()
|
|
172
|
+
return _error("access_denied", "The user denied the request")
|
|
173
|
+
|
|
174
|
+
if row.status == "pending":
|
|
175
|
+
too_fast = row.last_polled_at is not None and \
|
|
176
|
+
now - row.last_polled_at < timedelta(seconds=row.interval)
|
|
177
|
+
row.last_polled_at = now
|
|
178
|
+
if too_fast:
|
|
179
|
+
row.interval += SLOW_DOWN_SECONDS
|
|
180
|
+
sql_db.session.commit()
|
|
181
|
+
return _error("slow_down", "Polling too fast")
|
|
182
|
+
sql_db.session.commit()
|
|
183
|
+
return _error("authorization_pending",
|
|
184
|
+
"The user has not yet approved the request")
|
|
185
|
+
|
|
186
|
+
# Approved: issue the token once.
|
|
187
|
+
claims = row.claims or {}
|
|
188
|
+
additional_claims = {
|
|
189
|
+
key: claims[key] for key in ("provider", "provider_user_id")
|
|
190
|
+
if key in claims
|
|
191
|
+
}
|
|
192
|
+
token = get_jwt_generator().generate_token(
|
|
193
|
+
username=row.username,
|
|
194
|
+
email=claims.get("email"),
|
|
195
|
+
display_name=claims.get("name"),
|
|
196
|
+
additional_claims=additional_claims or None,
|
|
197
|
+
auth_time=row.auth_time,
|
|
198
|
+
)
|
|
199
|
+
sql_db.session.delete(row)
|
|
200
|
+
sql_db.session.commit()
|
|
201
|
+
|
|
202
|
+
token_claims = get_jwt_generator().verify_token(token) or {}
|
|
203
|
+
expires_in = max(0, int(token_claims.get("exp", 0)
|
|
204
|
+
- datetime.now(timezone.utc).timestamp()))
|
|
205
|
+
logger.info(f"Issued token to device login of {row.username}")
|
|
206
|
+
return jsonify({
|
|
207
|
+
"token": token,
|
|
208
|
+
"access_token": token,
|
|
209
|
+
"token_type": "Bearer",
|
|
210
|
+
"expires_in": expires_in,
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@oauth2_bp.route("/device/<user_code>", methods=["GET"])
|
|
215
|
+
def device_lookup(user_code):
|
|
216
|
+
"""Describe a pending request, for the webapp's approval dialog."""
|
|
217
|
+
if _session_from_bearer() is None:
|
|
218
|
+
return _error("invalid_token", "Missing or invalid token", 401)
|
|
219
|
+
row = _find_pending(user_code)
|
|
220
|
+
if row is None:
|
|
221
|
+
return _error("not_found", "Unknown or expired code", 404)
|
|
222
|
+
return jsonify({
|
|
223
|
+
"user_code": _format_user_code(row.user_code),
|
|
224
|
+
"client_name": row.client_name,
|
|
225
|
+
"created_at": row.created_at.replace(
|
|
226
|
+
tzinfo=timezone.utc).isoformat(),
|
|
227
|
+
"expires_at": row.expires_at.replace(
|
|
228
|
+
tzinfo=timezone.utc).isoformat(),
|
|
229
|
+
"status": row.status,
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _decide(user_code, approve):
|
|
234
|
+
from dservercore import sql_db
|
|
235
|
+
|
|
236
|
+
claims = _session_from_bearer()
|
|
237
|
+
if claims is None:
|
|
238
|
+
return _error("invalid_token", "Missing or invalid token", 401)
|
|
239
|
+
|
|
240
|
+
auth_time = _session_auth_time(claims)
|
|
241
|
+
max_age = timedelta(hours=get_config().jwt.max_session_hours)
|
|
242
|
+
if datetime.now(timezone.utc) >= \
|
|
243
|
+
datetime.fromtimestamp(auth_time, timezone.utc) + max_age:
|
|
244
|
+
return _error("invalid_token",
|
|
245
|
+
"Session expired, please log in again", 401)
|
|
246
|
+
|
|
247
|
+
row = _find_pending(user_code)
|
|
248
|
+
if row is None:
|
|
249
|
+
return _error("not_found", "Unknown or expired code", 404)
|
|
250
|
+
if row.status != "pending":
|
|
251
|
+
return _error("conflict", f"Request already {row.status}", 409)
|
|
252
|
+
|
|
253
|
+
username = claims.get("username", claims["sub"])
|
|
254
|
+
if approve:
|
|
255
|
+
row.status = "approved"
|
|
256
|
+
row.username = username
|
|
257
|
+
row.auth_time = auth_time
|
|
258
|
+
row.claims = {key: claims[key] for key in INHERITED_CLAIMS
|
|
259
|
+
if key in claims}
|
|
260
|
+
else:
|
|
261
|
+
row.status = "denied"
|
|
262
|
+
sql_db.session.commit()
|
|
263
|
+
|
|
264
|
+
logger.info(f"Device login {_format_user_code(row.user_code)} "
|
|
265
|
+
f"{row.status} by {username}")
|
|
266
|
+
return jsonify({"user_code": _format_user_code(row.user_code),
|
|
267
|
+
"status": row.status})
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
@oauth2_bp.route("/device/<user_code>/approve", methods=["POST"])
|
|
271
|
+
def device_approve(user_code):
|
|
272
|
+
"""Approve a pending request (authenticated with a Bearer token)."""
|
|
273
|
+
return _decide(user_code, approve=True)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
@oauth2_bp.route("/device/<user_code>/deny", methods=["POST"])
|
|
277
|
+
def device_deny(user_code):
|
|
278
|
+
"""Deny a pending request (authenticated with a Bearer token)."""
|
|
279
|
+
return _decide(user_code, approve=False)
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""
|
|
2
|
+
JWT token generation utilities.
|
|
3
|
+
|
|
4
|
+
This module handles JWT token creation and signing for authenticated users.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
from datetime import datetime, timedelta, timezone
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Optional
|
|
11
|
+
|
|
12
|
+
import jwt
|
|
13
|
+
|
|
14
|
+
from .config import JwtConfig
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class JwtTokenGenerator:
|
|
20
|
+
"""Generate and sign JWT tokens for authenticated users."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, config: JwtConfig):
|
|
23
|
+
"""
|
|
24
|
+
Initialize the JWT token generator.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
config: JWT configuration object
|
|
28
|
+
"""
|
|
29
|
+
self.config = config
|
|
30
|
+
self._private_key: Optional[str] = None
|
|
31
|
+
self._public_key: Optional[str] = None
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def private_key(self) -> str:
|
|
35
|
+
"""Load and cache the private key."""
|
|
36
|
+
if self._private_key is None:
|
|
37
|
+
self._private_key = self._load_key(self.config.private_key_file)
|
|
38
|
+
return self._private_key
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def public_key(self) -> str:
|
|
42
|
+
"""Load and cache the public key."""
|
|
43
|
+
if self._public_key is None:
|
|
44
|
+
self._public_key = self._load_key(self.config.public_key_file)
|
|
45
|
+
return self._public_key
|
|
46
|
+
|
|
47
|
+
@staticmethod
|
|
48
|
+
def _load_key(path: str) -> str:
|
|
49
|
+
"""Load a key from file."""
|
|
50
|
+
key_path = Path(path)
|
|
51
|
+
if not key_path.exists():
|
|
52
|
+
raise FileNotFoundError(f"Key file not found: {path}")
|
|
53
|
+
return key_path.read_text()
|
|
54
|
+
|
|
55
|
+
def generate_token(
|
|
56
|
+
self,
|
|
57
|
+
username: str,
|
|
58
|
+
email: Optional[str] = None,
|
|
59
|
+
display_name: Optional[str] = None,
|
|
60
|
+
permissions: Optional[list] = None,
|
|
61
|
+
additional_claims: Optional[dict] = None,
|
|
62
|
+
auth_time: Optional[int] = None,
|
|
63
|
+
) -> str:
|
|
64
|
+
"""
|
|
65
|
+
Generate a JWT token for an authenticated user.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
username: Unique username
|
|
69
|
+
email: User's email address
|
|
70
|
+
display_name: User's display name
|
|
71
|
+
permissions: List of permissions/roles
|
|
72
|
+
additional_claims: Any additional claims to include
|
|
73
|
+
auth_time: Time of the original login (Unix timestamp); now if
|
|
74
|
+
not given. The token never outlives the session, i.e. it
|
|
75
|
+
expires at the latest max_session_hours after auth_time.
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
Signed JWT token string
|
|
79
|
+
"""
|
|
80
|
+
now = datetime.now(timezone.utc)
|
|
81
|
+
if auth_time is None:
|
|
82
|
+
auth_time = int(now.timestamp())
|
|
83
|
+
session_end = datetime.fromtimestamp(auth_time, timezone.utc) + \
|
|
84
|
+
timedelta(hours=self.config.max_session_hours)
|
|
85
|
+
expiry = min(now + timedelta(hours=self.config.token_expiry_hours),
|
|
86
|
+
session_end)
|
|
87
|
+
|
|
88
|
+
payload = {
|
|
89
|
+
# Standard JWT claims
|
|
90
|
+
"iss": self.config.issuer,
|
|
91
|
+
"aud": self.config.audience,
|
|
92
|
+
"sub": username,
|
|
93
|
+
"iat": now,
|
|
94
|
+
"exp": expiry,
|
|
95
|
+
"nbf": now,
|
|
96
|
+
# Time of the original login (OpenID Connect "auth_time")
|
|
97
|
+
"auth_time": auth_time,
|
|
98
|
+
|
|
99
|
+
# Custom claims for dserver
|
|
100
|
+
"username": username,
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
# Add optional claims
|
|
104
|
+
if email:
|
|
105
|
+
payload["email"] = email
|
|
106
|
+
|
|
107
|
+
if display_name:
|
|
108
|
+
payload["name"] = display_name
|
|
109
|
+
|
|
110
|
+
if permissions:
|
|
111
|
+
payload["permissions"] = permissions
|
|
112
|
+
|
|
113
|
+
# Add any additional claims
|
|
114
|
+
if additional_claims:
|
|
115
|
+
payload.update(additional_claims)
|
|
116
|
+
|
|
117
|
+
# Sign the token
|
|
118
|
+
token = jwt.encode(
|
|
119
|
+
payload,
|
|
120
|
+
self.private_key,
|
|
121
|
+
algorithm=self.config.algorithm
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
logger.info(f"Generated JWT token for user: {username}")
|
|
125
|
+
return token
|
|
126
|
+
|
|
127
|
+
def verify_token(self, token: str) -> Optional[dict]:
|
|
128
|
+
"""
|
|
129
|
+
Verify and decode a JWT token.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
token: JWT token string
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
Decoded payload if valid, None otherwise
|
|
136
|
+
"""
|
|
137
|
+
try:
|
|
138
|
+
payload = jwt.decode(
|
|
139
|
+
token,
|
|
140
|
+
self.public_key,
|
|
141
|
+
algorithms=[self.config.algorithm],
|
|
142
|
+
audience=self.config.audience,
|
|
143
|
+
issuer=self.config.issuer,
|
|
144
|
+
)
|
|
145
|
+
return payload
|
|
146
|
+
except jwt.ExpiredSignatureError:
|
|
147
|
+
logger.warning("Token has expired")
|
|
148
|
+
except jwt.InvalidTokenError as e:
|
|
149
|
+
logger.warning(f"Invalid token: {e}")
|
|
150
|
+
return None
|
|
151
|
+
|
|
152
|
+
def refresh_token(self, token: str) -> Optional[str]:
|
|
153
|
+
"""
|
|
154
|
+
Refresh an existing valid token.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
token: Existing JWT token
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
New token with extended expiry, or None if original is invalid
|
|
161
|
+
"""
|
|
162
|
+
payload = self.verify_token(token)
|
|
163
|
+
if payload is None:
|
|
164
|
+
return None
|
|
165
|
+
|
|
166
|
+
# The session starts at the original login. Tokens issued before
|
|
167
|
+
# auth_time was recorded fall back to their issue time.
|
|
168
|
+
auth_time = int(payload.get("auth_time", payload["iat"]))
|
|
169
|
+
session_end = auth_time + self.config.max_session_hours * 3600
|
|
170
|
+
if datetime.now(timezone.utc).timestamp() >= session_end:
|
|
171
|
+
logger.warning(
|
|
172
|
+
f"Refusing to refresh token of {payload['username']}: "
|
|
173
|
+
f"session older than {self.config.max_session_hours} hours")
|
|
174
|
+
return None
|
|
175
|
+
|
|
176
|
+
# Generate new token with same claims and session start
|
|
177
|
+
additional_claims = {
|
|
178
|
+
key: payload[key]
|
|
179
|
+
for key in ("provider", "provider_user_id")
|
|
180
|
+
if key in payload
|
|
181
|
+
}
|
|
182
|
+
return self.generate_token(
|
|
183
|
+
username=payload["username"],
|
|
184
|
+
email=payload.get("email"),
|
|
185
|
+
display_name=payload.get("name"),
|
|
186
|
+
permissions=payload.get("permissions"),
|
|
187
|
+
additional_claims=additional_claims or None,
|
|
188
|
+
auth_time=auth_time,
|
|
189
|
+
)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""
|
|
2
|
+
dserver plugin registration for OAuth2 token generator.
|
|
3
|
+
|
|
4
|
+
This module provides the plugin class that integrates with dservercore's
|
|
5
|
+
plugin discovery system via the ExtensionABC interface.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
|
|
10
|
+
from flask import Flask
|
|
11
|
+
|
|
12
|
+
from .blueprint import oauth2_bp
|
|
13
|
+
from .config import PluginConfig
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class OAuth2TokenGeneratorPlugin:
|
|
19
|
+
"""
|
|
20
|
+
OAuth2 Token Generator Plugin for dserver.
|
|
21
|
+
|
|
22
|
+
This plugin provides OAuth 2.0 authentication for users via any
|
|
23
|
+
OAuth2/OIDC compliant Identity Provider and issues JWT tokens.
|
|
24
|
+
|
|
25
|
+
Implements the dservercore ExtensionABC interface.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(self, app: Flask = None):
|
|
29
|
+
"""
|
|
30
|
+
Initialize the plugin.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
app: Flask application instance (optional, can call init_app later)
|
|
34
|
+
"""
|
|
35
|
+
self.app = app
|
|
36
|
+
self.config: PluginConfig = None
|
|
37
|
+
|
|
38
|
+
if app is not None:
|
|
39
|
+
self.init_app(app)
|
|
40
|
+
|
|
41
|
+
def init_app(self, app: Flask, *args, **kwargs):
|
|
42
|
+
"""
|
|
43
|
+
Initialize the plugin with a Flask application.
|
|
44
|
+
|
|
45
|
+
This is called by dservercore's app factory.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
app: Flask application instance
|
|
49
|
+
"""
|
|
50
|
+
self.app = app
|
|
51
|
+
|
|
52
|
+
# Load configuration
|
|
53
|
+
self.config = PluginConfig.from_env()
|
|
54
|
+
|
|
55
|
+
# Configure Flask session. The OAuth2 state (CSRF) token lives in
|
|
56
|
+
# the session, so an unset SECRET_KEY silently breaks logins on
|
|
57
|
+
# every restart and weakens session integrity.
|
|
58
|
+
if not app.config.get("SECRET_KEY"):
|
|
59
|
+
if app.config.get("FLASK_ENV") == "development" or app.debug:
|
|
60
|
+
logger.warning(
|
|
61
|
+
"Flask SECRET_KEY not set. Sessions will not persist "
|
|
62
|
+
"across restarts."
|
|
63
|
+
)
|
|
64
|
+
else:
|
|
65
|
+
raise RuntimeError(
|
|
66
|
+
"Flask SECRET_KEY must be set for the OAuth2 token "
|
|
67
|
+
"generator: session-based CSRF protection depends on it. "
|
|
68
|
+
"Set the SECRET_KEY environment variable."
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
logger.debug(f"Session config: SECURE={app.config.get('SESSION_COOKIE_SECURE')}, "
|
|
72
|
+
f"SAMESITE={app.config.get('SESSION_COOKIE_SAMESITE')}")
|
|
73
|
+
|
|
74
|
+
logger.info("OAuth2 Token Generator plugin initialized")
|
|
75
|
+
logger.info(f"OAuth2 Provider: {self.config.oauth2.name}")
|
|
76
|
+
if self.config.oauth2.authorization_url:
|
|
77
|
+
logger.info(f"Authorization URL: {self.config.oauth2.authorization_url}")
|
|
78
|
+
else:
|
|
79
|
+
logger.warning("OAuth2 not fully configured - OAUTH2_AUTHORIZATION_URL not set")
|
|
80
|
+
|
|
81
|
+
def get_blueprint(self):
|
|
82
|
+
"""
|
|
83
|
+
Return the Flask blueprint for this extension.
|
|
84
|
+
|
|
85
|
+
Required by dservercore ExtensionABC.
|
|
86
|
+
"""
|
|
87
|
+
return oauth2_bp
|
|
88
|
+
|
|
89
|
+
def register_dataset(self, dataset_info):
|
|
90
|
+
"""
|
|
91
|
+
Register a dataset (no-op for auth plugin).
|
|
92
|
+
|
|
93
|
+
Required by dservercore PluginABC but not used for authentication.
|
|
94
|
+
"""
|
|
95
|
+
pass
|
|
96
|
+
|
|
97
|
+
def get_config(self):
|
|
98
|
+
"""
|
|
99
|
+
Return plugin configuration dictionary.
|
|
100
|
+
|
|
101
|
+
Required by dservercore PluginABC.
|
|
102
|
+
This is loaded BEFORE init_app, so session settings go here.
|
|
103
|
+
"""
|
|
104
|
+
return {
|
|
105
|
+
# Session cookie settings for OAuth2 flow
|
|
106
|
+
# SECURE must be False for HTTP (dev), True for HTTPS (prod)
|
|
107
|
+
# SAMESITE must be "Lax" for OAuth2 redirects to work
|
|
108
|
+
"SESSION_COOKIE_SECURE": False,
|
|
109
|
+
"SESSION_COOKIE_HTTPONLY": True,
|
|
110
|
+
"SESSION_COOKIE_SAMESITE": "Lax",
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
def get_config_secrets_to_obfuscate(self):
|
|
114
|
+
"""Return config keys that should not be exposed."""
|
|
115
|
+
return ["OAUTH2_CLIENT_SECRET"]
|
|
116
|
+
|
|
117
|
+
@staticmethod
|
|
118
|
+
def get_name() -> str:
|
|
119
|
+
"""Return the plugin name."""
|
|
120
|
+
return "oauth2-token-generator"
|
|
121
|
+
|
|
122
|
+
@staticmethod
|
|
123
|
+
def get_version() -> str:
|
|
124
|
+
"""Return the plugin version."""
|
|
125
|
+
from . import __version__
|
|
126
|
+
return __version__
|
|
127
|
+
|
|
128
|
+
@staticmethod
|
|
129
|
+
def get_description() -> str:
|
|
130
|
+
"""Return the plugin description."""
|
|
131
|
+
return "OAuth 2.0 token generator for dserver"
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""SQL models of the OAuth2 token generator plugin.
|
|
2
|
+
|
|
3
|
+
Tables live in dserver's SQL database and are created by the deployment's
|
|
4
|
+
database migrations (``flask db migrate`` / ``flask db upgrade``).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dservercore import sql_db as db
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DeviceAuthorization(db.Model):
|
|
11
|
+
"""Pending device authorization request (RFC 8628).
|
|
12
|
+
|
|
13
|
+
Created when a command-line client starts a login, approved or denied
|
|
14
|
+
by the user in the webapp, and deleted once the client has collected the
|
|
15
|
+
result (or the request has expired).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
__tablename__ = "oauth2_device_authorization"
|
|
19
|
+
|
|
20
|
+
id = db.Column(db.Integer, primary_key=True)
|
|
21
|
+
# SHA-256 of the device code; the code itself is only known to the client
|
|
22
|
+
device_code_hash = db.Column(db.String(64), unique=True, nullable=False,
|
|
23
|
+
index=True)
|
|
24
|
+
# Normalized user code (upper case, without dash)
|
|
25
|
+
user_code = db.Column(db.String(16), unique=True, nullable=False,
|
|
26
|
+
index=True)
|
|
27
|
+
client_name = db.Column(db.String(80), nullable=True)
|
|
28
|
+
created_at = db.Column(db.DateTime, nullable=False)
|
|
29
|
+
expires_at = db.Column(db.DateTime, nullable=False)
|
|
30
|
+
interval = db.Column(db.Integer, nullable=False)
|
|
31
|
+
last_polled_at = db.Column(db.DateTime, nullable=True)
|
|
32
|
+
# pending, approved or denied
|
|
33
|
+
status = db.Column(db.String(16), nullable=False, default="pending")
|
|
34
|
+
# Set on approval: the approving user and the claims of their session
|
|
35
|
+
username = db.Column(db.String(255), nullable=True)
|
|
36
|
+
auth_time = db.Column(db.Integer, nullable=True)
|
|
37
|
+
claims = db.Column(db.JSON, nullable=True)
|