diff --git a/connect-inject/container_init.go b/connect-inject/container_init.go index d3473b5fb2..35d0ec9c68 100644 --- a/connect-inject/container_init.go +++ b/connect-inject/container_init.go @@ -81,6 +81,12 @@ func (h *Handler) containerInit(pod *corev1.Pod, k8sNamespace string) (corev1.Co panic("No service found. This should be impossible since we default it.") } + // When ACLs are enabled, the ACL token returned from `consul login` is only + // valid for a service with the same name as the ServiceAccountName. + if data.AuthMethod != "" && data.ServiceName != pod.Spec.ServiceAccountName { + return corev1.Container{}, fmt.Errorf("serviceAccountName %q does not match service name %q", pod.Spec.ServiceAccountName, data.ServiceName) + } + // If a port is specified, then we determine the value of that port // and register that port for the host service. if raw, ok := pod.Annotations[annotationPort]; ok && raw != "" { diff --git a/connect-inject/container_init_test.go b/connect-inject/container_init_test.go index 365dbbc211..1115439a3e 100644 --- a/connect-inject/container_init_test.go +++ b/connect-inject/container_init_test.go @@ -627,6 +627,7 @@ func TestHandlerContainerInit_namespacesEnabled(t *testing.T) { }, }, }, + ServiceAccountName: "web", }, } } @@ -1323,6 +1324,7 @@ func TestHandlerContainerInit_authMethod(t *testing.T) { }, }, }, + ServiceAccountName: "foo", }, } container, err := h.containerInit(pod, k8sNamespace) @@ -1373,6 +1375,7 @@ func TestHandlerContainerInit_authMethodAndCentralConfig(t *testing.T) { }, }, }, + ServiceAccountName: "foo", }, } container, err := h.containerInit(pod, k8sNamespace) @@ -1514,3 +1517,51 @@ func TestHandlerContainerInit_Resources(t *testing.T) { }, }, container.Resources) } + +func TestHandlerContainerInit_MismatchedServiceNameServiceAccountNameWithACLsEnabled(t *testing.T) { + require := require.New(t) + h := Handler{ + AuthMethod: "auth-method", + } + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Annotations: map[string]string{ + annotationService: "foo", + }, + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "serviceName", + }, + }, + ServiceAccountName: "notServiceName", + }, + } + + _, err := h.containerInit(pod, k8sNamespace) + require.EqualError(err, `serviceAccountName "notServiceName" does not match service name "foo"`) +} + +func TestHandlerContainerInit_MismatchedServiceNameServiceAccountNameWithACLsDisabled(t *testing.T) { + require := require.New(t) + h := Handler{} + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Annotations: map[string]string{ + annotationService: "foo", + }, + }, + Spec: corev1.PodSpec{ + Containers: []corev1.Container{ + { + Name: "serviceName", + }, + }, + ServiceAccountName: "notServiceName", + }, + } + + _, err := h.containerInit(pod, k8sNamespace) + require.NoError(err) +}