Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
94 changes: 91 additions & 3 deletions pkg/plugin/adapter/auth/cancellation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down Expand Up @@ -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))
Expand All @@ -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")
})
}
}
10 changes: 7 additions & 3 deletions pkg/plugin/adapter/auth/identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")()

Expand All @@ -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
}
Expand All @@ -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")()

Expand All @@ -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)))
Expand Down
73 changes: 73 additions & 0 deletions pkg/plugin/adapter/auth/interactions.go
Original file line number Diff line number Diff line change
@@ -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)
}
151 changes: 151 additions & 0 deletions pkg/plugin/adapter/auth/interactions_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading