-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathproviders.go
More file actions
596 lines (460 loc) · 17.6 KB
/
Copy pathproviders.go
File metadata and controls
596 lines (460 loc) · 17.6 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
package config
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/go-version"
"github.com/sirupsen/logrus"
"github.com/thand-io/agent/internal/config/environment"
"github.com/thand-io/agent/internal/models"
"github.com/thand-io/agent/internal/providers"
providerSdk "github.com/thand-io/agent/sdk/providers"
"go.temporal.io/sdk/workflow"
// Load modules
_ "github.com/thand-io/agent/internal/providers/aws"
_ "github.com/thand-io/agent/internal/providers/cloudflare"
_ "github.com/thand-io/agent/internal/providers/email"
_ "github.com/thand-io/agent/internal/providers/gcp"
_ "github.com/thand-io/agent/internal/providers/gcp.iap"
_ "github.com/thand-io/agent/internal/providers/github"
_ "github.com/thand-io/agent/internal/providers/kubernetes"
_ "github.com/thand-io/agent/internal/providers/oauth2"
_ "github.com/thand-io/agent/internal/providers/oauth2.google"
_ "github.com/thand-io/agent/internal/providers/okta"
_ "github.com/thand-io/agent/internal/providers/salesforce"
_ "github.com/thand-io/agent/internal/providers/saml"
_ "github.com/thand-io/agent/internal/providers/slack"
_ "github.com/thand-io/agent/internal/providers/terraform"
_ "github.com/thand-io/agent/internal/providers/thand"
)
// LoadProviders loads providers from a file or URL and maps them to their implementations
func (c *Config) LoadProviders() (map[string]models.ProviderConfig, error) {
vaultData, err := c.loadProviderVaultData()
if err != nil {
return nil, err
}
foundProviders := []*models.ProviderDefinitions{}
if len(vaultData) > 0 || len(c.Providers.Path) > 0 || c.Providers.URL != nil {
importedProviders, err := loadDataFromSource(
c.Providers.Path,
c.Providers.URL,
vaultData,
models.ProviderDefinitions{},
)
if err != nil {
logrus.WithError(err).Errorln("Failed to load providers data")
return nil, fmt.Errorf("failed to load providers data: %w", err)
}
foundProviders = importedProviders
}
if len(foundProviders) == 0 {
logrus.Warningln("No providers found from any source, loading defaults")
foundProviders, err = environment.GetDefaultProviders(c.Environment.Platform)
if err != nil {
return nil, fmt.Errorf("failed to load default providers: %w", err)
}
logrus.Infoln("Loaded default providers:", len(foundProviders))
}
return c.ApplyProviders(foundProviders)
}
func (c *Config) ApplyProviders(foundProviders []*models.ProviderDefinitions) (map[string]models.ProviderConfig, error) {
providersLen := len(c.Providers.Definitions)
if providersLen > 0 {
// Prepend providers defined directly in config so they take
// priority over externally loaded or default providers.
logrus.Debugln("Adding providers defined directly in config: ", providersLen)
defaultVersion := version.Must(version.NewVersion("1.0.0"))
inlineProviders := make([]*models.ProviderDefinitions, 0, providersLen)
for providerKey, provider := range c.Providers.Definitions {
inlineProviders = append(inlineProviders, &models.ProviderDefinitions{
Version: defaultVersion,
Providers: map[string]models.ProviderConfig{
providerKey: provider,
},
})
}
foundProviders = append(inlineProviders, foundProviders...)
}
return c.processProviderDefinitions(foundProviders), nil
}
// loadProviderVaultData loads provider data from vault if configured
func (c *Config) loadProviderVaultData() (string, error) {
if len(c.Providers.Vault) == 0 {
return "", nil
}
if !c.HasVault() {
return "", fmt.Errorf("vault configuration is missing. Cannot load roles from vault")
}
logrus.Debugln("Loading providers from vault: ", c.Providers.Vault)
data, err := c.GetVault().GetSecret(c.Providers.Vault)
if err != nil {
logrus.WithError(err).Errorln("Error loading providers from vault")
return "", fmt.Errorf("failed to get secret from vault: %w", err)
}
logrus.Debugln("Loaded providers from vault: ", len(data), " bytes")
return string(data), nil
}
// processProviderDefinitions processes raw provider data and returns enabled providers
func (c *Config) processProviderDefinitions(foundProviders []*models.ProviderDefinitions) map[string]models.ProviderConfig {
defs := make(map[string]models.ProviderConfig)
logrus.Debugln("Processing loaded providers: ", len(foundProviders))
for _, provider := range foundProviders {
for providerKey, p := range provider.Providers {
if err := p.Validate(); err != nil {
logrus.WithError(err).Errorln("Provider definition validation failed")
continue
}
if !c.shouldIncludeProvider(providerKey, p, defs) {
continue
}
// Identifier is not set here as its a provider config.
// The identifier is set during provider initialization when we
// have the full provider config with all defaults applied.
// This allows providers to be referenced by their key in the config,
// but also allows the provider implementation to override the identifier if needed.
defs[providerKey] = p
logrus.WithFields(logrus.Fields{
"capabiltiies": p.Capabilities,
}).Infoln("Found provider:", providerKey, "of type", p.Provider)
}
}
return defs
}
// shouldIncludeProvider determines if a provider should be included in the final list
func (c *Config) shouldIncludeProvider(
providerKey string,
p models.ProviderConfig,
existingDefs map[string]models.ProviderConfig,
) bool {
if !p.Enabled {
logrus.Warningln("Provider disabled (not marked as enabled):", providerKey)
return false
}
if _, exists := existingDefs[providerKey]; exists {
logrus.Warningln("Duplicate provider key found, skipping:", providerKey)
return false
}
return true
}
// initResult represents the result of provider initialization
type initResult struct {
key string
provider models.Provider
err error
}
// InitializeProviders initializes all providers in parallel using channels
func (c *Config) InitializeProviders() error {
if c.IsServer() {
_ = c.GetServices()
}
defs := c.GetProviders().Definitions
logrus.Debugln("Initializing providers: ", len(defs))
resultChan := make(chan initResult, len(defs))
// Start goroutines for each provider
for providerKey, p := range defs {
go func(providerKey string, provider models.ProviderConfig) {
impl, err := c.initializeSingleProvider(providerKey, &provider)
resultChan <- initResult{
key: providerKey,
provider: impl,
err: err,
}
}(providerKey, p)
}
// Collect results from all goroutines
results := make(map[string]models.Provider)
for i := 0; i < len(defs); i++ {
result := <-resultChan
if result.err != nil {
logrus.WithError(result.err).Errorln("Failed to initialize provider:", result.key)
// Skip failed providers - don't add to results
continue
}
if result.provider == nil {
logrus.Errorln("Provider client is nil after initialization:", result.key)
// Skip providers with nil client
continue
}
providerResult := result.provider
// Check for capabilities for RBAC and Identities
if providerResult.HasAnyCapability(
models.ProviderCapabilityIdentities,
models.ProviderCapabilityUsers,
models.ProviderCapabilityGroups,
models.ProviderCapabilityResources,
models.ProviderCapabilityRoles,
models.ProviderCapabilityPermissions,
models.ProviderCapabilityTenants,
) {
logrus.Infoln("Provider", result.key, "supports RBAC/Identities capabilities")
// Register provider workflows and activities with Temporal if available
if c.IsServer() {
if c.GetServices() != nil && c.GetServices().HasTemporal() {
logrus.Infoln("Registering Temporal workflows/activities for provider", result.key)
temporalService := c.GetServices().GetTemporal()
worker := temporalService.GetWorker()
if worker == nil {
logrus.Errorln("Temporal client is configured but worker is nil, cannot register workflows/activities for provider", result.key)
continue
}
syncWorkflowName := models.CreateTemporalProviderWorkflowName(
providerResult.GetIdentifier(),
models.TemporalSynchronizeWorkflowName,
)
logrus.WithFields(logrus.Fields{
"workflow": syncWorkflowName,
}).Infoln("Registering provider synchronize workflow with name", syncWorkflowName)
// Register the provider Synchronize workflow. This updates roles, permissions,
// resources and identities for RBAC. We register this on the provider itself since it's a core part of the provider's functionality, but we register all other workflows and activities separately to allow providers to opt out of Temporal if they want.
worker.RegisterWorkflowWithOptions(
models.CreateProviderSynchronizeWorkflow(providerResult),
workflow.RegisterOptions{
Name: syncWorkflowName,
VersioningBehavior: workflow.VersioningBehaviorPinned,
},
)
if providerResult.HasCapability(models.ProviderCapabilityProvisioning) {
authWorkflowName := models.CreateTemporalProviderWorkflowName(
providerResult.GetIdentifier(),
models.TemporalAuthorizeRoleWorkflowName)
logrus.WithFields(logrus.Fields{
"workflow": authWorkflowName,
"provider": providerResult.GetIdentifier(),
}).Infoln("Registering provider authorize role workflow with name", authWorkflowName)
// Register the provider-specific authorize and revoke role workflows.
// These are closure-based: they capture the live provider instance so the
// child workflow can call provider.AuthorizeRole / RevokeRole with a
// full workflow.Context, allowing providers to dispatch activities,
// use workflow.Go, etc.
worker.RegisterWorkflowWithOptions(
models.CreateProviderAuthorizeRoleWorkflow(c, providerResult),
workflow.RegisterOptions{
Name: authWorkflowName,
VersioningBehavior: workflow.VersioningBehaviorPinned,
},
)
revokeWorkflowName := models.CreateTemporalProviderWorkflowName(
providerResult.GetIdentifier(),
models.TemporalRevokeRoleWorkflowName)
logrus.WithFields(logrus.Fields{
"workflow": revokeWorkflowName,
"provider": providerResult.GetIdentifier(),
}).Infoln("Registering provider revoke role workflow with name", revokeWorkflowName)
worker.RegisterWorkflowWithOptions(
models.CreateProviderRevokeRoleWorkflow(c, providerResult),
workflow.RegisterOptions{
Name: revokeWorkflowName,
VersioningBehavior: workflow.VersioningBehaviorPinned,
},
)
}
// Register all custom provider workflows
workflowsRegistry := providerResult.RegisterWorkflows()
if workflowsRegistry != nil {
logrus.Infoln("Registering Temporal workflows for provider", result.key)
worker.RegisterWorkflow(workflowsRegistry)
}
// Register default provider activities
err := models.RegisterProviderActivities(temporalService, providerResult)
if err != nil {
logrus.WithError(err).Errorln("Failed to register default activities for provider:", result.key)
continue
}
customActivities := providerResult.RegisterActivities()
if customActivities != nil {
// Now register any custom activities defined by the provider
err = models.RegisterActivities(
temporalService,
providerResult.GetIdentifier(),
customActivities,
)
if err != nil {
logrus.WithError(err).Errorln("Failed to register custom activities for provider:", result.key)
continue
}
}
}
logrus.Infoln("Synchronizing provider", result.key)
c.synchronizeProvider(result.provider)
} else {
logrus.Infoln("Skipping Temporal registration for provider", result.key, "in non-server mode")
// Non-server mode: provider won't be synchronized, mark ready immediately
providerResult.SetReady()
}
} else {
// Provider doesn't have RBAC/Identity capabilities, no sync needed
result.provider.SetReady()
}
// The provider returned from the goroutine already has the client set
results[result.key] = result.provider
}
c.mu.Lock()
c.providerInstances = results
c.mu.Unlock()
if err := c.StartTemporalWorkers(); err != nil {
return err
}
logrus.Debugln("All providers initialized successfully")
return nil
}
// initializeSingleProvider initializes a single provider
func (c *Config) initializeSingleProvider(providerKey string, p *models.ProviderConfig) (models.Provider, error) {
impl, err := c.getProviderImplementation(providerKey, p.Provider)
if err != nil {
return nil, err
}
// Before we initialize, we need to check if any of the provider's
// config has any environment variable references and resolve them
err = p.ResolveConfig(
map[string]any{},
)
if err != nil {
return nil, fmt.Errorf("failed to resolve environment variables for provider %s: %w", providerKey, err)
}
// Client mode proxies provider operations to the login server and should not
// require the full provider config locally. Synced provider metadata from
// /providers intentionally omits sensitive config such as client secrets, but
// any non-sensitive config that is present should still be resolved first.
if c.IsClient() {
if err := impl.Initialize(providerKey, *p); err != nil {
return nil, err
}
return impl, nil
}
err = providerSdk.ValidateConfig(p.Provider, p.Config)
if err != nil {
return nil, fmt.Errorf("provider config validation failed for provider %s: %w", providerKey, err)
}
if err := impl.Initialize(providerKey, *p); err != nil {
return nil, err
}
return impl, nil
}
// getProviderImplementation returns the appropriate provider implementation based on config mode
func (c *Config) getProviderImplementation(providerKey string, providerName string) (models.Provider, error) {
if c.IsServer() || c.IsAgent() {
return providers.CreateInstance(strings.ToLower(providerName))
}
// If we're a client, return a remote proxy. This will let us forward
// requests to the server for provider operations
if c.IsClient() {
return providers.NewRemoteProviderProxy(
providerKey,
c.DiscoverLoginServerApiUrl(
c.GetLoginServerUrl(),
),
), nil
}
return nil, fmt.Errorf("unknown config mode, cannot load providers")
}
func (c *Config) GetProviders() ProviderDefinitionsConfig {
return c.Providers
}
func (c *Config) GetProvider(providerName string) (string, models.Provider, error) {
// Get the first provider by provider name
c.mu.RLock()
defer c.mu.RUnlock()
for foundName, provider := range c.providerInstances {
if strings.Compare(provider.GetProvider(), providerName) == 0 {
return foundName, provider, nil
}
}
return "", nil, fmt.Errorf("provider not found: %s", providerName)
}
func (c *Config) GetProviderByName(name string) (models.Provider, error) {
c.mu.RLock()
defer c.mu.RUnlock()
if provider, exists := c.providerInstances[name]; exists {
return provider, nil
}
return nil, fmt.Errorf("provider not found: %s", name)
}
func (c *Config) HasProvider(name string) bool {
c.mu.RLock()
defer c.mu.RUnlock()
_, exists := c.providerInstances[name]
return exists
}
func (c *Config) AddProvider(name string, provider models.Provider) {
c.mu.Lock()
defer c.mu.Unlock()
if c.providerInstances == nil {
c.providerInstances = make(map[string]models.Provider)
}
c.providerInstances[name] = provider
}
func (c *Config) GetProvidersByCapability(capability ...models.ProviderCapability) map[string]models.Provider {
return c.GetProvidersByCapabilityWithUser(nil, capability...)
}
func (c *Config) GetProvidersByCapabilityWithUser(user *models.User, capability ...models.ProviderCapability) map[string]models.Provider {
providers := make(map[string]models.Provider)
c.mu.RLock()
defer c.mu.RUnlock()
for name, provider := range c.providerInstances {
// Skip providers that don't have a client initialized
if !provider.HasPermission(user) {
logrus.Debugln("Skipping provider", name, "due to missing permissions for user")
continue
}
if len(capability) != 0 && !provider.HasAnyCapability(capability...) {
logrus.WithFields(logrus.Fields{
"capabilities": provider.GetCapabilities(),
}).Debugln("Skipping provider", name, "due to missing capability:", capability)
continue
}
providers[name] = provider
}
return providers
}
func (p *ProviderDefinitionsConfig) GetProviderByName(name string) (*models.ProviderConfig, error) {
if provider, exists := p.Definitions[name]; exists {
return &provider, nil
}
return nil, fmt.Errorf("provider not found: %s", name)
}
func (r *Config) GetProviderRole(roleName string, providers ...string) *models.ProviderRole {
return r.GetProviderRoleWithIdentity(nil, roleName, providers...)
}
func (r *Config) GetProviderRoleWithIdentity(identity *models.Identity, roleName string, providers ...string) *models.ProviderRole {
ctx := context.TODO()
for _, providerName := range providers {
p, err := r.GetProviderByName(providerName)
if err != nil || p == nil {
continue
}
// Check provider-level permissions
// If identity is nil, pass nil user to HasPermission which handles it appropriately
var user *models.User
if identity != nil {
user = identity.GetUser()
}
if !p.HasPermission(user) {
continue
}
providerRole, err := p.GetRole(ctx, roleName)
if err != nil {
continue
}
if providerRole != nil {
return providerRole
}
}
return nil
}
func (r *Config) GetProviderPermission(permissionName string, providers ...string) *models.ProviderPermission {
ctx := context.TODO()
for _, providerName := range providers {
p, err := r.GetProviderByName(providerName)
if err != nil || p == nil {
continue
}
providerPermission, err := p.GetPermission(ctx, permissionName)
if err != nil {
continue
}
if providerPermission != nil {
return providerPermission
}
}
return nil
}