prepare.py 21.6 KB
Newer Older
1
import os
2
import sys
3 4 5
import json
import argparse
import requests
6
from functools import wraps
7 8 9 10 11
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

parser = argparse.ArgumentParser(description='The script to generate data for harbor v1.4.0')
parser.add_argument('--endpoint', '-e', dest='endpoint', required=True, help='The endpoint to harbor')
12 13
parser.add_argument('--version', '-v', dest='version', required=False, help='The version to harbor')
args = parser.parse_args()
14 15

url = "https://"+args.endpoint+"/api/"
16
endpoint_url = "https://"+args.endpoint
17
print(url)
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
with open("feature_map.json") as f:
    feature_map = json.load(f)

def get_branch(func_name, version):
    has_feature = False
    for node in feature_map[func_name]:
        has_feature = True
        if node["version"] == version:
            return node["branch"]
    if has_feature is False:
        return "No Restriction"
    else:
        return "Not Supported"

def get_feature_branch(func):
    @wraps(func)
    def inner_func(*args,**kwargs):
        branch=get_branch(inner_func.__name__, kwargs.get("version"))
        if branch == "No Restriction":
            func(*args,**kwargs)
        elif branch == "Not Supported":
            print("Feature {} is not supported in version {}".format(inner_func.__name__, kwargs.get("version")))
        else:
            kwargs["branch"] = branch
            func(*args,**kwargs)
        return
    return inner_func

47
class HarborAPI:
48 49 50 51 52 53 54 55
    @get_feature_branch
    def create_project(self, project, **kwargs):
        if kwargs["branch"] == 1:
            body=dict(body={"project_name": ""+project["name"]+"", "metadata": {"public": "true"}})
        elif kwargs["branch"] == 2:
            body=dict(body={"project_name": ""+project["name"]+"", "metadata": {"public": "true"},"count_limit":project["count_limit"],"storage_limit":project["storage_limit"]})
        else:
            raise Exception(r"Error: Feature {} has no branch {}.".format(sys._getframe().f_code.co_name, branch))
56
        request(url+"projects", 'post', **body)
57

58
    def create_user(self, username):
59
        payload = {"username":username, "email":username+"@vmware.com", "password":"Harbor12345", "realname":username, "comment":"string"}
60 61
        body=dict(body=payload)
        request(url+"users", 'post', **body)
62

63 64
    @get_feature_branch
    def set_user_admin(self, user, **kwargs):
65
        r = request(url+"users?username="+user+"", 'get')
66
        userid = str(r.json()[0]['user_id'])
67 68 69 70 71

        if kwargs["branch"] == 1:
            body=dict(body={"has_admin_role": 1})
        elif kwargs["branch"] == 2:
            body=dict(body={"has_admin_role": True})
72
        else:
73
            raise Exception(r"Error: Feature {} has no branch {}.".format(sys._getframe().f_code.co_name, branch))
74
        request(url+"users/"+userid+"/sysadmin", 'put', **body)
75

76 77
    @get_feature_branch
    def add_member(self, project, user, role, **kwargs):
78
        r = request(url+"projects?name="+project+"", 'get')
79
        projectid = str(r.json()[0]['project_id'])
80 81 82 83

        if kwargs["branch"] == 1:
            payload = {"roles": [role], "username":""+user+""}
        elif kwargs["branch"] == 2:
84 85
            payload = {"member_user":{ "username": ""+user+""},"role_id": role}
        else:
86
            raise Exception(r"Error: Feature {} has no branch {}.".format(sys._getframe().f_code.co_name, branch))
87 88
        body=dict(body=payload)
        request(url+"projects/"+projectid+"/members", 'post', **body)
89

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    @get_feature_branch
    def add_endpoint(self, endpointurl, endpointname, username, password, insecure, registry_type, **kwargs):
        if kwargs["branch"] == 1:
            payload = {"endpoint": ""+endpointurl+"", "name": ""+endpointname+"", "username": ""+username+"", "password": ""+password+"", "insecure": insecure}
            body=dict(body=payload)
            request(url+"targets", 'post', **body)
        elif kwargs["branch"] == 2:
            if registry_type == "harbor":
                endpointurl = endpoint_url
            payload = {
                "credential":{
                    "access_key":""+username+"",
                    "access_secret":""+password+"",
                    "type":"basic"
                },
                "insecure":insecure,
                "name":""+endpointname+"",
                "type":""+registry_type+"",
                "url":""+endpointurl+""
            }
            body=dict(body=payload)
