Skip to content

fix: add more validations to project attributes #1335

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/aap_eda/api/serializers/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,27 @@ class ProjectCreateRequestSerializer(serializers.ModelSerializer):
allow_null=True,
validators=[validators.check_credential_types_for_gpg],
)
url = serializers.CharField(
required=True,
allow_blank=False,
allow_null=False,
help_text="Source control repository URL.",
validators=[validators.check_if_scm_url_valid],
)
scm_branch = serializers.CharField(
required=False,
allow_blank=True,
allow_null=True,
help_text="Specific branch, tag or commit to checkout.",
validators=[validators.check_if_branch_valid],
)
scm_refspec = serializers.CharField(
required=False,
allow_blank=True,
allow_null=True,
help_text="For git projects, an additional refspec to fetch.",
validators=[validators.check_if_refspec_valid],
)

class Meta:
model = models.Project
Expand Down Expand Up @@ -177,12 +198,18 @@ class ProjectUpdateRequestSerializer(serializers.ModelSerializer):
allow_blank=True,
allow_null=True,
help_text="Specific branch, tag or commit to checkout.",
validators=[
validators.check_if_branch_valid,
],
)
scm_refspec = serializers.CharField(
required=False,
allow_blank=True,
allow_null=True,
help_text="For git projects, an additional refspec to fetch.",
validators=[
validators.check_if_refspec_valid,
],
)
proxy = serializers.CharField(
required=False,
Expand All @@ -195,6 +222,9 @@ class ProjectUpdateRequestSerializer(serializers.ModelSerializer):
allow_blank=True,
allow_null=True,
help_text="Source control repository URL.",
validators=[
validators.check_if_scm_url_valid,
],
)

class Meta:
Expand Down
19 changes: 19 additions & 0 deletions src/aap_eda/core/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
validate_schema,
)
from aap_eda.core.utils.k8s_service_name import is_rfc_1035_compliant
from aap_eda.services.project.scm import is_git_url_valid, is_refspec_valid

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -467,3 +468,21 @@ def check_if_activation_name_used(name: str) -> str:
f"Activation with name {name} already exists"
)
return name


def check_if_scm_url_valid(url: str) -> str:
if not is_git_url_valid(url):
raise serializers.ValidationError("Invalid source control URL")
return url


def check_if_branch_valid(branch: str) -> str:
if not is_refspec_valid(branch, is_branch=True):
raise serializers.ValidationError("Invalid branch/tag/commit")
return branch


def check_if_refspec_valid(refspec: str) -> str:
if not is_refspec_valid(refspec, is_branch=False):
raise serializers.ValidationError("Invalid refspec")
return refspec
37 changes: 37 additions & 0 deletions src/aap_eda/services/project/scm.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ class ExecutableNotFoundError(Exception):
raise ExecutableNotFoundError("Cannot find ansible-runner executable")


GIT_COMMAND = shutil.which("git")
if GIT_COMMAND is None:
raise ExecutableNotFoundError("Cannot find git executable")


class ScmRepository:
"""Represents a SCM repository."""

