Skip to content

Login guard middleware with automatic login #5204

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cli/azd/.vscode/cspell-azd-dictionary.txt
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ requirepass
resourcegraph
restoreapp
retriable
runtimes
rzip
secureobject
securestring
Expand Down
2 changes: 2 additions & 0 deletions cli/azd/cmd/actions/action_descriptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,8 @@ type ActionDescriptorOptions struct {
HelpOptions ActionHelpOptions
// Defines grouping options for the command
GroupingOptions CommandGroupOptions
// Whether or not the command requires a principal login
RequireLogin bool
}

// Completion function used for cobra command flag completion
Expand Down
4 changes: 3 additions & 1 deletion cli/azd/cmd/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,6 @@ func registerCommonDependencies(container *ioc.NestedContainer) {
ioc.RegisterInstance[auth.HttpClient](container, client)

// Auth
container.MustRegisterSingleton(auth.NewLoggedInGuard)
container.MustRegisterSingleton(auth.NewMultiTenantCredentialProvider)
container.MustRegisterSingleton(func(mgr *auth.Manager) CredentialProviderFn {
return mgr.CredentialForCurrentUser
Expand Down Expand Up @@ -579,6 +578,9 @@ func registerCommonDependencies(container *ioc.NestedContainer) {
})
container.MustRegisterScoped(auth.NewManager)
container.MustRegisterSingleton(azapi.NewUserProfileService)
container.MustRegisterScoped(func(authManager *auth.Manager) middleware.CurrentUserAuthManager {
return authManager
})
container.MustRegisterSingleton(account.NewSubscriptionsService)
container.MustRegisterSingleton(account.NewManager)
container.MustRegisterSingleton(account.NewSubscriptionsManager)
Expand Down
49 changes: 49 additions & 0 deletions cli/azd/cmd/middleware/login_guard.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package middleware

import (
"context"

"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/azure/azure-dev/cli/azd/cmd/actions"
"github.com/azure/azure-dev/cli/azd/pkg/auth"
"github.com/azure/azure-dev/cli/azd/pkg/cloud"
)

type CurrentUserAuthManager interface {
Cloud() *cloud.Cloud
CredentialForCurrentUser(
ctx context.Context,
options *auth.CredentialForCurrentUserOptions,
) (azcore.TokenCredential, error)
}

// LoginGuardMiddleware ensures that the user is logged in otherwise it returns an error
type LoginGuardMiddleware struct {
authManager CurrentUserAuthManager
}

// NewLoginGuardMiddleware creates a new instance of the LoginGuardMiddleware
func NewLoginGuardMiddleware(authManager CurrentUserAuthManager) Middleware {
return &LoginGuardMiddleware{
authManager: authManager,
}
}

// Run ensures that the user is logged in otherwise it returns an error
func (l *LoginGuardMiddleware) Run(ctx context.Context, next NextFn) (*actions.ActionResult, error) {
cred, err := l.authManager.CredentialForCurrentUser(ctx, nil)
if err != nil {
return nil, err
}

_, err = auth.EnsureLoggedInCredential(ctx, cred, l.authManager.Cloud())
if err != nil {
return nil, err
}

// At this point we have ensured a logged in user, continue execution of the action
return next(ctx)
}
81 changes: 81 additions & 0 deletions cli/azd/cmd/middleware/login_guard_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package middleware

import (
"context"
"testing"

"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/azure/azure-dev/cli/azd/cmd/actions"
"github.com/azure/azure-dev/cli/azd/pkg/auth"
"github.com/azure/azure-dev/cli/azd/pkg/cloud"
"github.com/azure/azure-dev/cli/azd/test/mocks"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)

func Test_LoginGuard_Run(t *testing.T) {
t.Run("LoggedIn", func(t *testing.T) {
mockContext := mocks.NewMockContext(context.Background())

mockAuthManager := &mockCurrentUserAuthManager{}
mockAuthManager.On("Cloud").Return(cloud.AzurePublic())
mockAuthManager.
On("CredentialForCurrentUser", *mockContext.Context, mock.Anything).
Return(mockContext.Credentials, nil)

middleware := LoginGuardMiddleware{
authManager: mockAuthManager,
}

result, err := middleware.Run(*mockContext.Context, next)
require.NoError(t, err)
require.NotNil(t, result)
})
t.Run("NotLoggedIn", func(t *testing.T) {
mockContext := mocks.NewMockContext(context.Background())

mockAuthManager := &mockCurrentUserAuthManager{}
mockAuthManager.On("Cloud").Return(cloud.AzurePublic())
mockAuthManager.
On("CredentialForCurrentUser", *mockContext.Context, mock.Anything).
Return(nil, auth.ErrNoCurrentUser)

middleware := LoginGuardMiddleware{
authManager: mockAuthManager,
}

result, err := middleware.Run(*mockContext.Context, next)
require.Error(t, err)
require.Nil(t, result)
})
}

func next(ctx context.Context) (*actions.ActionResult, error) {
return &actions.ActionResult{}, nil
}

type mockCurrentUserAuthManager struct {
mock.Mock
}

func (m *mockCurrentUserAuthManager) Cloud() *cloud.Cloud {
args := m.Called()
return args.Get(0).(*cloud.Cloud)
}

func (m *mockCurrentUserAuthManager) CredentialForCurrentUser(
ctx context.Context,
options *auth.CredentialForCurrentUserOptions,
) (azcore.TokenCredential, error) {
args := m.Called(ctx, options)

tokenVal := args.Get(0)
if tokenVal == nil {
return nil, args.Error(1)
}

return tokenVal.(azcore.TokenCredential), args.Error(1)
}
3 changes: 1 addition & 2 deletions cli/azd/cmd/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/MakeNowJust/heredoc/v2"
"github.com/azure/azure-dev/cli/azd/cmd/actions"
"github.com/azure/azure-dev/cli/azd/internal"
"github.com/azure/azure-dev/cli/azd/pkg/auth"
"github.com/azure/azure-dev/cli/azd/pkg/environment"
"github.com/azure/azure-dev/cli/azd/pkg/infra/provisioning"
"github.com/azure/azure-dev/cli/azd/pkg/input"
Expand Down Expand Up @@ -89,6 +88,7 @@ func pipelineActions(root *actions.ActionDescriptor) *actions.ActionDescriptor {
GroupingOptions: actions.CommandGroupOptions{
RootLevelHelp: actions.CmdGroupBeta,
},
RequireLogin: true,
})

group.Add("config", &actions.ActionDescriptorOptions{
Expand Down Expand Up @@ -134,7 +134,6 @@ type pipelineConfigAction struct {

func newPipelineConfigAction(
env *environment.Environment,
_ auth.LoggedInGuard,
console input.Console,
flags *pipelineConfigFlags,
prompters prompt.Prompter,
Expand Down
17 changes: 17 additions & 0 deletions cli/azd/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ func NewRootCmd(
GroupingOptions: actions.CommandGroupOptions{
RootLevelHelp: actions.CmdGroupAzure,
},
RequireLogin: true,
}).
UseMiddlewareWhen("hooks", middleware.NewHooksMiddleware, func(descriptor *actions.ActionDescriptor) bool {
if onPreview, _ := descriptor.Options.Command.Flags().GetBool("preview"); onPreview {
Expand Down Expand Up @@ -286,6 +287,7 @@ func NewRootCmd(
GroupingOptions: actions.CommandGroupOptions{
RootLevelHelp: actions.CmdGroupAzure,
},
RequireLogin: true,
}).
UseMiddleware("hooks", middleware.NewHooksMiddleware).
UseMiddleware("extensions", middleware.NewExtensionsMiddleware)
Expand All @@ -303,6 +305,7 @@ func NewRootCmd(
GroupingOptions: actions.CommandGroupOptions{
RootLevelHelp: actions.CmdGroupStart,
},
RequireLogin: true,
}).
UseMiddleware("hooks", middleware.NewHooksMiddleware).
UseMiddleware("extensions", middleware.NewExtensionsMiddleware)
Expand Down Expand Up @@ -334,6 +337,7 @@ func NewRootCmd(
GroupingOptions: actions.CommandGroupOptions{
RootLevelHelp: actions.CmdGroupAzure,
},
RequireLogin: true,
}).
UseMiddleware("hooks", middleware.NewHooksMiddleware).
UseMiddleware("extensions", middleware.NewExtensionsMiddleware)
Expand All @@ -356,6 +360,19 @@ func NewRootCmd(
UseMiddleware("ux", middleware.NewUxMiddleware).
UseMiddlewareWhen("telemetry", middleware.NewTelemetryMiddleware, func(descriptor *actions.ActionDescriptor) bool {
return !descriptor.Options.DisableTelemetry
}).
UseMiddlewareWhen("loginGuard", middleware.NewLoginGuardMiddleware, func(descriptor *actions.ActionDescriptor) bool {
// Check if the command or any of its parents require login
current := descriptor
for current != nil {
if current.Options != nil && current.Options.RequireLogin {
return true
}

current = current.Parent()
}

return false
})

// Register common dependencies for the IoC rootContainer
Expand Down
2 changes: 0 additions & 2 deletions cli/azd/cmd/up.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/azure/azure-dev/cli/azd/cmd/actions"
"github.com/azure/azure-dev/cli/azd/internal"
"github.com/azure/azure-dev/cli/azd/internal/cmd"
"github.com/azure/azure-dev/cli/azd/pkg/auth"
"github.com/azure/azure-dev/cli/azd/pkg/environment"
"github.com/azure/azure-dev/cli/azd/pkg/infra/provisioning"
"github.com/azure/azure-dev/cli/azd/pkg/infra/provisioning/bicep"
Expand Down Expand Up @@ -83,7 +82,6 @@ func newUpAction(
flags *upFlags,
console input.Console,
env *environment.Environment,
_ auth.LoggedInGuard,
projectConfig *project.ProjectConfig,
provisioningManager *provisioning.Manager,
envManager environment.Manager,
Expand Down
25 changes: 0 additions & 25 deletions cli/azd/pkg/auth/guard.go

This file was deleted.

5 changes: 5 additions & 0 deletions cli/azd/pkg/auth/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,11 @@ func (m *Manager) LoginScopes() []string {
return LoginScopes(m.cloud)
}

// Cloud returns the cloud that the manager is configured to use.
func (m *Manager) Cloud() *cloud.Cloud {
return m.cloud
}

func loginScopesMap(cloud *cloud.Cloud) map[string]struct{} {
resourceManagerUrl := cloud.Configuration.Services[azcloud.ResourceManager].Endpoint

Expand Down