File size: 3,741 Bytes
951488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30ed22f
951488d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Cloud Scheduler wrapper for the admin cron UI."""
import os, re
from google.cloud import scheduler_v1
from google.protobuf import field_mask_pb2

PROJECT = os.environ.get("GCP_PROJECT", "project-46559977-eb74-48c3-a1e")
LOCATION = os.environ.get("GCP_LOCATION", "us-central1")
PARENT = "projects/%s/locations/%s" % (PROJECT, LOCATION)

ACTION_MAP = {
    "scan_conservative": "/api/scan?mode=conservative",
    "scan_risk": "/api/scan?mode=risk",
    "flush_alerts": "/api/alerts/flush-telegram",
}

DOMAIN = "blindmonkeys.org"


def _client():
    return scheduler_v1.CloudSchedulerClient()


def _action_url(action, custom_url=""):
    if action in ACTION_MAP:
        return "https://" + DOMAIN + ACTION_MAP[action]
    if action == "custom" and custom_url:
        if not custom_url.startswith("https://" + DOMAIN):
            raise ValueError("custom URL must be on " + DOMAIN)
        return custom_url
    raise ValueError("unknown action: " + action)


def _job_to_dict(job, mask_secret=True):
    http = job.http_target
    headers = dict(http.headers) if http and http.headers else {}
    if mask_secret and "X-Cron-Secret" in headers:
        headers["X-Cron-Secret"] = "***"
    return {
        "name": job.name.split("/")[-1],
        "description": job.description or "",
        "schedule": job.schedule or "",
        "time_zone": job.time_zone or "UTC",
        "state": scheduler_v1.Job.State(job.state).name if job.state else "UNKNOWN",
        "uri": http.uri if http else "",
        "method": scheduler_v1.HttpMethod(http.http_method).name if http and http.http_method else "POST",
        "headers": headers,
        "last_attempt_time": job.last_attempt_time.isoformat() if job.last_attempt_time else None,
        "schedule_time": job.schedule_time.isoformat() if job.schedule_time else None,
    }


def list_jobs():
    client = _client()
    out = []
    for job in client.list_jobs(parent=PARENT):
        try:
            out.append(_job_to_dict(job))
        except Exception as e:
            print("list_jobs skip: " + str(e))
    return out


def _validate_name(name):
    if not re.match(r"^[a-z0-9][a-z0-9-]{0,62}$", name or ""):
        raise ValueError("name must be lowercase letters/digits/hyphens, 1-63 chars")


def create_job(name, description, schedule, time_zone, action, custom_url="", enabled=True):
    _validate_name(name)
    if not re.match(r"^[0-9*/,\- ]+$", schedule or "") or len((schedule or "").split()) != 5:
        raise ValueError("schedule must be a 5-field cron expression")
    url = _action_url(action, custom_url)
    secret = os.environ.get("CRON_SECRET", "")
    if not secret:
        raise ValueError("CRON_SECRET not configured on server")
    client = _client()
    job = scheduler_v1.Job()
    job.name = PARENT + "/jobs/" + name
    job.description = (description or "")[:500]
    job.schedule = schedule
    job.time_zone = time_zone or "America/New_York"
    job.http_target = scheduler_v1.HttpTarget()
    job.http_target.uri = url
    job.http_target.http_method = scheduler_v1.HttpMethod.POST
    job.http_target.headers = {"X-Cron-Secret": secret}
    created = client.create_job(parent=PARENT, job=job)
    if not enabled:
        client.pause_job(name=created.name)
        created = client.get_job(name=created.name)
    return _job_to_dict(created)


def _full(name):
    _validate_name(name)
    return PARENT + "/jobs/" + name


def pause_job(name):
    _client().pause_job(name=_full(name))
    return True


def resume_job(name):
    _client().resume_job(name=_full(name))
    return True


def delete_job(name):
    _client().delete_job(name=_full(name))
    return True


def run_job(name):
    _client().run_job(name=_full(name))
    return True