-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Refactor database DiscoveryResourceChecker
#29864
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| /* | ||
| Copyright 2023 Gravitational, Inc. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
|
|
||
| package cloud | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| "github.com/gravitational/trace" | ||
| "github.com/sirupsen/logrus" | ||
|
|
||
| "github.com/gravitational/teleport" | ||
| "github.com/gravitational/teleport/api/types" | ||
| "github.com/gravitational/teleport/lib/cloud" | ||
| "github.com/gravitational/teleport/lib/services" | ||
| ) | ||
|
|
||
| // DiscoveryResourceChecker defines an interface for checking database | ||
| // resources created by the discovery service. | ||
| type DiscoveryResourceChecker interface { | ||
| // Check performs required checks on provided database resource before it | ||
| // gets registered. | ||
| Check(ctx context.Context, database types.Database) error | ||
| } | ||
|
|
||
| // DiscoveryResourceCheckerConfig is the config for DiscoveryResourceChecker. | ||
| type DiscoveryResourceCheckerConfig struct { | ||
| // ResourceMatchers is a list of database resource matchers. | ||
| ResourceMatchers []services.ResourceMatcher | ||
| // Clients is an interface for retrieving cloud clients. | ||
| Clients cloud.Clients | ||
| // Context is the database server close context. | ||
| Context context.Context | ||
| // Log is used for logging. | ||
| Log logrus.FieldLogger | ||
| } | ||
|
|
||
| // CheckAndSetDefaults validates the config and sets default values. | ||
| func (c *DiscoveryResourceCheckerConfig) CheckAndSetDefaults() error { | ||
| if c.Clients == nil { | ||
| cloudClients, err := cloud.NewClients() | ||
| if err != nil { | ||
| return trace.Wrap(err) | ||
| } | ||
| c.Clients = cloudClients | ||
| } | ||
| if c.Context == nil { | ||
| c.Context = context.Background() | ||
| } | ||
| if c.Log == nil { | ||
| c.Log = logrus.WithField(trace.Component, teleport.ComponentDatabase) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // NewDiscoveryResourceChecker creates a new DiscoveryResourceChecker. | ||
| func NewDiscoveryResourceChecker(cfg DiscoveryResourceCheckerConfig) (DiscoveryResourceChecker, error) { | ||
| if err := cfg.CheckAndSetDefaults(); err != nil { | ||
| return nil, trace.Wrap(err) | ||
| } | ||
|
|
||
| c := &discoveryResourceChecker{} | ||
|
|
||
| // TODO(greedy52) implement url checker. | ||
| // TODO(greedy52) implement name checker. | ||
| if checker, err := newCrednentialsChecker(cfg); err != nil { | ||
| return nil, trace.Wrap(err) | ||
| } else { | ||
| c.checkers = append(c.checkers, checker) | ||
| } | ||
| return c, nil | ||
| } | ||
|
|
||
| // discoveryResourceChecker is a composite checker. | ||
| type discoveryResourceChecker struct { | ||
| checkers []DiscoveryResourceChecker | ||
| } | ||
|
|
||
| // Check calls Check from all its checkers and aggregate the errors. | ||
| func (c *discoveryResourceChecker) Check(ctx context.Context, database types.Database) error { | ||
| if database.Origin() != types.OriginCloud { | ||
| return nil | ||
| } | ||
|
|
||
| errors := make([]error, 0, len(c.checkers)) | ||
| for _, checker := range c.checkers { | ||
| errors = append(errors, trace.Wrap(checker.Check(ctx, database))) | ||
| } | ||
| return trace.NewAggregate(errors...) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| /* | ||
| Copyright 2023 Gravitational, Inc. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
|
|
||
| package cloud | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "time" | ||
|
|
||
| "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" | ||
| "github.com/gravitational/trace" | ||
| "github.com/sirupsen/logrus" | ||
| "golang.org/x/exp/slices" | ||
|
|
||
| "github.com/gravitational/teleport/api/types" | ||
| "github.com/gravitational/teleport/lib/cloud" | ||
| "github.com/gravitational/teleport/lib/cloud/aws" | ||
| "github.com/gravitational/teleport/lib/services" | ||
| "github.com/gravitational/teleport/lib/utils" | ||
| ) | ||
|
|
||
| // credentialsChecker performs some quick checks to see whether this database | ||
| // agent can handle the incoming database wrt to the agent's credentials. | ||
| // | ||
| // Note that this checker warns the user with suggestions on how to configure | ||
| // the credentials correctly instead of returning errors. | ||
| type credentialsChecker struct { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. moved from watcher.go without logic change |
||
| cloudClients cloud.Clients | ||
| resourceMatchers []services.ResourceMatcher | ||
| log logrus.FieldLogger | ||
| cache *utils.FnCache | ||
| } | ||
|
|
||
| func newCrednentialsChecker(cfg DiscoveryResourceCheckerConfig) (*credentialsChecker, error) { | ||
| cache, err := utils.NewFnCache(utils.FnCacheConfig{ | ||
| TTL: 10 * time.Minute, | ||
| Context: cfg.Context, | ||
| }) | ||
| if err != nil { | ||
| return nil, trace.Wrap(err) | ||
| } | ||
|
|
||
| return &credentialsChecker{ | ||
| cloudClients: cfg.Clients, | ||
| resourceMatchers: cfg.ResourceMatchers, | ||
| log: cfg.Log, | ||
| cache: cache, | ||
| }, nil | ||
| } | ||
|
|
||
| // Check performs some quick checks to see whether this database agent can | ||
| // handle the incoming database wrt to the agent's credentials. | ||
| func (c *credentialsChecker) Check(ctx context.Context, database types.Database) error { | ||
| switch { | ||
| case database.IsAWSHosted(): | ||
| c.checkAWS(ctx, database) | ||
| case database.IsAzure(): | ||
| c.checkAzure(ctx, database) | ||
| default: | ||
| c.log.Debugf("Database %q has unknown cloud type %q.", database.GetName(), database.GetType()) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func (c *credentialsChecker) checkAWS(ctx context.Context, database types.Database) { | ||
| meta := database.GetAWS() | ||
| identity, err := c.getAWSIdentity(ctx, &meta) | ||
| if err != nil { | ||
| c.warn(err, database, "Failed to get AWS identity when checking a database created by the discovery service.") | ||
| return | ||
| } | ||
|
|
||
| if meta.AccountID != "" && meta.AccountID != identity.GetAccountID() { | ||
| c.warn(nil, database, fmt.Sprintf("The database agent's identity and discovered database %q have different AWS account IDs (%s vs %s).", | ||
| database.GetName(), | ||
| identity.GetAccountID(), | ||
| meta.AccountID, | ||
| )) | ||
| return | ||
| } | ||
| } | ||
|
|
||
| // getAWSIdentity returns the identity used to access the given database, | ||
| // that is either the agent's identity or the database's configured assume-role. | ||
| func (c *credentialsChecker) getAWSIdentity(ctx context.Context, meta *types.AWS) (aws.Identity, error) { | ||
| if meta.AssumeRoleARN != "" { | ||
| // If the database has an assume role ARN, use that instead of | ||
| // agent identity. This avoids an unnecessary sts call too. | ||
| return aws.IdentityFromArn(meta.AssumeRoleARN) | ||
| } | ||
|
|
||
| identity, err := utils.FnCacheGet(ctx, c.cache, types.CloudAWS, func(ctx context.Context) (aws.Identity, error) { | ||
| client, err := c.cloudClients.GetAWSSTSClient(ctx, "") | ||
| if err != nil { | ||
| return nil, trace.Wrap(err) | ||
| } | ||
| return aws.GetIdentityWithClient(ctx, client) | ||
| }) | ||
| return identity, trace.Wrap(err) | ||
| } | ||
|
|
||
| func (c *credentialsChecker) checkAzure(ctx context.Context, database types.Database) { | ||
| allSubIDs, err := utils.FnCacheGet(ctx, c.cache, types.CloudAzure, func(ctx context.Context) ([]string, error) { | ||
| client, err := c.cloudClients.GetAzureSubscriptionClient() | ||
| if err != nil { | ||
| return nil, trace.Wrap(err) | ||
| } | ||
| return client.ListSubscriptionIDs(ctx) | ||
| }) | ||
| if err != nil { | ||
| c.warn(err, database, "Failed to get Azure subscription IDs when checking a database created by the discovery service.") | ||
| return | ||
| } | ||
|
|
||
| rid, err := arm.ParseResourceID(database.GetAzure().ResourceID) | ||
| if err != nil { | ||
| c.log.Warnf("Failed to parse resource ID of database %q: %v.", database.GetName(), err) | ||
| return | ||
| } | ||
|
|
||
| if !slices.Contains(allSubIDs, rid.SubscriptionID) { | ||
| c.warn(nil, database, fmt.Sprintf("The discovered database %q is in a subscription (ID: %s) that the database agent does not have access to.", | ||
| database.GetName(), | ||
| rid.SubscriptionID, | ||
| )) | ||
| return | ||
| } | ||
| } | ||
|
|
||
| func (c *credentialsChecker) warn(err error, database types.Database, msg string) { | ||
| log := c.log.WithField("database", database) | ||
| if err != nil { | ||
| log = log.WithField("error", err.Error()) | ||
| } | ||
|
|
||
| logLevel := logrus.InfoLevel | ||
| if c.isWildcardMatcher() { | ||
| logLevel = logrus.WarnLevel | ||
| } | ||
| log.Logf(logLevel, "%s You can update \"db_service.resources\" section of this agent's config file to filter out unwanted resources (see https://goteleport.com/docs/database-access/reference/configuration/ for more details). If this database is intended to be handled by this agent, please verify that valid cloud credentials are configured for the agent.", msg) | ||
| } | ||
|
|
||
| func (c *credentialsChecker) isWildcardMatcher() bool { | ||
| if len(c.resourceMatchers) != 1 { | ||
| return false | ||
| } | ||
|
|
||
| wildcardLabels := c.resourceMatchers[0].Labels[types.Wildcard] | ||
| return len(wildcardLabels) == 1 && wildcardLabels[0] == types.Wildcard | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
moved from watcher.go but now returns
error