111
            print(body)
112 113 114
            request(url+"/registries", 'post', **body)
        else:
            raise Exception(r"Error: Feature {} has no branch {}.".format(sys._getframe().f_code.co_name, branch))
115

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    @get_feature_branch
    def add_replication_rule(self, replicationrule, **kwargs):
        if kwargs["branch"] == 1:
            r = request(url+"projects?name="+replicationrule["project"]+"", 'get')
            projectid = r.json()[0]['project_id']
            r = request(url+"targets?name="+replicationrule["endpoint"]+"", 'get')
            targetid = r.json()[0]['id']
            payload = {"name": ""+replicationrule["rulename"]+"", "description": "string", "projects": [{"project_id": projectid,}], "targets": [{"id": targetid,}], "trigger": {"kind": ""+replicationrule["trigger"]+"", "schedule_param": {"type": "weekly", "weekday": 1, "offtime": 0}}}
            body=dict(body=payload)
            request(url+"policies/replication", 'post', **body)
        elif kwargs["branch"] == 2:
            r = request(url+"registries?name="+replicationrule["endpoint"]+"", 'get')
            targetid = r.json()[0]['id']
            if replicationrule["is_src_registry"] is True:
                registry = r'"src_registry": { "id": '+str(targetid)+r'},'
            else:
                registry = r'"dest_registry": { "id": '+str(targetid)+r'},'
133

134 135
            body=dict(body=json.loads(r'{"name":"'+replicationrule["rulename"]+r'","dest_namespace":"'+replicationrule["dest_namespace"]+r'","deletion": '+str(replicationrule["deletion"]).lower()+r',"enabled": '+str(replicationrule["enabled"]).lower()+r',"override": '+str(replicationrule["override"]).lower()+r',"description": "string",'+ registry + r'"trigger":{"type": "'+replicationrule["trigger_type"]+r'", "trigger_settings":{"cron":"'+replicationrule["cron"]+r'"}},"filters":[ {"type":"name","value":"'+replicationrule["name_filters"]+r'"},{"type":"tag","value":"'+replicationrule["tag_filters"]+r'"}]}'))
            print(body)
136 137 138 139 140 141
            request(url+"replication/policies", 'post', **body)
        else:
            raise Exception(r"Error: Feature {} has no branch {}.".format(sys._getframe().f_code.co_name, branch))

    #@get_feature_branch
    def update_project_setting_metadata(self, project, public, contenttrust, preventrunning, preventseverity, scanonpush):
142
        r = request(url+"projects?name="+project+"", 'get')
143 144 145
        projectid = str(r.json()[0]['project_id'])
        payload = {
            "metadata": {
146
                "public": public,
147
                "enable_content_trust": contenttrust,
148 149 150
                "prevent_vul": preventrunning,
                "severity": preventseverity,
                "auto_scan": scanonpush
151 152
            }
        }
153
        body=dict(body=payload)
154
        print(body)
155
        request(url+"projects/"+projectid+"", 'put', **body)
156

157
    @get_feature_branch
158
    def add_sys_allowlist(self, cve_id_list, **kwargs):
159 160 161 162 163 164
        cve_id_str = ""
        if kwargs["branch"] == 1:
            for index, cve_id in enumerate(cve_id_list["cve"]):
                cve_id_str = cve_id_str + '{"cve_id":"' +cve_id["id"] + '"}'
                if index != len(cve_id_list["cve"]) - 1:
                    cve_id_str = cve_id_str + ","
165
            body=dict(body=json.loads(r'{"items":['+cve_id_str+r'],"expires_at":'+cve_id_list["expires_at"]+'}'))
166 167 168 169 170
            request(url+"system/CVEWhitelist", 'put', **body)
        else:
            raise Exception(r"Error: Feature {} has no branch {}.".format(sys._getframe().f_code.co_name, branch))

    @get_feature_branch
171
    def update_project_setting_allowlist(self, project, reuse_sys_cve_whitelist, cve_id_list, **kwargs):
