manager.go 6.86 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/*
 * SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

package rbac

import (
	"context"
	"fmt"

	corev1 "k8s.io/api/core/v1"
	rbacv1 "k8s.io/api/rbac/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"
)

const (
	// RBAC resource kind constants
	kindClusterRole    = "ClusterRole"
	kindServiceAccount = "ServiceAccount"
	apiGroupRBAC       = "rbac.authorization.k8s.io"
)

// Manager handles dynamic RBAC creation for cluster-wide operator installations.
type Manager struct {
	client client.Client
}

// NewManager creates a new RBAC manager.
func NewManager(client client.Client) *Manager {
	return &Manager{client: client}
}

// needsRoleRefRecreate checks if the RoleRef has changed, which requires
// deleting and recreating the RoleBinding since RoleRef is immutable.
func needsRoleRefRecreate(existing *rbacv1.RoleBinding, clusterRoleName string) bool {
	return existing.RoleRef.Name != clusterRoleName ||
		existing.RoleRef.Kind != kindClusterRole ||
		existing.RoleRef.APIGroup != apiGroupRBAC
}

// needsSubjectUpdate checks if the Subjects field needs updating.
// Subjects are mutable so they can be updated in-place.
func needsSubjectUpdate(existing *rbacv1.RoleBinding, serviceAccountName, targetNamespace string) bool {
	return len(existing.Subjects) != 1 ||
		existing.Subjects[0].Kind != kindServiceAccount ||
		existing.Subjects[0].Name != serviceAccountName ||
		existing.Subjects[0].Namespace != targetNamespace
}

// EnsureServiceAccountWithRBAC creates or updates a ServiceAccount and RoleBinding
// in the target namespace. This should ONLY be called in cluster-wide mode.
//
// In cluster-wide mode, the operator dynamically creates:
//   - ServiceAccount in the target namespace
//   - RoleBinding in the target namespace that binds the SA to a ClusterRole
//
// The ClusterRole must already exist (created by Helm).
//
// Parameters:
//   - ctx: context
//   - targetNamespace: namespace to create RBAC resources in
//   - serviceAccountName: name of the ServiceAccount to create
//   - clusterRoleName: name of the ClusterRole to bind to (must exist)
func (m *Manager) EnsureServiceAccountWithRBAC(
	ctx context.Context,
	targetNamespace string,
	serviceAccountName string,
	clusterRoleName string,
) error {
	logger := log.FromContext(ctx)

	if targetNamespace == "" {
		return fmt.Errorf("target namespace is required")
	}
	if serviceAccountName == "" {
		return fmt.Errorf("service account name is required")
	}
	if clusterRoleName == "" {
		return fmt.Errorf("cluster role name is required")
	}

	// Verify ClusterRole exists before creating RoleBinding
	clusterRole := &rbacv1.ClusterRole{}
	if err := m.client.Get(ctx, client.ObjectKey{Name: clusterRoleName}, clusterRole); err != nil {
		if apierrors.IsNotFound(err) {
			return fmt.Errorf("cluster role %q does not exist: ensure it is created by Helm before deploying components", clusterRoleName)
		}
		return fmt.Errorf("failed to verify cluster role %q: %w", clusterRoleName, err)
	}
	logger.V(1).Info("ClusterRole verified",
		"clusterRole", clusterRoleName,
		"rules", len(clusterRole.Rules))

	// Create/update ServiceAccount
	sa := &corev1.ServiceAccount{
		ObjectMeta: metav1.ObjectMeta{
			Name:      serviceAccountName,
			Namespace: targetNamespace,
			Labels: map[string]string{
				"app.kubernetes.io/managed-by": "dynamo-operator",
				"app.kubernetes.io/component":  "rbac",
				"app.kubernetes.io/name":       serviceAccountName,
			},
		},
	}

	if err := m.client.Get(ctx, client.ObjectKeyFromObject(sa), sa); err != nil {
		if !apierrors.IsNotFound(err) {
			return fmt.Errorf("failed to get service account: %w", err)
		}
		// ServiceAccount doesn't exist, create it
		if err := m.client.Create(ctx, sa); err != nil {
			return fmt.Errorf("failed to create service account: %w", err)
		}
		logger.V(1).Info("ServiceAccount created",
			"serviceAccount", serviceAccountName,
			"namespace", targetNamespace)
	} else {
		logger.V(1).Info("ServiceAccount already exists",
			"serviceAccount", serviceAccountName,
			"namespace", targetNamespace)
	}

	// Create/update RoleBinding
	roleBindingName := fmt.Sprintf("%s-binding", serviceAccountName)
	rb := &rbacv1.RoleBinding{
		ObjectMeta: metav1.ObjectMeta{
			Name:      roleBindingName,
			Namespace: targetNamespace,
			Labels: map[string]string{
				"app.kubernetes.io/managed-by": "dynamo-operator",
				"app.kubernetes.io/component":  "rbac",
				"app.kubernetes.io/name":       serviceAccountName,
			},
		},
		Subjects: []rbacv1.Subject{{
			Kind:      kindServiceAccount,
			Name:      serviceAccountName,
			Namespace: targetNamespace,
		}},
		RoleRef: rbacv1.RoleRef{
			APIGroup: apiGroupRBAC,
			Kind:     kindClusterRole,
			Name:     clusterRoleName,
		},
	}

	existingRB := &rbacv1.RoleBinding{}
	if err := m.client.Get(ctx, client.ObjectKeyFromObject(rb), existingRB); err != nil {
		if !apierrors.IsNotFound(err) {
			return fmt.Errorf("failed to get role binding: %w", err)
		}
		// RoleBinding doesn't exist, create it
		if err := m.client.Create(ctx, rb); err != nil {
			return fmt.Errorf("failed to create role binding: %w", err)
		}
		logger.V(1).Info("RoleBinding created",
			"roleBinding", roleBindingName,
			"clusterRole", clusterRoleName,
			"namespace", targetNamespace)
	} else {
		// RoleBinding exists, check if it needs updating
		needsRecreate := needsRoleRefRecreate(existingRB, clusterRoleName)
		needsUpdate := needsSubjectUpdate(existingRB, serviceAccountName, targetNamespace)

		if needsRecreate {
			// RoleRef is immutable, so delete and recreate the RoleBinding
			if err := m.client.Delete(ctx, existingRB); err != nil {
				return fmt.Errorf("failed to delete role binding for recreation: %w", err)
			}
			logger.V(1).Info("RoleBinding deleted for recreation due to RoleRef change",
				"roleBinding", roleBindingName,
				"oldClusterRole", existingRB.RoleRef.Name,
				"newClusterRole", clusterRoleName,
				"namespace", targetNamespace)

			// Recreate with new RoleRef
			if err := m.client.Create(ctx, rb); err != nil {
				return fmt.Errorf("failed to recreate role binding: %w", err)
			}
			logger.V(1).Info("RoleBinding recreated",
				"roleBinding", roleBindingName,
				"clusterRole", clusterRoleName,
				"namespace", targetNamespace)
		} else if needsUpdate {
			// Only Subjects changed, can update in-place
			existingRB.Subjects = rb.Subjects
			if err := m.client.Update(ctx, existingRB); err != nil {
				return fmt.Errorf("failed to update role binding: %w", err)
			}
			logger.V(1).Info("RoleBinding subjects updated",
				"roleBinding", roleBindingName,
				"namespace", targetNamespace)
		} else {
			logger.V(1).Info("RoleBinding already up-to-date",
				"roleBinding", roleBindingName,
				"clusterRole", clusterRoleName,
				"namespace", targetNamespace)
		}
	}

	return nil
}