-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Azure integration command #47541
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
Azure integration command #47541
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
2d2683b
Initial command to create the managed identity and role
mvbrock ea52a58
Adding permissions and applying command params
mvbrock cf68e8a
Adding graph permissions to the MSI
mvbrock 0030cab
Updating parameters
mvbrock 8a20449
Adding some details and cleaning up comments
mvbrock 505b96e
Fixing go.sum
mvbrock 7356e35
Linting
mvbrock 9aa41d5
License
mvbrock 06d1141
PR feedback
mvbrock f635d2e
Decoupling sync config with an interface for testing
mvbrock 96b8b9f
Tweaks to test mocking
mvbrock a58348a
PR feedback
mvbrock 452a1c4
Rebase adjustments
mvbrock 23c67bb
PR feedback
mvbrock ee3fc47
Switch to empty struct maps instead of bool maps for set representation
mvbrock 993f16d
Godocs
mvbrock 61a4271
Adding user agent to Azure SDK requests
mvbrock 3f84256
Merge branch 'master' into mvbrock/azure-integration-cmd
mvbrock c76defb
Linting
mvbrock 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
File renamed without changes.
File renamed without changes.
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,276 @@ | ||
| /* | ||
| * Teleport | ||
| * Copyright (C) 2025 Gravitational, Inc. | ||
| * | ||
| * This program is free software: you can redistribute it and/or modify | ||
| * it under the terms of the GNU Affero General Public License as published by | ||
| * the Free Software Foundation, either version 3 of the License, or | ||
| * (at your option) any later version. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| * GNU Affero General Public License for more details. | ||
| * | ||
| * You should have received a copy of the GNU Affero General Public License | ||
| * along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| */ | ||
|
|
||
| package azureoidc | ||
|
|
||
| import ( | ||
| "context" | ||
| "io" | ||
| "maps" | ||
| "slices" | ||
| "strings" | ||
|
|
||
| "github.com/Azure/azure-sdk-for-go/sdk/azcore" | ||
| armpolicy "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/policy" | ||
| "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" | ||
| "github.com/Azure/azure-sdk-for-go/sdk/azidentity" | ||
| "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/authorization/armauthorization/v2" | ||
| "github.com/google/uuid" | ||
| "github.com/gravitational/trace" | ||
|
|
||
| "github.com/gravitational/teleport/lib/cloud/provisioning" | ||
| "github.com/gravitational/teleport/lib/msgraph" | ||
| libslices "github.com/gravitational/teleport/lib/utils/slices" | ||
| ) | ||
|
|
||
| // graphAppID is the pre-defined application ID of the Graph API | ||
| // Ref: [https://learn.microsoft.com/en-us/troubleshoot/entra/entra-id/governance/verify-first-party-apps-sign-in#application-ids-of-commonly-used-microsoft-applications]. | ||
| const graphAppID = "00000003-0000-0000-c000-000000000000" | ||
|
|
||
| // azureUserAgent defines the user agent for the Azure SDK to better identify misbehaving clients | ||
| const azureUserAgent = "teleport" | ||
|
|
||
| // requiredGraphRoleNames is the list of Graph API roles required for the managed identity to fetch resources from Azure | ||
| var requiredGraphRoleNames = map[string]struct{}{ | ||
| "User.ReadBasic.All": {}, | ||
| "Group.Read.All": {}, | ||
| "Directory.Read.All": {}, | ||
| "User.Read.All": {}, | ||
| "Policy.Read.All": {}, | ||
| } | ||
|
|
||
| // AccessGraphAzureConfigureClient provides an interface for granting the managed identity the necessary permissions | ||
| // to fetch Azure resources | ||
| type AccessGraphAzureConfigureClient interface { | ||
| // CreateRoleDefinition creates an Azure role definition | ||
| CreateRoleDefinition(ctx context.Context, scope string, roleDefinition armauthorization.RoleDefinition) (string, error) | ||
| // CreateRoleAssignment assigns a role to an Azure principal | ||
| CreateRoleAssignment(ctx context.Context, scope string, roleAssignment armauthorization.RoleAssignmentCreateParameters) error | ||
| // GetServicePrincipalByAppID returns a service principal based on its application ID | ||
| GetServicePrincipalByAppID(ctx context.Context, appID string) (*msgraph.ServicePrincipal, error) | ||
| // GrantAppRoleToServicePrincipal grants a specific type of application role to a service principal | ||
| GrantAppRoleToServicePrincipal(ctx context.Context, roleAssignment msgraph.AppRoleAssignment) error | ||
| } | ||
|
|
||
| // azureConfigClient wraps the role definition, role assignments, and Graph API clients | ||
| type azureConfigClient struct { | ||
| roleDefCli *armauthorization.RoleDefinitionsClient | ||
| roleAssignCli *armauthorization.RoleAssignmentsClient | ||
| graphCli *msgraph.Client | ||
| } | ||
|
|
||
| // NewAzureConfigClient returns a new config client for granting the managed identity the necessary permissions | ||
| // to fetch Azure resources | ||
| func NewAzureConfigClient(subscriptionID string) (AccessGraphAzureConfigureClient, error) { | ||
|
mvbrock marked this conversation as resolved.
|
||
| telemetryOpts := policy.TelemetryOptions{ | ||
| ApplicationID: azureUserAgent, | ||
| } | ||
| opts := &armpolicy.ClientOptions{ | ||
| ClientOptions: policy.ClientOptions{ | ||
| Telemetry: telemetryOpts, | ||
| }, | ||
| } | ||
| cred, err := azidentity.NewDefaultAzureCredential(&azidentity.DefaultAzureCredentialOptions{ | ||
| ClientOptions: azcore.ClientOptions{ | ||
| Telemetry: telemetryOpts, | ||
| }, | ||
| }) | ||
| if err != nil { | ||
| return nil, trace.Wrap(err) | ||
| } | ||
| roleDefCli, err := armauthorization.NewRoleDefinitionsClient(cred, opts) | ||
| if err != nil { | ||
| return nil, trace.BadParameter("failed to create role definitions client: %v", err) | ||
| } | ||
| roleAssignCli, err := armauthorization.NewRoleAssignmentsClient(subscriptionID, cred, opts) | ||
| if err != nil { | ||
| return nil, trace.BadParameter("failed to create role assignments client: %v", err) | ||
| } | ||
| graphCli, err := msgraph.NewClient(msgraph.Config{ | ||
| TokenProvider: cred, | ||
| }) | ||
| if err != nil { | ||
| return nil, trace.BadParameter("failed to create msgraph client: %v", err) | ||
| } | ||
| return &azureConfigClient{ | ||
| roleDefCli: roleDefCli, | ||
| roleAssignCli: roleAssignCli, | ||
| graphCli: graphCli, | ||
| }, nil | ||
| } | ||
|
|
||
| // CreateRoleDefinition creates an Azure role definition | ||
| func (c *azureConfigClient) CreateRoleDefinition(ctx context.Context, scope string, roleDefinition armauthorization.RoleDefinition) (string, error) { | ||
| newUuid, err := uuid.NewRandom() | ||
| if err != nil { | ||
| return "", trace.Wrap(err) | ||
| } | ||
| roleDefID := newUuid.String() | ||
| roleRes, err := c.roleDefCli.CreateOrUpdate(ctx, scope, roleDefID, roleDefinition, nil) | ||
| if err != nil { | ||
| return "", trace.Wrap(err) | ||
| } | ||
| return *roleRes.ID, err | ||
| } | ||
|
|
||
| // CreateRoleAssignment assigns a role to an Azure principal | ||
| func (c *azureConfigClient) CreateRoleAssignment(ctx context.Context, scope string, roleAssignment armauthorization.RoleAssignmentCreateParameters) error { | ||
| newUuid, err := uuid.NewRandom() | ||
| if err != nil { | ||
| return trace.Wrap(err) | ||
| } | ||
| assignID := newUuid.String() | ||
| if _, err = c.roleAssignCli.Create(ctx, scope, assignID, roleAssignment, nil); err != nil { | ||
| return trace.Wrap(err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // GetServicePrincipalByAppID returns a service principal based on its application ID | ||
| func (c *azureConfigClient) GetServicePrincipalByAppID(ctx context.Context, appID string) (*msgraph.ServicePrincipal, error) { | ||
| graphPrincipal, err := c.graphCli.GetServicePrincipalByAppId(ctx, appID) | ||
| if err != nil { | ||
| return nil, trace.BadParameter("failed to get the graph API service principal: %v", err) | ||
| } | ||
| return graphPrincipal, nil | ||
| } | ||
|
|
||
| // GrantAppRoleToServicePrincipal grants a specific type of application role to a service principal | ||
| func (c *azureConfigClient) GrantAppRoleToServicePrincipal(ctx context.Context, roleAssignment msgraph.AppRoleAssignment) error { | ||
| _, err := c.graphCli.GrantAppRoleToServicePrincipal(ctx, *roleAssignment.PrincipalID, &roleAssignment) | ||
| if err != nil { | ||
| return trace.Wrap(err) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // AccessGraphAzureConfigureRequest is a request to configure the required Policies to use the TAG AWS Sync. | ||
| type AccessGraphAzureConfigureRequest struct { | ||
| // ManagedIdentity is the principal performing the discovery | ||
| ManagedIdentity string | ||
| // RoleName is the name of the Azure Role to create and assign to the managed identity | ||
| RoleName string | ||
| // SubscriptionID is the Azure subscription containing resources for sync | ||
| SubscriptionID string | ||
| // AutoConfirm skips user confirmation of the operation plan if true | ||
| AutoConfirm bool | ||
| // stdout is used to override stdout output in tests. | ||
| stdout io.Writer | ||
| } | ||
|
|
||
| // roleAssignmentAction assigns both the Azure role and Graph API roles to the managed identity | ||
| func roleAssignmentAction(clt AccessGraphAzureConfigureClient, subscriptionID string, managedID string, roleName string) (*provisioning.Action, error) { | ||
| customRole := "CustomRole" | ||
| scope := "/subscriptions/" + subscriptionID | ||
| runnerFn := func(ctx context.Context) error { | ||
| // Create the role | ||
| roleDefinition := armauthorization.RoleDefinition{ | ||
| Name: &roleName, | ||
| Properties: &armauthorization.RoleDefinitionProperties{ | ||
| RoleName: &roleName, | ||
| RoleType: &customRole, | ||
| Permissions: []*armauthorization.Permission{ | ||
| { | ||
| Actions: libslices.ToPointers([]string{ | ||
| "Microsoft.Compute/virtualMachines/read", | ||
| "Microsoft.Compute/virtualMachineScaleSets/virtualMachines/read", | ||
| "Microsoft.Authorization/roleDefinitions/read", | ||
| "Microsoft.Authorization/roleAssignments/read", | ||
| }), | ||
| }, | ||
| }, | ||
| AssignableScopes: []*string{&scope}, // Scope must be provided | ||
| }, | ||
| } | ||
| roleID, err := clt.CreateRoleDefinition(ctx, scope, roleDefinition) | ||
| if err != nil { | ||
| return trace.Errorf("failed to create custom role: %v", err) | ||
| } | ||
|
|
||
| // Assign the new role to the managed identity | ||
| roleAssignParams := armauthorization.RoleAssignmentCreateParameters{ | ||
| Properties: &armauthorization.RoleAssignmentProperties{ | ||
| PrincipalID: &managedID, | ||
| RoleDefinitionID: &roleID, | ||
| }, | ||
| } | ||
| if err = clt.CreateRoleAssignment(ctx, scope, roleAssignParams); err != nil { | ||
| return trace.Errorf("failed to assign role %s to principal %s: %v", roleName, managedID, err) | ||
| } | ||
|
|
||
| // Assign the Graph API permissions to the managed identity | ||
| graphPrincipal, err := clt.GetServicePrincipalByAppID(ctx, graphAppID) | ||
| if err != nil { | ||
| return trace.Errorf("could not get the graph API service principal: %v", err) | ||
| } | ||
| rolesNotAssigned := make(map[string]struct{}) | ||
| for k, v := range requiredGraphRoleNames { | ||
| rolesNotAssigned[k] = v | ||
| } | ||
| for _, appRole := range graphPrincipal.AppRoles { | ||
| if _, ok := requiredGraphRoleNames[*appRole.Value]; ok { | ||
| roleAssignment := msgraph.AppRoleAssignment{ | ||
| AppRoleID: appRole.ID, | ||
| PrincipalID: &managedID, | ||
| ResourceID: graphPrincipal.ID, | ||
| } | ||
| if err = clt.GrantAppRoleToServicePrincipal(ctx, roleAssignment); err != nil { | ||
| return trace.Errorf("failed to assign graph API role to %s: %v", managedID, err) | ||
| } | ||
| delete(rolesNotAssigned, *appRole.Value) | ||
| } | ||
| } | ||
| if len(rolesNotAssigned) > 0 { | ||
| return trace.Errorf("could not assign all required roles: %v", slices.Collect(maps.Keys(rolesNotAssigned))) | ||
| } | ||
| return nil | ||
| } | ||
| cfg := provisioning.ActionConfig{ | ||
| Name: "AssignRole", | ||
| Summary: "Creates a new Azure role and attaches it to a managed identity for the Discovery service", | ||
| Details: strings.Join([]string{ | ||
|
mvbrock marked this conversation as resolved.
|
||
| "The Discovery Service needs to run as a credentialed Azure managed identity. This managed identity ", | ||
| "can be system assigned (i.e. tied to the lifecycle of a virtual machine running the Discovery service), ", | ||
| "or user-assigned (i.e. a persistent identity). The managed identity requires two types of permissions:\n\n", | ||
| "\t1) Azure resource permissions in order to fetch virtual machines, role definitions, etc, and\n", | ||
| "\t2) Graph API permissions to fetch users, groups, and service principals.\n\n", | ||
| "The command assigns both Azure resource permissions as well as Graph API permissions to the specified ", | ||
| "managed identity.", | ||
| }, ""), | ||
| RunnerFn: runnerFn, | ||
| } | ||
| return provisioning.NewAction(cfg) | ||
| } | ||
|
|
||
| // ConfigureAccessGraphSyncAzure sets up the managed identity and role required for Teleport to be able to pull | ||
| // Azure resources into Teleport. | ||
| func ConfigureAccessGraphSyncAzure(ctx context.Context, clt AccessGraphAzureConfigureClient, req AccessGraphAzureConfigureRequest) error { | ||
| managedIDAction, err := roleAssignmentAction(clt, req.SubscriptionID, req.ManagedIdentity, req.RoleName) | ||
| if err != nil { | ||
| return trace.Wrap(err) | ||
| } | ||
| opCfg := provisioning.OperationConfig{ | ||
| Name: "access-graph-azure-sync", | ||
| Actions: []provisioning.Action{ | ||
| *managedIDAction, | ||
| }, | ||
| AutoConfirm: req.AutoConfirm, | ||
| Output: req.stdout, | ||
| } | ||
| return trace.Wrap(provisioning.Run(ctx, opCfg)) | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.