Skip to content
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
6 changes: 6 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ History

* Added project models and management APIs.
* Added resource management APIs.
* Added ``CertificateFile``, the file type for X.509 certificates that DataMasque trusts to verify a server,
with the details of each certificate in ``certificates``.
``ResourceTypeName`` gains ``certificates``.
* ``list_resources`` leaves out a resource type that the client does not know,
and a ``ProjectDeleteConflict`` of such a type has ``type`` set to ``None``,
so a newer server's resource types do not break the client.
* ``move_resources`` moves all the resources or none, skips a resource already in the destination, and raises ``ResourceMoveConflictError`` on a conflict.
* Added ``default_project`` to ``DataMasqueInstanceConfig``.
* Added a ``project`` field to ``ConnectionConfig``, ``Ruleset``, ``RulesetLibrary``, ``DiscoveryConfig``,
Expand Down
4 changes: 4 additions & 0 deletions datamasque/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@
from datamasque.client.models.discovery_config_library import DiscoveryConfigLibrary, DiscoveryConfigLibraryId
from datamasque.client.models.dm_instance import DataMasqueInstanceConfig
from datamasque.client.models.files import (
CertificateDetails,
CertificateFile,
DataMasqueFile,
FileId,
OracleWalletFile,
Expand Down Expand Up @@ -240,6 +242,8 @@
"BundleImportResult",
"BundleImportStatus",
"CassandraConnectionConfig",
"CertificateDetails",
"CertificateFile",
"ColumnKind",
"ColumnPreview",
"CommonStatistics",
Expand Down
2 changes: 1 addition & 1 deletion datamasque/client/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def upload_file(
Uploads a file of the given type to the DataMasque server, into the given project.

`file_type` must be a concrete subclass of `DataMasqueFile`
(`SeedFile`, `OracleWalletFile`, `SslZipFile`, `SnowflakeKeyFile`).
(`SeedFile`, `OracleWalletFile`, `SslZipFile`, `SnowflakeKeyFile`, `CertificateFile`).
`file_path_or_content` may be a path (as `str` or `Path`), raw `bytes`, or a file-like object.
`project` is a `Project`, its `ProjectId` or its `<id>-<slug>` form.
"""
Expand Down
39 changes: 38 additions & 1 deletion datamasque/client/models/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@


class DataMasqueFile(BaseModel):
"""Base class for the concrete file types (`SeedFile`, `OracleWalletFile`, `SslZipFile`, `SnowflakeKeyFile`)."""
"""
Base class for the concrete file types.

They are `SeedFile`, `OracleWalletFile`, `SslZipFile`, `SnowflakeKeyFile` and `CertificateFile`.
"""

model_config = ConfigDict(extra="allow")

Expand Down Expand Up @@ -100,3 +104,36 @@ def get_url(cls) -> str:
@classmethod
def get_content_param_name(cls) -> str:
return "key_file"


class CertificateDetails(BaseModel):
"""One certificate in a `CertificateFile`."""

model_config = ConfigDict(extra="allow")

is_ca: bool
"""Whether the certificate is a CA certificate, which can sign others."""
is_self_signed: bool
not_valid_after: datetime
"""When the certificate expires."""


class CertificateFile(DataMasqueFile):
Comment thread
AaronBarnes07 marked this conversation as resolved.
Resolved
"""
Represents a file of one or more X.509 certificates that DataMasque trusts to verify a server.

The upload accepts PEM, DER and PKCS#7 files, and refuses a file that holds a private key.
The certificates cannot be changed after upload.
Requires server version 3.26.23.
"""

certificates: list[CertificateDetails] = []
"""The certificates in the file, in file order."""

@classmethod
def get_url(cls) -> str:
return "api/files/certificates/"

@classmethod
def get_content_param_name(cls) -> str:
return "certificate_file"
14 changes: 11 additions & 3 deletions datamasque/client/models/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
from enum import Enum
from typing import NewType, Optional, Union

from pydantic import BaseModel, ConfigDict
from pydantic import BaseModel, ConfigDict, field_validator

from datamasque.client.models.resource_type import ResourceTypeName
from datamasque.client.models.resource_type import RESOURCE_TYPE_NAME_VALUES, ResourceTypeName

ProjectId = NewType("ProjectId", int)

Expand Down Expand Up @@ -124,10 +124,18 @@ class ProjectDeleteConflict(BaseModel):
detail: str
"""A message that describes the conflict."""
type: Optional[ResourceTypeName] = None
"""For `name_in_use` and `file_exists`: the type of the resource that would move."""
"""
For `name_in_use` and `file_exists`: the type of the resource that would move.
`None` for a type this client does not know, which a newer server can report.
"""
id: Optional[str] = None
"""For `name_in_use` and `file_exists`: the ID of the resource that would move."""
name: Optional[str] = None
"""For `name_in_use` and `file_exists`: the name of the resource that would move."""
path: Optional[str] = None
"""For `file_exists` and `unexpected_file`: the path of the file or directory."""

@field_validator("type", mode="before")
@classmethod
def _drop_unknown_type(cls, value: object) -> object:
return value if value is None or value in RESOURCE_TYPE_NAME_VALUES else None
5 changes: 5 additions & 0 deletions datamasque/client/models/resource_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,15 @@ class ResourceTypeName(str, Enum):
connection_filesets = "connection_filesets"
oracle_wallets = "oracle_wallets"
snowflake_keys = "snowflake_keys"
certificates = "certificates"
table_references = "table_references"
rulesets = "rulesets"
ruleset_libraries = "ruleset_libraries"
discovery_configs = "discovery_configs"
discovery_config_libraries = "discovery_config_libraries"
ruleset_generation_configs = "ruleset_generation_configs"
seeds = "seeds"


RESOURCE_TYPE_NAME_VALUES = frozenset(type_name.value for type_name in ResourceTypeName)
"""Every `ResourceTypeName` value, to tell a type this client knows from one a newer server reports."""
7 changes: 6 additions & 1 deletion datamasque/client/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
ResourceOrdering,
ResourcesByType,
)
from datamasque.client.models.resource_type import ResourceTypeName
from datamasque.client.models.resource_type import RESOURCE_TYPE_NAME_VALUES, ResourceTypeName

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -60,6 +60,7 @@ def list_resources(
`ordering` and `descending` require server version 3.26.22.
An older server ignores them, and each resource's `position` is `None`.
The groups are the requested types, or every type the server has when `types` is not given.
A type the server lists that this client does not know is left out.
An empty `projects` or `types` matches no resources, without a request to the server.
Connections, rulesets and discovery configs are listed as `ConnectionResource`, `RulesetResource`
and `DiscoveryConfigResource`.
Expand Down Expand Up @@ -87,6 +88,10 @@ def list_resources(
resources: defaultdict[ResourceTypeName, list[Resource]] = defaultdict(list)
for results in self._iter_pages("/api/resources/", params=params, page_size=page_size):
for type_name, rows in results.items():
if type_name not in RESOURCE_TYPE_NAME_VALUES:
# A newer server can list a type this client does not know; leave it out rather than fail.
logger.debug('Skipped the resources of the unknown type "%s"', type_name)
continue
model = RESOURCE_MODEL_BY_TYPE_NAME.get(type_name, Resource)
resources[ResourceTypeName(type_name)].extend(model.model_validate(row) for row in rows)

Expand Down
59 changes: 48 additions & 11 deletions tests/test_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@
import requests_mock

from datamasque.client import DataMasqueClient
from datamasque.client.models.files import DataMasqueFile, OracleWalletFile, SeedFile, SnowflakeKeyFile, SslZipFile
from datamasque.client.models.files import (
CertificateFile,
DataMasqueFile,
OracleWalletFile,
SeedFile,
SnowflakeKeyFile,
SslZipFile,
)
from tests.helpers import OTHER_PROJECT, PROJECT, PROJECT_ID, fake, parse_multipart_form


Expand All @@ -26,7 +33,7 @@
)
@pytest.mark.parametrize(
"file_type",
[SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile],
[SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile, CertificateFile],
)
def test_upload_file(client, file_type, source_factory):
source = source_factory()
Expand Down Expand Up @@ -66,7 +73,7 @@ def test_upload_file(client, file_type, source_factory):

@pytest.mark.parametrize(
"file_type",
[SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile],
[SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile, CertificateFile],
)
def test_get_files_by_type(client, file_type):
id_1 = str(uuid.uuid4())
Expand Down Expand Up @@ -112,7 +119,7 @@ def test_get_files_by_type(client, file_type):

@pytest.mark.parametrize(
"file_type",
[SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile],
[SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile, CertificateFile],
)
def test_get_files_by_type_and_name(client, file_type):
id_1 = str(uuid.uuid4())
Expand Down Expand Up @@ -153,7 +160,7 @@ def test_get_files_by_type_and_name(client, file_type):
)
@pytest.mark.parametrize(
"file_type",
[SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile],
[SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile, CertificateFile],
)
def test_delete_file_if_exists(client, file_type, file_exists):
file_id = str(uuid.uuid4())
Expand Down Expand Up @@ -185,7 +192,7 @@ def test_delete_file_if_exists_raises_when_id_not_set(client):
client.delete_file_if_exists(unpersisted_file)


@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile])
@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile, CertificateFile])
def test_upload_file_if_not_exists_skips_when_same_name_exists(client, file_type):
"""Returns `None` and does not POST when a file of this type already has the same name."""
with patch("datamasque.client.base.open", mock_open(read_data=b"content")):
Expand All @@ -210,7 +217,7 @@ def test_upload_file_if_not_exists_skips_when_same_name_exists(client, file_type
assert m_request.request_history[0].method == "GET"


@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile])
@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile, CertificateFile])
def test_upload_file_if_not_exists_uploads_when_missing(client, file_type):
"""Uploads and returns the new file object when no existing file of the same name is present."""
new_id = str(uuid.uuid4())
Expand Down Expand Up @@ -292,7 +299,7 @@ def test_upload_ssl_zip_file_sends_mysql_database_type(client):
assert form["database_type"] == "mysql"


@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SnowflakeKeyFile])
@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SnowflakeKeyFile, CertificateFile])
def test_upload_non_ssl_zip_file_omits_database_type(client, file_type):
"""Only `SslZipFile` carries the `database_type` form field; other file types must not send it."""
with requests_mock.Mocker() as m_request:
Expand All @@ -312,7 +319,7 @@ def test_upload_non_ssl_zip_file_omits_database_type(client, file_type):
assert "database_type" not in form


@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile])
@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile, CertificateFile])
def test_upload_file_sends_project(client: DataMasqueClient, file_type: type[DataMasqueFile]) -> None:
with requests_mock.Mocker() as m_request:
m_request.post(
Expand All @@ -333,14 +340,14 @@ def test_upload_file_sends_project(client: DataMasqueClient, file_type: type[Dat
assert file.project == PROJECT


@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile])
@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile, CertificateFile])
def test_list_files_of_type_filters_by_project(client: DataMasqueClient, file_type: type[DataMasqueFile]) -> None:
with requests_mock.Mocker() as m_request:
m_request.get(f"http://test-server/{file_type.get_url()}?project={PROJECT_ID}", json=[], complete_qs=True)
assert client.list_files_of_type(file_type, PROJECT_ID) == []


@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile])
@pytest.mark.parametrize("file_type", [SeedFile, OracleWalletFile, SslZipFile, SnowflakeKeyFile, CertificateFile])
def test_get_file_of_type_by_name_is_scoped_to_the_project(
client: DataMasqueClient, file_type: type[DataMasqueFile]
) -> None:
Expand Down Expand Up @@ -380,3 +387,33 @@ def test_upload_file_sends_the_id_of_a_project(client: DataMasqueClient) -> None
)

assert parse_multipart_form(m_request.request_history[0])["project"] == "2"


def test_certificate_file_reads_each_certificate(client):
with requests_mock.Mocker() as m_request:
m_request.get(
f"http://test-server/{CertificateFile.get_url()}",
json=[
{
"id": "c1",
"name": "root-ca.pem",
"project": "1-default",
"created_date": "2026-11-18T00:00:00Z",
"modified_date": "2026-11-18T00:00:00Z",
"certificates": [
{
"is_ca": True,
"is_self_signed": True,
"not_valid_after": "2031-05-01T00:00:00Z",
}
],
"unusable_reason": None,
}
],
)
(file,) = client.list_files_of_type(CertificateFile)

(certificate,) = file.certificates
assert certificate.is_ca is True
assert certificate.is_self_signed is True
assert certificate.not_valid_after == datetime(2031, 5, 1, tzinfo=timezone.utc)
9 changes: 9 additions & 0 deletions tests/test_projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,15 @@ def test_get_project_delete_conflicts_parses_each_reason(client: DataMasqueClien
assert conflicts[2].name is None


def test_a_delete_conflict_of_a_type_the_client_does_not_know_has_no_type() -> None:
conflict = ProjectDeleteConflict.model_validate(
{"reason": "name_in_use", "detail": "taken", "type": "a_future_type", "id": "1", "name": "x"}
)

assert conflict.type is None
assert conflict.name == "x"


def test_get_project_delete_conflicts_returns_empty_list_when_project_can_be_deleted(
client: DataMasqueClient,
) -> None:
Expand Down
21 changes: 21 additions & 0 deletions tests/test_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,27 @@ def test_list_resources_groups_them_by_type_name(client: DataMasqueClient) -> No
assert seed.position is None


def test_list_resources_lists_certificate_files(client: DataMasqueClient) -> None:
certificate = {**BUILT_IN_SEED, "name": "root-ca.pem", "project": "7-banking"}
with requests_mock.Mocker() as m:
m.get("http://test-server/api/resources/", json=page({"certificates": [certificate]}))
resources = client.list_resources()

(listed,) = resources[ResourceTypeName.certificates]
assert listed.name == "root-ca.pem"


def test_list_resources_leaves_out_a_type_the_client_does_not_know(client: DataMasqueClient) -> None:
with requests_mock.Mocker() as m:
m.get(
"http://test-server/api/resources/",
json=page({"rulesets": [RULESET], "a_future_type": [{**RULESET, "id": "other"}]}),
)
resources = client.list_resources()

assert list(resources) == [ResourceTypeName.rulesets]


def test_list_resources_sends_its_filters(client: DataMasqueClient) -> None:
retail = Project.model_validate(
{
Expand Down
Loading