172 173 174 175 176 177 178 179
        r = request(url+"projects?name="+project+"", 'get')
        projectid = str(r.json()[0]['project_id'])
        cve_id_str = ""
        if kwargs["branch"] == 1:
            for index, cve_id in enumerate(cve_id_list["cve"]):
                cve_id_str = cve_id_str + '{"cve_id":"' +cve_id["id"] + '"}'
                if index != len(cve_id_list["cve"]) - 1:
                    cve_id_str = cve_id_str + ","
180
            print(cve_id_str)
181 182 183
            if reuse_sys_cve_whitelist == "true":
                payload = r'{"metadata":{"reuse_sys_cve_whitelist":"true"}}'
            else:
184 185
                payload = r'{"metadata":{"reuse_sys_cve_whitelist":"false"},"cve_whitelist":{"project_id":'+projectid+',"items":['+cve_id_str+r'],"expires_at":'+cve_id_list["expires_at"]+'}}'
            print(payload)
186 187 188 189 190
            body=dict(body=json.loads(payload))
            request(url+"projects/"+projectid+"", 'put', **body)
        else:
            raise Exception(r"Error: Feature {} has no branch {}.".format(sys._getframe().f_code.co_name, branch))

191 192 193
    @get_feature_branch
    def update_interrogation_services(self, cron, **kwargs):
        payload = {"schedule":{"type":"Custom","cron": cron}}
194
        print(payload)
195 196
        body=dict(body=payload)
        request(url+"system/scanAll/schedule", 'post', **body)
197

198
    def update_systemsetting(self, emailfrom, emailhost, emailport, emailuser, creation, selfreg, token, robot_token):
199 200 201 202 203 204 205 206 207 208 209 210 211
        payload = {
            "auth_mode": "db_auth",
            "email_from": emailfrom,
            "email_host": emailhost,
            "email_port": emailport,
            "email_identity": "string",
            "email_username": emailuser,
            "email_ssl": True,
            "email_insecure": True,
            "project_creation_restriction": creation,
            "read_only": False,
            "self_registration": selfreg,
            "token_expiration": token,
212
            "robot_token_duration":robot_token,
213 214 215 216 217 218 219
            "scan_all_policy": {
                "type": "none",
                "parameter": {
                    "daily_time": 0
                }
            }
        }
220
        print(payload)
221 222
        body=dict(body=payload)
        request(url+"configurations", 'put', **body)
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
    @get_feature_branch
    def add_project_robot_account(self, project, robot_account, **kwargs):
        r = request(url+"projects?name="+project+"", 'get')
        projectid = str(r.json()[0]['project_id'])

        if kwargs["branch"] == 1:
            if len(robot_account["access"]) == 1:
                robot_account_ac = robot_account["access"][0]
                payload = {
                    "name": robot_account["name"],
                    "access": [
                        {
                            "resource": "/project/"+projectid+"/repository",
                            "action": robot_account_ac["action"]
                        }
                    ]
                }
            elif len(robot_account["access"]) == 2:
                payload = {
                    "name": robot_account["name"],
                    "access": [
                        {
                            "resource": "/project/"+projectid+"/repository",
                            "action": "pull"
                        },
                        {
                            "resource": "/project/"+projectid+"/repository",
                            "action": "push"
                        }
                    ]
                }
            else:
                raise Exception(r"Error: Robot account count {} is not legal!".format(len(robot_account["access"])))
        else:
            raise Exception(r"Error: Feature {} has no branch {}.".format(sys._getframe().f_code.co_name, branch))
259
        print(payload)
260 261 262 263
        body=dict(body=payload)
        request(url+"projects/"+projectid+"/robots", 'post', **body)

    @get_feature_branch
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
    def add_tag_retention_rule(self, project, tag_retention_rule, **kwargs):
        r = request(url+"projects?name="+project+"", 'get')
        projectid = str(r.json()[0]['project_id'])
        if kwargs["branch"] == 1:
            payload = {
                "algorithm":"or",
                "rules":
                [
                    {
                        "disabled":False,
                        "action":"retain",
                        "scope_selectors":
                        {
                            "repository":
                            [
                                {
                                    "kind":"doublestar",
                                    "decoration":"repoMatches",
                                    "pattern":tag_retention_rule["repository_patten"]
                                }
                            ]
                        },
                        "tag_selectors":
                        [
                            {
                                "kind":"doublestar",
                                "decoration":"matches","pattern":tag_retention_rule["tag_decoration"]
                            }
                        ],
                        "params":{"latestPushedK":tag_retention_rule["latestPushedK"]},
                        "template":"latestPushedK"
                    }
                ],
                "trigger":
                {
                    "kind":"Schedule",
                    "references":{},
                    "settings":{"cron":tag_retention_rule["cron"]}
                },
                "scope":
                {
                "level":"project",
                    "ref":int(projectid)
                }
            }
