authentik.providers.proxy.controllers.k8s.httproute
1from dataclasses import asdict, dataclass, field 2from typing import TYPE_CHECKING 3from urllib.parse import urlparse 4 5from dacite.core import from_dict 6from kubernetes.client import ApiextensionsV1Api, CustomObjectsApi, V1ObjectMeta 7 8from authentik.outposts.controllers.base import FIELD_MANAGER 9from authentik.outposts.controllers.k8s.base import KubernetesObjectReconciler 10from authentik.outposts.controllers.k8s.triggers import NeedsUpdate 11from authentik.outposts.controllers.kubernetes import KubernetesController 12from authentik.providers.proxy.models import ProxyMode, ProxyProvider 13 14if TYPE_CHECKING: 15 from authentik.outposts.controllers.kubernetes import KubernetesController 16 17 18@dataclass(slots=True) 19class RouteBackendRef: 20 name: str 21 port: int 22 23 24@dataclass(slots=True) 25class RouteSpecParentRefs: 26 name: str 27 sectionName: str | None = None 28 port: int | None = None 29 namespace: str | None = None 30 kind: str = "Gateway" 31 group: str = "gateway.networking.k8s.io" 32 33 34@dataclass(slots=True) 35class HTTPRouteSpecRuleMatchPath: 36 type: str 37 value: str 38 39 40@dataclass(slots=True) 41class HTTPRouteSpecRuleMatchHeader: 42 name: str 43 value: str 44 type: str = "Exact" 45 46 47@dataclass(slots=True) 48class HTTPRouteSpecRuleMatch: 49 path: HTTPRouteSpecRuleMatchPath 50 headers: list[HTTPRouteSpecRuleMatchHeader] 51 52 53@dataclass(slots=True) 54class HTTPRouteSpecRule: 55 backendRefs: list[RouteBackendRef] 56 matches: list[HTTPRouteSpecRuleMatch] 57 58 59@dataclass(slots=True) 60class HTTPRouteSpec: 61 parentRefs: list[RouteSpecParentRefs] 62 hostnames: list[str] 63 rules: list[HTTPRouteSpecRule] 64 65 66@dataclass(slots=True) 67class HTTPRouteMetadata: 68 name: str 69 namespace: str 70 annotations: dict = field(default_factory=dict) 71 labels: dict = field(default_factory=dict) 72 73 74@dataclass(slots=True) 75class HTTPRoute: 76 apiVersion: str 77 kind: str 78 metadata: HTTPRouteMetadata 79 spec: HTTPRouteSpec 80 81 82class HTTPRouteReconciler(KubernetesObjectReconciler): 83 """Kubernetes Gateway API HTTPRoute Reconciler""" 84 85 def __init__(self, controller: KubernetesController) -> None: 86 super().__init__(controller) 87 self.api_ex = ApiextensionsV1Api(controller.client) 88 self.api = CustomObjectsApi(controller.client) 89 self.crd_group = "gateway.networking.k8s.io" 90 self.crd_version = "v1" 91 self.crd_plural = "httproutes" 92 93 @staticmethod 94 def reconciler_name() -> str: 95 return "httproute" 96 97 @property 98 def noop(self) -> bool: 99 if not self.crd_exists(): 100 self.logger.debug("CRD doesn't exist") 101 return True 102 config = self.controller.outpost.config 103 if ( 104 not config.kubernetes_httproute_parent_refs 105 and not config.kubernetes_listenerset_parent_ref 106 ): 107 self.logger.debug("HTTPRoute parentRefs and ListenerSet parentRef not set.") 108 return True 109 return False 110 111 def crd_exists(self) -> bool: 112 """Check if the Gateway API resources exists""" 113 return bool( 114 len( 115 self.api_ex.list_custom_resource_definition( 116 field_selector=f"metadata.name={self.crd_plural}.{self.crd_group}" 117 ).items 118 ) 119 ) 120 121 def reconcile(self, current: HTTPRoute, reference: HTTPRoute): 122 super().reconcile(current, reference) 123 if current.metadata.annotations != reference.metadata.annotations: 124 raise NeedsUpdate() 125 if current.spec.parentRefs != reference.spec.parentRefs: 126 raise NeedsUpdate() 127 if current.spec.hostnames != reference.spec.hostnames: 128 raise NeedsUpdate() 129 if current.spec.rules != reference.spec.rules: 130 raise NeedsUpdate() 131 132 def get_object_meta(self, **kwargs) -> V1ObjectMeta: 133 return super().get_object_meta( 134 **kwargs, 135 ) 136 137 def get_reference_object(self) -> HTTPRoute: 138 hostnames = [] 139 rules = [] 140 141 for proxy_provider in ProxyProvider.objects.filter(outpost__in=[self.controller.outpost]): 142 proxy_provider: ProxyProvider 143 external_host_name = urlparse(proxy_provider.external_host) 144 if proxy_provider.mode in [ProxyMode.FORWARD_SINGLE, ProxyMode.FORWARD_DOMAIN]: 145 rule = HTTPRouteSpecRule( 146 backendRefs=[RouteBackendRef(name=self.name, port=9000)], 147 matches=[ 148 HTTPRouteSpecRuleMatch( 149 headers=[ 150 HTTPRouteSpecRuleMatchHeader( 151 name="Host", 152 value=external_host_name.hostname, 153 ) 154 ], 155 path=HTTPRouteSpecRuleMatchPath( 156 type="PathPrefix", value="/outpost.goauthentik.io" 157 ), 158 ) 159 ], 160 ) 161 else: 162 rule = HTTPRouteSpecRule( 163 backendRefs=[RouteBackendRef(name=self.name, port=9000)], 164 matches=[ 165 HTTPRouteSpecRuleMatch( 166 headers=[ 167 HTTPRouteSpecRuleMatchHeader( 168 name="Host", 169 value=external_host_name.hostname, 170 ) 171 ], 172 path=HTTPRouteSpecRuleMatchPath(type="PathPrefix", value="/"), 173 ) 174 ], 175 ) 176 hostnames.append(external_host_name.hostname) 177 rules.append(rule) 178 179 parent_refs = [ 180 from_dict(RouteSpecParentRefs, spec) 181 for spec in self.controller.outpost.config.kubernetes_httproute_parent_refs 182 ] 183 if self.controller.outpost.config.kubernetes_listenerset_parent_ref: 184 # Routes attached to a Gateway don't attach to its ListenerSets' listeners 185 parent_refs.append(RouteSpecParentRefs(name=self.name, kind="ListenerSet")) 186 187 return HTTPRoute( 188 apiVersion=f"{self.crd_group}/{self.crd_version}", 189 kind="HTTPRoute", 190 metadata=HTTPRouteMetadata( 191 name=self.name, 192 namespace=self.namespace, 193 annotations=self.controller.outpost.config.kubernetes_httproute_annotations, 194 labels=self.get_object_meta().labels, 195 ), 196 spec=HTTPRouteSpec( 197 parentRefs=parent_refs, 198 hostnames=hostnames, 199 rules=rules, 200 ), 201 ) 202 203 def create(self, reference: HTTPRoute): 204 return self.api.create_namespaced_custom_object( 205 group=self.crd_group, 206 version=self.crd_version, 207 plural=self.crd_plural, 208 namespace=self.namespace, 209 body=asdict(reference), 210 field_manager=FIELD_MANAGER, 211 ) 212 213 def delete(self, reference: HTTPRoute): 214 return self.api.delete_namespaced_custom_object( 215 group=self.crd_group, 216 version=self.crd_version, 217 plural=self.crd_plural, 218 namespace=self.namespace, 219 name=self.name, 220 ) 221 222 def retrieve(self) -> HTTPRoute: 223 return from_dict( 224 HTTPRoute, 225 self.api.get_namespaced_custom_object( 226 group=self.crd_group, 227 version=self.crd_version, 228 plural=self.crd_plural, 229 namespace=self.namespace, 230 name=self.name, 231 ), 232 ) 233 234 def update(self, current: HTTPRoute, reference: HTTPRoute): 235 return self.api.patch_namespaced_custom_object( 236 group=self.crd_group, 237 version=self.crd_version, 238 plural=self.crd_plural, 239 namespace=self.namespace, 240 name=self.name, 241 body=asdict(reference), 242 field_manager=FIELD_MANAGER, 243 )
@dataclass(slots=True)
class
RouteBackendRef:
@dataclass(slots=True)
class
RouteSpecParentRefs:
25@dataclass(slots=True) 26class RouteSpecParentRefs: 27 name: str 28 sectionName: str | None = None 29 port: int | None = None 30 namespace: str | None = None 31 kind: str = "Gateway" 32 group: str = "gateway.networking.k8s.io"
@dataclass(slots=True)
class
HTTPRouteSpecRuleMatchPath:
@dataclass(slots=True)
class
HTTPRouteSpecRuleMatchHeader:
@dataclass(slots=True)
class
HTTPRouteSpecRuleMatch:
48@dataclass(slots=True) 49class HTTPRouteSpecRuleMatch: 50 path: HTTPRouteSpecRuleMatchPath 51 headers: list[HTTPRouteSpecRuleMatchHeader]
HTTPRouteSpecRuleMatch( path: HTTPRouteSpecRuleMatchPath, headers: list[HTTPRouteSpecRuleMatchHeader])
headers: list[HTTPRouteSpecRuleMatchHeader]
@dataclass(slots=True)
class
HTTPRouteSpecRule:
54@dataclass(slots=True) 55class HTTPRouteSpecRule: 56 backendRefs: list[RouteBackendRef] 57 matches: list[HTTPRouteSpecRuleMatch]
HTTPRouteSpecRule( backendRefs: list[RouteBackendRef], matches: list[HTTPRouteSpecRuleMatch])
backendRefs: list[RouteBackendRef]
matches: list[HTTPRouteSpecRuleMatch]
@dataclass(slots=True)
class
HTTPRouteSpec:
60@dataclass(slots=True) 61class HTTPRouteSpec: 62 parentRefs: list[RouteSpecParentRefs] 63 hostnames: list[str] 64 rules: list[HTTPRouteSpecRule]
HTTPRouteSpec( parentRefs: list[RouteSpecParentRefs], hostnames: list[str], rules: list[HTTPRouteSpecRule])
parentRefs: list[RouteSpecParentRefs]
rules: list[HTTPRouteSpecRule]
@dataclass(slots=True)
class
HTTPRouteMetadata:
67@dataclass(slots=True) 68class HTTPRouteMetadata: 69 name: str 70 namespace: str 71 annotations: dict = field(default_factory=dict) 72 labels: dict = field(default_factory=dict)
@dataclass(slots=True)
class
HTTPRoute:
75@dataclass(slots=True) 76class HTTPRoute: 77 apiVersion: str 78 kind: str 79 metadata: HTTPRouteMetadata 80 spec: HTTPRouteSpec
HTTPRoute( apiVersion: str, kind: str, metadata: HTTPRouteMetadata, spec: HTTPRouteSpec)
metadata: HTTPRouteMetadata
spec: HTTPRouteSpec
class
HTTPRouteReconciler(typing.Generic[T]):
83class HTTPRouteReconciler(KubernetesObjectReconciler): 84 """Kubernetes Gateway API HTTPRoute Reconciler""" 85 86 def __init__(self, controller: KubernetesController) -> None: 87 super().__init__(controller) 88 self.api_ex = ApiextensionsV1Api(controller.client) 89 self.api = CustomObjectsApi(controller.client) 90 self.crd_group = "gateway.networking.k8s.io" 91 self.crd_version = "v1" 92 self.crd_plural = "httproutes" 93 94 @staticmethod 95 def reconciler_name() -> str: 96 return "httproute" 97 98 @property 99 def noop(self) -> bool: 100 if not self.crd_exists(): 101 self.logger.debug("CRD doesn't exist") 102 return True 103 config = self.controller.outpost.config 104 if ( 105 not config.kubernetes_httproute_parent_refs 106 and not config.kubernetes_listenerset_parent_ref 107 ): 108 self.logger.debug("HTTPRoute parentRefs and ListenerSet parentRef not set.") 109 return True 110 return False 111 112 def crd_exists(self) -> bool: 113 """Check if the Gateway API resources exists""" 114 return bool( 115 len( 116 self.api_ex.list_custom_resource_definition( 117 field_selector=f"metadata.name={self.crd_plural}.{self.crd_group}" 118 ).items 119 ) 120 ) 121 122 def reconcile(self, current: HTTPRoute, reference: HTTPRoute): 123 super().reconcile(current, reference) 124 if current.metadata.annotations != reference.metadata.annotations: 125 raise NeedsUpdate() 126 if current.spec.parentRefs != reference.spec.parentRefs: 127 raise NeedsUpdate() 128 if current.spec.hostnames != reference.spec.hostnames: 129 raise NeedsUpdate() 130 if current.spec.rules != reference.spec.rules: 131 raise NeedsUpdate() 132 133 def get_object_meta(self, **kwargs) -> V1ObjectMeta: 134 return super().get_object_meta( 135 **kwargs, 136 ) 137 138 def get_reference_object(self) -> HTTPRoute: 139 hostnames = [] 140 rules = [] 141 142 for proxy_provider in ProxyProvider.objects.filter(outpost__in=[self.controller.outpost]): 143 proxy_provider: ProxyProvider 144 external_host_name = urlparse(proxy_provider.external_host) 145 if proxy_provider.mode in [ProxyMode.FORWARD_SINGLE, ProxyMode.FORWARD_DOMAIN]: 146 rule = HTTPRouteSpecRule( 147 backendRefs=[RouteBackendRef(name=self.name, port=9000)], 148 matches=[ 149 HTTPRouteSpecRuleMatch( 150 headers=[ 151 HTTPRouteSpecRuleMatchHeader( 152 name="Host", 153 value=external_host_name.hostname, 154 ) 155 ], 156 path=HTTPRouteSpecRuleMatchPath( 157 type="PathPrefix", value="/outpost.goauthentik.io" 158 ), 159 ) 160 ], 161 ) 162 else: 163 rule = HTTPRouteSpecRule( 164 backendRefs=[RouteBackendRef(name=self.name, port=9000)], 165 matches=[ 166 HTTPRouteSpecRuleMatch( 167 headers=[ 168 HTTPRouteSpecRuleMatchHeader( 169 name="Host", 170 value=external_host_name.hostname, 171 ) 172 ], 173 path=HTTPRouteSpecRuleMatchPath(type="PathPrefix", value="/"), 174 ) 175 ], 176 ) 177 hostnames.append(external_host_name.hostname) 178 rules.append(rule) 179 180 parent_refs = [ 181 from_dict(RouteSpecParentRefs, spec) 182 for spec in self.controller.outpost.config.kubernetes_httproute_parent_refs 183 ] 184 if self.controller.outpost.config.kubernetes_listenerset_parent_ref: 185 # Routes attached to a Gateway don't attach to its ListenerSets' listeners 186 parent_refs.append(RouteSpecParentRefs(name=self.name, kind="ListenerSet")) 187 188 return HTTPRoute( 189 apiVersion=f"{self.crd_group}/{self.crd_version}", 190 kind="HTTPRoute", 191 metadata=HTTPRouteMetadata( 192 name=self.name, 193 namespace=self.namespace, 194 annotations=self.controller.outpost.config.kubernetes_httproute_annotations, 195 labels=self.get_object_meta().labels, 196 ), 197 spec=HTTPRouteSpec( 198 parentRefs=parent_refs, 199 hostnames=hostnames, 200 rules=rules, 201 ), 202 ) 203 204 def create(self, reference: HTTPRoute): 205 return self.api.create_namespaced_custom_object( 206 group=self.crd_group, 207 version=self.crd_version, 208 plural=self.crd_plural, 209 namespace=self.namespace, 210 body=asdict(reference), 211 field_manager=FIELD_MANAGER, 212 ) 213 214 def delete(self, reference: HTTPRoute): 215 return self.api.delete_namespaced_custom_object( 216 group=self.crd_group, 217 version=self.crd_version, 218 plural=self.crd_plural, 219 namespace=self.namespace, 220 name=self.name, 221 ) 222 223 def retrieve(self) -> HTTPRoute: 224 return from_dict( 225 HTTPRoute, 226 self.api.get_namespaced_custom_object( 227 group=self.crd_group, 228 version=self.crd_version, 229 plural=self.crd_plural, 230 namespace=self.namespace, 231 name=self.name, 232 ), 233 ) 234 235 def update(self, current: HTTPRoute, reference: HTTPRoute): 236 return self.api.patch_namespaced_custom_object( 237 group=self.crd_group, 238 version=self.crd_version, 239 plural=self.crd_plural, 240 namespace=self.namespace, 241 name=self.name, 242 body=asdict(reference), 243 field_manager=FIELD_MANAGER, 244 )
Kubernetes Gateway API HTTPRoute Reconciler
HTTPRouteReconciler( controller: authentik.outposts.controllers.kubernetes.KubernetesController)
86 def __init__(self, controller: KubernetesController) -> None: 87 super().__init__(controller) 88 self.api_ex = ApiextensionsV1Api(controller.client) 89 self.api = CustomObjectsApi(controller.client) 90 self.crd_group = "gateway.networking.k8s.io" 91 self.crd_version = "v1" 92 self.crd_plural = "httproutes"
@staticmethod
def
reconciler_name() -> str:
A name this reconciler is identified by in the configuration
noop: bool
98 @property 99 def noop(self) -> bool: 100 if not self.crd_exists(): 101 self.logger.debug("CRD doesn't exist") 102 return True 103 config = self.controller.outpost.config 104 if ( 105 not config.kubernetes_httproute_parent_refs 106 and not config.kubernetes_listenerset_parent_ref 107 ): 108 self.logger.debug("HTTPRoute parentRefs and ListenerSet parentRef not set.") 109 return True 110 return False
Return true if this object should not be created/updated/deleted in this cluster
def
crd_exists(self) -> bool:
112 def crd_exists(self) -> bool: 113 """Check if the Gateway API resources exists""" 114 return bool( 115 len( 116 self.api_ex.list_custom_resource_definition( 117 field_selector=f"metadata.name={self.crd_plural}.{self.crd_group}" 118 ).items 119 ) 120 )
Check if the Gateway API resources exists
122 def reconcile(self, current: HTTPRoute, reference: HTTPRoute): 123 super().reconcile(current, reference) 124 if current.metadata.annotations != reference.metadata.annotations: 125 raise NeedsUpdate() 126 if current.spec.parentRefs != reference.spec.parentRefs: 127 raise NeedsUpdate() 128 if current.spec.hostnames != reference.spec.hostnames: 129 raise NeedsUpdate() 130 if current.spec.rules != reference.spec.rules: 131 raise NeedsUpdate()
Check what operations should be done, should be raised as ReconcileTrigger
def
get_object_meta(self, **kwargs) -> kubernetes.client.models.v1_object_meta.V1ObjectMeta:
133 def get_object_meta(self, **kwargs) -> V1ObjectMeta: 134 return super().get_object_meta( 135 **kwargs, 136 )
Get common object metadata
138 def get_reference_object(self) -> HTTPRoute: 139 hostnames = [] 140 rules = [] 141 142 for proxy_provider in ProxyProvider.objects.filter(outpost__in=[self.controller.outpost]): 143 proxy_provider: ProxyProvider 144 external_host_name = urlparse(proxy_provider.external_host) 145 if proxy_provider.mode in [ProxyMode.FORWARD_SINGLE, ProxyMode.FORWARD_DOMAIN]: 146 rule = HTTPRouteSpecRule( 147 backendRefs=[RouteBackendRef(name=self.name, port=9000)], 148 matches=[ 149 HTTPRouteSpecRuleMatch( 150 headers=[ 151 HTTPRouteSpecRuleMatchHeader( 152 name="Host", 153 value=external_host_name.hostname, 154 ) 155 ], 156 path=HTTPRouteSpecRuleMatchPath( 157 type="PathPrefix", value="/outpost.goauthentik.io" 158 ), 159 ) 160 ], 161 ) 162 else: 163 rule = HTTPRouteSpecRule( 164 backendRefs=[RouteBackendRef(name=self.name, port=9000)], 165 matches=[ 166 HTTPRouteSpecRuleMatch( 167 headers=[ 168 HTTPRouteSpecRuleMatchHeader( 169 name="Host", 170 value=external_host_name.hostname, 171 ) 172 ], 173 path=HTTPRouteSpecRuleMatchPath(type="PathPrefix", value="/"), 174 ) 175 ], 176 ) 177 hostnames.append(external_host_name.hostname) 178 rules.append(rule) 179 180 parent_refs = [ 181 from_dict(RouteSpecParentRefs, spec) 182 for spec in self.controller.outpost.config.kubernetes_httproute_parent_refs 183 ] 184 if self.controller.outpost.config.kubernetes_listenerset_parent_ref: 185 # Routes attached to a Gateway don't attach to its ListenerSets' listeners 186 parent_refs.append(RouteSpecParentRefs(name=self.name, kind="ListenerSet")) 187 188 return HTTPRoute( 189 apiVersion=f"{self.crd_group}/{self.crd_version}", 190 kind="HTTPRoute", 191 metadata=HTTPRouteMetadata( 192 name=self.name, 193 namespace=self.namespace, 194 annotations=self.controller.outpost.config.kubernetes_httproute_annotations, 195 labels=self.get_object_meta().labels, 196 ), 197 spec=HTTPRouteSpec( 198 parentRefs=parent_refs, 199 hostnames=hostnames, 200 rules=rules, 201 ), 202 )
Return object as it should be
204 def create(self, reference: HTTPRoute): 205 return self.api.create_namespaced_custom_object( 206 group=self.crd_group, 207 version=self.crd_version, 208 plural=self.crd_plural, 209 namespace=self.namespace, 210 body=asdict(reference), 211 field_manager=FIELD_MANAGER, 212 )
API Wrapper to create object
214 def delete(self, reference: HTTPRoute): 215 return self.api.delete_namespaced_custom_object( 216 group=self.crd_group, 217 version=self.crd_version, 218 plural=self.crd_plural, 219 namespace=self.namespace, 220 name=self.name, 221 )
API Wrapper to delete object
223 def retrieve(self) -> HTTPRoute: 224 return from_dict( 225 HTTPRoute, 226 self.api.get_namespaced_custom_object( 227 group=self.crd_group, 228 version=self.crd_version, 229 plural=self.crd_plural, 230 namespace=self.namespace, 231 name=self.name, 232 ), 233 )
API Wrapper to retrieve object
235 def update(self, current: HTTPRoute, reference: HTTPRoute): 236 return self.api.patch_namespaced_custom_object( 237 group=self.crd_group, 238 version=self.crd_version, 239 plural=self.crd_plural, 240 namespace=self.namespace, 241 name=self.name, 242 body=asdict(reference), 243 field_manager=FIELD_MANAGER, 244 )
API Wrapper to update object