From 46c99535bb3c676712838903c2ce8bd0d5f5cae9 Mon Sep 17 00:00:00 2001 From: "Azzam S.A" Date: Mon, 3 Apr 2023 15:50:10 +0700 Subject: [PATCH] feat: validate srv owner --- api/app/controllers/api/record.py | 5 ++++- api/app/helpers/validator.py | 28 ++++++++++++++++++++++++++++ api/tests/unit/test_validator.py | 14 ++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/api/app/controllers/api/record.py b/api/app/controllers/api/record.py index ff43ccfd..ac600da8 100644 --- a/api/app/controllers/api/record.py +++ b/api/app/controllers/api/record.py @@ -136,7 +136,10 @@ def post(self): # rtype no need to be validated & no need to check its length # `get_typeid` will raise error for non existing rtype validator.validate(rtype, rdata) - validator.validate("owner", owner) + if rtype == "srv": + validator.validate("owner-srv", owner) + else: + validator.validate("owner", owner) except Exception as e: return response(422, message=f"{e}") diff --git a/api/app/helpers/validator.py b/api/app/helpers/validator.py index 8dd40206..0bbad582 100644 --- a/api/app/helpers/validator.py +++ b/api/app/helpers/validator.py @@ -159,6 +159,33 @@ def check_hypen(label): raise ValueError("Bad OWNER") +def is_valid_srv_owner(owner): + """Check if it's a valid srv owner. + + Rules: + - must contain service and protocol name + - can't contain the zone name + - enfore the service name to be prefixed with _ + - enfore the protocol to be prefixed with _ + """ + + if "." not in owner: + raise ValueError("Bad OWNER") + + labels = owner.split(".") + if len(labels) < 2: + raise ValueError("Bad OWNER") + + service_name = labels[0] + protocol_type = labels[1] + if not service_name.startswith("_"): + raise ValueError("Service name must start with underscore") + if not protocol_type.startswith("_"): + raise ValueError("Protocol type must start with underscore") + + is_valid_owner(owner) + + functions = { "A": is_valid_ip, "AAAA": is_valid_ip, @@ -171,6 +198,7 @@ def check_hypen(label): "TXT": is_valid_txt, "SRV": is_valid_srv, "OWNER": is_valid_owner, + "OWNER-SRV": is_valid_srv_owner, } diff --git a/api/tests/unit/test_validator.py b/api/tests/unit/test_validator.py index 7b6e1cda..3d4ec647 100644 --- a/api/tests/unit/test_validator.py +++ b/api/tests/unit/test_validator.py @@ -135,6 +135,20 @@ def test_valid_owner(): validator.is_valid_owner("a" * 256) +def test_valid_srv_owner(): + validator.is_valid_srv_owner("_xmpp._tcp") + + with pytest.raises(Exception): + # owner ends with dot + validator.is_valid_srv_owner("_xmpp._tcp.example.com.") + with pytest.raises(Exception): + # service name doesn't prefixed with _ + validator.is_valid_srv_owner("xmpp._tcp") + with pytest.raises(Exception): + # protocol type doesn't prefixed with _ + validator.is_valid_srv_owner("_xmpp.tcp") + + def test_validate_func(): # validator exists validator.validate("A", "192.0.2.1")