Expand Down Expand Up @@ -322,3 +327,35 @@ def __call__(
raise ScmAuthenticationError(err_msg)
raise ScmError(f"{self.ERROR_PREFIX} {err_msg}")
raise ScmError(f"{self.ERROR_PREFIX} {outputs.getvalue().strip()}")


URL_REGEX = re.compile(
r"^((git|ssh|http(s)?)|git\+ssh|(git@[\w\.-]+))(:(//)?)"
r"([\w\.@\:/\-~]+)(\.git)?(/)?$"
)


def is_git_url_valid(url: str) -> bool:
if not URL_REGEX.match(url):
logger.error(f"Invalid SCM URL {url}")
return False
return True


def is_refspec_valid(refspec: str, is_branch: bool) -> bool:
if is_branch:
args = [GIT_COMMAND, "check-ref-format", "--branch", refspec]
else:
args = [GIT_COMMAND, "check-ref-format", refspec]
with tempfile.TemporaryDirectory(prefix="EDA_REFSPEC") as home_dir:
result = subprocess.run(args, cwd=home_dir)
if result.returncode != 0:
logger.error(
f"git check-ref-format {refspec} failed with exit code "
f"{result.returncode}"
)
return False
if is_branch and all(arg in refspec for arg in ["{{", "}}", "lookup"]):
logger.error(f"branch {refspec} is invalid")
return False
return True
53 changes: 46 additions & 7 deletions tests/integration/api/test_project.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def test_create_or_update_project_with_right_signature_credential(
"eda_credential_id": credential.id,
"signature_validation_credential_id": default_gpg_credential.id,
"scm_branch": "main",
"scm_refspec": "ref1",
"scm_refspec": "path/to/ref1",
"organization_id": default_organization.id,
}

Expand All @@ -205,7 +205,7 @@ def test_create_or_update_project_with_right_signature_credential(
"eda_credential_id": credential.id,
"signature_validation_credential_id": default_gpg_credential.id,
"scm_branch": "main",
"scm_refspec": "ref1",
"scm_refspec": "path/to/ref1",
"verify_ssl": True,
"proxy": "http://user:$encrypted$@myproxy.com",
}
Expand Down Expand Up @@ -338,7 +338,7 @@ def test_create_or_update_project_with_right_eda_credential(
"eda_credential_id": default_scm_credential.id,
"signature_validation_credential_id": credential.id,
"scm_branch": "main",
"scm_refspec": "ref1",
"scm_refspec": "path/to/ref1",
"organization_id": default_organization.id,
}

Expand All @@ -355,7 +355,7 @@ def test_create_or_update_project_with_right_eda_credential(
"eda_credential_id": default_scm_credential.id,
"signature_validation_credential_id": credential.id,
"scm_branch": "main",
"scm_refspec": "ref1",
"scm_refspec": "path/to/ref1",
"verify_ssl": True,
"proxy": "http://user:$encrypted$@myproxy.com",
}
Expand Down Expand Up @@ -463,7 +463,7 @@ def raise_connection_error(*args, **kwargs):
"eda_credential_id": default_scm_credential.id,
"signature_validation_credential_id": credential.id,
"scm_branch": "main",
"scm_refspec": "ref1",
"scm_refspec": "path/to/ref1",
"organization_id": default_organization.id,
}

Expand Down Expand Up @@ -506,6 +506,31 @@ def test_create_project_wrong_ids(admin_client: APIClient):
assert "id 3000001 does not exist" in str(response.json())


@pytest.mark.django_db
def test_create_project_with_invalid_git_parameters(
admin_client: APIClient,
default_organization: models.Organization,
):
body = {
"name": "test-project-01",
"url": "https://git.{{example}}.com/acme/project-01",
"scm_branch": "bad branch",
"scm_refspec": "path",
"organization_id": default_organization.id,
}

response = admin_client.post(
f"{api_url_v1}/projects/",
data=body,
)

assert response.status_code == status.HTTP_400_BAD_REQUEST
error = str(response.json())
assert "Invalid source control URL" in error
assert "Invalid branch/tag/commit" in error
assert "Invalid refspec" in error


@pytest.mark.django_db
@mock.patch(
"aap_eda.api.views.project.RedisDependencyMixin.redis_is_available"
Expand Down Expand Up @@ -710,6 +735,20 @@ def test_update_project_with_400(
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "id 3000001 does not exist" in str(response.json())

data = {
"url": "https://git.{{example}}.com/acme/project-01",
"scm_branch": "bad branch",
"scm_refspec": "path",
}
response = admin_client.patch(
f"{api_url_v1}/projects/{default_project.id}/", data=data
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
error = str(response.json())
assert "Invalid source control URL" in error
assert "Invalid branch/tag/commit" in error
assert "Invalid refspec" in error


@pytest.mark.django_db
def test_partial_update_project(
Expand All @@ -729,7 +768,7 @@ def test_partial_update_project(
"eda_credential_id": default_scm_credential.id,
"signature_validation_credential_id": default_gpg_credential.id,
"scm_branch": "main",
"scm_refspec": "ref1",
"scm_refspec": "path/to/ref1",
"verify_ssl": True,
"proxy": "http://user:$encrypted$@myproxy.com",
}
Expand Down Expand Up @@ -846,7 +885,7 @@ def test_project_by_fields(
"url": "https://git.example.com/acme/project-01",
"eda_credential_id": default_scm_credential.id,
"scm_branch": "main",
"scm_refspec": "ref1",
"scm_refspec": "path/to/ref1",
"organization_id": default_organization.id,
}

Expand Down
Loading