Skip to content

Commit

Permalink
test, refact: add check expiration date tests, add print flag to chec…
Browse files Browse the repository at this point in the history
…k expiration function
  • Loading branch information
renatav committed Oct 2, 2023
1 parent 46ff21b commit 02bdbc8
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 9 deletions.
18 changes: 15 additions & 3 deletions taf/api/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ def check_expiration_dates(
interval: Optional[int] = None,
start_date: Optional[datetime] = None,
excluded_roles: Optional[List[str]] = None,
print: bool = True,
) -> None:
"""
Check if any metadata files (roles) are expired or will expire in the next <interval> days.
Expand All @@ -49,17 +50,28 @@ def check_expiration_dates(
interval, start_date, excluded_roles
)

if expired_dict or will_expire_dict:
if print:
print_expiration_dates(
expired_dict, will_expire_dict, start_date=start_date, interval=interval
)

return expired_dict, will_expire_dict


def print_expiration_dates(
expired: Dict, will_expire: Dict, start_date: datetime, interval: int
) -> None:
if expired or will_expire:
now = datetime.now()
print(
f"Given a {interval} day interval from ({start_date.strftime('%Y-%m-%d')}):"
)
for role, expiry_date in expired_dict.items():
for role, expiry_date in expired.items():
delta = now - expiry_date
print(
f"{role} expired {delta.days} days ago (on {expiry_date.strftime('%Y-%m-%d')})"
)
for role, expiry_date in will_expire_dict.items():
for role, expiry_date in will_expire.items():
delta = expiry_date - now
print(
f"{role} will expire in {delta.days} days (on {expiry_date.strftime('%Y-%m-%d')})"
Expand Down
16 changes: 10 additions & 6 deletions taf/api/targets.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def add_target_repo(
custom: Optional[Dict] = None,
commit: Optional[bool] = True,
prompt_for_keys: Optional[bool] = False,
push: Optional[bool] = True
push: Optional[bool] = True,
) -> None:
"""
Add a new target repository by adding it to repositories.json, creating a delegation (if targets is not
Expand Down Expand Up @@ -143,7 +143,9 @@ def add_target_repo(
repositories_json = {"repositories": {}}
repositories = repositories_json["repositories"]
if target_repo.name in repositories:
taf_logger.info(f"{target_repo.name} already added to repositories.json. Overwriting")
taf_logger.info(
f"{target_repo.name} already added to repositories.json. Overwriting"
)
repositories[target_repo.name] = {}
if custom:
repositories[target_name]["custom"] = custom
Expand Down Expand Up @@ -387,7 +389,7 @@ def remove_target_repo(
target_name: str,
keystore: str,
prompt_for_keys: Optional[bool] = False,
push: Optional[bool] = True
push: Optional[bool] = True,
) -> None:
"""
Remove target repository from repositories.json, remove delegation, and target files and
Expand Down Expand Up @@ -463,7 +465,9 @@ def remove_target_repo(
scheme=DEFAULT_RSA_SIGNATURE_SCHEME,
prompt_for_keys=prompt_for_keys,
)
auth_repo.commit(git_commit_message("remove-from-delegated-paths", target_name=target_name))
auth_repo.commit(
git_commit_message("remove-from-delegated-paths", target_name=target_name)
)
changes_committed = True
else:
taf_logger.info(f"{target_name} not among delegated paths")
Expand Down Expand Up @@ -511,7 +515,7 @@ def update_target_repos_from_repositories_json(
scheme: Optional[str] = DEFAULT_RSA_SIGNATURE_SCHEME,
commit: Optional[bool] = True,
prompt_for_keys: Optional[bool] = False,
push: Optional[bool] = True
push: Optional[bool] = True,
) -> None:
"""
Create or update target files by reading the latest commit's repositories.json
Expand Down Expand Up @@ -574,7 +578,7 @@ def update_and_sign_targets(
scheme: str,
commit: Optional[bool] = True,
prompt_for_keys: Optional[bool] = False,
push: Optional[bool] = True
push: Optional[bool] = True,
) -> None:
"""
Save the top commit of specified target repositories to the corresponding target files and sign.
Expand Down
67 changes: 67 additions & 0 deletions taf/tests/test_api/test_metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import datetime
import shutil
import uuid
from freezegun import freeze_time
from pathlib import Path
from taf.messages import git_commit_message
from taf.auth_repo import AuthenticationRepository
from taf.git import GitRepository
from pytest import fixture
from taf.api.repository import create_repository
from taf.tests.conftest import CLIENT_DIR_PATH
from taf.utils import on_rm_error
from taf.api.metadata import check_expiration_dates


AUTH_REPO_NAME = "auth"


@fixture(scope="module")
def auth_repo_path():
random_name = str(uuid.uuid4())
root_dir = CLIENT_DIR_PATH / random_name
auth_path = root_dir / AUTH_REPO_NAME
auth_path.mkdir(exist_ok=True, parents=True)
yield auth_path
shutil.rmtree(root_dir, onerror=on_rm_error)


@freeze_time("2021-12-31")
def test_setup_auth_repo_expired(
auth_repo_path,
with_delegations_no_yubikeys_path,
api_keystore,
):

create_repository(
str(auth_repo_path),
roles_key_infos=with_delegations_no_yubikeys_path,
keystore=api_keystore,
commit=True,
)


@freeze_time("2023-01-01")
def test_check_expiration_date_when_all_expired(auth_repo_path):
expired, will_expire = check_expiration_dates(auth_repo_path, print=False)
# expect expire after 1 day
start = datetime.datetime(2021, 12, 31)
_check_expired_role("timestamp", start, 1, expired)
_check_expired_role("snapshot", start, 7, expired)
# expect expire afer 90 days
for target_role in ("targets", "delegated_role", "inner_role"):
_check_expired_role(target_role, start, 91, expired)
_check_expired_role("root", start, 365, expired)


def _check_expired_role(role_name, start_time, interval, expired_dict):
assert role_name in expired_dict
expected_expiration_date = start_time + datetime.timedelta(days=interval)
actual_expiration_time = expired_dict[role_name]
# strip hours and minutes, they are set in case of targets and root
actual_expiration_date = datetime.datetime(
actual_expiration_time.year,
actual_expiration_time.month,
actual_expiration_time.day,
)
assert expected_expiration_date == actual_expiration_date

0 comments on commit 02bdbc8

Please sign in to comment.