-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathpermissions.go
More file actions
268 lines (233 loc) · 9.45 KB
/
permissions.go
File metadata and controls
268 lines (233 loc) · 9.45 KB
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package dresources
import (
"context"
"fmt"
"reflect"
"strings"
"github.com/databricks/cli/libs/structs/structvar"
"github.com/databricks/databricks-sdk-go"
"github.com/databricks/databricks-sdk-go/service/iam"
)
// GetAPIRequestObjectType is used by direct to construct a request to permissions API:
// https://github.com/databricks/terraform-provider-databricks/blob/430902d/permissions/permission_definitions.go#L775C24-L775C32
var permissionResourceToObjectType = map[string]string{
"alerts": "/alertsv2/",
"apps": "/apps/",
"clusters": "/clusters/",
"dashboards": "/dashboards/",
"database_instances": "/database-instances/",
"postgres_projects": "/database-projects/",
"jobs": "/jobs/",
"experiments": "/experiments/",
"models": "/registered-models/",
"model_serving_endpoints": "/serving-endpoints/",
"pipelines": "/pipelines/",
"sql_warehouses": "/sql/warehouses/",
}
type ResourcePermissions struct {
client *databricks.WorkspaceClient
}
// StatePermission represents a permission entry in deployment state.
type StatePermission struct {
Level iam.PermissionLevel `json:"level,omitempty"`
UserName string `json:"user_name,omitempty"`
ServicePrincipalName string `json:"service_principal_name,omitempty"`
GroupName string `json:"group_name,omitempty"`
}
// Note __embed__ name is not enforced by libs/structs, it's a convention we follow here.
// Technically we could keep on using "permissions" or "grants" for this, but this would make it
// harder for 3rd-party tools that only see JSON and not Golang type to associate state object with the pass from "changes".
// Alternative to __embed_ would be have a convention that we name this inner field same as outer field.
// e.g. permissions.permissions or grants.grants. However, there is no guarantee that this convention is not also triggered
// by unrelated types and it's harder to evaluate that fixed string because it's non-local.
type PermissionsState struct {
ObjectID string `json:"object_id"`
// By convention, EmbedSlice fields should have __embed__ json tag, see permissions.go for details
EmbeddedSlice []StatePermission `json:"__embed__,omitempty"`
}
func PreparePermissionsInputConfig(inputConfig any, node string) (*structvar.StructVar, error) {
baseNode, ok := strings.CutSuffix(node, ".permissions")
if !ok {
return nil, fmt.Errorf("internal error: node %q does not end with .permissions", node)
}
parts := strings.Split(baseNode, ".")
if len(parts) < 2 {
return nil, fmt.Errorf("internal error: unexpected node format %q", baseNode)
}
resourceType := parts[1]
prefix, ok := permissionResourceToObjectType[resourceType]
if !ok {
return nil, fmt.Errorf("unsupported permissions resource type: %s", resourceType)
}
permissions, err := toStatePermissions(inputConfig)
if err != nil {
return nil, err
}
objectIdRef := prefix + "${" + baseNode + ".id}"
// For permissions, model serving endpoint uses its internal ID, which is different
// from its CRUD APIs which use the name.
// We have a wrapper struct [RefreshOutput] from which we read the internal ID
// in order to set the appropriate permissions.
if strings.HasPrefix(baseNode, "resources.model_serving_endpoints.") {
objectIdRef = prefix + "${" + baseNode + ".endpoint_id}"
}
// MLflow models use the model name as the state ID (for CRUD operations),
// but the permissions API requires the numeric model ID.
if strings.HasPrefix(baseNode, "resources.models.") {
objectIdRef = prefix + "${" + baseNode + ".model_id}"
}
// Postgres projects store their hierarchical name ("projects/{project_id}") as the state ID,
// but the permissions API expects just the project_id.
if strings.HasPrefix(baseNode, "resources.postgres_projects.") {
objectIdRef = prefix + "${" + baseNode + ".project_id}"
}
return &structvar.StructVar{
Value: &PermissionsState{
ObjectID: "", // Always a reference, defined in Refs below
EmbeddedSlice: permissions,
},
Refs: map[string]string{
"object_id": objectIdRef,
},
}, nil
}
func (*ResourcePermissions) New(client *databricks.WorkspaceClient) *ResourcePermissions {
return &ResourcePermissions{client: client}
}
func (*ResourcePermissions) PrepareState(s *PermissionsState) *PermissionsState {
return s
}
// toStatePermissions converts any slice of typed permission structs (e.g. []JobPermission)
// to []StatePermission. All permission types share the same underlying struct layout.
func toStatePermissions(ps any) ([]StatePermission, error) {
v := reflect.ValueOf(ps)
if v.Kind() == reflect.Pointer {
v = v.Elem()
}
if v.Kind() != reflect.Slice {
return nil, fmt.Errorf("expected permissions slice, got %T", ps)
}
result := make([]StatePermission, v.Len())
for i := range v.Len() {
elem := v.Index(i)
result[i] = StatePermission{
Level: iam.PermissionLevel(elem.FieldByName("Level").String()),
UserName: elem.FieldByName("UserName").String(),
ServicePrincipalName: elem.FieldByName("ServicePrincipalName").String(),
GroupName: elem.FieldByName("GroupName").String(),
}
}
return result, nil
}
func permissionKey(x StatePermission) (string, string) {
if x.UserName != "" {
return "user_name", x.UserName
}
if x.ServicePrincipalName != "" {
return "service_principal_name", x.ServicePrincipalName
}
if x.GroupName != "" {
return "group_name", x.GroupName
}
return "", ""
}
func (*ResourcePermissions) KeyedSlices() map[string]any {
// Empty key because EmbeddedSlice appears at the root path of
// PermissionsState (no "permissions" prefix in struct walker paths).
return map[string]any{
"": permissionKey,
}
}
// parsePermissionsID extracts the object type and ID from a permissions ID string.
// Handles both 3-part IDs ("/jobs/123") and 4-part IDs ("/sql/warehouses/uuid").
func parsePermissionsID(id string) (extractedType, extractedID string, err error) {
idParts := strings.Split(id, "/")
if len(idParts) < 3 { // need at least "/type/id"
return "", "", fmt.Errorf("cannot parse id: %q", id)
}
if len(idParts) == 3 { // "/jobs/123"
extractedType = idParts[1]
extractedID = idParts[2]
} else if len(idParts) == 4 { // "/sql/warehouses/uuid"
extractedType = idParts[1] + "/" + idParts[2] // "sql/warehouses"
extractedID = idParts[3]
} else {
return "", "", fmt.Errorf("cannot parse id: %q", id)
}
return extractedType, extractedID, nil
}
func (r *ResourcePermissions) DoRead(ctx context.Context, id string) (*PermissionsState, error) {
extractedType, extractedID, err := parsePermissionsID(id)
if err != nil {
return nil, err
}
acl, err := r.client.Permissions.Get(ctx, iam.GetPermissionRequest{
RequestObjectId: extractedID,
RequestObjectType: extractedType,
})
if err != nil {
return nil, err
}
result := PermissionsState{
ObjectID: id,
EmbeddedSlice: nil,
}
for _, accessControl := range acl.AccessControlList {
for _, permission := range accessControl.AllPermissions {
// Inherited permissions can be ignored, as they are not set by the user (following TF)
if permission.Inherited {
continue
}
result.EmbeddedSlice = append(result.EmbeddedSlice, StatePermission{
Level: permission.PermissionLevel,
GroupName: accessControl.GroupName,
UserName: accessControl.UserName,
ServicePrincipalName: accessControl.ServicePrincipalName,
})
}
}
return &result, nil
}
// DoCreate calls https://docs.databricks.com/api/workspace/jobs/setjobpermissions.
func (r *ResourcePermissions) DoCreate(ctx context.Context, newState *PermissionsState) (string, *PermissionsState, error) {
// should we remember the default here?
_, err := r.DoUpdate(ctx, newState.ObjectID, newState, nil)
if err != nil {
return "", nil, err
}
return newState.ObjectID, nil, nil
}
// DoUpdate calls https://docs.databricks.com/api/workspace/jobs/setjobpermissions.
func (r *ResourcePermissions) DoUpdate(ctx context.Context, _ string, newState *PermissionsState, _ *PlanEntry) (*PermissionsState, error) {
extractedType, extractedID, err := parsePermissionsID(newState.ObjectID)
if err != nil {
return nil, err
}
acl := make([]iam.AccessControlRequest, len(newState.EmbeddedSlice))
for i, p := range newState.EmbeddedSlice {
acl[i] = iam.AccessControlRequest{
PermissionLevel: p.Level,
UserName: p.UserName,
ServicePrincipalName: p.ServicePrincipalName,
GroupName: p.GroupName,
ForceSendFields: nil,
}
}
_, err = r.client.Permissions.Set(ctx, iam.SetObjectPermissions{
RequestObjectId: extractedID,
RequestObjectType: extractedType,
AccessControlList: acl,
})
return nil, err
}
// DoDelete is activated in 2 distinct cases:
// 1) 'permissions' field is deleted in DABs config. In that case terraform would restore the default permissions (IS_OWNER for current user).
// 2) the parent resource is deleted; in that case there is no need to do anything; parent resource deletion is enough.
// Let's do nothing in both cases. If user no longer wishes to manage permissions with DABs they can go ahead and manage
// it themselves. Trying to fix permissions back requires
// - making assumptions on what it should look like
// - storing current user somewhere or storing original permissions somewhere
func (r *ResourcePermissions) DoDelete(ctx context.Context, id string) error {
// intentional noop
return nil
}