-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgit-credential-outlook
More file actions
executable file
·532 lines (454 loc) · 18.7 KB
/
git-credential-outlook
File metadata and controls
executable file
·532 lines (454 loc) · 18.7 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
#!/usr/bin/env python3
#
# Copyright 2012 Google Inc.
# Copyright 2025 Aditya Garg
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
if "--help" in sys.argv:
print("""
Usage: git-credential-outlook [OPTIONS]
Options:
--help * Show this help message and exit.
--set-client * Set the client details to use for authentication.
--delete-client * Delete the client details set using --set-client.
--authenticate * Authenticate with Outlook using OAuth2.
--device * Use device code flow for authentication.
Use this option with --authenticate.
--external-auth * Authenticate using an external browser.
Use this option with --authenticate.
--force-refresh-token * Force refresh the access token.
--delete-token * Delete the credentials saved using --authenticate.
Description:
This script allows you to authenticate with Outlook using OAuth2 and
retrieve access tokens for use with IMAP, POP, and SMTP protocols.
Examples:
Authenticate using the browser-based flow:
git-credential-outlook --authenticate
Authenticate using the device code flow:
git-credential-outlook --authenticate --device
""")
sys.exit(0)
import keyring
import os
import requests
import time
import urllib.parse
# https://github.com/mozilla/releases-comm-central/blob/master/mailnews/base/src/OAuth2Providers.sys.mjs
ClientId_Thunderbird_Desktop = "9e5f94bc-e8a4-4e73-b8be-63364c29d753"
Redirect_URI_Thunderbird_Desktop = "https://localhost"
# https://github.com/thunderbird/thunderbird-android/blob/main/app-thunderbird/src/release/kotlin/net/thunderbird/android/auth/TbOAuthConfigurationFactory.kt
ClientId_Thunderbird_Android = "e6f8716e-299d-4ed9-bbf3-453f192f44e5"
Redirect_URI_Thunderbird_Android = "https://login.live.com/oauth20_desktop.srf"
# https://github.com/thunderbird/thunderbird-android/blob/main/app-k9mail/src/release/kotlin/app/k9mail/auth/K9OAuthConfigurationFactory.kt
ClientId_K9_Mail = "e647013a-ada4-4114-b419-e43d250f99c5"
Redirect_URI_K9_Mail = "msauth://com.fsck.k9/Dx8yUsuhyU3dYYba1aA16Wxu5eM%3D"
# https://gitlab.gnome.org/GNOME/evolution-data-server/-/commit/7554d3b95124486ac98d9a5052e069e46242a216
ClientId_Evolution = "cc6e0693-0e26-4220-8322-9d363e308fc6"
Redirect_URI_Evolution = "https://login.live.com/oauth20_desktop.srf"
# https://gitlab.gnome.org/GNOME/gnome-online-accounts/-/blob/master/meson_options.txt
ClientId_Gnome = "8ef61e06-9fd5-49af-9b63-6983aede4213"
Redirect_URI_Gnome = "goa-oauth2://localhost"
# https://github.com/M66B/FairEmail/blob/master/app/src/main/res/xml/providers.xml
ClientId_FairEmail_1 = "3514cf2c-e7a3-45a2-80d4-6a3c3498eca0"
Redirect_URI_FairEmail_1 = "msauth.eu.faircode.email://auth"
# https://github.com/M66B/FairEmail/blob/master/app/src/main/res/xml/providers.xml
ClientId_FairEmail_2 = "835c3383-543c-4aa2-98ca-c465eb039987"
Redirect_URI_FairEmail_2 = "msauth://eu.faircode.email/xSLzBBuLJunOQPB89rtzM54FXx4%3D"
# https://github.com/M66B/FairEmail/blob/master/app/src/main/res/xml/providers.xml
ClientId_FairEmail_3 = "17e57eca-a59b-4574-ac91-b343004898a6"
Redirect_URI_FairEmail_3 = "msauth://eu.faircode.email/xSLzBBuLJunOQPB89rtzM54FXx4%3D"
Scopes = 'https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send offline_access openid profile'
ServiceName = "git-credential-outlook"
def save_refresh_token(refresh_token):
keyring.set_password(ServiceName, "refresh_token", refresh_token)
def load_refresh_token():
return keyring.get_password(ServiceName, "refresh_token")
def delete_refresh_token():
keyring.delete_password(ServiceName, "refresh_token")
def save_access_token(access_token, expiry):
keyring.set_password(ServiceName, "access_token", access_token)
keyring.set_password(ServiceName, "access_token_expiry", expiry)
def load_access_token():
return keyring.get_password(ServiceName, "access_token")
def load_access_token_expiry():
return keyring.get_password(ServiceName, "access_token_expiry")
def delete_access_token():
keyring.delete_password(ServiceName, "access_token")
keyring.delete_password(ServiceName, "access_token_expiry")
def print_access_token(access_token):
if "get" in sys.argv:
print(f"password={access_token}")
else:
print(access_token)
def set_client(client_id, redirect_uri):
keyring.set_password(ServiceName, "client_id", client_id)
keyring.set_password(ServiceName, "redirect_uri", redirect_uri)
def load_client_id():
return keyring.get_password(ServiceName, "client_id")
def load_redirect_uri():
return keyring.get_password(ServiceName, "redirect_uri")
def delete_client():
keyring.delete_password(ServiceName, "client_id")
keyring.delete_password(ServiceName, "redirect_uri")
def qr_encode(url):
try:
try:
import qrcode
qr = qrcode.QRCode(border=2)
qr.add_data(url)
qr.make(fit=True)
qr.print_ascii(invert=True)
except Exception:
headers = {'User-Agent': 'curl'}
url_qr = f"https://qrenco.de/{url}"
response = requests.get(url_qr, headers=headers)
response.raise_for_status()
content = response.text
print(content)
except Exception:
# let's not interrupt the process if qrenco.de is down
pass
def get_code_from_url(url):
parsed_url = urllib.parse.urlparse(url)
parsed_query = urllib.parse.parse_qs(parsed_url.query)
return parsed_query.get('code', [''])[0]
def extract_redirect_scheme(url):
scheme = urllib.parse.urlparse(url).scheme.lower()
return scheme
def AccountsUrl(command):
return '%s/%s' % ('https://login.microsoftonline.com', command)
def UrlEscape(text):
return urllib.parse.quote(text, safe='~-._')
def FormatUrlParams(params):
param_fragments = []
for param in sorted(params.items(), key=lambda x: x[0]):
param_fragments.append('%s=%s' % (param[0], UrlEscape(param[1])))
return '&'.join(param_fragments)
def GeneratePermissionUrl(redirect_uri):
params = {}
params['client_id'] = ClientId
params['redirect_uri'] = redirect_uri
params['response_type'] = 'code'
params['response_mode'] = 'query'
params['scope'] = Scopes
return '%s?%s' % (AccountsUrl('common/oauth2/v2.0/authorize'), FormatUrlParams(params))
def AuthorizeTokens(authorization_code):
params = {}
params['client_id'] = ClientId
params['code'] = authorization_code
params['redirect_uri'] = Redirect_URI
params['grant_type'] = 'authorization_code'
request_url = AccountsUrl('common/oauth2/v2.0/token')
try:
response = requests.post(request_url, data=params)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError:
print(f"HTTP Error {response.status_code}: {response.reason}")
print("Response Body:", response.text)
sys.exit("\nFailed to get refresh token due to an HTTP error.")
except Exception as e:
print(f"Unexpected error: {e}")
sys.exit("\nFailed to get refresh token due to an unexpected error.")
def RefreshToken(refresh_token):
params = {}
params['client_id'] = ClientId
params['refresh_token'] = refresh_token
params['grant_type'] = 'refresh_token'
params['redirect_uri'] = Redirect_URI
request_url = AccountsUrl('common/oauth2/v2.0/token')
try:
response = requests.post(request_url, data=params)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError:
print(f"HTTP Error {response.status_code}: {response.reason}")
print("Response Body:", response.text)
sys.exit("\nFailed to get access token due to an HTTP error.\nTry running `git credential-outlook --authenticate` to get a new refresh token.")
except Exception as e:
print(f"Unexpected error: {e}")
sys.exit("\nFailed to get access token due to an unexpected error.\nTry running `git credential-outlook --authenticate` to get a new refresh token.")
def DeviceFlowCode():
params = {}
params['client_id'] = ClientId
params['tenant'] = 'common'
params['scope'] = Scopes
request_url = AccountsUrl('common/oauth2/v2.0/devicecode')
try:
response = requests.post(request_url, data=params)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError:
return response.text
except Exception as e:
return str(e)
def PollDeviceToken(device_code):
params = {}
params['client_id'] = ClientId
params['tenant'] = 'common'
params['grant_type'] = 'urn:ietf:params:oauth:grant-type:device_code'
params['device_code'] = device_code
request_url = AccountsUrl('common/oauth2/v2.0/token')
while True:
try:
response = requests.post(request_url, data=params)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError:
error = response.json()
if error['error'] == 'authorization_pending':
time.sleep(5)
else:
print(f"HTTP Error {response.status_code}: {response.reason}")
print("Response Body:", response.text)
sys.exit("\nFailed to get refresh token due to an HTTP error.")
except Exception as e:
print(f"Unexpected error: {e}")
sys.exit("\nFailed to get refresh token due to an unexpected error.")
def get_code_from_device_flow(open_browser=False):
device_flow = DeviceFlowCode()
if "error" in device_flow:
if open_browser:
raise Exception
else:
sys.exit(f"Failed to initiate device flow: {device_flow}")
if open_browser:
print(f"Enter this code when asked to do so by your browser: \033[1m{device_flow['user_code']}\033[0m\n")
webbrowser.open(device_flow['verification_uri'])
else:
qr_encode(device_flow['verification_uri'])
print(f"Visit {device_flow['verification_uri']} on a web browser.\nEnter this code when asked to do so: \033[1m{device_flow['user_code']}\033[0m\n")
return PollDeviceToken(device_flow['device_code'])
ClientId = load_client_id()
Redirect_URI = load_redirect_uri()
if ClientId is None:
ClientId = ClientId_Thunderbird_Desktop
Redirect_URI = Redirect_URI_Thunderbird_Desktop
elif Redirect_URI is None:
Redirect_URI = 'https://login.microsoftonline.com/common/oauth2/nativeclient'
if "--set-client" in sys.argv:
print("What client details do you want to use?\n")
print("1. Thunderbird")
print("2. K-9 Mail")
print("3. FairEmail")
print("4. GNOME Evolution")
print("5. GNOME Online Accounts")
print("6. Use your own custom client details")
answer = input("\nType the number of your choice and press enter: ")
if answer == "1":
print("\nChoose any Thunderbird variant:\n")
print("1. Thunderbird Desktop")
print("2. Thunderbird Mobile")
answer_alt = input("\nType the number of your choice and press enter: ")
if answer_alt == "1":
ClientId = ClientId_Thunderbird_Desktop
Redirect_URI = Redirect_URI_Thunderbird_Desktop
elif answer_alt == "2":
ClientId = ClientId_Thunderbird_Android
Redirect_URI = Redirect_URI_Thunderbird_Android
elif answer == "2":
ClientId = ClientId_K9_Mail
Redirect_URI = Redirect_URI_K9_Mail
elif answer == "3":
print("\nThis client provides multiple client IDs. Choose any one:\n")
print("1. Default")
print("2. Alternative 1")
print("3. Alternative 2")
answer_alt = input("\nType the number of your choice and press enter: ")
if answer_alt == "1":
ClientId = ClientId_FairEmail_1
Redirect_URI = Redirect_URI_FairEmail_1
elif answer_alt == "2":
ClientId = ClientId_FairEmail_2
Redirect_URI = Redirect_URI_FairEmail_2
elif answer_alt == "3":
ClientId = ClientId_FairEmail_3
Redirect_URI = Redirect_URI_FairEmail_3
elif answer == "4":
ClientId = ClientId_Evolution
Redirect_URI = Redirect_URI_Evolution
elif answer == "5":
ClientId = ClientId_Gnome
Redirect_URI = Redirect_URI_Gnome
elif answer == "6":
ClientId = input("\nEnter the Client ID: ")
Redirect_URI = input("Enter the Redirect URI: ")
else:
sys.exit("\nInvalid choice")
set_client(ClientId, Redirect_URI)
print("\nClient details saved to keyring")
elif "--delete-client" in sys.argv:
try:
delete_client()
print("Client details deleted from keyring")
except keyring.errors.PasswordDeleteError:
sys.exit("No client details found in keyring")
elif "--authenticate" in sys.argv:
if "--device" in sys.argv:
token = get_code_from_device_flow()
else:
scheme = extract_redirect_scheme(Redirect_URI)
Redirect_URI_is_http = 'false'
if scheme == 'http' or scheme == 'https':
Redirect_URI_is_http = 'true'
url = GeneratePermissionUrl(Redirect_URI)
code = ''
if "--external-auth" in sys.argv:
# Use external browser for authentication
qr_encode(url)
print("Navigate to the following URL in a web browser:\n")
print(url)
if Redirect_URI_is_http == 'true':
print("\nAfter login, you will be redirected to a blank or error page.")
codeurl = input("Copy the URL of that page and paste it here:\n")
else:
print("\nThis client uses a non-http redirect URI.")
print("Before login enable network logging in your browser.")
print("After login, check the network logs for a URL that:")
print(f" 1. Starts with \"{scheme}://\".")
print(" 2. Has \"code\" in it.")
codeurl = input("Copy that URL and paste it here:\n")
code = get_code_from_url(codeurl)
token = AuthorizeTokens(code)
print()
else:
print("Opening a browser window for authentication...\n")
try:
from PyQt6.QtCore import QUrl, QLoggingCategory
from PyQt6.QtWidgets import QApplication, QMainWindow
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile, QWebEngineUrlSchemeHandler, QWebEngineUrlRequestJob, QWebEngineUrlScheme
qt_available = True
except Exception:
try:
from PySide6.QtCore import QUrl, QLoggingCategory
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile, QWebEngineUrlSchemeHandler, QWebEngineUrlRequestJob, QWebEngineUrlScheme
qt_available = True
except Exception:
import webbrowser
qt_available = False
if qt_available:
if "--verbose" in sys.argv:
loglevel = 0
else:
loglevel = 3
QLoggingCategory("qt.webenginecontext").setFilterRules("*.info=false") # Suppress info logs
os.environ["QTWEBENGINE_CHROMIUM_FLAGS"] = f"--enable-logging --log-level={loglevel}"
def register_scheme(name: str):
scheme = QWebEngineUrlScheme(name.encode())
scheme.setFlags(
QWebEngineUrlScheme.Flag.SecureScheme
| QWebEngineUrlScheme.Flag.LocalAccessAllowed
)
QWebEngineUrlScheme.registerScheme(scheme)
class CatchAllHandler(QWebEngineUrlSchemeHandler):
def requestStarted(self, job: QWebEngineUrlRequestJob):
job.fail(QWebEngineUrlRequestJob.Error.UrlInvalid)
class Page(QWebEnginePage):
def acceptNavigationRequest(self, url: QUrl, nav_type, is_main_frame: bool) -> bool:
if "code=" in url.toString() and url.toString().startswith(Redirect_URI):
global code
code = get_code_from_url(url.toString())
QApplication.instance().quit()
return super().acceptNavigationRequest(url, nav_type, is_main_frame)
class BrowserWindow(QMainWindow):
def __init__(self, profile: QWebEngineProfile):
super().__init__()
self.setWindowTitle("OAuth2 Login")
self.resize(800, 600)
self.browser = QWebEngineView()
self.browser.setPage(Page(profile, self.browser))
self.setCentralWidget(self.browser)
self.browser.load(QUrl(url))
self.show()
if Redirect_URI_is_http == 'false':
register_scheme(scheme)
webapp = QApplication(sys.argv)
profile = QWebEngineProfile.defaultProfile()
handler = CatchAllHandler()
if Redirect_URI_is_http == 'false':
profile.installUrlSchemeHandler(scheme.encode(), handler)
window = BrowserWindow(profile)
webapp.exec()
token = AuthorizeTokens(code)
else:
try:
# Lets try to use device code flow first
token = get_code_from_device_flow(open_browser=True)
except Exception:
webbrowser.open(url)
print("Authenticate in the browser window that opened.")
if Redirect_URI_is_http == 'true':
print("\nAfter login, you will be redirected to a blank or error page.")
codeurl = input("Copy the URL of that page and paste it here:\n")
else:
print("\nThis client uses a non-http redirect URI.")
print("Before login enable network logging in your browser.")
print("After login, check the network logs for a URL that:")
print(f" 1. Starts with \"{scheme}://\".")
print(" 2. Has \"code\" in it.")
print("Copy that URL and paste it here:\n")
codeurl = input("Alternatively cancel the process (Ctrl+C) and install either PyQt6-WebEngine or PySide6 for easier login.\n")
code = get_code_from_url(codeurl)
print()
token = AuthorizeTokens(code)
if 'error' in token:
print(token)
sys.exit("\nFailed to get refresh token")
save_refresh_token(token['refresh_token'])
try:
delete_access_token()
except keyring.errors.PasswordDeleteError:
pass
print('Saved refresh token to keyring')
elif "--delete-token" in sys.argv:
exit_error = 0
try:
delete_refresh_token()
print("Refresh token deleted from keyring")
except keyring.errors.PasswordDeleteError:
print("No refresh token found in keyring")
exit_error = 1
try:
delete_access_token()
print("Access token deleted from keyring")
except keyring.errors.PasswordDeleteError:
print("No access token found in keyring")
exit_error = 1
sys.exit(exit_error)
else:
need_new_access_token = False
access_token = load_access_token()
access_token_expiry = load_access_token_expiry()
if access_token is None or access_token_expiry is None or (int(access_token_expiry) - int(time.time())) <= 0 or "--force-refresh-token" in sys.argv:
need_new_access_token = True
if need_new_access_token:
# Lets use the refresh token to get a new access token
refresh_token = load_refresh_token()
if refresh_token is None:
sys.exit("No refresh token found.\nPlease authenticate first by running `git credential-outlook --authenticate`")
token = RefreshToken(refresh_token)
if 'error' in token:
print(token)
sys.exit("Failed to get access token from the server")
else:
access_token = token['access_token']
access_token_expiry = int(time.time()) + int(token['expires_in']) - 120 # Subtract 2 minutes to ensure we never get an expired token
try: # Some credential helpers hate such long access tokens (looking at you Windows). Still we can refresh the token right ;)
save_access_token(access_token, str(access_token_expiry))
except Exception:
pass
print_access_token(access_token)