-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
2311 lines (2163 loc) · 98.6 KB
/
Copy pathserver.py
File metadata and controls
2311 lines (2163 loc) · 98.6 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
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
"""
Minimal OAuth2 Authorization Server in Python
--------------------------------------------
Features:
- OAuth 2.0 Authorization Code grant with PKCE
- Consent screen (Google-style approve/deny)
- Refresh tokens (rotating)
- Scope support (openid, profile, email as examples; you can add custom scopes)
- User login (very simple demo, replace with your auth)
- Client registration (static seed + CLI helper to add more)
Stack:
- Flask
- Authlib (authorization server)
- SQLAlchemy (SQLite for demo)
Run:
python3 -m venv .venv && source .venv/bin/activate
pip install flask authlib sqlalchemy
python server.py # starts on http://127.0.0.1:8000
Test OAuth Flow (PKCE):
1) Create a client: GET http://127.0.0.1:8000/dev/seed (or POST /dev/create_client)
2) Generate PKCE verifier & challenge (script printed at startup).
3) Hit /authorize in a browser; login user: alice / password: alice
4) Approve consent; code returns to redirect_uri; POST to /token with code+verifier
Security Notes:
- Demo uses HTTP and SQLite; for production, use HTTPS and Postgres/MySQL.
- Replace demo login, password policy, session security, CSRF protection
- Strictly validate redirect_uris; never use wildcards in prod
- Configure token lifetimes and refresh-token rotation
This file intentionally keeps templates inline (render_template_string) so you can run from one file.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import os
import base64
import secrets
import hashlib
from urllib.parse import urlencode, urlparse
import json
from flask import Flask, request, redirect, session, url_for, abort, jsonify, render_template_string
from flask import make_response
from werkzeug.security import gen_salt, generate_password_hash, check_password_hash
from sqlalchemy import Column, Integer, String, DateTime, Text, Boolean, ForeignKey
from sqlalchemy import create_engine
from sqlalchemy.orm import relationship, sessionmaker, scoped_session, declarative_base, selectinload
from authlib.oauth2 import OAuth2Error
from authlib.oauth2.rfc6749 import grants
from authlib.integrations.flask_oauth2 import AuthorizationServer, ResourceProtector, current_token
from authlib.oauth2.rfc7636 import CodeChallenge
from authlib.oauth2.rfc6749.util import scope_to_list
from authlib.oauth2.rfc6750 import BearerTokenValidator
from authlib.jose import jwt, JsonWebKey
# ----------------------
# Flask & DB Setup
# ----------------------
app = Flask(__name__)
app.secret_key = os.environ.get("APP_SECRET", os.urandom(32))
# Keep the Authorization Server session for 30 days unless explicitly logged out
app.permanent_session_lifetime = timedelta(days=30)
DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///oauth.db")
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {})
SessionLocal = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()
# ----------------------
# Models
# ----------------------
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
username = Column(String(40), unique=True, nullable=False)
password_hash = Column(String(200), nullable=False)
email = Column(String(120), unique=True)
def verify_password(self, pw: str) -> bool:
return check_password_hash(self.password_hash, pw)
class OAuth2Client(Base):
__tablename__ = 'oauth2_client'
id = Column(Integer, primary_key=True)
client_id = Column(String(48), unique=True, nullable=False)
client_secret = Column(String(120), nullable=True) # public clients may be None
client_name = Column(String(120))
client_uri = Column(String(256))
logo_uri = Column(String(256))
grant_types = Column(String(120)) # space separated
redirect_uris = Column(Text) # space/newline separated
response_types = Column(String(120))
scope = Column(Text) # space separated
token_endpoint_auth_method = Column(String(120), default="none")
require_consent = Column(Boolean, default=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
def check_redirect_uri(self, uri: str) -> bool:
if not self.redirect_uris:
return False
allowed = [u.strip() for u in self.redirect_uris.replace("\n", " ").split(" ") if u.strip()]
return uri in allowed
def get_default_redirect_uri(self) -> str | None:
if not self.redirect_uris:
return None
allowed = [u.strip() for u in self.redirect_uris.replace("\n", " ").split(" ") if u.strip()]
return allowed[0] if allowed else None
def get_allowed_scope(self, scope: str) -> str:
if not scope:
return ''
client_scopes = set(scope_to_list(self.scope))
req = set(scope_to_list(scope))
return ' '.join(sorted(req & client_scopes))
def check_client_secret(self, secret: str | None) -> bool:
if self.token_endpoint_auth_method == 'none':
return True
return bool(secret and secrets.compare_digest(self.client_secret or '', secret))
def check_endpoint_auth_method(self, method: str, endpoint: str) -> bool:
"""
Authlib calls this to verify the client's allowed auth method for a given endpoint.
We only store a single setting (`token_endpoint_auth_method`) and use it for the token endpoint.
Valid values include: 'none', 'client_secret_basic', 'client_secret_post'.
"""
configured = (self.token_endpoint_auth_method or '').strip() or 'client_secret_basic'
if endpoint == 'token':
# Public clients (no client_secret) may use 'none' (and often send only client_id in body)
if not self.client_secret:
return method in ('none', 'client_secret_post')
return method == configured
# For unknown endpoints, be strict.
return False
def check_response_type(self, response_type: str) -> bool:
if not self.response_types:
return False
allowed = [t.strip() for t in self.response_types.replace("\n", " ").split(" ") if t.strip()]
return response_type in allowed
def check_grant_type(self, grant_type: str) -> bool:
if not self.grant_types:
return False
allowed = [t.strip() for t in self.grant_types.replace("\n", " ").split(" ") if t.strip()]
return grant_type in allowed
@property
def client_id_issued_at(self):
return int(self.created_at.timestamp())
@property
def client_secret_expires_at(self):
return 0
class OAuth2AuthorizationCode(Base):
__tablename__ = 'oauth2_code'
id = Column(Integer, primary_key=True)
code = Column(String(120), unique=True, nullable=False)
client_id = Column(String(48), nullable=False)
redirect_uri = Column(String(256), nullable=False)
scope = Column(Text)
user_id = Column(Integer, ForeignKey('user.id'))
user = relationship('User')
code_challenge = Column(String(128))
code_challenge_method = Column(String(10))
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
expires_in = Column(Integer, default=600)
consumed = Column(Boolean, default=False)
def is_expired(self):
return datetime.now(timezone.utc) > self.created_at + timedelta(seconds=self.expires_in)
# Authlib v1 expects these helpers on the authorization code model
def get_redirect_uri(self):
return self.redirect_uri
def get_scope(self):
return (self.scope or '')
class OAuth2Token(Base):
__tablename__ = 'oauth2_token'
id = Column(Integer, primary_key=True)
client_id = Column(String(48), nullable=False)
user_id = Column(Integer, ForeignKey('user.id'))
user = relationship('User')
token_type = Column(String(40))
access_token = Column(String(255), unique=True)
refresh_token = Column(String(255), unique=True, nullable=True)
scope = Column(Text)
revoked = Column(Boolean, default=False)
issued_at = Column(Integer, default=lambda: int(datetime.now(timezone.utc).timestamp()))
expires_in = Column(Integer, default=3600)
def is_expired(self) -> bool:
"""Authlib expects tokens to implement is_expired()."""
now = int(datetime.now(timezone.utc).timestamp())
return now >= (self.issued_at + (self.expires_in or 0))
def is_revoked(self) -> bool:
"""Authlib v1 calls token.is_revoked() during resource validation."""
return bool(self.revoked)
def is_refresh_token_active(self):
if self.revoked or not self.refresh_token:
return False
# Default 30 days, can be overridden by per-client policy
ttl_days = 30
db = SessionLocal()
try:
pol = db.query(ClientPolicy).filter_by(client_id=self.client_id).first()
if pol and pol.refresh_token_ttl_days:
ttl_days = int(pol.refresh_token_ttl_days)
except Exception:
pass
finally:
db.close()
return int(datetime.now(timezone.utc).timestamp()) < self.issued_at + ttl_days * 24 * 3600
# Authlib's ResourceProtector may call get_scope(); return a space-delimited string
def get_scope(self):
return (self.scope or '')
# Authlib RefreshTokenGrant expects token.check_client(client)
def check_client(self, client) -> bool:
return self.client_id == getattr(client, 'client_id', None)
class OIDCKey(Base):
__tablename__ = 'oidc_key'
id = Column(Integer, primary_key=True)
kid = Column(String(64), unique=True, nullable=False)
alg = Column(String(16), default='RS256')
use = Column(String(16), default='sig')
public_jwk = Column(Text, nullable=False)
private_jwk = Column(Text, nullable=False)
active = Column(Boolean, default=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Scope(Base):
__tablename__ = 'scope'
name = Column(String(120), primary_key=True)
description = Column(String(256))
claims = Column(Text) # JSON array
class RememberedConsent(Base):
__tablename__ = 'remembered_consent'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('user.id'))
client_id = Column(String(48), nullable=False)
scope = Column(Text, nullable=False) # normalized scope string
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class ClientPolicy(Base):
__tablename__ = 'client_policy'
id = Column(Integer, primary_key=True)
client_id = Column(String(48), unique=True, nullable=False)
allowed_scopes = Column(Text) # space-delimited
default_scopes = Column(Text) # space-delimited
post_logout_redirect_uris = Column(Text) # space-delimited
require_pkce = Column(Boolean, default=True)
consent_policy = Column(String(16), default='once') # 'always'|'once'|'skip'
access_token_lifetime = Column(Integer) # seconds
refresh_token_ttl_days = Column(Integer) # days
token_format = Column(String(16), default='opaque')
class ServerSettings(Base):
__tablename__ = 'server_settings'
id = Column(Integer, primary_key=True)
initialized = Column(Boolean, default=False)
admin_token_hash = Column(String(255), nullable=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
# Create tables with checkfirst to avoid race conditions with multiple workers
try:
Base.metadata.create_all(engine, checkfirst=True)
except Exception as e:
# If tables already exist (race condition with multiple workers), ignore
print(f"Note: Database tables may already exist: {e}")
# ----------------------
# OAuth2 Server Setup
# ----------------------
class AuthorizationCodeGrant(grants.AuthorizationCodeGrant):
TOKEN_ENDPOINT_AUTH_METHODS = ["none", "client_secret_basic", "client_secret_post"]
def save_authorization_code(self, code, request):
db = SessionLocal()
# Prefer Authlib v1+ payload scope; fallback to request.scope
payload = getattr(request, 'payload', None)
scope_val = None
if payload is not None:
scope_val = getattr(payload, 'scope', None)
if scope_val is None and isinstance(payload, dict):
scope_val = payload.get('scope', '')
if scope_val is None:
scope_val = getattr(request, 'scope', '') or ''
# Prefer payload.redirect_uri when available (avoid deprecation warning)
redirect_uri_val = None
if payload is not None:
redirect_uri_val = getattr(payload, 'redirect_uri', None)
if redirect_uri_val is None and isinstance(payload, dict):
redirect_uri_val = payload.get('redirect_uri')
if not redirect_uri_val:
redirect_uri_val = request.redirect_uri
# Prefer payload.data for PKCE fields when available
data_obj = None
if payload is not None:
data_obj = getattr(payload, 'data', None)
if data_obj is None and isinstance(payload, dict):
data_obj = payload.get('data', None)
item = OAuth2AuthorizationCode(
# In Authlib v1+, `code` is a string value, not a dict
code=code,
client_id=request.client.client_id,
redirect_uri=redirect_uri_val,
scope=scope_val,
user_id=request.user.id,
code_challenge=(data_obj.get("code_challenge") if data_obj else request.data.get("code_challenge")),
code_challenge_method=(data_obj.get("code_challenge_method") if data_obj else request.data.get("code_challenge_method")),
)
db.add(item)
db.commit()
db.close()
return code
# Ensure refresh tokens are issued on authorization_code exchange when requested/allowed
def should_issue_refresh_token(self, request=None):
req = request or getattr(self, 'request', None)
# Prefer payload.scope (Authlib v1), fallback to request.scope
payload = getattr(req, 'payload', None)
scope_str = None
if payload is not None:
scope_str = getattr(payload, 'scope', None)
if scope_str is None and isinstance(payload, dict):
scope_str = payload.get('scope', '')
if scope_str is None:
scope_str = getattr(req, 'scope', '') or ''
# OIDC-style: issue refresh token when offline_access is requested
if 'offline_access' in scope_to_list(scope_str):
return True
# Or when client explicitly allows refresh_token grant type
client = getattr(req, 'client', None)
if client and hasattr(client, 'check_grant_type') and client.check_grant_type('refresh_token'):
return True
return False
def query_authorization_code(self, code, client):
db = SessionLocal()
item = db.query(OAuth2AuthorizationCode).filter_by(code=code, client_id=client.client_id).first()
db.close()
return item
def delete_authorization_code(self, authorization_code):
db = SessionLocal()
authorization_code.consumed = True
db.add(authorization_code)
db.commit()
db.close()
def authenticate_user(self, authorization_code):
# Avoid lazy-loading 'user' on a detached instance; fetch via a new session
db = SessionLocal()
try:
u = db.get(User, authorization_code.user_id)
finally:
db.close()
return u
def validate_code_challenge(self, authorization_code, request):
# Enforce PKCE if a challenge was present during /authorize
# Prefer request.payload.data (Authlib v1) with fallback to request.data
payload = getattr(request, 'payload', None)
data_obj = None
if payload is not None:
data_obj = getattr(payload, 'data', None)
if data_obj is None and isinstance(payload, dict):
data_obj = payload.get('data')
verifier = (data_obj.get("code_verifier") if data_obj else request.data.get("code_verifier"))
if authorization_code.code_challenge:
if not verifier:
raise OAuth2Error(error="invalid_grant", description="Missing code_verifier")
method = authorization_code.code_challenge_method or "plain"
if not CodeChallenge(method).verify(authorization_code.code_challenge, verifier):
raise OAuth2Error(error="invalid_grant", description="Invalid code_verifier")
return True
class RefreshTokenGrant(grants.RefreshTokenGrant):
INCLUDE_NEW_REFRESH_TOKEN = True # rotation
# Allow public clients (no client_secret) to refresh tokens in this demo
TOKEN_ENDPOINT_AUTH_METHODS = ["none", "client_secret_basic", "client_secret_post"]
def authenticate_refresh_token(self, refresh_token):
db = SessionLocal()
try:
tok = (
db.query(OAuth2Token)
.options(selectinload(OAuth2Token.user))
.filter_by(refresh_token=refresh_token)
.first()
)
if tok and tok.is_refresh_token_active():
# Touch to fully load before session closes
_ = tok.user.id if tok.user else None
return tok
finally:
db.close()
def authenticate_user(self, credential):
return credential.user
def revoke_old_credential(self, credential):
db = SessionLocal()
credential.revoked = True
db.add(credential)
db.commit()
db.close()
class MyBearerTokenValidator(BearerTokenValidator):
def authenticate_token(self, token_string):
db = SessionLocal()
try:
tok = (
db.query(OAuth2Token)
.options(selectinload(OAuth2Token.user))
.filter_by(access_token=token_string)
.first()
)
# Access relationship once to ensure it's loaded before session close
if tok and tok.user is not None:
_ = tok.user.id # touch attribute to force load
return tok
finally:
db.close()
def request_invalid(self, request):
return False
def token_revoked(self, token):
return token.revoked
require_oauth = ResourceProtector()
require_oauth.register_token_validator(MyBearerTokenValidator())
auth_server = AuthorizationServer()
# ----------------------
# OIDC signing keys (RSA) with persistence
# ----------------------
def _load_active_signing_key():
db = SessionLocal()
try:
item = db.query(OIDCKey).filter_by(active=True).first()
if not item:
kid = os.environ.get("OIDC_JWK_KID", "dev-1")
key = JsonWebKey.generate_key("RSA", 2048, is_private=True)
pub = key.as_dict(is_private=False)
priv = key.as_dict()
# attach kid to JWK dicts for JWKS consumers
pub["kid"] = kid
priv["kid"] = kid
item = OIDCKey(kid=kid, alg='RS256', use='sig', public_jwk=json.dumps(pub), private_jwk=json.dumps(priv), active=True)
db.add(item)
db.commit()
priv = json.loads(item.private_jwk)
key = JsonWebKey.import_key(priv)
return item.kid, key
finally:
db.close()
KID, SIGNING_JWK = _load_active_signing_key()
def _issuer() -> str:
# Compute issuer based on current host, e.g., http://127.0.0.1:8000
try:
return (request.host_url or "http://127.0.0.1:8000/").rstrip('/')
except RuntimeError:
# outside request context
return "http://127.0.0.1:8000"
def _b64url_no_pad(b: bytes) -> str:
return base64.urlsafe_b64encode(b).decode().rstrip('=')
def _make_id_token(user: User, client_id: str, access_token: str | None, expires_in: int | None) -> str:
now = int(datetime.now(timezone.utc).timestamp())
exp = now + int(expires_in or 3600)
payload = {
'iss': _issuer(),
'sub': str(user.id),
'aud': client_id,
'iat': now,
'exp': exp,
}
# Include at_hash when access_token is available (recommended)
if access_token:
h = hashlib.sha256(access_token.encode()).digest()
half = h[:len(h)//2]
payload['at_hash'] = _b64url_no_pad(half)
header = {'alg': 'RS256', 'kid': KID}
return jwt.encode(header, payload, SIGNING_JWK).decode()
def query_client(client_id: str) -> OAuth2Client | None:
db = SessionLocal()
client = db.query(OAuth2Client).filter_by(client_id=client_id).first()
db.close()
return client
# ----------------------
# Admin endpoints (secured by X-Admin-Token)
# ----------------------
def _require_admin():
# Prefer DB-stored admin token (created via setup). Fallback to env ADMIN_TOKEN.
hdr = (request.headers.get('X-Admin-Token') or '').strip()
db = SessionLocal()
try:
s = db.query(ServerSettings).first()
finally:
db.close()
if s and s.initialized and s.admin_token_hash:
if not hdr or not check_password_hash(s.admin_token_hash, hdr):
abort(401)
return
admin_token = os.environ.get('ADMIN_TOKEN')
if not admin_token or not secrets.compare_digest(hdr, admin_token):
abort(401)
@app.route('/admin/rotate_jwk', methods=['POST'])
def admin_rotate_jwk():
_require_admin()
db = SessionLocal()
try:
db.query(OIDCKey).filter_by(active=True).update({'active': False})
kid = 'kid-' + secrets.token_urlsafe(6)
key = JsonWebKey.generate_key('RSA', 2048, is_private=True)
pub = key.as_dict(is_private=False)
priv = key.as_dict()
pub["kid"] = kid
priv["kid"] = kid
row = OIDCKey(kid=kid, alg='RS256', use='sig', public_jwk=json.dumps(pub), private_jwk=json.dumps(priv), active=True)
db.add(row)
db.commit()
global KID, SIGNING_JWK
KID, SIGNING_JWK = row.kid, JsonWebKey.import_key(priv)
return jsonify({'rotated': True, 'kid': row.kid})
finally:
db.close()
@app.route('/admin/scopes', methods=['GET', 'POST'])
def admin_scopes():
_require_admin()
db = SessionLocal()
try:
if request.method == 'GET':
items = db.query(Scope).all()
return jsonify([{'name': s.name, 'description': s.description, 'claims': json.loads(s.claims or '[]')} for s in items])
data = request.json or {}
name = data.get('name')
if not name:
abort(400, 'name required')
item = db.query(Scope).filter_by(name=name).first()
claims = data.get('claims') or []
if item:
item.description = data.get('description', item.description)
item.claims = json.dumps(claims)
else:
item = Scope(name=name, description=data.get('description'), claims=json.dumps(claims))
db.add(item)
db.commit()
return jsonify({'ok': True})
finally:
db.close()
@app.route('/admin/scopes/<name>', methods=['DELETE'])
def admin_delete_scope(name):
_require_admin()
db = SessionLocal()
try:
db.query(Scope).filter_by(name=name).delete()
db.commit()
return jsonify({'ok': True})
finally:
db.close()
@app.route('/admin/clients/<client_id>/policy', methods=['GET', 'POST'])
def admin_client_policy(client_id):
_require_admin()
db = SessionLocal()
try:
pol = db.query(ClientPolicy).filter_by(client_id=client_id).first()
if request.method == 'GET':
if not pol:
return jsonify({})
return jsonify({
'client_id': pol.client_id,
'allowed_scopes': pol.allowed_scopes,
'default_scopes': pol.default_scopes,
'post_logout_redirect_uris': pol.post_logout_redirect_uris,
'require_pkce': pol.require_pkce,
'consent_policy': pol.consent_policy,
'access_token_lifetime': pol.access_token_lifetime,
'refresh_token_ttl_days': pol.refresh_token_ttl_days,
'token_format': pol.token_format,
})
data = request.json or {}
if not pol:
pol = ClientPolicy(client_id=client_id)
db.add(pol)
for field in ['allowed_scopes','default_scopes','post_logout_redirect_uris','consent_policy','token_format']:
if field in data and data[field] is not None:
setattr(pol, field, data[field])
for field in ['require_pkce']:
if field in data and data[field] is not None:
setattr(pol, field, bool(data[field]))
for field in ['access_token_lifetime','refresh_token_ttl_days']:
if field in data and data[field] is not None:
setattr(pol, field, int(data[field]))
db.commit()
return jsonify({'ok': True})
finally:
db.close()
@app.route('/admin/users', methods=['GET','POST'])
def admin_users():
_require_admin()
db = SessionLocal()
try:
if request.method == 'GET':
items = db.query(User).all()
return jsonify([
{'id': u.id, 'username': u.username, 'email': u.email}
for u in items
])
data = request.json or {}
username = (data.get('username') or '').strip()
password = (data.get('password') or '').strip()
email = (data.get('email') or '').strip() or None
if not username or not password:
abort(400, 'username and password required')
if db.query(User).filter_by(username=username).first():
abort(409, 'username already exists')
u = User(username=username, email=email, password_hash=generate_password_hash(password))
db.add(u)
db.commit()
return jsonify({'id': u.id, 'username': u.username, 'email': u.email}), 201
finally:
db.close()
@app.route('/admin/users/<int:user_id>', methods=['GET','DELETE'])
def admin_user_detail_api(user_id):
_require_admin()
db = SessionLocal()
try:
u = db.get(User, user_id)
if not u:
abort(404)
if request.method == 'GET':
return jsonify({'id': u.id, 'username': u.username, 'email': u.email})
# DELETE: cleanup related records then remove user
db.query(OAuth2Token).filter_by(user_id=user_id).delete()
db.query(OAuth2AuthorizationCode).filter_by(user_id=user_id).delete()
db.query(RememberedConsent).filter_by(user_id=user_id).delete()
db.delete(u)
db.commit()
return jsonify({'ok': True})
finally:
db.close()
@app.route('/admin/clients', methods=['GET','POST'])
def admin_clients_api():
"""Admin API endpoint to list all OAuth2 clients and their configuration."""
_require_admin()
db = SessionLocal()
try:
if request.method == 'GET':
# Query all clients and return their configuration
clients = db.query(OAuth2Client).all()
result = []
for c in clients:
# Get associated policy if exists
policy = db.query(ClientPolicy).filter_by(client_id=c.client_id).first()
client_data = {
'client_id': c.client_id,
'client_name': c.client_name,
'client_secret': c.client_secret,
'redirect_uris': c.redirect_uris,
'scope': c.scope,
'grant_types': c.grant_types,
'response_types': c.response_types,
'token_endpoint_auth_method': c.token_endpoint_auth_method,
'require_consent': c.require_consent,
}
if policy:
client_data['policy'] = {
'allowed_scopes': policy.allowed_scopes,
'default_scopes': policy.default_scopes,
'post_logout_redirect_uris': policy.post_logout_redirect_uris,
'consent_policy': policy.consent_policy,
'require_pkce': policy.require_pkce,
'token_format': policy.token_format,
'access_token_lifetime': policy.access_token_lifetime,
'refresh_token_ttl_days': policy.refresh_token_ttl_days,
}
result.append(client_data)
return jsonify(result)
# POST: Create a new client
data = request.json or {}
client_id = (data.get('client_id') or '').strip()
if not client_id:
abort(400, 'client_id required')
if db.query(OAuth2Client).filter_by(client_id=client_id).first():
abort(409, 'client_id already exists')
c = OAuth2Client(
client_id=client_id,
client_secret=data.get('client_secret'),
client_name=data.get('client_name', ''),
redirect_uris=data.get('redirect_uris', ''),
scope=data.get('scope', 'openid profile email'),
grant_types=data.get('grant_types', 'authorization_code'),
response_types=data.get('response_types', 'code'),
token_endpoint_auth_method=data.get('token_endpoint_auth_method', 'client_secret_basic'),
require_consent=data.get('require_consent', True)
)
db.add(c)
db.commit()
return jsonify({'client_id': c.client_id, 'message': 'Client created'}), 201
finally:
db.close()
@app.route('/admin/clients/<client_id>', methods=['GET','PUT','PATCH','DELETE'])
def admin_client_detail_api(client_id):
"""Admin API endpoint to get, update, or delete a specific OAuth2 client."""
_require_admin()
db = SessionLocal()
try:
c = db.query(OAuth2Client).filter_by(client_id=client_id).first()
if not c:
abort(404, 'Client not found')
if request.method == 'GET':
policy = db.query(ClientPolicy).filter_by(client_id=c.client_id).first()
client_data = {
'client_id': c.client_id,
'client_name': c.client_name,
'client_secret': c.client_secret,
'redirect_uris': c.redirect_uris,
'scope': c.scope,
'grant_types': c.grant_types,
'response_types': c.response_types,
'token_endpoint_auth_method': c.token_endpoint_auth_method,
'require_consent': c.require_consent,
}
if policy:
client_data['policy'] = {
'allowed_scopes': policy.allowed_scopes,
'default_scopes': policy.default_scopes,
'post_logout_redirect_uris': policy.post_logout_redirect_uris,
'consent_policy': policy.consent_policy,
'require_pkce': policy.require_pkce,
'token_format': policy.token_format,
'access_token_lifetime': policy.access_token_lifetime,
'refresh_token_ttl_days': policy.refresh_token_ttl_days,
}
return jsonify(client_data)
if request.method in ('PUT', 'PATCH'):
# Update client configuration
data = request.json or {}
if 'client_name' in data:
c.client_name = data['client_name']
if 'client_secret' in data:
c.client_secret = data['client_secret']
if 'redirect_uris' in data:
c.redirect_uris = data['redirect_uris']
if 'scope' in data:
c.scope = data['scope']
if 'grant_types' in data:
c.grant_types = data['grant_types']
if 'response_types' in data:
c.response_types = data['response_types']
if 'token_endpoint_auth_method' in data:
c.token_endpoint_auth_method = data['token_endpoint_auth_method']
if 'require_consent' in data:
c.require_consent = data['require_consent']
# Update policy if provided
if 'policy' in data:
policy = db.query(ClientPolicy).filter_by(client_id=client_id).first()
if not policy:
policy = ClientPolicy(client_id=client_id)
db.add(policy)
policy_data = data['policy']
if 'allowed_scopes' in policy_data:
policy.allowed_scopes = policy_data['allowed_scopes']
if 'default_scopes' in policy_data:
policy.default_scopes = policy_data['default_scopes']
if 'post_logout_redirect_uris' in policy_data:
policy.post_logout_redirect_uris = policy_data['post_logout_redirect_uris']
if 'consent_policy' in policy_data:
policy.consent_policy = policy_data['consent_policy']
if 'require_pkce' in policy_data:
policy.require_pkce = policy_data['require_pkce']
if 'token_format' in policy_data:
policy.token_format = policy_data['token_format']
if 'access_token_lifetime' in policy_data:
policy.access_token_lifetime = policy_data['access_token_lifetime']
if 'refresh_token_ttl_days' in policy_data:
policy.refresh_token_ttl_days = policy_data['refresh_token_ttl_days']
db.commit()
return jsonify({'client_id': c.client_id, 'message': 'Client updated'})
if request.method == 'DELETE':
# Delete client and related records
db.query(OAuth2AuthorizationCode).filter_by(client_id=client_id).delete()
db.query(OAuth2Token).filter_by(client_id=client_id).delete()
db.query(ClientPolicy).filter_by(client_id=client_id).delete()
db.query(RememberedConsent).filter_by(client_id=client_id).delete()
db.delete(c)
db.commit()
return jsonify({'ok': True, 'message': 'Client deleted'})
finally:
db.close()
# Legacy decorators removed; `init_app(app, query_client=..., save_token=...)` is used instead.
def get_client(client_id):
return query_client(client_id)
def get_token(token_str):
db = SessionLocal()
tok = db.query(OAuth2Token).filter_by(access_token=token_str).first()
db.close()
return tok
# ----------------------
# Server settings & first-time setup
# ----------------------
def _get_settings() -> ServerSettings:
db = SessionLocal()
try:
s = db.query(ServerSettings).first()
if not s:
s = ServerSettings(initialized=False)
db.add(s)
db.commit()
db.refresh(s)
return s
finally:
db.close()
@app.before_request
def _enforce_setup_wizard():
# Allow the setup flow and a few public endpoints while uninitialized
s = _get_settings()
if s.initialized:
return None
path = request.path or '/'
allowed = {
'/setup',
'/favicon.ico',
'/.well-known/openid-configuration',
'/.well-known/jwks.json',
'/health',
}
if path == '/' or path.startswith('/setup'):
return None
if path in allowed or path.startswith('/static/'):
return None
# Everything else redirects to setup until initialized
return redirect(url_for('setup'))
SETUP_TEMPLATE = """
<!doctype html>
<meta charset="utf-8">
<title>First-time Setup</title>
<style>
body{font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;background:#0b1020;color:#e8ecf1;margin:0}
.wrap{max-width:720px;margin:48px auto;padding:0 20px}
.card{background:#151b2f;border:1px solid #26314f;border-radius:12px;padding:24px 28px;box-shadow:0 10px 30px rgba(0,0,0,.35)}
input,button{width:100%;padding:10px 12px;border-radius:10px;border:1px solid #3d4f77;background:#0f1426;color:#e8ecf1}
button{margin-top:12px;background:#2d6cdf;border:none;font-weight:600}
.muted{color:#a7b1c2}
.ok{color:#42d392}
code{background:#0f1426;padding:2px 6px;border-radius:6px}
.row{display:flex;gap:12px;align-items:center}
.btn{padding:8px 12px;background:#2d6cdf;color:#fff;border-radius:8px;text-decoration:none;font-weight:600;border:none}
.info{padding:10px 12px;border-radius:10px;border:1px solid #3d4f77;background:#0f1426}
.copy{user-select:all}
}</style>
<div class="wrap">
<div class="card">
<h2>First-time Setup</h2>
{% if not generated %}
<p>Set an admin token to secure the Admin UI and APIs. This token will be shown once, then only a hash is stored.</p>
<form method="post">
<label>Admin Token (leave blank to auto-generate a secure token)
<input name="admin_token" placeholder="e.g. copy a strong random string">
</label>
<button type="submit">Initialize Server</button>
</form>
<p class="muted">You can rotate keys, add scopes/clients later in the Admin UI.</p>
{% else %}
<p class="ok">Initialized.</p>
<p>Copy your admin token now and store it securely:</p>
<div class="info copy">{{admin_token}}</div>
<p class="muted">Use it for Admin UI login and X-Admin-Token header for Admin APIs.</p>
<p><a class="btn" href="{{ url_for('admin_login') }}">Go to Admin Login</a></p>
{% endif %}
</div>
</div>
"""
@app.route('/setup', methods=['GET','POST'])
def setup():
s = _get_settings()
if s.initialized:
return redirect(url_for('admin_login'))
if request.method == 'GET':
return render_template_string(SETUP_TEMPLATE, generated=False)
# POST: initialize
token = (request.form.get('admin_token') or '').strip()
if not token:
token = base64.urlsafe_b64encode(os.urandom(36)).decode().rstrip('=')
db = SessionLocal()
try:
s = db.query(ServerSettings).first()
s.admin_token_hash = generate_password_hash(token)
s.initialized = True
s.updated_at = datetime.now(timezone.utc)
# Ensure core scopes exist
def upsert_scope(name, desc):
sc = db.query(Scope).filter_by(name=name).first()
if sc:
sc.description = desc
else:
db.add(Scope(name=name, description=desc, claims=json.dumps([])))
for name, desc in [('openid','Sign you in'),('profile','Read your basic profile'),('email','Read your email address'),('offline_access','Get a refresh token for offline access')]:
upsert_scope(name, desc)
db.commit()
finally:
db.close()
# Show token once
return render_template_string(SETUP_TEMPLATE, generated=True, admin_token=token)
# ----------------------
# Admin Web UI (configurable, no hardcoding)
# ----------------------
def _admin_logged_in() -> bool:
return bool(session.get('admin'))
def _require_admin_ui():
if not _admin_logged_in():
nxt = request.path if request.method == 'GET' else url_for('admin_ui')
return redirect(url_for('admin_login', next=nxt))
return None
ADMIN_LOGIN_TEMPLATE = """
<!doctype html>
<meta charset="utf-8">
<title>Admin Login</title>
<style>
body{font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;background:#0b1020;color:#e8ecf1;margin:0;display:flex;align-items:center;justify-content:center;height:100vh}
.card{background:#151b2f;border:1px solid #26314f;border-radius:12px;padding:26px 30px;width:420px;box-shadow:0 10px 30px rgba(0,0,0,.35)}
input,button{width:100%;padding:10px 12px;border-radius:10px;border:1px solid #3d4f77;background:#0f1426;color:#e8ecf1}
button{margin-top:12px;background:#2d6cdf;border:none;font-weight:600}
.muted{color:#a7b1c2}
</style>
<div class="card">
<h3>Admin Login</h3>
<form method="post">
<input name="token" placeholder="Admin token" required>
<button type="submit">Continue</button>
</form>
{% if error %}<p style="color:#ff7272">{{error}}</p>{% endif %}
<p class="muted">Use the admin token set during setup. If ADMIN_TOKEN is set in the environment and no setup token exists, it will be accepted.</p>
</div>
"""
def _admin_layout(body: str) -> str:
return f"""
<!doctype html>
<meta charset='utf-8'>
<title>Admin</title>
<style>
body{{font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;background:#0b1020;color:#e8ecf1;margin:0}}
.wrap{{max-width:1000px;margin:36px auto;padding:0 20px}}
.nav{{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px}}
.card{{background:#151b2f;border:1px solid #26314f;border-radius:12px;padding:20px 24px;box-shadow:0 10px 30px rgba(0,0,0,.35)}}
a.btn,button.btn{{padding:8px 12px;background:#2d6cdf;color:#fff;border-radius:8px;text-decoration:none;font-weight:600;border:none}}
input,textarea,select{{width:100%;padding:10px 12px;border-radius:10px;border:1px solid #3d4f77;background:#0f1426;color:#e8ecf1}}
label{{display:block;margin:10px 0 14px}}
.field{{margin-bottom:14px}}