-
Notifications
You must be signed in to change notification settings - Fork 391
/
azure_auth.go
289 lines (273 loc) · 9.07 KB
/
azure_auth.go
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package common
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/azure/auth"
"github.com/golang-jwt/jwt/v4"
)
// List of management information
const azureDatabricksProdLoginAppID string = "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d"
func (aa *DatabricksClient) GetAzureDatabricksLoginAppId() string {
if aa.AzureDatabricksLoginAppId != "" {
return aa.AzureDatabricksLoginAppId
}
return azureDatabricksProdLoginAppID
}
func (aa *DatabricksClient) GetAzureJwtProperty(key string) (any, error) {
if !aa.IsAzure() {
return "", fmt.Errorf("can't get Azure JWT token in non-Azure environment")
}
if key == "tid" && aa.AzureTenantID != "" {
return aa.AzureTenantID, nil
}
err := aa.Authenticate(context.TODO())
if err != nil {
return nil, err
}
request, err := http.NewRequest("GET", aa.Host, nil)
if err != nil {
return nil, err
}
if err = aa.authVisitor(request); err != nil {
return nil, err
}
header := request.Header.Get("Authorization")
var stoken string
if len(header) > 0 && strings.HasPrefix(string(header), "Bearer ") {
log.Printf("[DEBUG] Got Bearer token")
stoken = strings.TrimSpace(strings.TrimPrefix(string(header), "Bearer "))
}
if stoken == "" {
return nil, fmt.Errorf("can't obtain Azure JWT token")
}
if strings.HasPrefix(stoken, "dapi") {
return nil, fmt.Errorf("can't use Databricks PAT")
}
parser := jwt.Parser{SkipClaimsValidation: true}
token, _, err := parser.ParseUnverified(stoken, jwt.MapClaims{})
if err != nil {
return nil, err
}
claims := token.Claims.(jwt.MapClaims)
v, ok := claims[key]
if !ok {
return nil, fmt.Errorf("can't find field '%s' in parsed JWT", key)
}
return v, nil
}
func (aa *DatabricksClient) getAzureEnvironment() (azure.Environment, error) {
if aa.AzureEnvironment != nil {
// used for testing purposes
return *aa.AzureEnvironment, nil
}
if aa.AzurermEnvironment == "" {
return azure.PublicCloud, nil
}
envName := fmt.Sprintf("AZURE%sCLOUD", strings.ToUpper(aa.AzurermEnvironment))
return azure.EnvironmentFromName(envName)
}
// IsAzureClientSecretSet returns true if client id/secret and tenand id are supplied
func (aa *DatabricksClient) IsAzureClientSecretSet() bool {
return aa.AzureClientID != "" && aa.AzureClientSecret != "" && aa.AzureTenantID != ""
}
func (aa *DatabricksClient) configureWithAzureClientSecret(ctx context.Context) (func(*http.Request) error, error) {
if !aa.IsAzure() {
return nil, nil
}
if !aa.IsAzureClientSecretSet() {
return nil, nil
}
log.Printf("[INFO] Generating AAD token for Azure Service Principal")
return aa.simpleAADRequestVisitor(ctx, aa.getClientSecretAuthorizer, aa.addSpManagementTokenVisitor)
}
// variable, so that we can mock it in tests
var msiAvailabilityChecker = adal.MSIAvailable
func (aa *DatabricksClient) configureWithAzureManagedIdentity(ctx context.Context) (func(*http.Request) error, error) {
if !aa.IsAzure() {
return nil, nil
}
if !aa.AzureUseMSI {
return nil, nil
}
if !msiAvailabilityChecker(ctx, aa.httpClient.HTTPClient) {
return nil, fmt.Errorf("managed identity is not available")
}
log.Printf("[INFO] Using Azure Managed Identity authentication")
return aa.simpleAADRequestVisitor(ctx, func(resource string) (autorest.Authorizer, error) {
return auth.MSIConfig{
Resource: resource,
}.Authorizer()
}, aa.addSpManagementTokenVisitor)
}
func (aa *DatabricksClient) addSpManagementTokenVisitor(r *http.Request, management autorest.Authorizer) error {
log.Printf("[DEBUG] Setting 'X-Databricks-Azure-SP-Management-Token' header")
ba, ok := management.(*autorest.BearerAuthorizer)
if !ok {
return fmt.Errorf("supposed to get BearerAuthorizer, but got %#v", management)
}
tokenProvider := ba.TokenProvider()
if tokenProvider == nil {
return fmt.Errorf("token provider is nil")
}
if rf, ok := tokenProvider.(adal.RefresherWithContext); ok {
err := rf.EnsureFreshWithContext(r.Context())
if err != nil {
return fmt.Errorf("cannot refresh AAD token: %w", err)
}
}
accessToken := tokenProvider.OAuthToken()
r.Header.Set("X-Databricks-Azure-SP-Management-Token", accessToken)
return nil
}
// go nolint
func (aa *DatabricksClient) simpleAADRequestVisitor(
ctx context.Context,
authorizerFactory func(resource string) (autorest.Authorizer, error),
visitors ...func(r *http.Request, ma autorest.Authorizer) error) (func(r *http.Request) error, error) {
managementAuthorizer, err := authorizerFactory(aa.AzureEnvironment.ServiceManagementEndpoint)
if err != nil {
return nil, fmt.Errorf("cannot authorize management: %w", err)
}
err = aa.ensureWorkspaceURL(ctx, managementAuthorizer)
if err != nil {
return nil, fmt.Errorf("cannot get workspace: %w", err)
}
armDatabricksResourceID := aa.GetAzureDatabricksLoginAppId()
platformAuthorizer, err := authorizerFactory(armDatabricksResourceID)
if err != nil {
return nil, fmt.Errorf("cannot authorize databricks: %w", err)
}
return func(r *http.Request) error {
if len(visitors) > 0 {
err = visitors[0](r, managementAuthorizer)
if err != nil {
return err
}
}
if aa.AzureResourceID != "" {
r.Header.Set("X-Databricks-Azure-Workspace-Resource-Id", aa.AzureResourceID)
}
_, err = autorest.Prepare(r, platformAuthorizer.WithAuthorization())
if err != nil {
return fmt.Errorf("cannot prepare request: %w", err)
}
return nil
}, nil
}
func maybeExtendAuthzError(err error) error {
fmtString := "Azure authorization error. Does your SPN have Contributor access to Databricks workspace? %v"
if e, ok := err.(APIError); ok && e.StatusCode == 403 {
return fmt.Errorf(fmtString, err)
} else if strings.Contains(err.Error(), "does not have authorization to perform action") {
return fmt.Errorf(fmtString, err)
}
return err
}
func (aa *DatabricksClient) ensureWorkspaceURL(ctx context.Context,
managementAuthorizer autorest.Authorizer) error {
if aa.Host != "" {
return nil
}
resourceID := aa.AzureResourceID
if resourceID == "" {
return fmt.Errorf("please set `azure_workspace_resource_id` provider argument")
}
log.Println("[DEBUG] Getting Workspace ID via management token.")
// All azure endpoints typically end with a trailing slash removing it because resourceID starts with slash
managementResourceURL := strings.TrimSuffix(aa.AzureEnvironment.ResourceManagerEndpoint, "/") + resourceID
var workspace azureDatabricksWorkspace
resp, err := aa.genericQuery(ctx, http.MethodGet,
managementResourceURL,
map[string]string{
"api-version": "2018-04-01",
}, func(r *http.Request) error {
_, err := autorest.Prepare(r, managementAuthorizer.WithAuthorization())
if err != nil {
return maybeExtendAuthzError(err)
}
return nil
})
if err != nil {
return maybeExtendAuthzError(err)
}
err = json.Unmarshal(resp, &workspace)
if err != nil {
return err
}
aa.Host = fmt.Sprintf("https://%s/", workspace.Properties.WorkspaceURL)
return nil
}
func (aa *DatabricksClient) getClientSecretAuthorizer(resource string) (autorest.Authorizer, error) {
if aa.azureAuthorizer != nil {
return aa.azureAuthorizer, nil
}
armDatabricksResourceID := aa.GetAzureDatabricksLoginAppId()
if resource != armDatabricksResourceID {
es := auth.EnvironmentSettings{
Values: map[string]string{
auth.ClientID: aa.AzureClientID,
auth.ClientSecret: aa.AzureClientSecret,
auth.TenantID: aa.AzureTenantID,
auth.Resource: resource,
},
Environment: *aa.AzureEnvironment,
}
return es.GetAuthorizer()
}
platformTokenOAuthCfg, err := adal.NewOAuthConfigWithAPIVersion(
aa.AzureEnvironment.ActiveDirectoryEndpoint,
aa.AzureTenantID,
nil)
if err != nil {
return nil, maybeExtendAuthzError(err)
}
spt, err := adal.NewServicePrincipalToken(
*platformTokenOAuthCfg,
aa.AzureClientID,
aa.AzureClientSecret,
armDatabricksResourceID)
if err != nil {
return nil, maybeExtendAuthzError(err)
}
return autorest.NewBearerAuthorizer(spt), nil
}
type azureDatabricksWorkspace struct {
Name string `json:"name"`
ID string `json:"id"`
Type string `json:"type"`
Sku struct {
Name string `json:"name"`
} `json:"sku"`
Location string `json:"location"`
Properties struct {
ManagedResourceGroupID string `json:"managedResourceGroupId"`
Parameters any `json:"parameters"`
ProvisioningState string `json:"provisioningState"`
UIDefinitionURI string `json:"uiDefinitionUri"`
Authorizations []struct {
PrincipalID string `json:"principalId"`
RoleDefinitionID string `json:"roleDefinitionId"`
} `json:"authorizations"`
CreatedBy struct {
Oid string `json:"oid"`
Puid string `json:"puid"`
ApplicationID string `json:"applicationId"`
} `json:"createdBy"`
UpdatedBy struct {
Oid string `json:"oid"`
Puid string `json:"puid"`
ApplicationID string `json:"applicationId"`
} `json:"updatedBy"`
CreatedDateTime time.Time `json:"createdDateTime"`
WorkspaceID string `json:"workspaceId"`
WorkspaceURL string `json:"workspaceUrl"`
} `json:"properties"`
}