diff --git a/pkg/plugin/adapter/auth/cancellation_test.go b/pkg/plugin/adapter/auth/cancellation_test.go index 489963ac88e..09cdb358d6c 100644 --- a/pkg/plugin/adapter/auth/cancellation_test.go +++ b/pkg/plugin/adapter/auth/cancellation_test.go @@ -2,16 +2,23 @@ package auth import ( "context" + "encoding/json" "os" + "path/filepath" "testing" "time" "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" errUtils "github.com/cloudposse/atmos/errors" + "github.com/cloudposse/atmos/pkg/auth/types" "github.com/cloudposse/atmos/pkg/keyring" + "github.com/cloudposse/atmos/pkg/plugin/credential" pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" "github.com/cloudposse/atmos/pkg/plugin/testkit/fakeplugin" + "github.com/cloudposse/atmos/pkg/schema" ) type discard struct{} @@ -72,9 +79,10 @@ func TestInvocationDeadlineSurfacesPluginTimeoutThroughAuthTranslation(t *testin definition.Timeout = 500 * time.Millisecond err := definition.invoke(t.Context(), "corporate", "realm", nil, func(operation *invocation) error { require.NotNil(t, operation.request.Deadline) - ctx, cancel := context.WithDeadline(t.Context(), operation.request.Deadline.AsTime()) - defer cancel() - return operation.handle.Command(ctx, &pluginv1.CommandRequest{Invocation: operation.request, Name: "hang"}, discard{}, discard{}) + deadline, bounded := operation.ctx.Deadline() + require.True(t, bounded, "the RPC context must enforce the advertised invocation deadline") + require.Equal(t, operation.request.Deadline.AsTime(), deadline.UTC()) + return operation.handle.Command(operation.ctx, &pluginv1.CommandRequest{Invocation: operation.request, Name: "hang"}, discard{}, discard{}) }) require.ErrorIs(t, err, errUtils.ErrPluginTimeout) require.NotEmpty(t, errUtils.AllHints(err)) @@ -91,3 +99,83 @@ func TestCompletedInvocationIsNotReportedAsTimeout(t *testing.T) { }) require.NoError(t, err) } + +const ( + authDeadlineFixtureName = "deadline-fixture" + authDeadlineRecordFile = "auth-rpc-deadline.json" +) + +type authDeadlineObservation struct { + PID int + RPCDeadline time.Time + InvocationDeadline time.Time +} + +// hangUntilAuthDeadline records the deadline received by a real RPC before +// waiting for cancellation. A fallback bounds regressions that omit the deadline. +func hangUntilAuthDeadline(ctx context.Context, invocation *pluginv1.Invocation) error { + deadline, _ := ctx.Deadline() + observed := authDeadlineObservation{PID: os.Getpid(), RPCDeadline: deadline} + if advertised := invocation.GetDeadline(); advertised != nil { + observed.InvocationDeadline = advertised.AsTime() + } + record, err := json.Marshal(observed) + if err != nil { + return err + } + if err := os.WriteFile(authDeadlineRecordFile, record, 0o600); err != nil { + return err + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-time.After(5 * time.Second): + return status.Error(codes.FailedPrecondition, "auth RPC did not enforce its invocation deadline") + } +} + +func TestAuthRPCsEnforceInvocationDeadline(t *testing.T) { + for _, tt := range []struct { + name string + run func(context.Context, *provider, *identity) error + }{ + {"provider authenticate", func(ctx context.Context, p *provider, _ *identity) error { + _, err := p.Authenticate(ctx) + return err + }}, + {"provider logout", func(ctx context.Context, p *provider, _ *identity) error { return p.Logout(ctx) }}, + {"identity authenticate", func(ctx context.Context, _ *provider, i *identity) error { + _, err := i.Authenticate(ctx, &types.AWSCredentials{ + AccessKeyID: "fixture-access", SecretAccessKey: "fixture-secret", SessionToken: "fixture-session", + Expiration: time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + }) + return err + }}, + {"identity logout", func(ctx context.Context, _ *provider, i *identity) error { return i.Logout(ctx) }}, + } { + t.Run(tt.name, func(t *testing.T) { + definition, directory := fakeDefinition(t, fakeplugin.ModeEcho) + definition.Timeout = 500 * time.Millisecond + definition.Credentials = credential.New() + p := &provider{name: authDeadlineFixtureName, realm: "fixture", definition: definition, config: providerConfig(nil)} + i := &identity{ + name: authDeadlineFixtureName, realm: "fixture", definition: definition, config: &schema.Identity{Kind: "plugin/broker"}, + accepts: []string{"aws/v1"}, materializer: EnvironmentMaterializer(authDeadlineFixtureName, nil), + } + err := tt.run(t.Context(), p, i) + require.ErrorIs(t, err, errUtils.ErrPluginTimeout) + require.ErrorIs(t, err, context.DeadlineExceeded) + require.NotEmpty(t, errUtils.AllHints(err)) + record, err := os.ReadFile(filepath.Join(directory, authDeadlineRecordFile)) + require.NoError(t, err, "the actual auth RPC must run before the timeout") + var observed authDeadlineObservation + require.NoError(t, json.Unmarshal(record, &observed)) + require.False(t, observed.RPCDeadline.IsZero(), "the auth RPC must receive a bounded context") + require.False(t, observed.InvocationDeadline.IsZero()) + require.WithinDuration(t, observed.InvocationDeadline, observed.RPCDeadline, 100*time.Millisecond) + require.Positive(t, observed.PID) + require.Eventually(t, func() bool { return !processAlive(observed.PID) }, 20*time.Second, 20*time.Millisecond, + "the plugin must not outlive its auth RPC deadline") + }) + } +} diff --git a/pkg/plugin/adapter/auth/identity.go b/pkg/plugin/adapter/auth/identity.go index 5a722cb9fb9..697f9df71fc 100644 --- a/pkg/plugin/adapter/auth/identity.go +++ b/pkg/plugin/adapter/auth/identity.go @@ -92,6 +92,8 @@ func (i *identity) Validate() error { return i.definition.Schema(i.config.Principal) } +// Authenticate exchanges upstream credentials with the identity plugin using +// the invocation's context and validated interaction handler. func (i *identity) Authenticate(ctx context.Context, upstream types.ICredentials) (types.ICredentials, error) { defer perf.Track(nil, "auth.identity.Authenticate")() @@ -109,13 +111,13 @@ func (i *identity) Authenticate(ctx context.Context, upstream types.ICredentials } var result types.ICredentials err = i.definition.invoke(ctx, i.name, i.realm, i.sessionSettings(), func(call *invocation) error { - stream, err := call.handle.Identity.Authenticate(ctx, &pluginv1.IdentityAuthenticateRequest{ + stream, err := call.handle.Identity.Authenticate(call.ctx, &pluginv1.IdentityAuthenticateRequest{ Identity: &pluginv1.IdentityRequest{Invocation: call.request, Kind: i.Kind(), Name: i.name, Principal: principal, Spec: spec, Realm: i.realm}, Upstream: encoded, }) if err != nil { return err } - envelope, err := receiveCredentials(stream) + envelope, err := receiveCredentials(stream, interactionHandler(call.ctx, call.request.GetInteractive(), presentDeviceCode)) if err != nil { return err } @@ -136,6 +138,8 @@ func (i *identity) Environment() (map[string]string, error) { return i.materiali //nolint:lintroller // Trivial accessor, pure lookup, factory option, or delegation; exempt under repository tracking policy. func (i *identity) Paths() ([]types.Path, error) { return i.materializer.Paths() } +// Logout combines plugin revocation and private-session cleanup with +// cancellation-independent removal of materialized credentials. func (i *identity) Logout(ctx context.Context) error { defer perf.Track(nil, "auth.identity.Logout")() @@ -148,7 +152,7 @@ func (i *identity) Logout(ctx context.Context) error { return err } logoutErr := i.definition.logout(ctx, i.name, i.realm, i.sessionSettings(), func(call *invocation) error { - _, err := call.handle.Identity.Logout(ctx, &pluginv1.IdentityRequest{Invocation: call.request, Kind: i.Kind(), Name: i.name, Principal: principal, Spec: spec, Realm: i.realm}) + _, err := call.handle.Identity.Logout(call.ctx, &pluginv1.IdentityRequest{Invocation: call.request, Kind: i.Kind(), Name: i.name, Principal: principal, Spec: spec, Realm: i.realm}) return err }) return errors.Join(logoutErr, i.materializer.Logout(context.WithoutCancel(ctx))) diff --git a/pkg/plugin/adapter/auth/interactions.go b/pkg/plugin/adapter/auth/interactions.go new file mode 100644 index 00000000000..d919171ede2 --- /dev/null +++ b/pkg/plugin/adapter/auth/interactions.go @@ -0,0 +1,73 @@ +package auth + +import ( + "context" + "net/url" + "regexp" + "strings" + + errUtils "github.com/cloudposse/atmos/errors" + "github.com/cloudposse/atmos/pkg/perf" + pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" + "github.com/cloudposse/atmos/pkg/ui" +) + +const ( + deviceCodeInteractionKind = "device_code" + maxVerificationURILength = 2048 +) + +var publicDeviceCode = regexp.MustCompile(`^[A-Za-z0-9-]{4,32}$`) + +// interactionHandler permits a typed device prompt only on the host's UI channel. +// Arbitrary titles, progress text, and complete/token-bearing URLs are never rendered. +func interactionHandler(ctx context.Context, interactive bool, present func(string, string)) func(*pluginv1.Interaction) error { + return func(event *pluginv1.Interaction) error { + if err := ctx.Err(); err != nil { + return err + } + if !interactive || present == nil { + return errUtils.ErrPluginInteractionRequired + } + uri, code, err := parseDeviceCode(event) + if err != nil { + return err + } + present(uri, code) + return nil + } +} + +// parseDeviceCode accepts only the device prompt fields that are safe to render +// and rejects unsupported interaction kinds or malformed protocol data. +func parseDeviceCode(event *pluginv1.Interaction) (string, string, error) { + if event.GetKind() != deviceCodeInteractionKind { + return "", "", errUtils.ErrPluginInteractionRequired + } + fields := event.GetFields() + uri, code := fields["verification_uri"], fields["user_code"] + if len(fields) != 2 || !publicDeviceCode.MatchString(code) || !publicVerificationURI(uri) { + return "", "", errUtils.ErrPluginProtocol + } + return uri, code, nil +} + +// publicVerificationURI permits printable HTTPS verification links without +// credentials, queries or fragments. Complete authorization URLs use the browser API. +func publicVerificationURI(raw string) bool { + if len(raw) > maxVerificationURILength || strings.IndexFunc(raw, func(r rune) bool { return r < '!' || r > '~' }) >= 0 { + return false + } + parsed, err := url.Parse(raw) + if err != nil { + return false + } + return parsed.Scheme == "https" && parsed.Hostname() != "" && parsed.User == nil && + parsed.RawQuery == "" && !parsed.ForceQuery && parsed.Fragment == "" +} + +func presentDeviceCode(uri, code string) { + defer perf.Track(nil, "auth.presentDeviceCode")() + + ui.Infof("Open %s and enter code %s.", uri, code) +} diff --git a/pkg/plugin/adapter/auth/interactions_test.go b/pkg/plugin/adapter/auth/interactions_test.go new file mode 100644 index 00000000000..280b9378194 --- /dev/null +++ b/pkg/plugin/adapter/auth/interactions_test.go @@ -0,0 +1,151 @@ +package auth + +import ( + "bytes" + "context" + "fmt" + "io" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" + + errUtils "github.com/cloudposse/atmos/errors" + "github.com/cloudposse/atmos/pkg/data" + iolib "github.com/cloudposse/atmos/pkg/io" + pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" + "github.com/cloudposse/atmos/pkg/ui" +) + +//go:generate go run go.uber.org/mock/mockgen -destination mock_interaction_streams_test.go -package auth github.com/cloudposse/atmos/pkg/io Streams + +func deviceInteraction() *pluginv1.Interaction { + return &pluginv1.Interaction{Kind: deviceCodeInteractionKind, Title: "synthetic-private-title", Fields: map[string]string{ + "verification_uri": "https://issuer.example/device", "user_code": "ABCD-EFGH", + }} +} + +func TestDeviceInteractionOnlyPresentsValidatedFields(t *testing.T) { + t.Parallel() + var output strings.Builder + handler := interactionHandler(t.Context(), true, func(uri, code string) { fmt.Fprintf(&output, "%s %s", uri, code) }) + require.NoError(t, handler(deviceInteraction())) + assert.Equal(t, "https://issuer.example/device ABCD-EFGH", output.String()) + assert.NotContains(t, output.String(), "synthetic-private") +} + +func TestDeviceInteractionRejectsUnsafeOrUnknownData(t *testing.T) { + t.Parallel() + for _, change := range []func(*pluginv1.Interaction){ + func(p *pluginv1.Interaction) { p.Kind = "synthetic-private-kind" }, + func(p *pluginv1.Interaction) { p.Fields["debug"] = "synthetic-private-debug" }, + func(p *pluginv1.Interaction) { delete(p.Fields, "user_code") }, + func(p *pluginv1.Interaction) { p.Fields["user_code"] = "BAD\nCODE" }, + func(p *pluginv1.Interaction) { p.Fields["user_code"] = strings.Repeat("A", 33) }, + func(p *pluginv1.Interaction) { p.Fields["verification_uri"] = "http://issuer.example/device" }, + func(p *pluginv1.Interaction) { + p.Fields["verification_uri"] = "https://issuer.example/%zz-synthetic-private" + }, + func(p *pluginv1.Interaction) { + p.Fields["verification_uri"] = "https://user:synthetic-private@issuer.example/device" + }, + func(p *pluginv1.Interaction) { + p.Fields["verification_uri"] = "https://issuer.example/device?token=synthetic-private" + }, + func(p *pluginv1.Interaction) { + p.Fields["verification_uri"] = "https://issuer.example/device#synthetic-private" + }, + func(p *pluginv1.Interaction) { p.Fields["verification_uri"] = "https://issuer.example/device\x1b[31m" }, + func(p *pluginv1.Interaction) { + p.Fields["verification_uri"] = strings.Repeat("x", maxVerificationURILength+1) + }, + } { + prompt := deviceInteraction() + change(prompt) + handler := interactionHandler(t.Context(), true, func(string, string) { t.Error("invalid prompt reached UI") }) + err := handler(prompt) + require.Error(t, err) + assert.NotContains(t, err.Error(), "synthetic-private") + } +} + +func TestDeviceInteractionRequiresAnActiveInteractiveInvocation(t *testing.T) { + t.Parallel() + never := func(string, string) { t.Error("unavailable invocation reached UI") } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + require.ErrorIs(t, interactionHandler(ctx, true, never)(deviceInteraction()), context.Canceled) + require.ErrorIs(t, interactionHandler(t.Context(), false, never)(deviceInteraction()), errUtils.ErrPluginInteractionRequired) + require.ErrorIs(t, interactionHandler(t.Context(), true, nil)(deviceInteraction()), errUtils.ErrPluginInteractionRequired) +} + +func TestCredentialStreamPresentsDeviceCodeBeforeReturningCredentials(t *testing.T) { + t.Parallel() + prompt := &pluginv1.AuthenticateEvent{Event: &pluginv1.AuthenticateEvent_Interaction{Interaction: deviceInteraction()}} + credentials := &pluginv1.Credentials{Type: "oidc/v1"} + result := &pluginv1.AuthenticateEvent{Event: &pluginv1.AuthenticateEvent_Result{Result: credentials}} + stream := NewMockcredentialStream(gomock.NewController(t)) + gomock.InOrder( + stream.EXPECT().Recv().Return(prompt, nil), + stream.EXPECT().Recv().Return(result, nil), + stream.EXPECT().Recv().Return(nil, io.EOF), + ) + presented := false + actual, err := receiveCredentials(stream, interactionHandler(t.Context(), true, func(string, string) { presented = true })) + require.NoError(t, err) + assert.True(t, presented) + assert.Equal(t, credentials, actual) +} + +func TestCredentialStreamPresentsDeviceCodeOnStderrBeforeResult(t *testing.T) { + t.Setenv("ATMOS_FORCE_TTY", "false") + t.Setenv("ATMOS_FORCE_COLOR", "false") + t.Setenv("NO_COLOR", "1") + var stdout, stderr bytes.Buffer + previous := iolib.GetContext() + streams := NewMockStreams(gomock.NewController(t)) + streams.EXPECT().RawOutput().Return(&stdout).AnyTimes() + streams.EXPECT().RawError().Return(&stderr).AnyTimes() + ctx, err := iolib.NewContext(iolib.WithStreams(streams)) + require.NoError(t, err) + data.InitWriter(ctx) + ui.InitFormatter(ctx) + t.Cleanup(func() { + data.InitWriter(previous) + ui.InitFormatter(previous) + }) + + credentials := &pluginv1.Credentials{Type: "oidc/v1"} + stream := NewMockcredentialStream(gomock.NewController(t)) + gomock.InOrder( + stream.EXPECT().Recv().Return(&pluginv1.AuthenticateEvent{ + Event: &pluginv1.AuthenticateEvent_Interaction{Interaction: deviceInteraction()}, + }, nil), + stream.EXPECT().Recv().DoAndReturn(func() (*pluginv1.AuthenticateEvent, error) { + require.Contains(t, stderr.String(), "https://issuer.example/device", "the URI must reach stderr before the credential result") + require.Contains(t, stderr.String(), "ABCD-EFGH", "the user code must reach stderr before the credential result") + require.NotContains(t, stderr.String(), "synthetic-private") + require.Empty(t, stdout.String(), "the device prompt must leave the data channel empty") + return &pluginv1.AuthenticateEvent{Event: &pluginv1.AuthenticateEvent_Result{Result: credentials}}, nil + }), + stream.EXPECT().Recv().Return(nil, io.EOF), + ) + actual, err := receiveCredentials(stream, interactionHandler(t.Context(), true, presentDeviceCode)) + require.NoError(t, err) + require.Equal(t, credentials, actual) + require.Empty(t, stdout.String()) +} + +func TestCredentialStreamRejectsUnrenderableOrRepeatedInteractions(t *testing.T) { + t.Parallel() + for _, interactive := range []bool{false, true} { + stream := NewMockcredentialStream(gomock.NewController(t)) + prompt := &pluginv1.AuthenticateEvent{Event: &pluginv1.AuthenticateEvent_Interaction{Interaction: deviceInteraction()}} + stream.EXPECT().Recv().Return(prompt, nil).Times(map[bool]int{false: 1, true: 2}[interactive]) + actual, err := receiveCredentials(stream, interactionHandler(t.Context(), interactive, func(string, string) {})) + require.ErrorIs(t, err, errUtils.ErrPluginInteractionRequired) + assert.Nil(t, actual) + } +} diff --git a/pkg/plugin/adapter/auth/invoke.go b/pkg/plugin/adapter/auth/invoke.go index 164ca5c99ff..6f41988c3fc 100644 --- a/pkg/plugin/adapter/auth/invoke.go +++ b/pkg/plugin/adapter/auth/invoke.go @@ -20,10 +20,13 @@ import ( const maxCredentialEvents = 1024 type invocation struct { + ctx context.Context handle *native.Handle request *pluginv1.Invocation } +// invoke runs a namespaced plugin transaction and passes the invocation's +// deadline-bound context to the operation. func (d *Definition) invoke(ctx context.Context, name, realm string, settings map[string]any, operation func(*invocation) error) error { namespace, err := d.sessionNamespace(name, realm, settings) if err != nil { @@ -45,7 +48,7 @@ func (d *Definition) invoke(ctx context.Context, name, realm string, settings ma scope.Secrets = d.Services.Secrets(name, settings) } return translateError(handle.Invoke(ctx, scope, func(ctx context.Context, request *pluginv1.Invocation) error { - return operation(&invocation{handle: handle, request: request}) + return operation(&invocation{ctx: ctx, handle: handle, request: request}) })) }) } @@ -58,13 +61,26 @@ func toStruct(value map[string]any) (*structpb.Struct, error) { return result, nil } -func receiveCredentials(stream grpc.ServerStreamingClient[pluginv1.AuthenticateEvent]) (*pluginv1.Credentials, error) { +// receiveCredentials handles at most one interaction and requires the credential +// result to terminate the bounded event stream. +func receiveCredentials(stream grpc.ServerStreamingClient[pluginv1.AuthenticateEvent], interact func(*pluginv1.Interaction) error) (*pluginv1.Credentials, error) { // Progress is bounded and not blindly printed: plugin text can contain secrets. + interactionSeen := false for range maxCredentialEvents { event, err := stream.Recv() if err != nil { return nil, errors.Join(errUtils.ErrPluginProtocol, err) } + if prompt := event.GetInteraction(); prompt != nil { + if interactionSeen || interact == nil { + return nil, errUtils.ErrPluginInteractionRequired + } + interactionSeen = true + if err := interact(prompt); err != nil { + return nil, err + } + continue + } if event.GetResult() == nil { continue } @@ -100,8 +116,10 @@ func translateError(err error) error { } } +// translateLocalError preserves recognized protocol and cancellation causes +// while hiding unclassified plugin error details. func translateLocalError(err error) error { - for _, cause := range []error{errUtils.ErrPluginProtocol, context.Canceled, context.DeadlineExceeded} { + for _, cause := range []error{errUtils.ErrPluginProtocol, errUtils.ErrPluginInteractionRequired, context.Canceled, context.DeadlineExceeded} { if errors.Is(err, cause) { return cause } diff --git a/pkg/plugin/adapter/auth/invoke_test.go b/pkg/plugin/adapter/auth/invoke_test.go index 654dd3ad371..c44ecea8ba5 100644 --- a/pkg/plugin/adapter/auth/invoke_test.go +++ b/pkg/plugin/adapter/auth/invoke_test.go @@ -45,7 +45,7 @@ func TestCredentialStreamRequiresOneTerminalResult(t *testing.T) { calls = append(calls, stream.EXPECT().Recv().Return(nil, tt.terminal)) } gomock.InOrder(calls...) - actual, err := receiveCredentials(stream) + actual, err := receiveCredentials(stream, nil) if tt.valid { require.NoError(t, err) assert.Equal(t, result, actual) @@ -61,6 +61,7 @@ func TestTranslateErrorPreservesSafeClassification(t *testing.T) { t.Parallel() for _, tt := range []struct{ input, target error }{ {nil, nil}, + {errUtils.ErrPluginInteractionRequired, errUtils.ErrPluginInteractionRequired}, {status.Error(codes.FailedPrecondition, "secret"), errUtils.ErrPluginInteractionRequired}, {status.Error(codes.Canceled, "secret"), context.Canceled}, {status.Error(codes.DeadlineExceeded, "secret"), context.DeadlineExceeded}, diff --git a/pkg/plugin/adapter/auth/main_test.go b/pkg/plugin/adapter/auth/main_test.go index 12c46f91587..f5218509a12 100644 --- a/pkg/plugin/adapter/auth/main_test.go +++ b/pkg/plugin/adapter/auth/main_test.go @@ -34,6 +34,9 @@ type providerFixture struct { } func (*providerFixture) Authenticate(request *pluginv1.ProviderRequest, stream grpc.ServerStreamingServer[pluginv1.AuthenticateEvent]) error { + if request.Name == authDeadlineFixtureName { + return hangUntilAuthDeadline(stream.Context(), request.Invocation) + } if request.Name != "corporate" || request.Kind != "plugin/test" || request.Realm != "fixture" { return status.Error(codes.InvalidArgument, "provider configuration was not forwarded") } @@ -46,7 +49,10 @@ func (*providerFixture) Authenticate(request *pluginv1.ProviderRequest, stream g }}}) } -func (*providerFixture) Logout(context.Context, *pluginv1.ProviderRequest) (*emptypb.Empty, error) { +func (*providerFixture) Logout(ctx context.Context, request *pluginv1.ProviderRequest) (*emptypb.Empty, error) { + if request.Name == authDeadlineFixtureName { + return nil, hangUntilAuthDeadline(ctx, request.Invocation) + } return &emptypb.Empty{}, os.WriteFile("provider-logout", []byte("revoked"), 0o600) } @@ -57,6 +63,9 @@ type identityFixture struct { func (*identityFixture) Authenticate(request *pluginv1.IdentityAuthenticateRequest, stream grpc.ServerStreamingServer[pluginv1.AuthenticateEvent]) error { identity := request.Identity + if identity.Name == authDeadlineFixtureName { + return hangUntilAuthDeadline(stream.Context(), identity.Invocation) + } if identity.Name != "broker" || identity.Kind != "plugin/broker" || identity.Realm != "fixture" || identity.Principal.GetFields()["endpoint"].GetStringValue() != "https://broker.example" || identity.Spec.GetFields()["tenant"].GetStringValue() != "test" || @@ -75,6 +84,9 @@ func (*identityFixture) Authenticate(request *pluginv1.IdentityAuthenticateReque }}}) } -func (*identityFixture) Logout(context.Context, *pluginv1.IdentityRequest) (*emptypb.Empty, error) { +func (*identityFixture) Logout(ctx context.Context, request *pluginv1.IdentityRequest) (*emptypb.Empty, error) { + if request.Name == authDeadlineFixtureName { + return nil, hangUntilAuthDeadline(ctx, request.Invocation) + } return &emptypb.Empty{}, os.WriteFile("identity-logout", []byte("revoked"), 0o600) } diff --git a/pkg/plugin/adapter/auth/mock_interaction_streams_test.go b/pkg/plugin/adapter/auth/mock_interaction_streams_test.go new file mode 100644 index 00000000000..3a083066cbf --- /dev/null +++ b/pkg/plugin/adapter/auth/mock_interaction_streams_test.go @@ -0,0 +1,111 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/cloudposse/atmos/pkg/io (interfaces: Streams) +// +// Generated by this command: +// +// mockgen -destination mock_interaction_streams_test.go -package auth github.com/cloudposse/atmos/pkg/io Streams +// + +// Package auth is a generated GoMock package. +package auth + +import ( + io "io" + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockStreams is a mock of Streams interface. +type MockStreams struct { + ctrl *gomock.Controller + recorder *MockStreamsMockRecorder + isgomock struct{} +} + +// MockStreamsMockRecorder is the mock recorder for MockStreams. +type MockStreamsMockRecorder struct { + mock *MockStreams +} + +// NewMockStreams creates a new mock instance. +func NewMockStreams(ctrl *gomock.Controller) *MockStreams { + mock := &MockStreams{ctrl: ctrl} + mock.recorder = &MockStreamsMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockStreams) EXPECT() *MockStreamsMockRecorder { + return m.recorder +} + +// Error mocks base method. +func (m *MockStreams) Error() io.Writer { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Error") + ret0, _ := ret[0].(io.Writer) + return ret0 +} + +// Error indicates an expected call of Error. +func (mr *MockStreamsMockRecorder) Error() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*MockStreams)(nil).Error)) +} + +// Input mocks base method. +func (m *MockStreams) Input() io.Reader { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Input") + ret0, _ := ret[0].(io.Reader) + return ret0 +} + +// Input indicates an expected call of Input. +func (mr *MockStreamsMockRecorder) Input() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Input", reflect.TypeOf((*MockStreams)(nil).Input)) +} + +// Output mocks base method. +func (m *MockStreams) Output() io.Writer { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Output") + ret0, _ := ret[0].(io.Writer) + return ret0 +} + +// Output indicates an expected call of Output. +func (mr *MockStreamsMockRecorder) Output() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Output", reflect.TypeOf((*MockStreams)(nil).Output)) +} + +// RawError mocks base method. +func (m *MockStreams) RawError() io.Writer { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RawError") + ret0, _ := ret[0].(io.Writer) + return ret0 +} + +// RawError indicates an expected call of RawError. +func (mr *MockStreamsMockRecorder) RawError() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RawError", reflect.TypeOf((*MockStreams)(nil).RawError)) +} + +// RawOutput mocks base method. +func (m *MockStreams) RawOutput() io.Writer { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RawOutput") + ret0, _ := ret[0].(io.Writer) + return ret0 +} + +// RawOutput indicates an expected call of RawOutput. +func (mr *MockStreamsMockRecorder) RawOutput() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RawOutput", reflect.TypeOf((*MockStreams)(nil).RawOutput)) +} diff --git a/pkg/plugin/adapter/auth/provider.go b/pkg/plugin/adapter/auth/provider.go index 732af8a1d5f..a8276cc5391 100644 --- a/pkg/plugin/adapter/auth/provider.go +++ b/pkg/plugin/adapter/auth/provider.go @@ -94,11 +94,11 @@ func (p *provider) Authenticate(ctx context.Context) (types.ICredentials, error) } var result types.ICredentials err = p.definition.invoke(ctx, p.name, p.realm, p.sessionSettings(), func(call *invocation) error { - stream, err := call.handle.Provider.Authenticate(ctx, &pluginv1.ProviderRequest{Invocation: call.request, Name: p.name, Kind: p.Kind(), Spec: spec, Realm: p.realm}) + stream, err := call.handle.Provider.Authenticate(call.ctx, &pluginv1.ProviderRequest{Invocation: call.request, Name: p.name, Kind: p.Kind(), Spec: spec, Realm: p.realm}) if err != nil { return err } - envelope, err := receiveCredentials(stream) + envelope, err := receiveCredentials(stream, interactionHandler(call.ctx, call.request.GetInteractive(), presentDeviceCode)) if err != nil { return err } @@ -117,7 +117,7 @@ func (p *provider) Logout(ctx context.Context) error { return err } return p.definition.logout(ctx, p.name, p.realm, p.sessionSettings(), func(call *invocation) error { - _, err := call.handle.Provider.Logout(ctx, &pluginv1.ProviderRequest{Invocation: call.request, Name: p.name, Kind: p.Kind(), Spec: spec, Realm: p.realm}) + _, err := call.handle.Provider.Logout(call.ctx, &pluginv1.ProviderRequest{Invocation: call.request, Name: p.name, Kind: p.Kind(), Spec: spec, Realm: p.realm}) return err }) } diff --git a/website/docs/cli/configuration/plugins.mdx b/website/docs/cli/configuration/plugins.mdx index 1481afebdca..3038f49b2ce 100644 --- a/website/docs/cli/configuration/plugins.mdx +++ b/website/docs/cli/configuration/plugins.mdx @@ -216,6 +216,24 @@ Authentication rereads the stores. Five-minute credentials allow reuse within th The package version is independent of the Atmos version. Releases contain all six supported platforms in an OCI index; installation downloads only your platform's executable payload. See the [official package release guide](https://github.com/cloudposse/atmos/tree/main/plugins) for publication and public GHCR setup. +### Native authentication interactions + +Native providers and identities can emit one typed `Interaction` event before their credential result. Atmos displays a `device_code` interaction only when the host invocation is interactive. Its `fields` must contain exactly `verification_uri` and `user_code`: + +```json +{ + "kind": "device_code", + "fields": { + "verification_uri": "https://login.example.com/device", + "user_code": "ABCD-EFGH" + } +} +``` + +The verification URI must be a public HTTPS URL without user information, query parameters, fragments, whitespace, or terminal controls, and at most 2048 bytes. The user code must contain 4–32 ASCII letters, digits, or hyphens. Atmos writes the validated URL and code to its UI channel on stderr. It does not display plugin-supplied titles or progress messages. Unknown interaction kinds, repeated interactions, extra fields, and invalid values stop authentication. Noninteractive invocations cannot request a device prompt. + +Use the host Browser API to open a complete authorization URL with query parameters. Do not put complete authorization URLs, tokens, or private diagnostics in an interaction's public fields. Authentication RPCs enforce the host invocation's cancellation and deadline. + ### Native identity schema selection Native identity exports validate `principal` by default. Plugin authors whose configuration belongs in `spec` can select that target in their `plugin.yaml` capability metadata: