-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_email_webhook.py
More file actions
217 lines (192 loc) · 7.78 KB
/
get_email_webhook.py
File metadata and controls
217 lines (192 loc) · 7.78 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
import os
import json
import hmac
import hashlib
import requests
from msal import ConfidentialClientApplication
from datetime import datetime, timezone, timedelta
# --- Determine mode ---
TEST_MODE = os.getenv("TEST_MODE", "true").lower() == "true"
# Import Flask only if not in TEST_MODE
if not TEST_MODE:
from flask import Flask, request
app = Flask(__name__)
# --- Microsoft Graph Email Sending Function ---
def send_email_via_graph(subject, body):
TENANT_ID = os.getenv("TENANT_ID")
CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET = os.getenv("CLIENT_SECRET")
FROM_EMAIL = os.getenv("FROM_EMAIL")
TO_EMAIL = os.getenv("TO_EMAIL")
if not all([TENANT_ID, CLIENT_ID, CLIENT_SECRET, FROM_EMAIL, TO_EMAIL]):
print("❌ Missing required environment variables")
return
try:
app_msal = ConfidentialClientApplication(
CLIENT_ID,
authority=f"https://login.microsoftonline.com/{TENANT_ID}",
client_credential=CLIENT_SECRET
)
token = app_msal.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
access_token = token.get("access_token")
if not access_token:
print(f"❌ Failed to get access token: {token}")
return
email_msg = {
"message": {
"subject": subject,
"body": {"contentType": "Text", "content": body},
"toRecipients": [{"emailAddress": {"address": TO_EMAIL}}]
}
}
response = requests.post(
f"https://graph.microsoft.com/v1.0/users/{FROM_EMAIL}/sendMail",
headers={"Authorization": f"Bearer {access_token}", "Content-Type": "application/json"},
json=email_msg
)
if response.status_code == 202:
print(f"✅ Email sent to {TO_EMAIL}")
else:
print(f"❌ Failed to send email: {response.status_code} {response.text}")
except Exception as e:
print(f"❌ Exception occurred while sending email: {e}")
# --- Verify GitHub webhook signature ---
def verify_github_signature(payload_body, signature, secret):
if not secret:
print("⚠️ No webhook secret set, skipping verification")
return True
if not signature:
print("❌ No signature provided in headers")
return False
mac = hmac.new(secret.encode(), msg=payload_body, digestmod=hashlib.sha256)
expected_signature = "sha256=" + mac.hexdigest()
return hmac.compare_digest(expected_signature, signature)
# --- Convert UTC timestamp to UTC+4 ---
def convert_to_utc4(timestamp):
if not timestamp:
return "N/A"
try:
dt_utc = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
dt_utc4 = dt_utc.astimezone(timezone(timedelta(hours=4)))
return dt_utc4.strftime("%Y-%m-%d %H:%M:%S")
except Exception as e:
print(f"⚠️ Failed to convert timestamp {timestamp}: {e}")
return timestamp
# --- Format GitHub repository event for email ---
def format_repo_event(repo, action):
repo_name = repo["full_name"]
visibility_icon = "🔒 Private" if repo.get("private") else "🌐 Public"
owner = repo["owner"]["login"]
default_branch = repo.get("default_branch", "N/A")
created_at = convert_to_utc4(repo.get("created_at"))
updated_at = convert_to_utc4(repo.get("updated_at"))
url = repo.get("html_url", "")
# Special cases for visibility changes
if action == "publicized":
subject = f"[GitHub Alert] Repository changed from PRIVATE → PUBLIC: {repo_name}"
body = (
f"The repository visibility has been changed.\n\n"
f"➡️ Now PUBLIC\n\n"
f"📌 Repository Name: {repo_name}\n"
f"{visibility_icon}\n"
f"👤 Owner: {owner}\n"
f"🌿 Default branch: {default_branch}\n"
f"🕒 Created at: {created_at}\n"
f"🕒 Last updated: {updated_at}\n"
f"🌍 URL: {url}\n"
)
elif action == "privatized":
subject = f"[GitHub Alert] Repository changed from PUBLIC → PRIVATE: {repo_name}"
body = (
f"The repository visibility has been changed.\n\n"
f"➡️ Now PRIVATE\n\n"
f"📌 Repository Name: {repo_name}\n"
f"{visibility_icon}\n"
f"👤 Owner: {owner}\n"
f"🌿 Default branch: {default_branch}\n"
f"🕒 Created at: {created_at}\n"
f"🕒 Last updated: {updated_at}\n"
f"🌍 URL: {url}\n"
)
else:
# Generic events
action_labels = {
"created": "Repository created",
"deleted": "Repository deleted",
"archived": "Repository archived",
"unarchived": "Repository unarchived",
"edited": "Repository edited",
"renamed": "Repository renamed",
"transferred": "Repository transferred"
}
subject = f"[GitHub Alert] {action_labels.get(action, action)}: {repo_name}"
body = (
f"A repository event occurred: {action_labels.get(action, action)}\n\n"
f"📌 Repository Name: {repo_name}\n"
f"{visibility_icon}\n"
f"👤 Owner: {owner}\n"
f"🌿 Default branch: {default_branch}\n"
f"🕒 Created at: {created_at}\n"
f"🕒 Last updated: {updated_at}\n"
f"🌍 URL: {url}\n"
)
return subject, body
# --- GitHub Webhook + Health Handlers ---
if not TEST_MODE:
@app.route("/webhook", methods=["POST"])
def github_webhook():
payload_body = request.data
signature = request.headers.get("X-Hub-Signature-256")
secret = os.getenv("GITHUB_WEBHOOK_SECRET")
print("📥 Incoming GitHub webhook")
print(f"📥 Event: {request.headers.get('X-GitHub-Event')}")
print(f"📥 Signature header: {signature}")
if not verify_github_signature(payload_body, signature, secret):
print(f"❌ Invalid signature! Webhook rejected.")
return "❌ Invalid signature", 401
try:
data = request.json or {}
except Exception as e:
print(f"❌ Failed to parse JSON payload: {e}")
return "❌ Bad payload", 400
event = request.headers.get("X-GitHub-Event", "")
action = data.get("action", "")
repo_actions = [
"created",
"deleted",
"publicized", # private → public
"privatized", # public → private
"archived",
"unarchived",
"edited",
"renamed",
"transferred"
]
if event == "repository" and action in repo_actions:
subject, body = format_repo_event(data["repository"], action)
print(f"📩 Sending email alert: {subject}")
send_email_via_graph(subject, body)
else:
print(f"ℹ️ Ignored event: {event}, action: {action}")
return "OK", 200
@app.route("/health", methods=["GET"])
def health_check():
return {"status": "running"}, 200
# --- Main Entry Point ---
if __name__ == "__main__":
if TEST_MODE:
print("🔹 TEST_MODE: sending test email")
test_repo = {
"full_name": "quantori/sadsrepo",
"private": True,
"owner": {"login": "quantori"},
"default_branch": "main",
"created_at": "2025-09-09T13:06:02Z",
"updated_at": "2025-09-09T13:09:20Z",
"html_url": "https://github.com/quantori/sadsrepo"
}
subject, body = format_repo_event(test_repo, "publicized")
send_email_via_graph(subject, body)
else:
print("✅ Flask is up and listening on /webhook and /health")
app.run(host="0.0.0.0", port=8000)