309
            print(payload)
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
            body=dict(body=payload)
            request(url+"retentions", 'post', **body)
        else:
            raise Exception(r"Error: Feature {} has no branch {}.".format(sys._getframe().f_code.co_name, kwargs["branch"]))

    @get_feature_branch
    def add_tag_immutability_rule(self, project, tag_immutability_rule, **kwargs):
        r = request(url+"projects?name="+project+"", 'get')
        projectid = str(r.json()[0]['project_id'])
        if kwargs["branch"] == 1:
            payload = {
                "disabled":False,
                "action":"immutable",
                "scope_selectors":
                {
                    "repository":
                    [
                        {
                            "kind":"doublestar",
                            "decoration":tag_immutability_rule["repo_decoration"],
                            "pattern":tag_immutability_rule["repo_pattern"]
                        }
                    ]
                },
                "tag_selectors":
                [
                    {
                        "kind":"doublestar",
                        "decoration":tag_immutability_rule["tag_decoration"],
                        "pattern":tag_immutability_rule["tag_pattern"]
                    }
                ],
                "project_id":int(projectid),
                "priority":0,
                "template":"immutable_template"
            }
346
            print(payload)
347 348 349 350
            body=dict(body=payload)
            request(url+"projects/"+projectid+"/immutabletagrules", 'post', **body)
        else:
            raise Exception(r"Error: Feature {} has no branch {}.".format(sys._getframe().f_code.co_name, kwargs["branch"]))
351 352

    @get_feature_branch
353 354 355
    def add_webhook(self, project, webhook, **kwargs):
        r = request(url+"projects?name="+project+"", 'get')
        projectid = str(r.json()[0]['project_id'])
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
        if kwargs["branch"] == 1:
            payload = {
                "targets":[
                    {
                        "type":"http",
                        "address":webhook["address"],
                        "skip_cert_verify":webhook["skip_cert_verify"],
                        "auth_header":webhook["auth_header"]
                    }
                ],
                "event_types":[
                    "downloadChart",
                    "deleteChart",
                    "uploadChart",
                    "deleteImage",
                    "pullImage",
                    "pushImage",
                    "scanningFailed",
                    "scanningCompleted"
                ],
376
                "enabled":webhook["enabled"]
377
            }
378
            print(payload)
379
            body=dict(body=payload)
380
            request(url+"projects/"+projectid+"/webhook/policies", 'post', **body)
381 382 383
        else:
            raise Exception(r"Error: Feature {} has no branch {}.".format(sys._getframe().f_code.co_name, kwargs["branch"]))

384
    def update_repoinfo(self, reponame):
385
        payload = {"description": "testdescription"}
386
        print(payload)
387 388
        body=dict(body=payload)
        request(url+"repositories/"+reponame+"", 'put', **body)
389 390

    def get_ca(self, target='/harbor/ca/ca.crt'):
391 392 393 394 395 396
        url = "https://" + args.endpoint + "/api/systeminfo/getcert"
        resp = request(url, 'get')
        try:
            ca_content = json.loads(resp.text)
        except ValueError:
            ca_content = resp.text
397 398 399 400
        ca_path = '/harbor/ca'
        if not os.path.exists(ca_path):
            try:
                os.makedirs(ca_path)
401 402
            except Exception as e:
                print(str(e))
403
                pass
404
        open(target, 'wb').write(ca_content.encode('utf-8'))
405

406 407
    @get_feature_branch
    def push_artifact(self, project, **kwargs):
408

409 410 411
def request(url, method, user = None, userp = None, **kwargs):
    if user is None:
        user = "admin"
412
    if userp is None:
