-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
58 lines (45 loc) · 1.36 KB
/
server.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
import os
import subprocess
from ipaddress import ip_address
from ipaddress import ip_network
from fastapi import FastAPI
from fastapi import HTTPException
from fastapi import Request
from loguru import logger
from pydantic import BaseModel
from starlette import status
app = FastAPI()
github_nets = [
"192.30.252.0/22",
"185.199.108.0/22",
"140.82.112.0/20",
"143.55.64.0/20",
]
def validate_ip(addr: str) -> bool:
ip = ip_address(addr)
for net in github_nets:
if ip in ip_network(net):
return True
return False
def execute_script(script_name: str) -> None:
script_path = f"./scripts/{script_name}.sh"
if not os.path.exists(script_path):
logger.info(f"{script_name} doesn't exist")
return
logger.info("Executing logs:")
subprocess.call(script_path)
class PayloadScheme(BaseModel):
class Repository(BaseModel):
name: str
ref: str
repository: Repository
@app.post("/payload")
async def receive_webhook(request: Request, data: PayloadScheme):
ip = request.client.host
logger.info(f"New request from {ip}")
if not validate_ip(ip):
raise HTTPException(status.HTTP_403_FORBIDDEN, "Go Away")
branch_name = data.ref.split("/")[-1]
script_name = f"{data.repository.name}-{branch_name}"
logger.info(f"Executing {script_name}")
execute_script(script_name)