-
Notifications
You must be signed in to change notification settings - Fork 148
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Python OAuth implementation #320
Merged
Merged
Changes from 4 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
72bd18a
First pass at translating oauth implementation
MichaelGHSeg 790d104
Assorted small fixes
MichaelGHSeg a6d7458
Possibly working oauth implementation
MichaelGHSeg c03d881
Working OAuth implementation
MichaelGHSeg 1cf8d07
Logging improvements and change for 429 handling
MichaelGHSeg 303477a
Fixeds for logging
MichaelGHSeg ce155d6
Cleanup and restore unit tests to functioning order
MichaelGHSeg 10bf0fc
All unit tests actually working now
MichaelGHSeg cbe2bf2
Missed setup file
MichaelGHSeg 1b231e0
Fixing up some more unit test things
MichaelGHSeg 2f5945c
Various fixes, tests, and clock skew adjustment
MichaelGHSeg 0e3bd5b
Removing extraneous sample data
MichaelGHSeg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import sys | ||
import os | ||
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) | ||
import segment.analytics as analytics | ||
|
||
privatekey = '''-----BEGIN PRIVATE KEY----- | ||
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDVll7uJaH322IN | ||
PQsH2aOXZJ2r1q+6hpVK1R5JV1p41PUzn8pOxyXFHWB+53dUd4B8qywKS36XQjp0 | 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BjVgj7gncZW/kIrcP1xYYe | ||
yfQSU8XmV40UjFfCGz/G318lmP0VOdByeVKtCV3talsMEPHyPqI8E+6DL/uOebYJ | ||
qUqINK6XKnOgWOY4kvnGillqTQCcry1XQp61PlDOmj7kB75KxPXYrj6AAQKBgQDa | ||
+ixCv6hURuEyy77cE/YT/Q4zYnL6wHjtP5+UKwWUop1EkwG6o+q7wtiul90+t6ah | ||
1VUCP9X/QFM0Qg32l0PBohlO0pFrVnG17TW8vSHxwyDkds1f97N19BOT8ZR5jebI | ||
sKPfP9LVRnY+l1BWLEilvB+xBzqMwh2YWkIlWI6PMQKBgGi6TBnxp81lOYrxVRDj | ||
/3ycRnVDmBdlQKFunvfzUBmG1mG/G0YHeVSUKZJGX7w2l+jnDwIA383FcUeA8X6A | ||
l9q+amhtkwD/6fbkAu/xoWNl+11IFoxd88y2ByBFoEKB6UVLuCTSKwXDqzEZet7x | ||
mDyRxq7ohIzLkw8b8buDeuXZ | ||
-----END PRIVATE KEY----- | ||
''' # Should be read from a file on disk which can be rotated out | ||
|
||
analytics.write_key = '9BWoGOi4lWVaQBP5NRheT7N0C1t4HTJM' | ||
analytics.host = 'https://api.segment.build' | ||
analytics.oauth_client_id = '2VRbiyEPtsDBjFqO9Tu7EXvQH5H' # OAuth application ID from segment dashboard | ||
analytics.oauth_client_key = privatekey # generated as a public/private key pair in PEM format from OpenSSL | ||
analytics.oauth_key_id = '2VRbiuUFSMo4AGyrYyxxyONzqiP' # From segment dashboard after uploading public key | ||
analytics.oauth_auth_server = 'https://oauth2.segment.build' | ||
analytics.oauth_scope = 'tracking_api:write' # 'public_api:read_write' | ||
|
||
def on_error(error, items): | ||
print("An error occurred: ", error) | ||
analytics.debug = True | ||
analytics.on_error = on_error | ||
|
||
analytics.track('AUser', 'track') | ||
|
||
input("Press ENTER to exit after receiving a response...") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
from datetime import date, datetime | ||
import logging | ||
import threading | ||
import time | ||
import uuid | ||
from requests import sessions | ||
import jwt | ||
|
||
_session = sessions.Session() | ||
|
||
class OauthManager(object): | ||
def __init__(self, | ||
client_id, | ||
client_key, | ||
key_id, | ||
auth_server, | ||
scope, | ||
timeout, | ||
max_retries): | ||
self.log = logging.getLogger('segment') | ||
self.client_id = client_id | ||
self.client_key = client_key | ||
self.key_id = key_id | ||
self.auth_server = auth_server | ||
self.scope = scope | ||
self.timeout = timeout | ||
self.max_retries = max_retries | ||
self.retry_count = 0 | ||
self.thread = None | ||
self.token_mutex = threading.Lock() | ||
self.token = None | ||
self.error = None | ||
|
||
def get_token(self): | ||
with self.token_mutex: | ||
if self.token: | ||
return self.token | ||
# No good token, start the loop | ||
self.thread = threading.Thread(target=self._poller_loop) | ||
self.thread.start() | ||
|
||
while True: | ||
# Wait for a token or error | ||
with self.token_mutex: | ||
if self.token: | ||
return self.token | ||
if self.error: | ||
error = self.error | ||
self.error = None | ||
raise Exception(error) | ||
if self.thread: | ||
self.thread.join() | ||
|
||
def clear_token(self): | ||
with self.token_mutex: | ||
self.token = None | ||
|
||
def _request_token(self): | ||
jwt_body = { | ||
"iss": self.client_id, | ||
"sub": self.client_id, | ||
"aud": "https://oauth2.segment.io", | ||
"iat": int(time.time())-1, | ||
"exp": int(time.time()) + 59, | ||
"jti": str(uuid.uuid4()) | ||
} | ||
|
||
signed_jwt = jwt.encode( | ||
jwt_body, | ||
self.client_key, | ||
algorithm="RS256", | ||
headers={"kid": self.key_id}, | ||
) | ||
|
||
request_body = 'grant_type=client_credentials&client_assertion_type='\ | ||
'urn:ietf:params:oauth:client-assertion-type:jwt-bearer&'\ | ||
'client_assertion={}&scope={}'.format(signed_jwt, self.scope) | ||
|
||
token_endpoint = f'{self.auth_server}/token' | ||
|
||
res = _session.post(url=token_endpoint, data=request_body, timeout=self.timeout, | ||
headers={'Content-Type': 'application/x-www-form-urlencoded'}) | ||
return res | ||
|
||
def _poller_loop(self): | ||
refresh_timer_ms = 25 | ||
response = None | ||
|
||
try: | ||
response = self._request_token() | ||
except Exception as e: | ||
self.log.error(e) | ||
self.retry_count += 1 | ||
if self.retry_count < self.max_retries: | ||
self.thread = threading.Timer(refresh_timer_ms / 1000.0, self._poller_loop) | ||
self.thread.setDaemon(True) | ||
self.thread.start() | ||
return | ||
# Too many retries, giving up | ||
self.error = e | ||
return | ||
|
||
if response.status_code == 200: | ||
data = None | ||
try: | ||
data = response.json() | ||
except Exception as e: | ||
self.retry_count += 1 | ||
if self.retry_count < self.max_retries: | ||
self.thread = threading.Timer(refresh_timer_ms / 1000.0, self._poller_loop) | ||
self.thread.setDaemon(True) | ||
self.thread.start() | ||
return | ||
# Too many retries, giving up | ||
self.error = e | ||
return | ||
try: | ||
with self.token_mutex: | ||
self.token = data['access_token'] | ||
# success! | ||
self.retry_count = 0 | ||
except Exception as e: | ||
# No access token in response? | ||
self.log.error(e) | ||
try: | ||
refresh_timer_ms = int(data['expires_in']) / 2 * 1000 | ||
except Exception as e: | ||
refresh_timer_ms = 60 * 1000 | ||
|
||
elif response.status_code == 429: | ||
self.retry_count += 1 | ||
rate_limit_reset_time = None | ||
try: | ||
rate_limit_reset_time = int(response.headers.get("X-RateLimit-Reset")) | ||
except Exception as e: | ||
self.log.error(e) | ||
if rate_limit_reset_time: | ||
refresh_timer_ms = rate_limit_reset_time - time.time() * 1000 | ||
else: | ||
refresh_timer_ms = 5 * 1000 | ||
elif response.status_code in [400, 401, 415]: | ||
# unrecoverable errors | ||
self.retry_count = 0 | ||
self.error = Exception(f'[{response.status_code}] {response.reason}') | ||
self.log.error(self.error) | ||
return | ||
else: | ||
# any other error | ||
self.log.error(f'[{response.status_code}] {response.reason}') | ||
self.retry_count += 1 | ||
|
||
if self.retry_count % self.max_retries == 0: | ||
# every time we pass the retry count, put up an error to release any waiting token requests | ||
self.error = Exception(f'[{response.status_code}] {response.reason}') | ||
|
||
# loop | ||
self.thread = threading.Timer(refresh_timer_ms / 1000.0, self._poller_loop) | ||
self.thread.setDaemon(True) | ||
self.thread.start() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we update the urls to the prod versions?