|
| 1 | +from typing import Any |
| 2 | + |
| 3 | +import portforward |
| 4 | +import pytest |
| 5 | +import requests |
| 6 | +import structlog |
| 7 | +from ocp_resources.cron_job import CronJob |
| 8 | +from ocp_resources.network_policy import NetworkPolicy |
| 9 | +from pytest_testconfig import config as py_config |
| 10 | + |
| 11 | +from tests.model_serving.maas_billing.maas_subscription.utils import search_active_api_keys |
| 12 | +from tests.model_serving.maas_billing.utils import build_maas_headers |
| 13 | + |
| 14 | +LOGGER = structlog.get_logger(name=__name__) |
| 15 | + |
| 16 | + |
| 17 | +@pytest.mark.usefixtures( |
| 18 | + "maas_subscription_controller_enabled_latest", |
| 19 | + "maas_gateway_api", |
| 20 | + "maas_api_gateway_reachable", |
| 21 | +) |
| 22 | +class TestEphemeralKeyCleanup: |
| 23 | + """Tests for ephemeral API key cleanup (CronJob + internal endpoint).""" |
| 24 | + |
| 25 | + @pytest.mark.tier1 |
| 26 | + def test_cronjob_exists_and_configured(self, maas_cleanup_cronjob: CronJob) -> None: |
| 27 | + """Verify the maas-api-key-cleanup CronJob exists with expected configuration.""" |
| 28 | + spec = maas_cleanup_cronjob.instance.spec |
| 29 | + |
| 30 | + assert spec.schedule == "*/15 * * * *", f"Expected schedule '*/15 * * * *', got '{spec.schedule}'" |
| 31 | + assert spec.concurrencyPolicy == "Forbid", ( |
| 32 | + "CronJob should use Forbid concurrency policy to prevent overlapping runs" |
| 33 | + ) |
| 34 | + |
| 35 | + containers = spec.jobTemplate.spec.template.spec.containers |
| 36 | + assert len(containers) >= 1, "CronJob should have at least one container" |
| 37 | + container_spec = containers[0] |
| 38 | + cmd_str = " ".join(container_spec.command or []) |
| 39 | + assert "/internal/v1/api-keys/cleanup" in cmd_str, ( |
| 40 | + f"CronJob command should target the internal cleanup endpoint, got: {cmd_str}" |
| 41 | + ) |
| 42 | + |
| 43 | + sec_ctx = getattr(container_spec, "securityContext", None) |
| 44 | + assert sec_ctx is not None, "Cleanup container should have securityContext configured" |
| 45 | + assert sec_ctx.runAsNonRoot is True, "Cleanup container should run as non-root" |
| 46 | + assert sec_ctx.readOnlyRootFilesystem is True, "Cleanup container should have read-only root filesystem" |
| 47 | + |
| 48 | + LOGGER.info(f"[ephemeral] CronJob validated: schedule={spec.schedule}, concurrency={spec.concurrencyPolicy}") |
| 49 | + |
| 50 | + @pytest.mark.tier1 |
| 51 | + def test_cleanup_networkpolicy_exists(self, maas_cleanup_networkpolicy: NetworkPolicy) -> None: |
| 52 | + """Verify the cleanup NetworkPolicy restricts cleanup pod egress to maas-api only.""" |
| 53 | + spec = maas_cleanup_networkpolicy.instance.spec |
| 54 | + |
| 55 | + assert spec.podSelector.matchLabels.get("app") == "maas-api-cleanup", ( |
| 56 | + f"NetworkPolicy should target app=maas-api-cleanup pods, got: {spec.podSelector.matchLabels}" |
| 57 | + ) |
| 58 | + for policy_type in ("Egress", "Ingress"): |
| 59 | + assert policy_type in spec.policyTypes, f"NetworkPolicy should control {policy_type} traffic" |
| 60 | + |
| 61 | + ingress_rules = getattr(spec, "ingress", None) |
| 62 | + assert ingress_rules in ([], None), "Cleanup pods should have no inbound traffic allowed" |
| 63 | + |
| 64 | + egress_rules = getattr(spec, "egress", None) |
| 65 | + assert egress_rules, "NetworkPolicy should define at least one egress rule" |
| 66 | + |
| 67 | + LOGGER.info("[ephemeral] NetworkPolicy validated: cleanup pods restricted to maas-api egress only") |
| 68 | + |
| 69 | + @pytest.mark.tier1 |
| 70 | + @pytest.mark.parametrize("ocp_token_for_actor", [{"type": "free"}], indirect=True) |
| 71 | + def test_ephemeral_key_visible_with_include_filter( |
| 72 | + self, |
| 73 | + request_session_http: requests.Session, |
| 74 | + base_url: str, |
| 75 | + ocp_token_for_actor: str, |
| 76 | + ephemeral_api_key: dict[str, Any], |
| 77 | + ) -> None: |
| 78 | + """Verify ephemeral key is marked as ephemeral and visible when includeEphemeral=True.""" |
| 79 | + key_id = ephemeral_api_key["id"] |
| 80 | + |
| 81 | + assert ephemeral_api_key.get("ephemeral") is True, "Key should be marked as ephemeral" |
| 82 | + |
| 83 | + items = search_active_api_keys( |
| 84 | + request_session_http=request_session_http, |
| 85 | + base_url=base_url, |
| 86 | + ocp_user_token=ocp_token_for_actor, |
| 87 | + include_ephemeral=True, |
| 88 | + ) |
| 89 | + assert key_id in [item["id"] for item in items], ( |
| 90 | + f"Ephemeral key {key_id} should appear in search with includeEphemeral=True" |
| 91 | + ) |
| 92 | + LOGGER.info(f"[ephemeral] Ephemeral key {key_id} visible with includeEphemeral=True") |
| 93 | + |
| 94 | + @pytest.mark.tier1 |
| 95 | + @pytest.mark.parametrize("ocp_token_for_actor", [{"type": "free"}], indirect=True) |
| 96 | + def test_ephemeral_key_hidden_from_default_search( |
| 97 | + self, |
| 98 | + request_session_http: requests.Session, |
| 99 | + base_url: str, |
| 100 | + ocp_token_for_actor: str, |
| 101 | + ephemeral_api_key: dict[str, Any], |
| 102 | + ) -> None: |
| 103 | + """Verify ephemeral key is hidden from default search when includeEphemeral is not set.""" |
| 104 | + key_id = ephemeral_api_key["id"] |
| 105 | + |
| 106 | + default_items = search_active_api_keys( |
| 107 | + request_session_http=request_session_http, |
| 108 | + base_url=base_url, |
| 109 | + ocp_user_token=ocp_token_for_actor, |
| 110 | + include_ephemeral=False, |
| 111 | + ) |
| 112 | + assert key_id not in [item["id"] for item in default_items], ( |
| 113 | + "Ephemeral key should be excluded from default search (includeEphemeral defaults to False)" |
| 114 | + ) |
| 115 | + LOGGER.info(f"[ephemeral] Ephemeral key {key_id} correctly hidden from default search") |
| 116 | + |
| 117 | + @pytest.mark.tier1 |
| 118 | + @pytest.mark.parametrize("ocp_token_for_actor", [{"type": "free"}], indirect=True) |
| 119 | + def test_trigger_cleanup_preserves_active_keys( |
| 120 | + self, |
| 121 | + request_session_http: requests.Session, |
| 122 | + base_url: str, |
| 123 | + ocp_token_for_actor: str, |
| 124 | + ephemeral_api_key: dict[str, Any], |
| 125 | + maas_api_pod_name: str, |
| 126 | + ) -> None: |
| 127 | + """Verify the cleanup endpoint does not delete active (non-expired) ephemeral keys.""" |
| 128 | + applications_namespace = py_config["applications_namespace"] |
| 129 | + key_id = ephemeral_api_key["id"] |
| 130 | + api_keys_endpoint = f"{base_url}/v1/api-keys" |
| 131 | + auth_header = build_maas_headers(token=ocp_token_for_actor) |
| 132 | + |
| 133 | + LOGGER.info(f"[ephemeral] Triggering cleanup via port-forward into pod={maas_api_pod_name}") |
| 134 | + |
| 135 | + with portforward.forward( |
| 136 | + pod_or_service=maas_api_pod_name, |
| 137 | + namespace=applications_namespace, |
| 138 | + from_port=8080, |
| 139 | + to_port=8080, |
| 140 | + waiting=20, |
| 141 | + ): |
| 142 | + cleanup_response = requests.post( |
| 143 | + url="http://localhost:8080/internal/v1/api-keys/cleanup", |
| 144 | + timeout=30, |
| 145 | + ) |
| 146 | + |
| 147 | + assert cleanup_response.status_code == 200, ( |
| 148 | + f"Cleanup endpoint returned unexpected status: {cleanup_response.status_code}: " |
| 149 | + f"{(cleanup_response.text or '')[:200]}" |
| 150 | + ) |
| 151 | + cleanup_resp = cleanup_response.json() |
| 152 | + deleted_count = cleanup_resp.get("deletedCount", -1) |
| 153 | + assert deleted_count >= 0, f"Cleanup response should have non-negative deletedCount, got: {cleanup_resp}" |
| 154 | + LOGGER.info(f"[ephemeral] Cleanup completed: deletedCount={deleted_count}") |
| 155 | + |
| 156 | + r_get = request_session_http.get( |
| 157 | + url=f"{api_keys_endpoint}/{key_id}", |
| 158 | + headers=auth_header, |
| 159 | + timeout=30, |
| 160 | + ) |
| 161 | + assert r_get.status_code == 200, ( |
| 162 | + f"Active ephemeral key {key_id} should survive cleanup, got {r_get.status_code}: {(r_get.text or '')[:200]}" |
| 163 | + ) |
| 164 | + get_body = r_get.json() |
| 165 | + assert get_body.get("status") == "active", ( |
| 166 | + f"Key should still be active after cleanup, got: {get_body.get('status')}" |
| 167 | + ) |
| 168 | + LOGGER.info(f"[ephemeral] Active key {key_id} survived cleanup correctly") |
0 commit comments