This repository has been archived by the owner on Jul 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pd_ip_gatherer.py
137 lines (90 loc) · 3.5 KB
/
pd_ip_gatherer.py
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
"""
Gather PagerDuty webhook IP safelist from their help documents repo.
IPs pulled can include both US and EU ranges or from a specific region.
Support Documentation:
https://support.pagerduty.com/docs/safelist-ips#webhooks
Developer Documentation:
https://developer.pagerduty.com/docs/ZG9jOjQ4OTcxMDMx-webhook-i-ps
Documentation Repo:
https://github.com/PagerDuty/developer-docs
Target sources:
https://developer.pagerduty.com/ip-safelists/webhooks-us-service-region-json
https://developer.pagerduty.com/ip-safelists/webhooks-eu-service-region-json
Example Usage:
Output to console:
Optional "us" or "eu" will limit results to that region. Default is both regions
$ pd-ip-gatherer [eu|us]
Importing as module:
import pd_ip_gatherer
full_ip_list = pd_ip_gatherer.get_all_safelist()
eu_ip_list = pd_ip_gatherer.get_eu_safelist()
us_ip_list = pd_ip_gatherer.get_us_safelist()
"""
from __future__ import annotations
import json
import logging
import sys
from http.client import HTTPSConnection
SOURCE_ROUTES: dict[str, list[str]] = {
"us": [
"developer.pagerduty.com",
"/ip-safelists/webhooks-us-service-region-json",
],
"eu": [
"developer.pagerduty.com",
"/ip-safelists/webhooks-eu-service-region-json",
],
}
TIMEOUT_SECONDS = 3
log = logging.getLogger(__name__)
def _get_url_page(url: str, route: str) -> str:
"""
HTTPS GET request a url, return the text of the response.
Args:
url: URL of page to pull, exclude HTTPS:// (e.g. "app.pagerduty.com")
route: Route following url. e.g. "/webhook_ip"
Returns:
String content returned from GET of target url/route, can be empty
"""
conn = HTTPSConnection(host=url, timeout=TIMEOUT_SECONDS)
conn.request("GET", route if route.startswith("/") else f"/{route}")
resp = conn.getresponse()
if resp.status not in range(200, 300):
log.error("Invalid response from %s, %s. %d", url, route, resp.status)
return ""
return resp.read().decode()
def _get_webhooks_ips(region: str | None = None, new_source: bool = True) -> list[str]:
"""
Pull webhook IPs from PagerDuty's source(s).
Args:
region: Valid values are `US` or `EU`, case agnostic. `None` will pull both
new_source: Use the new developer doc source for IPs.
"""
regions = [region.lower()] if region is not None else list(SOURCE_ROUTES.keys())
full_list: list[str] = []
for target_region in regions:
url, route = SOURCE_ROUTES[target_region]
result = _get_url_page(url, route)
if result:
full_list.extend(json.loads(result))
return full_list
def get_all_safelist() -> set[str]:
"""Return all safelist IPs (US and Euro region) in the form of a set."""
us_set = get_us_safelist()
eu_set = get_eu_safelist()
return us_set.union(eu_set)
def get_us_safelist() -> set[str]:
"""Return all safelist IPs from US region in the form of a set."""
return set(_get_webhooks_ips("us"))
def get_eu_safelist() -> set[str]:
"""Return all safelist IPs from EU region in the form of a set."""
return set(_get_webhooks_ips("eu"))
def _console_output() -> int:
"""Display results to console."""
cli = {"us": get_us_safelist, "eu": get_eu_safelist}
arg = sys.argv[1].lower() if len(sys.argv) > 1 else "all"
result = cli.get(arg, get_all_safelist)()
print("\n".join(result))
return 0
if __name__ == "__main__":
raise SystemExit(_console_output())