413
        userp = "Harbor12345"
414 415 416 417 418 419
    kwargs.setdefault('headers', kwargs.get('headers', {}))
    kwargs['headers']['Accept'] = 'application/json'
    if 'body' in kwargs:
        kwargs['headers']['Content-Type'] = 'application/json'
        kwargs['data'] = json.dumps(kwargs['body'])
        del kwargs['body']
420
    print("url: ", url)
421
    resp = requests.request(method, url, verify=False, auth=(user, userp), **kwargs)
422
    if resp.status_code >= 400:
423 424
        raise Exception("[Exception Message] - {}".format(resp.text))
    return resp
425 426 427 428 429 430 431 432 433 434

with open("data.json") as f:
    data = json.load(f)

def pull_image(*image):
    for i in image:
        os.system("docker pull "+i)

def push_image(image, project):
    os.system("docker tag "+image+" "+args.endpoint+"/"+project+"/"+image)
435
    os.system("docker login "+args.endpoint+" -u admin"+" -p Harbor12345")
436 437 438 439 440 441 442 443
    os.system("docker push "+args.endpoint+"/"+project+"/"+image)

def push_signed_image(image, project, tag):
    os.system("./sign_image.sh" + " " + args.endpoint + " " + project + " " + image + " " + tag)

def do_data_creation():
    harborAPI = HarborAPI()
    harborAPI.get_ca()
444

445 446
    for user in data["users"]:
        harborAPI.create_user(user["name"])
447

448
    for user in data["admin"]:
449
        harborAPI.set_user_admin(user["name"], version=args.version)
450

451
    for project in data["projects"]:
452
        harborAPI.create_project(project, version=args.version)
453
        for member in project["member"]:
454 455 456
            harborAPI.add_member(project["name"], member["name"], member["role"], version=args.version)
        for robot_account in project["robot_account"]:
            harborAPI.add_project_robot_account(project["name"], robot_account, version=args.version)
457 458 459
        harborAPI.add_webhook(project["name"], project["webhook"], version=args.version)
        harborAPI.add_tag_retention_rule(project["name"], project["tag_retention_rule"], version=args.version)
        harborAPI.add_tag_immutability_rule(project["name"], project["tag_immutability_rule"], version=args.version)
460

461 462 463 464 465
    pull_image("busybox", "redis", "haproxy", "alpine", "httpd:2")
    push_image("busybox", data["projects"][0]["name"])
    push_signed_image("alpine", data["projects"][0]["name"], "latest")

    for endpoint in data["endpoint"]:
466 467
        harborAPI.add_endpoint(endpoint["url"], endpoint["name"], endpoint["user"], endpoint["pass"], endpoint["insecure"], endpoint["type"], version=args.version)

468
    for replicationrule in data["replicationrule"]:
469 470
        harborAPI.add_replication_rule(replicationrule, version=args.version)

471
    for project in data["projects"]:
472
        harborAPI.update_project_setting_metadata(project["name"],
473
                                        project["configuration"]["public"],
474
                                        project["configuration"]["enable_content_trust"],
475 476 477 478 479
                                        project["configuration"]["prevent_vul"],
                                        project["configuration"]["severity"],
                                        project["configuration"]["auto_scan"])

    for project in data["projects"]:
480 481
        harborAPI.update_project_setting_allowlist(project["name"],
                                    project["configuration"]["reuse_sys_cve_allowlist"],
482 483 484
                                    project["configuration"]["deployment_security"], version=args.version)

    harborAPI.update_interrogation_services(data["interrogation_services"]["cron"], version=args.version)
485

486 487 488 489
    harborAPI.update_systemsetting(data["configuration"]["emailsetting"]["emailfrom"],
                                   data["configuration"]["emailsetting"]["emailserver"],
                                   float(data["configuration"]["emailsetting"]["emailport"]),
                                   data["configuration"]["emailsetting"]["emailuser"],
490 491
                                   data["configuration"]["projectcreation"],
                                   data["configuration"]["selfreg"],
492 493
                                   float(data["configuration"]["token"]),
                                   float(data["configuration"]["robot_token"])*60*24)
494

495
    harborAPI.add_sys_allowlist(data["configuration"]["deployment_security"], version=args.version)
496

497
do_data_creation()