From 81e7e7c5d0a00231869e7d9f358ed1970a402b33 Mon Sep 17 00:00:00 2001 From: Noel Date: Wed, 11 Nov 2026 17:30:37 +0100 Subject: [PATCH 1/5] fix(auth): display native device prompts and enforce invocation deadlines --- pkg/plugin/adapter/auth/cancellation_test.go | 7 +- pkg/plugin/adapter/auth/identity.go | 6 +- pkg/plugin/adapter/auth/interactions.go | 71 +++++++++++++ pkg/plugin/adapter/auth/interactions_test.go | 103 +++++++++++++++++++ pkg/plugin/adapter/auth/invoke.go | 18 +++- pkg/plugin/adapter/auth/invoke_test.go | 3 +- pkg/plugin/adapter/auth/provider.go | 6 +- website/docs/cli/configuration/plugins.mdx | 18 ++++ 8 files changed, 219 insertions(+), 13 deletions(-) create mode 100644 pkg/plugin/adapter/auth/interactions.go create mode 100644 pkg/plugin/adapter/auth/interactions_test.go diff --git a/pkg/plugin/adapter/auth/cancellation_test.go b/pkg/plugin/adapter/auth/cancellation_test.go index 489963ac88e..25044f0a0e3 100644 --- a/pkg/plugin/adapter/auth/cancellation_test.go +++ b/pkg/plugin/adapter/auth/cancellation_test.go @@ -72,9 +72,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)) diff --git a/pkg/plugin/adapter/auth/identity.go b/pkg/plugin/adapter/auth/identity.go index 5a722cb9fb9..22dfded147d 100644 --- a/pkg/plugin/adapter/auth/identity.go +++ b/pkg/plugin/adapter/auth/identity.go @@ -109,13 +109,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 } @@ -148,7 +148,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..70bf072adc7 --- /dev/null +++ b/pkg/plugin/adapter/auth/interactions.go @@ -0,0 +1,71 @@ +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 + } +} + +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 +} + +// A public verification URI is distinct from a complete authorization URL. +// Browser API calls can open URLs with queries without writing them to the UI. +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..43519217f68 --- /dev/null +++ b/pkg/plugin/adapter/auth/interactions_test.go @@ -0,0 +1,103 @@ +package auth + +import ( + "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" + pluginv1 "github.com/cloudposse/atmos/pkg/plugin/proto/atmos/plugin/v1" +) + +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://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 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..40ca71d7378 100644 --- a/pkg/plugin/adapter/auth/invoke.go +++ b/pkg/plugin/adapter/auth/invoke.go @@ -20,6 +20,7 @@ import ( const maxCredentialEvents = 1024 type invocation struct { + ctx context.Context handle *native.Handle request *pluginv1.Invocation } @@ -45,7 +46,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 +59,24 @@ func toStruct(value map[string]any) (*structpb.Struct, error) { return result, nil } -func receiveCredentials(stream grpc.ServerStreamingClient[pluginv1.AuthenticateEvent]) (*pluginv1.Credentials, error) { +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 } @@ -101,7 +113,7 @@ func translateError(err error) error { } 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/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: From 193c264f796139b4c3dd30f8d7ade38194e726b3 Mon Sep 17 00:00:00 2001 From: Noel Date: Wed, 11 Nov 2026 18:18:43 +0100 Subject: [PATCH 2/5] Cover auth RPC deadlines and real device prompt output --- pkg/plugin/adapter/auth/cancellation_test.go | 85 ++++++++++++++ pkg/plugin/adapter/auth/interactions_test.go | 45 +++++++ pkg/plugin/adapter/auth/main_test.go | 16 ++- .../auth/mock_interaction_streams_test.go | 111 ++++++++++++++++++ 4 files changed, 255 insertions(+), 2 deletions(-) create mode 100644 pkg/plugin/adapter/auth/mock_interaction_streams_test.go diff --git a/pkg/plugin/adapter/auth/cancellation_test.go b/pkg/plugin/adapter/auth/cancellation_test.go index 25044f0a0e3..1781e6c4f10 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{} @@ -92,3 +99,81 @@ 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/interactions_test.go b/pkg/plugin/adapter/auth/interactions_test.go index 43519217f68..f6e72c11fdb 100644 --- a/pkg/plugin/adapter/auth/interactions_test.go +++ b/pkg/plugin/adapter/auth/interactions_test.go @@ -1,6 +1,7 @@ package auth import ( + "bytes" "context" "fmt" "io" @@ -12,9 +13,14 @@ import ( "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", @@ -90,6 +96,45 @@ func TestCredentialStreamPresentsDeviceCodeBeforeReturningCredentials(t *testing 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} { 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)) +} From 9525f5eef8d4291d16aa94e2a33825596cd78f7e Mon Sep 17 00:00:00 2001 From: Noel Date: Wed, 11 Nov 2026 19:07:35 +0100 Subject: [PATCH 3/5] test(auth): reject malformed device verification URLs --- pkg/plugin/adapter/auth/interactions_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/pkg/plugin/adapter/auth/interactions_test.go b/pkg/plugin/adapter/auth/interactions_test.go index f6e72c11fdb..32203c2dd38 100644 --- a/pkg/plugin/adapter/auth/interactions_test.go +++ b/pkg/plugin/adapter/auth/interactions_test.go @@ -45,6 +45,7 @@ func TestDeviceInteractionRejectsUnsafeOrUnknownData(t *testing.T) { 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" }, From a500097231a7e410ba1da0563fa354f8088051a9 Mon Sep 17 00:00:00 2001 From: Noel Date: Thu, 12 Nov 2026 14:45:37 +0100 Subject: [PATCH 4/5] docs(auth): document native credential interactions --- pkg/plugin/adapter/auth/identity.go | 4 ++++ pkg/plugin/adapter/auth/interactions.go | 6 ++++-- pkg/plugin/adapter/auth/invoke.go | 6 ++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/pkg/plugin/adapter/auth/identity.go b/pkg/plugin/adapter/auth/identity.go index 22dfded147d..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")() @@ -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")() diff --git a/pkg/plugin/adapter/auth/interactions.go b/pkg/plugin/adapter/auth/interactions.go index 70bf072adc7..d919171ede2 100644 --- a/pkg/plugin/adapter/auth/interactions.go +++ b/pkg/plugin/adapter/auth/interactions.go @@ -38,6 +38,8 @@ func interactionHandler(ctx context.Context, interactive bool, present func(stri } } +// 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 @@ -50,8 +52,8 @@ func parseDeviceCode(event *pluginv1.Interaction) (string, string, error) { return uri, code, nil } -// A public verification URI is distinct from a complete authorization URL. -// Browser API calls can open URLs with queries without writing them to the UI. +// 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 diff --git a/pkg/plugin/adapter/auth/invoke.go b/pkg/plugin/adapter/auth/invoke.go index 40ca71d7378..6f41988c3fc 100644 --- a/pkg/plugin/adapter/auth/invoke.go +++ b/pkg/plugin/adapter/auth/invoke.go @@ -25,6 +25,8 @@ type invocation struct { 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 { @@ -59,6 +61,8 @@ func toStruct(value map[string]any) (*structpb.Struct, error) { return result, nil } +// 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 @@ -112,6 +116,8 @@ 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, errUtils.ErrPluginInteractionRequired, context.Canceled, context.DeadlineExceeded} { if errors.Is(err, cause) { From 885b2a61bdcc9136ee5a3793e5056138f731f71f Mon Sep 17 00:00:00 2001 From: Noel Date: Thu, 12 Nov 2026 22:16:47 +0100 Subject: [PATCH 5/5] style(auth): format native adapter regression tests --- pkg/plugin/adapter/auth/cancellation_test.go | 6 ++++-- pkg/plugin/adapter/auth/interactions_test.go | 4 +++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/pkg/plugin/adapter/auth/cancellation_test.go b/pkg/plugin/adapter/auth/cancellation_test.go index 1781e6c4f10..09cdb358d6c 100644 --- a/pkg/plugin/adapter/auth/cancellation_test.go +++ b/pkg/plugin/adapter/auth/cancellation_test.go @@ -158,8 +158,10 @@ func TestAuthRPCsEnforceInvocationDeadline(t *testing.T) { 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)} + 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) diff --git a/pkg/plugin/adapter/auth/interactions_test.go b/pkg/plugin/adapter/auth/interactions_test.go index 32203c2dd38..280b9378194 100644 --- a/pkg/plugin/adapter/auth/interactions_test.go +++ b/pkg/plugin/adapter/auth/interactions_test.go @@ -45,7 +45,9 @@ func TestDeviceInteractionRejectsUnsafeOrUnknownData(t *testing.T) { 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://issuer.example/%zz-synthetic-private" + }, func(p *pluginv1.Interaction) { p.Fields["verification_uri"] = "https://user:synthetic-private@issuer.example/device" },