Skip to content

python

FQDN Field Validation with Pydantic

The Problem

Customers were configuring egress entries for external services using incorrect syntax. This would lead to validation errors from Istio when deploying microservice CRDs, so the controller that manages the CRD's owned resources would then begin generating errors when attempting to update resources that Istio's validatingwebhook would reject:

microserviceDeployment.yaml
...
DeploymentStrategy:
  ServiceDependencies:
    egress:
    - hosts:
      - external/some-external-serviceentry # (1)
...
  1. When the CRD is applied, various Istio resources are generated. Istio's DestinationRule resource expects host values that reference ServiceEntry resources to be formatted as namespace/service-entry-name.namespace.svc.cluster.local.

The microservice pipeline would validate that the field contained a list of strings:

src/service_dependency_schema.py
from pydantic import BaseModel, parse_obj_as
from Faker import Faker
from faker.providers import python
import pytest

class Egress(BaseModel, extra="forbid"):
    port: Optional[Port]
    hosts: list[str]


fake = Faker()
fake.add_provider(python)


@pytest.fixture
def egress_data():
    return {"hosts": [pystr()]}


def test_egress_schema(egress_data):
    # when
    parsed = parse_obj_as(Egress, egress_data)

    # then
    assert isinstance(parsed.hosts, list)
    assert isinstance(parsed.hosts[0], str)