Setting the file. One moment.
Auth Callback Server · Launch With AWS · aws/agent-toolkit-for-aws · Skills Docs
ContentsBack to the top of the page 69
Creating Amazon Aurora Db Cluster With Instances
92
Routing Traffic With Route53 And CloudFront
Resilience Program Design
Debugging Lambda Timeouts
(opens in a new tab)
scripts/ auth_callback_server.py
Python · 105 lines · 3 KB
"""
18
19 import argparse
20 import json
21 import sys
22 import threading
23 from http.server import HTTPServer
24 from pathlib import Path
25
26 sys.path.insert( 0 , str (Path( __file__ ).parent))
27
28 from dataclasses import fields
29
30 from auth import (
31 _CallbackHandler,
32 _exchange_code,
33 _OAuthState,
34 save_session,
35 )
36 from launch_config import (
37 CALLBACK_TIMEOUT_SECS ,
38 SSO_OIDC_REGION ,
39 ClientCredentials,
40 StoredSession,
41 )
42
43
44 def main () -> None :
45 parser = argparse.ArgumentParser()
46 parser.add_argument( "--state" , required = True )
47 parser.add_argument( "--timeout" , type = float , default = CALLBACK_TIMEOUT_SECS )
48 args = parser.parse_args()
49
50 # Configuration arrives as a JSON blob on stdin.
51 raw = sys.stdin.read()
52 if not raw:
53 sys.stderr.write( "No configuration received on stdin \n " )
54 sys.exit( 1 )
55 payload = json.loads(raw)
56
57 credentials = ClientCredentials(
58 client_id = payload[ "client_id" ],
59 client_secret = payload[ "client_secret" ],
60 client_expires_at = payload[ "client_expires_at" ],
61 authorize_endpoint = f "https://oidc. { SSO_OIDC_REGION } .amazonaws.com/authorize" ,
62 token_endpoint = f "https://oidc. { SSO_OIDC_REGION } .amazonaws.com/token" ,
63 scopes = payload[ "scopes" ],
64 )
65 code_verifier = payload[ "code_verifier" ]
66
67 oauth_state = _OAuthState(args.state)
68 server = HTTPServer(( "127.0.0.1" , 0 ), _CallbackHandler)
69 setattr (server, "oauth_state" , oauth_state)
70 port = server.server_address[ 1 ]
71
72 # Signal port to parent, then close stdout.
73 sys.stdout.write( f " { port }\n " )
74 sys.stdout.flush()
75 sys.stdout.close()
76
77 server_thread = threading.Thread( target = server.serve_forever, daemon = True )
78 server_thread.start()
79
80 redirect_uri = f "http://127.0.0.1: { port } "
81
82 if not oauth_state.code_received.wait( timeout = args.timeout):
83 server.shutdown()
84 sys.exit( 1 )
85
86 server.shutdown()
87
88 if oauth_state.error or not oauth_state.auth_code:
89 sys.exit( 1 )
90
91 access_token, refresh_tok, token_expires_at = _exchange_code(
92 credentials, oauth_state.auth_code, code_verifier, redirect_uri
93 )
94
95 new_session = StoredSession(
96 ** {f.name: getattr (credentials, f.name) for f in fields(ClientCredentials)},
97 access_token = access_token,
98 refresh_token = refresh_tok,
99 token_expires_at = token_expires_at,
100 )
101 save_session(new_session)
102
103
104 if __name__ == "__main__" :
105 main()