Skip to content
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

Add unusual rolename tests #138

Merged
merged 6 commits into from
Aug 14, 2024
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
11 changes: 11 additions & 0 deletions clients/python-tuf/python_tuf.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
# SPDX-License-Identifier: MIT OR Apache-2.0

import argparse
import logging
import os
import shutil
import sys
Expand Down Expand Up @@ -61,6 +62,7 @@ def main() -> int:
parser.add_argument("--target-name", required=False)
parser.add_argument("--target-dir", required=False)
parser.add_argument("--target-base-url", required=False)
parser.add_argument("-v", "--verbose", action="count", default=0)

sub_command = parser.add_subparsers(dest="sub_command")
init_parser = sub_command.add_parser(
Expand All @@ -81,6 +83,15 @@ def main() -> int:

command_args = parser.parse_args()

if command_args.verbose <= 1:
loglevel = logging.WARNING
elif command_args.verbose == 2:
loglevel = logging.INFO
else:
loglevel = logging.DEBUG

logging.basicConfig(level=loglevel)

# initialize the TUF Client Example infrastructure
if command_args.sub_command == "init":
init(command_args.metadata_dir, command_args.trusted_root)
Expand Down
19 changes: 15 additions & 4 deletions tuf_conformance/client_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from tempfile import TemporaryDirectory

from tuf.api.exceptions import StorageError
from tuf.api.metadata import Metadata

from tuf_conformance.metadata import MetadataTest
from tuf_conformance.simulator_server import ClientInitData, SimulatorServer
Expand Down Expand Up @@ -76,6 +77,7 @@ def refresh(self, data: ClientInitData, days_in_future: int = 0) -> int:
return self._run(cmd)

def download_target(self, data: ClientInitData, target_name: str) -> int:
self._server.debug_dump(self.test_name)
cmd = [
*self._cmd,
"--metadata-url",
Expand Down Expand Up @@ -110,7 +112,16 @@ def _files_exist(self, roles: Iterable[str]) -> bool:
local_metadata_files = sorted(os.listdir(self.metadata_dir))
return all(x in local_metadata_files for x in expected_files)

def _content(self, role: str) -> bytes:
"""Return role metadata as bytes"""
with open(os.path.join(self.metadata_dir, f"{role}.json"), "rb") as f:
return f.read()
def trusted_roles(self) -> list[tuple[str, int]]:
"""Return dict of current trusted role names and versions

Note that delegated role names may be encoded in a application specific way"""
roles = []
for filename in sorted(os.listdir(self.metadata_dir)):
if not filename.endswith(".json"):
continue
rolename = filename.removesuffix(".json")
md = Metadata.from_file(os.path.join(self.metadata_dir, filename))
roles.append((rolename, md.signed.version))

return roles
7 changes: 4 additions & 3 deletions tuf_conformance/simulator_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,16 @@ def new_test(self, name: str) -> tuple[ClientInitData, RepositorySimulator]:
* A new repository simulator (for test case to control)
* client initialization parameters (so client can find the simulated repo)
"""
dump_dir = path.join(self._dump_dir, name) if self._dump_dir else None
safe_name = parse.quote(name, "")
dump_dir = path.join(self._dump_dir, safe_name) if self._dump_dir else None
repo = RepositorySimulator(dump_dir)
self.repos[name] = repo

host, port = self.server_address[0], self.server_address[1]
assert isinstance(host, str)
client_data = ClientInitData(
f"http://{host}:{port}/{parse.quote(name, '')}/metadata/",
f"http://{host}:{port}/{parse.quote(name, '')}/targets/",
f"http://{host}:{port}/{safe_name}/metadata/",
f"http://{host}:{port}/{safe_name}/targets/",
repo.fetch_metadata("root", 1),
)

Expand Down
45 changes: 45 additions & 0 deletions tuf_conformance/test_quoting_issues.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from urllib import parse

import pytest
from tuf.api.metadata import DelegatedRole, Targets

from tuf_conformance.client_runner import ClientRunner
from tuf_conformance.simulator_server import SimulatorServer

unusual_role_names = [
"?",
"#",
"/delegatedrole",
"../delegatedrole",
]


@pytest.mark.parametrize("role", unusual_role_names)
def test_unusual_role_name(
client: ClientRunner, server: SimulatorServer, role: str
) -> None:
"""Test various unusual rolenames

Role names are used in http requests and potentially file names:
verify that both uses seem safe.
"""
init_data, repo = server.new_test(client.test_name)

# Add a delegation
delegated_role = DelegatedRole(role, [], 1, False, ["*"])
delegated_targets = Targets(1, None, repo.safe_expiry, {}, None)
repo.add_delegation(Targets.type, delegated_role, delegated_targets)

# Add signer, add the key to roles delegation
repo.add_key(role, Targets.type)

repo.targets.version += 1
repo.update_snapshot()

client.init_client(init_data)
assert client.download_target(init_data, "nonexistent target") == 1

# Make sure the correctly quoted request was made
assert (parse.quote(role, ""), 1) in repo.metadata_statistics
# count trusted roles (don't check name since we do not know how client encodes it)
assert len(client.trusted_roles()) == 5
Loading