|
| 1 | +# Copyright 2025 Red Hat, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +"""Synchronize Certificates with Gateway.""" |
| 15 | +import hashlib |
| 16 | +import logging |
| 17 | +from typing import Optional |
| 18 | +from urllib.parse import urljoin |
| 19 | + |
| 20 | +import requests |
| 21 | +import yaml |
| 22 | +from ansible_base.resource_registry import resource_server |
| 23 | +from django.conf import settings |
| 24 | +from django.db.models.signals import post_save |
| 25 | +from django.dispatch import receiver |
| 26 | +from rest_framework import status |
| 27 | + |
| 28 | +from aap_eda.core import enums, models |
| 29 | +from aap_eda.core.exceptions import GatewayAPIError, MissingCredentials |
| 30 | + |
| 31 | +LOGGER = logging.getLogger(__name__) |
| 32 | +SLUG = "api/gateway/v1/ca_certificates/" |
| 33 | +DEFAULT_TIMEOUT = 30 |
| 34 | +SERVICE_TOKEN_HEADER = "X-ANSIBLE-SERVICE-AUTH" |
| 35 | + |
| 36 | + |
| 37 | +class SyncCertificates: |
| 38 | + """This class synchronizes the certificates with Gateway.""" |
| 39 | + |
| 40 | + def __init__(self, eda_credential_id: int): |
| 41 | + self.eda_credential_id = eda_credential_id |
| 42 | + self.gateway_url = settings.RESOURCE_SERVER["URL"] |
| 43 | + self.gateway_ssl_verify = settings.RESOURCE_SERVER.get( |
| 44 | + "VALIDATE_HTTPS", True |
| 45 | + ) |
| 46 | + |
| 47 | + self.eda_credential = models.EdaCredential.objects.get( |
| 48 | + id=self.eda_credential_id |
| 49 | + ) |
| 50 | + |
| 51 | + def update(self): |
| 52 | + """Handle creating and updating the certificate in Gateway.""" |
| 53 | + inputs = yaml.safe_load(self.eda_credential.inputs.get_secret_value()) |
| 54 | + existing_object = self._fetch_from_gateway() |
| 55 | + |
| 56 | + # If the user had a certificate and then they deleted it |
| 57 | + # remove it from Gateway |
| 58 | + if existing_object and not inputs["certificate"]: |
| 59 | + return self.delete() |
| 60 | + |
| 61 | + # If the user has not provided any certificate nothing to do |
| 62 | + if not inputs["certificate"]: |
| 63 | + return |
| 64 | + |
| 65 | + sha256 = hashlib.sha256( |
| 66 | + inputs["certificate"].encode("utf-8") |
| 67 | + ).hexdigest() |
| 68 | + |
| 69 | + if existing_object.get("sha256", "") != sha256: |
| 70 | + data = { |
| 71 | + "name": self.eda_credential.name, |
| 72 | + "pem_data": inputs["certificate"], |
| 73 | + "sha256": sha256, |
| 74 | + "eda_credential_id": self._get_remote_id(), |
| 75 | + } |
| 76 | + headers = self._prep_headers() |
| 77 | + if existing_object: |
| 78 | + slug = f"{SLUG}/{existing_object['id']}/" |
| 79 | + url = urljoin(self.gateway_url, slug) |
| 80 | + response = requests.patch( |
| 81 | + url, |
| 82 | + json=data, |
| 83 | + headers=headers, |
| 84 | + verify=self.gateway_ssl_verify, |
| 85 | + timeout=DEFAULT_TIMEOUT, |
| 86 | + ) |
| 87 | + else: |
| 88 | + url = urljoin(self.gateway_url, SLUG) |
| 89 | + response = requests.post( |
| 90 | + url, |
| 91 | + json=data, |
| 92 | + headers=headers, |
| 93 | + verify=self.gateway_ssl_verify, |
| 94 | + timeout=DEFAULT_TIMEOUT, |
| 95 | + ) |
| 96 | + |
| 97 | + if response.status_code in [ |
| 98 | + status.HTTP_200_OK, |
| 99 | + status.HTTP_201_CREATED, |
| 100 | + ]: |
| 101 | + LOGGER.debug("Certificate updated") |
| 102 | + elif response.status_code == status.HTTP_400_BAD_REQUEST: |
| 103 | + LOGGER.error("Update failed") |
| 104 | + else: |
| 105 | + LOGGER.error("Couldn't update certificate") |
| 106 | + |
| 107 | + else: |
| 108 | + LOGGER.debug("No changes detected") |
| 109 | + |
| 110 | + def delete(self, event_stream_id: Optional[int]): |
| 111 | + """Delete the Certificate from Gateway.""" |
| 112 | + existing_object = self._fetch_from_gateway() |
| 113 | + if not existing_object: |
| 114 | + return |
| 115 | + |
| 116 | + objects = models.EventStream.objects.filter( |
| 117 | + eda_credential_id=self.eda_credential |
| 118 | + ) |
| 119 | + if not event_stream_id: |
| 120 | + self._delete_from_gateway(existing_object) |
| 121 | + elif len(objects) == 1 and event_stream_id == objects[0].id: |
| 122 | + self._delete_from_gateway(existing_object) |
| 123 | + |
| 124 | + def _delete_from_gateway(self, existing_object: dict): |
| 125 | + slug = f"{SLUG}/{existing_object['id']}/" |
| 126 | + url = urljoin(self.gateway_url, slug) |
| 127 | + headers = self._prep_headers() |
| 128 | + response = requests.delete( |
| 129 | + url, |
| 130 | + headers=headers, |
| 131 | + verify=self.gateway_ssl_verify, |
| 132 | + timeout=DEFAULT_TIMEOUT, |
| 133 | + ) |
| 134 | + if response.status_code == status.HTTP_200_OK: |
| 135 | + LOGGER.debug("Certificate object deleted") |
| 136 | + if response.status_code == status.HTTP_404_NOT_FOUND: |
| 137 | + LOGGER.warning("Certificate object missing during delete") |
| 138 | + else: |
| 139 | + LOGGER.error( |
| 140 | + "Could not delete certificate object in gateway. " |
| 141 | + f"Error code: {response.status_code}" |
| 142 | + ) |
| 143 | + LOGGER.error(f"Error message: {response.text}") |
| 144 | + raise GatewayAPIError |
| 145 | + |
| 146 | + def _fetch_from_gateway(self): |
| 147 | + slug = f"{SLUG}/?eda_credential_id={self._get_remote_id()}" |
| 148 | + url = urljoin(self.gateway_url, slug) |
| 149 | + headers = self._prep_headers() |
| 150 | + response = requests.get( |
| 151 | + url, |
| 152 | + headers=headers, |
| 153 | + verify=self.gateway_ssl_verify, |
| 154 | + timeout=DEFAULT_TIMEOUT, |
| 155 | + ) |
| 156 | + |
| 157 | + if response.status_code == status.HTTP_200_OK: |
| 158 | + LOGGER.debug("Certificate object exists in gateway") |
| 159 | + data = response.json() |
| 160 | + if data["count"] > 0: |
| 161 | + return data["results"][0] |
| 162 | + else: |
| 163 | + return {} |
| 164 | + if response.status_code == status.HTTP_404_NOT_FOUND: |
| 165 | + LOGGER.debug("Certificate object does not exist in gateway") |
| 166 | + return {} |
| 167 | + |
| 168 | + LOGGER.error( |
| 169 | + "Error fetching certificate object. " |
| 170 | + f"Error code: {response.status_code}" |
| 171 | + ) |
| 172 | + LOGGER.error(f"Error message: {response.text}") |
| 173 | + raise GatewayAPIError |
| 174 | + |
| 175 | + def _get_remote_id(self) -> str: |
| 176 | + return f"eda_{self.eda_credential_id}" |
| 177 | + |
| 178 | + def _prep_headers(self) -> dict: |
| 179 | + token = resource_server.get_service_token() |
| 180 | + if token: |
| 181 | + return {SERVICE_TOKEN_HEADER: token} |
| 182 | + |
| 183 | + LOGGER.error("Cannot connect to gateway service token") |
| 184 | + raise MissingCredentials |
| 185 | + |
| 186 | + |
| 187 | +@receiver(post_save, sender=models.EdaCredential) |
| 188 | +def gw_handler(sender, instance, **kwargs): |
| 189 | + """Handle updates to EdaCredential object and force a certificate sync.""" |
| 190 | + if ( |
| 191 | + instance.credential_type is not None |
| 192 | + and instance.credential_type.name |
| 193 | + == enums.EventStreamCredentialType.MTLS |
| 194 | + and hasattr(instance, "_request") |
| 195 | + ): |
| 196 | + try: |
| 197 | + objects = models.EventStream.objects.filter( |
| 198 | + eda_credential_id=instance.id |
| 199 | + ) |
| 200 | + if len(objects) > 0: |
| 201 | + SyncCertificates(instance.id).update() |
| 202 | + except (GatewayAPIError, MissingCredentials) as ex: |
| 203 | + LOGGER.error( |
| 204 | + "Couldn't trigger gateway certificate updates %s", str(ex) |
| 205 | + ) |
0 commit comments