carlos / platform Public

grouprollaws: run framed box verbs through Session Manager

Run calls ssm:StartSession with the config's document and the framed
command, then session-manager-plugin on a raw pseudo-terminal in its own
session, with the answer only in AWS_SSM_START_SESSION_RESPONSE and the
SDK-resolved SSM endpoint in argv. It keeps session_output's 4 MiB cap,
per-verb bounds, session-id reporting and process-group SIGKILL.
CancelSession is ssm:TerminateSession; plugins at or below 1.2.497.0
are refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 182fe4aaf3f72d3e09997bc85dcb242465808ce6 parent a493072
13 files changed, +1,533 −3
  • internal/grouprollaws/config_test.go +11 −1
  • internal/grouprollaws/group.go +1 −0
  • internal/grouprollaws/group_test.go +5 −2
  • internal/grouprollaws/pty_darwin.go +56 −0
  • internal/grouprollaws/pty_linux.go +44 −0
  • internal/grouprollaws/pty_other.go +22 −0
  • internal/grouprollaws/pty_unix.go +163 −0
  • internal/grouprollaws/session.go +392 −0
  • internal/grouprollaws/session_test.go +677 −0
  • internal/grouprollaws/testdata/fakeplugin/main.go +147 −0
  • internal/grouprollaws/testdata/fakeplugin/termios_darwin.go +5 −0
  • internal/grouprollaws/testdata/fakeplugin/termios_linux.go +5 −0
  • region_ha_boundary_test.go +5 −0

Intent

Human

<task-notification> <task-id>a0293bed8650bafbf</task-id> <tool-use-id>toolu_0148ezP4qjcnLsqzt663v7DF</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/a0293bed8650bafbf.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: AWS adapter" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>The open path is closed: the credential clients the SDK builds while loading (STS assume-role, SSO and OIDC) now read their answers under the same 2 s read bound and 4 MiB cap as the service clients. It is committed as `a493072c` on `group-roll-verb` (not pushed). The package tests, `TestRegionHA`, `go vet` and the darwin/windows cross-builds pass. **I did not do it the way you asked.** Passing the bounded client in through `WithHTTPClient` would break `AWS_CA_BUNDLE`, which the spec allow-lists. The SDK fails the whole config load if a CA bundle is set and the client is not its own buildable type (`config@v1.32.6/resolve.go:57-60`). Instead, the reading limits are now SDK middleware, handed to `LoadDefaultConfig` as an API option. The SDK installs those options before it builds the credential clients, and each credential client copies the config, so all of them carry it. The service clients get it too, and the timeouts are unchanged from round 1. **Tests:** a new `TestAssumeRoleAnswersAreBounded` uses an assume-role profile with `role_session_name` set and static source keys. - When STS sends headers and then stalls the body, the first `Describe` fails as `Uncertain api` with timeout after about 2 s. - When STS returns an error body over 4 MiB, it fails as `Uncertain api` with `output_too_large`. - In both cases the only request sent is `AssumeRole`, and nothing reaches Auto Scaling. I also broke the code on purpose four ways (no middleware in the loader, none on the service clients, middleware placed outside the decoder, no freeze), and each one fails a test. The adapter's tests now take about 4 s because of two 2-second stall tests. The fix report is appended to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-group-roll-verb/.superpowers/sdd/2026-11-09-group-roll-verb/task-3-report.md`.</result> <usage><subagent_tokens>262628</subagent_tokens><tool_uses>10</tool_uses><duration_ms>250500</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bn8i4a3ak</task-id> <tool-use-id>toolu_01TV3rZtSuXfEFjbnMwdZHf6</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/bn8i4a3ak.output</output-file> <status>completed</status> <summary>Background command "Wait for re-review round 2" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 22.6 g CO₂e (2,899,204 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on group-roll-verb, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/grouprollaws/config_test.go b/internal/grouprollaws/config_test.go
index 5c3048f16..7f805c706 100644
--- a/internal/grouprollaws/config_test.go
+++ b/internal/grouprollaws/config_test.go
@@ -28,9 +28,19 @@ func TestMain(m *testing.M) {
runHelper(name)
os.Exit(0)
}
- os.Exit(m.Run())
+ cleanup := func() {}
+ if buildFakePlugin != nil {
+ cleanup = buildFakePlugin()
+ }
+ code := m.Run()
+ cleanup()
+ os.Exit(code)
}
+// buildFakePlugin builds the fake session-manager-plugin where the session
+// tests run (session_test.go); it returns the cleanup.
+var buildFakePlugin func() (cleanup func())
+
type helperOutput struct {
NewError string `json:"new_error,omitempty"`
AccessKey string `json:"access_key,omitempty"`
diff --git a/internal/grouprollaws/group.go b/internal/grouprollaws/group.go
index b57ad7946..272bdd975 100644
--- a/internal/grouprollaws/group.go
+++ b/internal/grouprollaws/group.go
@@ -40,6 +40,7 @@ type Adapter struct {
ec2 *ec2.Client
ssm *ssm.Client
sts *sts.Client
+ plugin pluginCheck // session.go: the plugin's path and version, once
}
func newAdapter(cfg aws.Config, c grouproll.Config) *Adapter {
diff --git a/internal/grouprollaws/group_test.go b/internal/grouprollaws/group_test.go
index 98b8c89c6..6fba4faf3 100644
--- a/internal/grouprollaws/group_test.go
+++ b/internal/grouprollaws/group_test.go
@@ -514,8 +514,11 @@ func TestWriteShapes(t *testing.T) {
names = append(names, typ.Method(i).Name)
}
sort.Strings(names)
- want := []string{"Activities", "CallerIdentity", "Describe", "Hook", "Instance", "Membership", "Online",
- "Park", "RaiseDesired", "SetMinimum", "Targets", "TemplateRelease", "Terminate", "Unpark"}
+ // Run, CancelSession and CheckPlugin (session.go) are the Session
+ // Manager transport: none touches the group's capacity.
+ want := []string{"Activities", "CallerIdentity", "CancelSession", "CheckPlugin", "Describe", "Hook",
+ "Instance", "Membership", "Online", "Park", "RaiseDesired", "Run", "SetMinimum", "Targets",
+ "TemplateRelease", "Terminate", "Unpark"}
if !reflect.DeepEqual(names, want) {
t.Fatalf("Adapter methods = %v\nwant %v", names, want)
}
diff --git a/internal/grouprollaws/pty_darwin.go b/internal/grouprollaws/pty_darwin.go
new file mode 100644
index 000000000..a50ded5b4
--- /dev/null
+++ b/internal/grouprollaws/pty_darwin.go
@@ -0,0 +1,56 @@
+//go:build darwin
+
+package grouprollaws
+
+import (
+ "bytes"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+)
+
+const (
+ ioctlGetTermios = unix.TIOCGETA
+ ioctlSetTermiosFlush = unix.TIOCSETAF // tcsetattr(TCSAFLUSH)
+)
+
+// openPTY opens a pseudo-terminal pair with posix_openpt semantics:
+// /dev/ptmx, then grantpt (TIOCPTYGRANT), unlockpt (TIOCPTYUNLK) and
+// ptsname (TIOCPTYGNAME), and the slave set raw as Python's tty.setraw
+// does.
+func openPTY() (*pty, error) {
+ master, err := unix.Open("/dev/ptmx", unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, err
+ }
+ p := &pty{master: master, slave: -1}
+ if err := unix.IoctlSetInt(master, unix.TIOCPTYGRANT, 0); err != nil {
+ p.close()
+ return nil, err
+ }
+ if err := unix.IoctlSetInt(master, unix.TIOCPTYUNLK, 0); err != nil {
+ p.close()
+ return nil, err
+ }
+ var name [128]byte
+ if _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(master), uintptr(unix.TIOCPTYGNAME),
+ uintptr(unsafe.Pointer(&name[0]))); errno != 0 {
+ p.close()
+ return nil, errno
+ }
+ n := bytes.IndexByte(name[:], 0)
+ if n < 0 {
+ n = len(name)
+ }
+ path := string(name[:n])
+ if p.slave, err = unix.Open(path, unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0); err != nil {
+ p.slave = -1
+ p.close()
+ return nil, err
+ }
+ if err := setRaw(p.slave); err != nil {
+ p.close()
+ return nil, err
+ }
+ return p, nil
+}
diff --git a/internal/grouprollaws/pty_linux.go b/internal/grouprollaws/pty_linux.go
new file mode 100644
index 000000000..e48f86aed
--- /dev/null
+++ b/internal/grouprollaws/pty_linux.go
@@ -0,0 +1,44 @@
+//go:build linux
+
+package grouprollaws
+
+import (
+ "strconv"
+
+ "golang.org/x/sys/unix"
+)
+
+const (
+ ioctlGetTermios = unix.TCGETS
+ ioctlSetTermiosFlush = unix.TCSETSF // tcsetattr(TCSAFLUSH)
+)
+
+// openPTY opens a pseudo-terminal pair: /dev/ptmx, unlocked with
+// TIOCSPTLCK (grantpt is a no-op on devpts), the slave named by TIOCGPTN,
+// and the slave set raw as Python's tty.setraw does.
+func openPTY() (*pty, error) {
+ master, err := unix.Open("/dev/ptmx", unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, err
+ }
+ p := &pty{master: master, slave: -1}
+ if err := unix.IoctlSetPointerInt(master, unix.TIOCSPTLCK, 0); err != nil {
+ p.close()
+ return nil, err
+ }
+ n, err := unix.IoctlGetInt(master, unix.TIOCGPTN)
+ if err != nil {
+ p.close()
+ return nil, err
+ }
+ if p.slave, err = unix.Open("/dev/pts/"+strconv.Itoa(n), unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0); err != nil {
+ p.slave = -1
+ p.close()
+ return nil, err
+ }
+ if err := setRaw(p.slave); err != nil {
+ p.close()
+ return nil, err
+ }
+ return p, nil
+}
diff --git a/internal/grouprollaws/pty_other.go b/internal/grouprollaws/pty_other.go
new file mode 100644
index 000000000..628357032
--- /dev/null
+++ b/internal/grouprollaws/pty_other.go
@@ -0,0 +1,22 @@
+//go:build !(linux || darwin)
+
+package grouprollaws
+
+import (
+ "context"
+ "time"
+
+ "github.com/carlosframework/platform/internal/grouproll"
+)
+
+// pty is unsupported here: the session transport needs a Unix
+// pseudo-terminal and process groups.
+type pty struct{}
+
+func openPTY() (*pty, error) { return nil, grouproll.Refusal{Key: "windows"} }
+
+func (p *pty) close() {}
+
+func (p *pty) run(context.Context, string, []string, []string, time.Time, func(string)) ([]byte, error) {
+ return nil, grouproll.Refusal{Key: "windows"}
+}
diff --git a/internal/grouprollaws/pty_unix.go b/internal/grouprollaws/pty_unix.go
new file mode 100644
index 000000000..de8461b37
--- /dev/null
+++ b/internal/grouprollaws/pty_unix.go
@@ -0,0 +1,163 @@
+//go:build linux || darwin
+
+package grouprollaws
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "syscall"
+ "time"
+ "unsafe"
+
+ "golang.org/x/sys/unix"
+
+ "github.com/carlosframework/platform/internal/grouproll"
+)
+
+// pty is one pseudo-terminal pair. The plugin gets the slave as stdin,
+// stdout and stderr; the master is read and never written, so stdin stays
+// open and silent (the plugin exits on EOF).
+type pty struct {
+ master, slave int
+}
+
+func (p *pty) close() {
+ if p.master >= 0 {
+ _ = unix.Close(p.master)
+ p.master = -1
+ }
+ if p.slave >= 0 {
+ _ = unix.Close(p.slave)
+ p.slave = -1
+ }
+}
+
+// setRaw is Python's tty.setraw (cfmakeraw) with TCSAFLUSH.
+func setRaw(fd int) error {
+ t, err := unix.IoctlGetTermios(fd, ioctlGetTermios)
+ if err != nil {
+ return err
+ }
+ t.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.IGNCR | unix.INLCR | unix.ICRNL | unix.INPCK |
+ unix.ISTRIP | unix.IXON | unix.PARMRK
+ t.Oflag &^= unix.OPOST
+ t.Cflag &^= unix.PARENB | unix.CSIZE
+ t.Cflag |= unix.CS8
+ t.Lflag &^= unix.ECHO | unix.ECHOE | unix.ECHOK | unix.ECHONL | unix.ICANON | unix.IEXTEN |
+ unix.ISIG | unix.NOFLSH | unix.TOSTOP
+ t.Cc[unix.VMIN] = 1
+ t.Cc[unix.VTIME] = 0
+ return unix.IoctlSetTermios(fd, ioctlSetTermiosFlush, t)
+}
+
+// fdSetSize is FD_SETSIZE: select cannot wait on a higher descriptor.
+const fdSetSize = int(unsafe.Sizeof(unix.FdSet{})) * 8
+
+// readable waits up to d for the master to have data or reach its end, as
+// the script's select.select([master], [], [], ...).
+func readable(fd int, d time.Duration) (bool, error) {
+ if fd >= fdSetSize {
+ return false, unix.EBADF
+ }
+ var set unix.FdSet
+ set.Zero()
+ set.Set(fd)
+ tv := unix.NsecToTimeval(d.Nanoseconds())
+ n, err := unix.Select(fd+1, &set, nil, nil, &tv)
+ if err != nil {
+ return false, err
+ }
+ return n > 0 && set.IsSet(fd), nil
+}
+
+// run is the script's session_output: start the plugin on the slave in a
+// new session and process group, read the master until it ends or end
+// passes, report each session id banner as it appears, then reap. Whatever
+// happens, an unreaped plugin's group is killed with SIGKILL before its
+// leader is reaped, so the group id cannot be reused meanwhile.
+func (p *pty) run(ctx context.Context, path string, argv, env []string, end time.Time, report func(string)) ([]byte, error) {
+ slave := os.NewFile(uintptr(p.slave), "pty")
+ p.slave = -1
+ cmd := &exec.Cmd{
+ Path: path,
+ Args: append([]string{pluginName}, argv...),
+ Env: env,
+ Stdin: slave,
+ Stdout: slave,
+ Stderr: slave,
+ SysProcAttr: &syscall.SysProcAttr{Setsid: true},
+ }
+ err := cmd.Start()
+ slave.Close()
+ if err != nil {
+ return nil, grouproll.Uncertain{Key: "remote"}
+ }
+ done := make(chan error, 1)
+ go func() { done <- cmd.Wait() }()
+ reaped := false
+ kill := func() {
+ if !reaped {
+ _ = unix.Kill(-cmd.Process.Pid, unix.SIGKILL)
+ <-done
+ reaped = true
+ }
+ }
+ defer kill()
+
+ var body []byte
+ buf := make([]byte, 65536)
+ from := 0
+ for time.Now().Before(end) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ ready, err := readable(p.master, min(200*time.Millisecond, max(0, time.Until(end))))
+ if errors.Is(err, unix.EINTR) {
+ continue
+ }
+ if err != nil {
+ return nil, grouproll.Uncertain{Key: "remote"}
+ }
+ if !ready {
+ continue
+ }
+ n, err := unix.Read(p.master, buf)
+ if errors.Is(err, unix.EINTR) {
+ continue
+ }
+ if err != nil || n <= 0 {
+ // EIO once every slave descriptor is closed: the end.
+ break
+ }
+ body = append(body, buf[:n]...)
+ if len(body) > outputCap {
+ return nil, grouproll.Refusal{Key: "remote"}
+ }
+ from = scanSessions(body, from, report)
+ }
+ if !time.Now().Before(end) {
+ return nil, grouproll.Uncertain{Key: "remote", Timeout: true}
+ }
+ timer := time.NewTimer(max(10*time.Millisecond, time.Until(end)))
+ defer timer.Stop()
+ select {
+ case err := <-done:
+ reaped = true
+ if err != nil {
+ var exit *exec.ExitError
+ if errors.As(err, &exit) {
+ return nil, grouproll.Refusal{Key: "remote"}
+ }
+ return nil, grouproll.Uncertain{Key: "remote"}
+ }
+ return body, nil
+ case <-timer.C:
+ kill()
+ return nil, grouproll.Uncertain{Key: "remote", Timeout: true}
+ case <-ctx.Done():
+ kill()
+ return nil, ctx.Err()
+ }
+}
diff --git a/internal/grouprollaws/session.go b/internal/grouprollaws/session.go
new file mode 100644
index 000000000..97b8c158c
--- /dev/null
+++ b/internal/grouprollaws/session.go
@@ -0,0 +1,392 @@
+package grouprollaws
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "os"
+ "os/exec"
+ "regexp"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/ssm"
+
+ "github.com/carlosframework/platform/internal/grouproll"
+)
+
+var _ grouproll.Box = (*Adapter)(nil)
+
+// pluginName is the Session Manager plugin the AWS CLI runs.
+const pluginName = "session-manager-plugin"
+
+// pluginFloor is LAST_PLUGIN_VERSION_WITHOUT_ENV_VAR in the AWS CLI's
+// awscli/customizations/sessionmanager.py (aws-cli develop, read
+// 2026-11-10). The CLI hands the StartSession answer over in the
+// environment only to a plugin strictly newer than this (the version
+// check is not inclusive); older plugins get it in argv, token and all, so
+// they are refused (spec §5.3, §7 V8).
+const pluginFloor = "1.2.497.0"
+
+// pluginFloorShown is the version the plugin_old text names as the oldest
+// accepted ("Version {floor} or later"): the first four-part version above
+// pluginFloor, since pluginFloor itself is refused.
+const pluginFloorShown = "1.2.497.1"
+
+// responseVariable is the CLI's DEFAULT_SSM_ENV_NAME: the plugin reads the
+// StartSession answer from the variable argv names.
+const responseVariable = "AWS_SSM_START_SESSION_RESPONSE"
+
+// sessionTimeouts are the script's SESSION_TIMEOUTS (:228-230): each verb's
+// local bound, the box-side bound plus a margin. Other verbs get
+// defaultSessionTimeout, the script's invoke(timeout=15).
+var sessionTimeouts = map[string]time.Duration{
+ "prepare": 360 * time.Second,
+ "apply": 990 * time.Second,
+ "rollback": 990 * time.Second,
+ "drain": (grouproll.DrainBound + 90) * time.Second,
+ "edge-stop": (grouproll.EdgeStopBound + 90) * time.Second,
+ "fence-clear": 60 * time.Second,
+ "drain-cancel": (grouproll.CancelBound + 90) * time.Second,
+}
+
+const defaultSessionTimeout = 15 * time.Second
+
+func sessionBound(verb string) time.Duration {
+ if d, ok := sessionTimeouts[verb]; ok {
+ return d
+ }
+ return defaultSessionTimeout
+}
+
+var (
+ // sessionBanner is the plugin's banner as session_output scraped it
+ // while reading; sessionBannerAny is the request branch's scan of the
+ // whole text afterwards.
+ sessionBanner = regexp.MustCompile(`Starting session with SessionId: ([A-Za-z0-9_-]+)\r?\n`)
+ sessionBannerAny = regexp.MustCompile(`Starting session with SessionId: ([A-Za-z0-9_-]+)`)
+ bannerPrefix = []byte("Starting session with SessionId: ")
+ sessionID = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
+ pluginVersion = regexp.MustCompile(`^[0-9]+(\.[0-9]+)*$`)
+ plainVersion = regexp.MustCompile(`^[0-9A-Za-z.+_-]{1,64}$`)
+)
+
+// pluginCheck caches the plugin's path and version check for one Adapter.
+type pluginCheck struct {
+ mu sync.Mutex
+ done bool
+ path string
+ err error
+}
+
+// pluginEnvironment is the plugin's environment: the spec §4 allow-list and
+// the three fixed values, whatever the process environment holds now.
+func (a *Adapter) pluginEnvironment() []string {
+ return append(allowedEnvironment(os.Environ()),
+ "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS=true",
+ "AWS_EC2_METADATA_DISABLED=true",
+ "AWS_PROFILE="+a.c.Profile)
+}
+
+// CheckPlugin finds session-manager-plugin on PATH and refuses one whose
+// --version is not strictly above pluginFloor. It runs the plugin once per
+// Adapter; the engine calls it at plan, and Run calls it before any
+// session.
+func (a *Adapter) CheckPlugin(ctx context.Context) error {
+ _, err := a.checkedPlugin(ctx)
+ return err
+}
+
+func (a *Adapter) checkedPlugin(ctx context.Context) (string, error) {
+ a.plugin.mu.Lock()
+ defer a.plugin.mu.Unlock()
+ if a.plugin.done {
+ return a.plugin.path, a.plugin.err
+ }
+ path, err := checkPlugin(ctx, a.pluginEnvironment())
+ if ctx.Err() != nil {
+ // An interrupted check is not an answer; the next call asks again.
+ return "", ctx.Err()
+ }
+ a.plugin.done, a.plugin.path, a.plugin.err = true, path, err
+ return path, err
+}
+
+func checkPlugin(ctx context.Context, env []string) (string, error) {
+ path, err := exec.LookPath(pluginName)
+ if err != nil {
+ return "", grouproll.Refusal{Key: "plugin_missing"}
+ }
+ vctx, cancel := context.WithTimeout(ctx, defaultSessionTimeout)
+ defer cancel()
+ out := &cappedBuffer{max: 4096}
+ cmd := exec.CommandContext(vctx, path, "--version")
+ cmd.Env = env
+ cmd.Stdout = out
+ runErr := cmd.Run()
+ version := strings.TrimSpace(out.String())
+ if runErr != nil || !versionAbove(version, pluginFloor) {
+ shown := version
+ if !plainVersion.MatchString(shown) {
+ if len(shown) > 64 {
+ shown = shown[:64]
+ }
+ shown = strconv.QuoteToASCII(shown)
+ }
+ return "", grouproll.Refusal{Key: "plugin_old", Args: map[string]string{
+ "version": shown, "floor": pluginFloorShown}}
+ }
+ return path, nil
+}
+
+// versionAbove reports whether dotted numeric version v is strictly greater
+// than floor; missing components count as zero. Anything else is not.
+func versionAbove(v, floor string) bool {
+ parse := func(s string) ([]uint64, bool) {
+ if !pluginVersion.MatchString(s) {
+ return nil, false
+ }
+ var parts []uint64
+ for _, p := range strings.Split(s, ".") {
+ n, err := strconv.ParseUint(p, 10, 64)
+ if err != nil {
+ return nil, false
+ }
+ parts = append(parts, n)
+ }
+ return parts, true
+ }
+ have, ok := parse(v)
+ want, _ := parse(floor)
+ if !ok {
+ return false
+ }
+ for i := 0; i < len(have) || i < len(want); i++ {
+ var h, w uint64
+ if i < len(have) {
+ h = have[i]
+ }
+ if i < len(want) {
+ w = want[i]
+ }
+ if h != w {
+ return h > w
+ }
+ }
+ return false
+}
+
+type cappedBuffer struct {
+ buf bytes.Buffer
+ max int
+}
+
+func (b *cappedBuffer) Write(p []byte) (int, error) {
+ if room := b.max - b.buf.Len(); room > 0 {
+ if len(p) > room {
+ b.buf.Write(p[:room])
+ } else {
+ b.buf.Write(p)
+ }
+ }
+ return len(p), nil
+}
+
+func (b *cappedBuffer) String() string { return b.buf.String() }
+
+// pluginEndpoint is the SSM endpoint the SDK resolves for the client's
+// region and partition, as the CLI passes client.meta.endpoint_url. The
+// client has no configured endpoint (newAdapter clears it), so these are
+// the parameters its own requests resolve with.
+func (a *Adapter) pluginEndpoint(ctx context.Context) (string, error) {
+ o := a.ssm.Options()
+ ep, err := o.EndpointResolverV2.ResolveEndpoint(ctx, ssm.EndpointParameters{
+ Region: aws.String(o.Region),
+ UseFIPS: aws.Bool(o.EndpointOptions.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled),
+ UseDualStack: aws.Bool(o.EndpointOptions.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled),
+ })
+ if err != nil {
+ return "", grouproll.Refusal{Key: "config_invalid"}
+ }
+ return ep.URI.String(), nil
+}
+
+// startRequest is the StartSession request as the plugin gets it in argv
+// (the CLI's json.dumps(parameters)). It holds no secret.
+type startRequest struct {
+ Target string `json:"Target"`
+ DocumentName string `json:"DocumentName"`
+ Parameters map[string][]string `json:"Parameters"`
+}
+
+// startResponse is the StartSession answer the plugin reads from
+// responseVariable. TokenValue is a session credential: it goes only into
+// the child's environment, never into argv, an error or a log.
+type startResponse struct {
+ SessionId string `json:"SessionId"`
+ TokenValue string `json:"TokenValue"`
+ StreamUrl string `json:"StreamUrl"`
+}
+
+func compactJSON(v any) (string, error) {
+ var b bytes.Buffer
+ enc := json.NewEncoder(&b)
+ enc.SetEscapeHTML(false)
+ if err := enc.Encode(v); err != nil {
+ return "", err
+ }
+ return strings.TrimSuffix(b.String(), "\n"), nil
+}
+
+func newNonce() string {
+ var b [16]byte
+ _, _ = rand.Read(b[:]) // never fails (crypto/rand)
+ return hex.EncodeToString(b[:])
+}
+
+// Run runs one framed verb on member iid through Session Manager: the
+// script's AWS.request session branch (:963-989) over session_output
+// (:733-784). It calls ssm:StartSession with the config's document and the
+// framed command, then session-manager-plugin on a fresh pseudo-terminal
+// in its own session and process group, reading until the plugin ends or
+// the verb's local bound. Each session id is reported to onSession once,
+// synchronously, as soon as it is seen: the StartSession answer's first,
+// then any other the plugin prints.
+//
+// Errors: the 4 MiB output cap and a nonzero plugin exit are
+// Refusal(remote); the bound is Uncertain{remote, Timeout} after the
+// plugin's process group is killed; a failure to run the plugin is
+// Uncertain(remote); a failed StartSession is Uncertain(api); Ctrl-C (ctx)
+// kills the group and returns ctx.Err(). The output is then ParseFramed's.
+func (a *Adapter) Run(ctx context.Context, iid, verb string, args grouproll.BoxArgs, onSession func(id string)) (grouproll.BoxResult, error) {
+ var none grouproll.BoxResult
+ if err := requireIID(iid, "record"); err != nil {
+ return none, err
+ }
+ nonce := newNonce()
+ command, err := grouproll.RemoteCommand(verb, args, nonce)
+ if err != nil {
+ return none, err
+ }
+ path, err := a.checkedPlugin(ctx)
+ if err != nil {
+ return none, err
+ }
+ endpoint, err := a.pluginEndpoint(ctx)
+ if err != nil {
+ return none, err
+ }
+ request := startRequest{Target: iid, DocumentName: a.c.Document,
+ Parameters: map[string][]string{"command": {command}}}
+ requestJSON, err := compactJSON(request)
+ if err != nil {
+ return none, grouproll.Refusal{Key: "record"}
+ }
+
+ // The terminal first: failing here costs no session.
+ term, err := openPTY()
+ if err != nil {
+ var r grouproll.Refusal
+ if errors.As(err, &r) {
+ return none, r
+ }
+ return none, grouproll.Uncertain{Key: "remote"}
+ }
+ defer term.close()
+
+ end := time.Now().Add(sessionBound(verb))
+ seen := map[string]bool{}
+ last := ""
+ report := func(id string) {
+ if !seen[id] {
+ seen[id] = true
+ last = id
+ if onSession != nil {
+ onSession(id)
+ }
+ }
+ }
+
+ out, err := call(ctx, func(c context.Context) (*ssm.StartSessionOutput, error) {
+ return a.ssm.StartSession(c, &ssm.StartSessionInput{
+ Target: aws.String(iid),
+ DocumentName: aws.String(a.c.Document),
+ Parameters: request.Parameters,
+ })
+ })
+ if err != nil {
+ return none, err
+ }
+ if out.SessionId == nil || !sessionID.MatchString(*out.SessionId) {
+ return none, malformed()
+ }
+ report(*out.SessionId)
+ if out.TokenValue == nil || out.StreamUrl == nil {
+ return none, malformed()
+ }
+ responseJSON, err := compactJSON(startResponse{SessionId: *out.SessionId,
+ TokenValue: *out.TokenValue, StreamUrl: *out.StreamUrl})
+ if err != nil {
+ return none, malformed()
+ }
+
+ argv := []string{responseVariable, a.c.Region, "StartSession", a.c.Profile, requestJSON, endpoint}
+ env := append(a.pluginEnvironment(), responseVariable+"="+responseJSON)
+ body, err := term.run(ctx, path, argv, env, end, report)
+ if err != nil {
+ return none, err
+ }
+ // The script decoded the bytes before anything else; bytes that do not
+ // decode reached main as the record text.
+ if !utf8.Valid(body) {
+ return none, grouproll.Refusal{Key: "record"}
+ }
+ text := string(body)
+ if ids := sessionBannerAny.FindAllStringSubmatch(text, -1); len(ids) == 1 && ids[0][1] != last {
+ last = ids[0][1]
+ if onSession != nil {
+ onSession(last)
+ }
+ }
+ return grouproll.ParseFramed(text, nonce, verb)
+}
+
+// scanSessions reports every complete banner in body[from:] and returns
+// where the next scan starts: at a banner still waiting for its line end,
+// or just short of the end, so a banner split across reads is found once
+// it completes. It finds what the script's findall over the whole body
+// found, without rescanning megabytes on every read.
+func scanSessions(body []byte, from int, report func(string)) int {
+ next := from
+ for _, m := range sessionBanner.FindAllSubmatchIndex(body[from:], -1) {
+ report(string(body[from+m[2] : from+m[3]]))
+ next = from + m[1]
+ }
+ if i := bytes.LastIndex(body[next:], bannerPrefix); i >= 0 {
+ return next + i
+ }
+ if tail := len(body) - len(bannerPrefix) + 1; tail > next {
+ return tail
+ }
+ return next
+}
+
+// CancelSession ends session id (ssm:TerminateSession), as the script's
+// terminate_session op does after a cut. A malformed id is refused with no
+// call.
+func (a *Adapter) CancelSession(ctx context.Context, id string) error {
+ if !sessionID.MatchString(id) {
+ return grouproll.Refusal{Key: "remote"}
+ }
+ _, err := call(ctx, func(c context.Context) (*ssm.TerminateSessionOutput, error) {
+ return a.ssm.TerminateSession(c, &ssm.TerminateSessionInput{SessionId: aws.String(id)})
+ })
+ return err
+}
diff --git a/internal/grouprollaws/session_test.go b/internal/grouprollaws/session_test.go
new file mode 100644
index 000000000..d41e9e364
--- /dev/null
+++ b/internal/grouprollaws/session_test.go
@@ -0,0 +1,677 @@
+//go:build linux || darwin
+
+package grouprollaws
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "regexp"
+ "runtime"
+ "sort"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/service/ssm"
+
+ "github.com/carlosframework/platform/internal/grouproll"
+)
+
+// fakePluginDir holds the fake session-manager-plugin TestMain built.
+var fakePluginDir string
+
+func init() {
+ buildFakePlugin = func() func() {
+ dir, err := os.MkdirTemp(os.Getenv("TMPDIR"), "fakeplugin-")
+ if err != nil {
+ panic(err)
+ }
+ cmd := exec.Command("go", "build", "-o", filepath.Join(dir, pluginName), "./testdata/fakeplugin")
+ cmd.Stdout, cmd.Stderr = os.Stderr, os.Stderr
+ if err := cmd.Run(); err != nil {
+ os.RemoveAll(dir)
+ panic(fmt.Sprintf("building the fake plugin: %v", err))
+ }
+ fakePluginDir = dir
+ return func() { os.RemoveAll(dir) }
+ }
+}
+
+const (
+ testSession = "op-0a1b2c3d4e5f60718"
+ testToken = "TOKEN-c2VjcmV0LXNlc3Npb24tdG9rZW4tZm9yLXRlc3Rz"
+ testStream = "wss://ssmmessages.eu-west-1.amazonaws.com/v1/data-channel/op-0a1b2c3d4e5f60718?role=publish_subscribe"
+ statusBody = `{"v":1,"iid":"i-0123456789abcdef0"}`
+)
+
+func startAnswer() string {
+ return `{"SessionId":"` + testSession + `","TokenValue":"` + testToken + `","StreamUrl":"` + testStream + `"}`
+}
+
+type fakeControl struct {
+ Version string `json:"version,omitempty"`
+ Mode string `json:"mode,omitempty"`
+ Body string `json:"body,omitempty"`
+ Code string `json:"code,omitempty"`
+ Exit int `json:"exit,omitempty"`
+ FloodTotal int `json:"flood_total,omitempty"`
+ BannerID string `json:"banner_id,omitempty"`
+}
+
+type fakeRecord struct {
+ Argv []string `json:"argv"`
+ Env []string `json:"env"`
+ PID int `json:"pid"`
+ Child int `json:"child"`
+ SID int `json:"sid"`
+ PGID int `json:"pgid"`
+ StdinTTY bool `json:"stdin_tty"`
+ StdinEOF bool `json:"stdin_eof"`
+ Raw bool `json:"raw"`
+}
+
+// withFakePlugin puts the fake plugin first on PATH and gives it a fresh
+// TMPDIR holding its instructions. It returns that directory.
+func withFakePlugin(t *testing.T, c fakeControl) string {
+ t.Helper()
+ if fakePluginDir == "" {
+ t.Fatal("the fake plugin was not built")
+ }
+ dir := t.TempDir()
+ t.Setenv("TMPDIR", dir)
+ t.Setenv("PATH", fakePluginDir+string(os.PathListSeparator)+os.Getenv("PATH"))
+ setControl(t, dir, c)
+ return dir
+}
+
+func setControl(t *testing.T, dir string, c fakeControl) {
+ t.Helper()
+ raw, _ := json.Marshal(c)
+ if err := os.WriteFile(filepath.Join(dir, "fakeplugin.json"), raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func readRecord(t *testing.T, dir string) fakeRecord {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join(dir, "fakeplugin-record.json"))
+ if err != nil {
+ t.Fatalf("the fake plugin left no record: %v", err)
+ }
+ var r fakeRecord
+ if err := json.Unmarshal(raw, &r); err != nil {
+ t.Fatal(err)
+ }
+ return r
+}
+
+func versionCalls(t *testing.T, dir string) []string {
+ t.Helper()
+ raw, err := os.ReadFile(filepath.Join(dir, "fakeplugin-version.log"))
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return strings.Split(strings.TrimSuffix(string(raw), "\n"), "\n")
+}
+
+// shortBound sets the status verb's local bound for one test.
+func shortBound(t *testing.T, d time.Duration) {
+ t.Helper()
+ old, had := sessionTimeouts["status"]
+ sessionTimeouts["status"] = d
+ t.Cleanup(func() {
+ if had {
+ sessionTimeouts["status"] = old
+ } else {
+ delete(sessionTimeouts, "status")
+ }
+ })
+}
+
+type observer struct{ ids []string }
+
+func (o *observer) seen(id string) { o.ids = append(o.ids, id) }
+
+func sessionAdapter(t *testing.T, region string) (*Adapter, *recorder) {
+ t.Helper()
+ rec := newRecorder().on("StartSession", startAnswer()).on("TerminateSession", `{"SessionId":"`+testSession+`"}`)
+ cfg := aws.Config{
+ Region: region,
+ Credentials: credentials.NewStaticCredentialsProvider("AKIATEST", "secret", ""),
+ HTTPClient: rec,
+ RetryMaxAttempts: 1,
+ }
+ c := testConfig()
+ c.Region = region
+ return newAdapter(cfg, c), rec
+}
+
+func TestSessionReadsFrame(t *testing.T) {
+ dir := withFakePlugin(t, fakeControl{Body: statusBody})
+ a, rec := sessionAdapter(t, "eu-west-1")
+ var o observer
+ r, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, o.seen)
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ want := map[string]any{"v": int64(1), "iid": testIID}
+ if r.Verb != "status" || !reflect.DeepEqual(r.Value, want) {
+ t.Fatalf("result %#v, want status %v", r, want)
+ }
+ if !reflect.DeepEqual(o.ids, []string{testSession}) {
+ t.Fatalf("sessions reported %q, want exactly %q once", o.ids, testSession)
+ }
+ if got := rec.actions(); !reflect.DeepEqual(got, []string{"StartSession"}) {
+ t.Fatalf("requests %v", got)
+ }
+ f := readRecord(t, dir)
+ if !f.StdinTTY || !f.Raw {
+ t.Errorf("stdin is a terminal %v, raw %v; want a raw pseudo-terminal", f.StdinTTY, f.Raw)
+ }
+ if f.StdinEOF {
+ t.Error("stdin reached EOF; it must stay open and silent")
+ }
+ if f.SID != f.PID || f.PGID != f.PID {
+ t.Errorf("plugin pid %d sid %d pgid %d; want a new session and process group", f.PID, f.SID, f.PGID)
+ }
+}
+
+func TestSessionScrapesLateBanner(t *testing.T) {
+ // The StartSession answer's id is reported before the plugin runs; a
+ // banner naming another id is reported as it appears, and a banner with
+ // no line end only by the scan of the whole text afterwards (the
+ // script's request branch). Each id once.
+ const other = "op-ffffffffffffffff1"
+ for _, mode := range []string{"", "latebanner"} {
+ withFakePlugin(t, fakeControl{Body: statusBody, Mode: mode, BannerID: other})
+ a, _ := sessionAdapter(t, "eu-west-1")
+ var o observer
+ if _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, o.seen); err != nil {
+ t.Fatalf("%q: %v", mode, err)
+ }
+ if !reflect.DeepEqual(o.ids, []string{testSession, other}) {
+ t.Fatalf("%q: sessions reported %q", mode, o.ids)
+ }
+ }
+}
+
+func TestScanSessionsSplitReads(t *testing.T) {
+ text := []byte("noise\nStarting session with SessionId: op-1\r\nmore Starting session with SessionId: op-2\nStarting session with SessionId: op-1\n")
+ for step := 1; step <= len(text); step++ {
+ var got []string
+ from := 0
+ for end := step; ; end += step {
+ if end > len(text) {
+ end = len(text)
+ }
+ from = scanSessions(text[:end], from, func(id string) { got = append(got, id) })
+ if end == len(text) {
+ break
+ }
+ }
+ // The script's findall over the whole body, without its seen set.
+ if !reflect.DeepEqual(got, []string{"op-1", "op-2", "op-1"}) {
+ t.Fatalf("reads of %d bytes: %q", step, got)
+ }
+ }
+}
+
+func processGone(pid int) bool {
+ if err := syscall.Kill(pid, 0); errors.Is(err, syscall.ESRCH) {
+ return true
+ }
+ if runtime.GOOS != "linux" {
+ return false
+ }
+ raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
+ if err != nil {
+ return true
+ }
+ // A zombie waiting for its new parent has nothing left running.
+ i := bytes.LastIndexByte(raw, ')')
+ return i > 0 && len(raw) > i+2 && raw[i+2] == 'Z'
+}
+
+func waitGone(t *testing.T, what string, pid int) {
+ t.Helper()
+ if pid <= 0 {
+ t.Fatalf("%s pid %d not recorded", what, pid)
+ }
+ deadline := time.Now().Add(3 * time.Second)
+ for !processGone(pid) {
+ if time.Now().After(deadline) {
+ _ = syscall.Kill(pid, syscall.SIGKILL)
+ t.Fatalf("%s %d is still running after the bound", what, pid)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+func TestSessionBoundKillsGroup(t *testing.T) {
+ dir := withFakePlugin(t, fakeControl{Mode: "hang"})
+ shortBound(t, 1500*time.Millisecond)
+ a, _ := sessionAdapter(t, "eu-west-1")
+ var o observer
+ start := time.Now()
+ _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, o.seen)
+ elapsed := time.Since(start)
+ u := uncertainKey(t, err)
+ if u.Key != "remote" || !u.Timeout {
+ t.Fatalf("error %#v, want Uncertain{remote, timeout}", u)
+ }
+ if elapsed < 1500*time.Millisecond || elapsed > 5*time.Second {
+ t.Fatalf("Run took %v, want about the 1.5 s bound", elapsed)
+ }
+ f := readRecord(t, dir)
+ // Both ignore SIGTERM; the group's SIGKILL takes both.
+ waitGone(t, "plugin", f.PID)
+ waitGone(t, "plugin child", f.Child)
+ if !reflect.DeepEqual(o.ids, []string{testSession}) {
+ t.Fatalf("sessions reported %q, want %q", o.ids, testSession)
+ }
+}
+
+func TestSessionContextCancelKillsGroup(t *testing.T) {
+ dir := withFakePlugin(t, fakeControl{Mode: "hang"})
+ a, _ := sessionAdapter(t, "eu-west-1")
+ c, cancel := context.WithCancel(ctx)
+ time.AfterFunc(700*time.Millisecond, cancel)
+ _, err := a.Run(c, testIID, "status", grouproll.BoxArgs{}, func(string) {})
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("error %v, want context.Canceled", err)
+ }
+ f := readRecord(t, dir)
+ waitGone(t, "plugin", f.PID)
+ waitGone(t, "plugin child", f.Child)
+}
+
+func TestSessionOutputCap(t *testing.T) {
+ t.Run("over", func(t *testing.T) {
+ withFakePlugin(t, fakeControl{Mode: "flood", Body: statusBody, FloodTotal: 4<<20 + 1})
+ a, _ := sessionAdapter(t, "eu-west-1")
+ _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, func(string) {})
+ if k := refusalKey(t, err); k != "remote" {
+ t.Fatalf("refusal %q, want remote", k)
+ }
+ })
+ t.Run("exactly", func(t *testing.T) {
+ withFakePlugin(t, fakeControl{Mode: "flood", Body: statusBody, FloodTotal: 4 << 20})
+ a, _ := sessionAdapter(t, "eu-west-1")
+ r, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, func(string) {})
+ if err != nil {
+ t.Fatalf("4 MiB exactly: %v", err)
+ }
+ if r.Verb != "status" {
+ t.Fatalf("result %#v", r)
+ }
+ })
+}
+
+func TestSessionPluginExitNonzero(t *testing.T) {
+ withFakePlugin(t, fakeControl{Mode: "exit", Exit: 3, Body: statusBody})
+ a, _ := sessionAdapter(t, "eu-west-1")
+ _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, func(string) {})
+ if k := refusalKey(t, err); k != "remote" {
+ t.Fatalf("refusal %q, want remote", k)
+ }
+}
+
+func TestSessionFrameParsed(t *testing.T) {
+ // The verb's own refusal (frame code 3) is ParseFramed's remote.
+ withFakePlugin(t, fakeControl{Body: statusBody, Code: "3"})
+ a, _ := sessionAdapter(t, "eu-west-1")
+ _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, func(string) {})
+ if k := refusalKey(t, err); k != "remote" {
+ t.Fatalf("refusal %q, want remote", k)
+ }
+}
+
+func TestSessionStartFailure(t *testing.T) {
+ dir := withFakePlugin(t, fakeControl{Body: statusBody})
+ a, rec := sessionAdapter(t, "eu-west-1")
+ rec.responses["StartSession"] = []canned{{status: 500}}
+ var o observer
+ _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, o.seen)
+ if u := uncertainKey(t, err); u.Key != "api" {
+ t.Fatalf("error %#v, want Uncertain api", u)
+ }
+ if len(o.ids) != 0 {
+ t.Fatalf("sessions reported %q", o.ids)
+ }
+ if _, err := os.Stat(filepath.Join(dir, "fakeplugin-record.json")); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("the plugin ran without a session")
+ }
+}
+
+func TestPluginMissing(t *testing.T) {
+ empty := t.TempDir()
+ t.Setenv("PATH", empty)
+ a, rec := sessionAdapter(t, "eu-west-1")
+ for _, err := range []error{a.CheckPlugin(ctx), func() error {
+ _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, func(string) {})
+ return err
+ }()} {
+ if k := refusalKey(t, err); k != "plugin_missing" {
+ t.Fatalf("refusal %q, want plugin_missing", k)
+ }
+ if !strings.Contains(err.Error(), "session-manager-plugin") {
+ t.Fatalf("refusal %q does not name the plugin", err)
+ }
+ }
+ if len(rec.requests()) != 0 {
+ t.Fatalf("requests sent: %v", rec.actions())
+ }
+}
+
+var commandNonce = regexp.MustCompile(`([0-9a-f]{32}):BEGIN`)
+
+func TestSessionStartArgs(t *testing.T) {
+ withFakePlugin(t, fakeControl{Body: statusBody})
+ a, rec := sessionAdapter(t, "eu-west-1")
+ args := grouproll.BoxArgs{SHA256: strings.Repeat("ab", 32)}
+ if _, err := a.Run(ctx, testIID, "prepare", args, func(string) {}); err != nil {
+ t.Fatal(err)
+ }
+ reqs := rec.requests()
+ if len(reqs) != 1 || reqs[0].Action != "StartSession" {
+ t.Fatalf("requests %v", rec.actions())
+ }
+ body := reqs[0].JSON
+ if body["Target"] != testIID || body["DocumentName"] != "carlos-group-roll" {
+ t.Fatalf("StartSession target %v document %v", body["Target"], body["DocumentName"])
+ }
+ params, _ := body["Parameters"].(map[string]any)
+ cmds, _ := params["command"].([]any)
+ if len(params) != 1 || len(cmds) != 1 {
+ t.Fatalf("Parameters %v, want exactly {command: [one]}", params)
+ }
+ cmd, _ := cmds[0].(string)
+ m := commandNonce.FindStringSubmatch(cmd)
+ if m == nil {
+ t.Fatalf("command %q has no nonce", cmd)
+ }
+ want, err := grouproll.RemoteCommand("prepare", args, m[1])
+ if err != nil || cmd != want {
+ t.Fatalf("command\n%q\nwant RemoteCommand\n%q (%v)", cmd, want, err)
+ }
+ if len(body) != 3 {
+ t.Fatalf("StartSession body %v carries more than target, document and parameters", body)
+ }
+}
+
+func TestPluginArgs(t *testing.T) {
+ for _, region := range []string{"eu-west-1", "cn-north-1"} {
+ t.Run(region, func(t *testing.T) {
+ for _, kv := range [][2]string{
+ {"AWS_ACCESS_KEY_ID", "AKIAAMBIENT"}, {"AWS_SECRET_ACCESS_KEY", "ambient"},
+ {"AWS_SESSION_TOKEN", "ambient-token"}, {"AWS_PROFILE", "other"},
+ {"AWS_DEFAULT_PROFILE", "other"}, {"AWS_ENDPOINT_URL_SSM", "https://evil.example.com"},
+ {"AWS_ENDPOINT_URL", "https://evil.example.com"}, {"AWS_CONTAINER_CREDENTIALS_FULL_URI", "http://x"},
+ {"UNRELATED", "x"}, {"LC_ALL", "C"},
+ } {
+ t.Setenv(kv[0], kv[1])
+ }
+ dir := withFakePlugin(t, fakeControl{Body: statusBody})
+ a, rec := sessionAdapter(t, region)
+ var o observer
+ if _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, o.seen); err != nil {
+ t.Fatal(err)
+ }
+ f := readRecord(t, dir)
+ resolved, err := ssm.NewDefaultEndpointResolverV2().ResolveEndpoint(ctx, ssm.EndpointParameters{
+ Region: aws.String(region), UseFIPS: aws.Bool(false), UseDualStack: aws.Bool(false)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ endpoint := resolved.URI.String()
+ wantHost := "ssm." + region + ".amazonaws.com"
+ if strings.HasPrefix(region, "cn-") {
+ wantHost += ".cn"
+ }
+ if endpoint != "https://"+wantHost {
+ t.Fatalf("SDK resolution %q, want https://%s", endpoint, wantHost)
+ }
+ if h := rec.requests()[0].Host; h != wantHost {
+ t.Fatalf("StartSession went to %q, want %q", h, wantHost)
+ }
+ if len(f.Argv) != 6 {
+ t.Fatalf("argv %q", f.Argv)
+ }
+ wantArgv := []string{"AWS_SSM_START_SESSION_RESPONSE", region, "StartSession", "op", f.Argv[4], endpoint}
+ if !reflect.DeepEqual(f.Argv, wantArgv) {
+ t.Fatalf("argv %q\nwant %q", f.Argv, wantArgv)
+ }
+ var request map[string]any
+ if err := json.Unmarshal([]byte(f.Argv[4]), &request); err != nil {
+ t.Fatalf("request argument %q: %v", f.Argv[4], err)
+ }
+ if !reflect.DeepEqual(request, rec.requests()[0].JSON) {
+ t.Fatalf("plugin request %v\nStartSession request %v", request, rec.requests()[0].JSON)
+ }
+
+ // The answer, token included, is only in the named variable.
+ var answer string
+ var others []string
+ for _, kv := range f.Env {
+ if v, ok := strings.CutPrefix(kv, "AWS_SSM_START_SESSION_RESPONSE="); ok {
+ answer = v
+ } else {
+ others = append(others, kv)
+ }
+ }
+ var resp map[string]any
+ if err := json.Unmarshal([]byte(answer), &resp); err != nil {
+ t.Fatalf("response variable %q: %v", answer, err)
+ }
+ wantResp := map[string]any{"SessionId": testSession, "TokenValue": testToken, "StreamUrl": testStream}
+ if !reflect.DeepEqual(resp, wantResp) {
+ t.Fatalf("response variable %v, want %v", resp, wantResp)
+ }
+ for _, s := range append(append([]string{}, f.Argv...), others...) {
+ if strings.Contains(s, testToken) {
+ t.Fatalf("the token is in %q", s)
+ }
+ }
+ for _, id := range o.ids {
+ if strings.Contains(id, testToken) {
+ t.Fatalf("the token reached the observer: %q", id)
+ }
+ }
+
+ // The rest is the isolated environment, whatever the caller had.
+ want := allowedEnvironment(os.Environ())
+ want = append(want, "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS=true", "AWS_EC2_METADATA_DISABLED=true", "AWS_PROFILE=op")
+ sort.Strings(want)
+ sort.Strings(others)
+ if !reflect.DeepEqual(others, want) {
+ t.Fatalf("plugin environment\n%q\nwant\n%q", others, want)
+ }
+ for _, kv := range others {
+ for _, bad := range []string{"AWS_ACCESS_KEY_ID=", "AWS_SECRET_ACCESS_KEY=", "AWS_SESSION_TOKEN=",
+ "AWS_DEFAULT_PROFILE=", "AWS_ENDPOINT_URL", "AWS_CONTAINER_", "UNRELATED=", "AWS_PROFILE=other"} {
+ if strings.HasPrefix(kv, bad) {
+ t.Fatalf("ambient %q reached the plugin", kv)
+ }
+ }
+ }
+ // The --version call ran in the same isolated environment,
+ // without the session answer.
+ calls := versionCalls(t, dir)
+ if len(calls) != 1 {
+ t.Fatalf("version calls %d, want 1", len(calls))
+ }
+ venv := strings.Split(calls[0], "\x00")
+ sort.Strings(venv)
+ if !reflect.DeepEqual(venv, want) {
+ t.Fatalf("--version environment\n%q\nwant\n%q", venv, want)
+ }
+ })
+ }
+}
+
+func TestTokenNeverInErrors(t *testing.T) {
+ for _, c := range []fakeControl{
+ {Mode: "exit", Exit: 2, Body: statusBody},
+ {Mode: "flood", Body: statusBody, FloodTotal: 4<<20 + 1},
+ {Body: "not json"},
+ {Body: statusBody, Code: "1"},
+ } {
+ withFakePlugin(t, c)
+ a, _ := sessionAdapter(t, "eu-west-1")
+ var o observer
+ _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, o.seen)
+ if err == nil {
+ t.Fatalf("%+v: no error", c)
+ }
+ if strings.Contains(err.Error(), testToken) || strings.Contains(fmt.Sprintf("%#v", err), testToken) {
+ t.Fatalf("%+v: the token is in the error %v", c, err)
+ }
+ for _, id := range o.ids {
+ if strings.Contains(id, testToken) {
+ t.Fatalf("the token reached the observer: %q", id)
+ }
+ }
+ }
+ shortBound(t, 500*time.Millisecond)
+ withFakePlugin(t, fakeControl{Mode: "hang"})
+ a, _ := sessionAdapter(t, "eu-west-1")
+ _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, func(string) {})
+ if err == nil || strings.Contains(fmt.Sprintf("%v %#v", err, err), testToken) {
+ t.Fatalf("timeout error %#v", err)
+ }
+}
+
+func TestPluginVersionFloor(t *testing.T) {
+ cases := []struct {
+ version string
+ ok bool
+ }{
+ {"1.2.835.0", true},
+ {"1.2.497.1", true},
+ {"1.2.498.0", true},
+ {"1.10.0.0", true},
+ {"2", true},
+ {"1.2.497.0.1", true},
+ {"1.2.497.0", false}, // the floor itself: the CLI's check is strict
+ {"1.2.497", false},
+ {"1.2.496.999", false},
+ {"1.1.999.0", false},
+ {"0.9", false},
+ {"garbage", false},
+ {"1.2.x.0", false},
+ {" ", false},
+ }
+ for _, c := range cases {
+ t.Run(c.version, func(t *testing.T) {
+ dir := withFakePlugin(t, fakeControl{Version: c.version, Body: statusBody})
+ a, rec := sessionAdapter(t, "eu-west-1")
+ err := a.CheckPlugin(ctx)
+ if c.ok {
+ if err != nil {
+ t.Fatalf("CheckPlugin: %v", err)
+ }
+ return
+ }
+ r, ok := err.(grouproll.Refusal)
+ if !ok || r.Key != "plugin_old" {
+ t.Fatalf("error %#v, want Refusal plugin_old", err)
+ }
+ if r.Args["floor"] != pluginFloorShown || r.Args["version"] == "" {
+ t.Fatalf("refusal args %v", r.Args)
+ }
+ if c.version != "" && c.version == strings.TrimSpace(c.version) && r.Args["version"] != c.version {
+ t.Fatalf("refusal names version %q, want %q", r.Args["version"], c.version)
+ }
+ _, err = a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, func(string) {})
+ if k := refusalKey(t, err); k != "plugin_old" {
+ t.Fatalf("Run refusal %q", k)
+ }
+ if len(rec.requests()) != 0 {
+ t.Fatalf("requests sent with an old plugin: %v", rec.actions())
+ }
+ if n := len(versionCalls(t, dir)); n != 1 {
+ t.Fatalf("--version ran %d times, want once per adapter", n)
+ }
+ })
+ }
+}
+
+func TestPluginVersionCached(t *testing.T) {
+ dir := withFakePlugin(t, fakeControl{Body: statusBody})
+ a, _ := sessionAdapter(t, "eu-west-1")
+ for i := 0; i < 2; i++ {
+ if err := a.CheckPlugin(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := a.Run(ctx, testIID, "status", grouproll.BoxArgs{}, func(string) {}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if n := len(versionCalls(t, dir)); n != 1 {
+ t.Fatalf("--version ran %d times, want 1", n)
+ }
+}
+
+func TestPluginFloorVersion(t *testing.T) {
+ // awscli/customizations/sessionmanager.py LAST_PLUGIN_VERSION_WITHOUT_ENV_VAR.
+ if pluginFloor != "1.2.497.0" {
+ t.Fatalf("floor %q", pluginFloor)
+ }
+}
+
+func TestCancelSession(t *testing.T) {
+ a, rec := sessionAdapter(t, "eu-west-1")
+ if err := a.CancelSession(ctx, testSession); err != nil {
+ t.Fatal(err)
+ }
+ reqs := rec.requests()
+ if len(reqs) != 1 || reqs[0].Action != "TerminateSession" || reqs[0].JSON["SessionId"] != testSession {
+ t.Fatalf("requests %+v", reqs)
+ }
+ for _, bad := range []string{"", "op 1", "../x", "op;x", "op\n"} {
+ if k := refusalKey(t, a.CancelSession(ctx, bad)); k != "remote" {
+ t.Fatalf("%q: refusal %q, want remote", bad, k)
+ }
+ }
+ if len(rec.requests()) != 1 {
+ t.Fatalf("a bad id was sent: %v", rec.actions())
+ }
+ rec.responses["TerminateSession"] = []canned{{status: 500}}
+ if u := uncertainKey(t, a.CancelSession(ctx, testSession)); u.Key != "api" {
+ t.Fatalf("failed TerminateSession: %#v", u)
+ }
+}
+
+func TestSessionTimeouts(t *testing.T) {
+ want := map[string]time.Duration{
+ "prepare": 360 * time.Second, "apply": 990 * time.Second, "rollback": 990 * time.Second,
+ "drain": 3690 * time.Second, "edge-stop": 210 * time.Second, "fence-clear": 60 * time.Second,
+ "drain-cancel": 390 * time.Second,
+ }
+ if !reflect.DeepEqual(sessionTimeouts, want) {
+ t.Fatalf("session timeouts %v, want %v", sessionTimeouts, want)
+ }
+ for verb, d := range want {
+ if sessionBound(verb) != d {
+ t.Fatalf("%s bound %v", verb, sessionBound(verb))
+ }
+ }
+ for _, verb := range []string{"status", "permit", "revoke"} {
+ if sessionBound(verb) != 15*time.Second {
+ t.Fatalf("%s bound %v, want the 15 s default", verb, sessionBound(verb))
+ }
+ }
+}
diff --git a/internal/grouprollaws/testdata/fakeplugin/main.go b/internal/grouprollaws/testdata/fakeplugin/main.go
new file mode 100644
index 000000000..96eafed08
--- /dev/null
+++ b/internal/grouprollaws/testdata/fakeplugin/main.go
@@ -0,0 +1,147 @@
+// Command fakeplugin stands in for session-manager-plugin in the
+// grouprollaws session tests. Its environment is the adapter's isolated
+// one, so it takes its instructions from $TMPDIR/fakeplugin.json and
+// records what it saw in $TMPDIR/fakeplugin-record.json (and each
+// --version call as a line in $TMPDIR/fakeplugin-version.log).
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "syscall"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+type control struct {
+ Version string `json:"version"`
+ Mode string `json:"mode"` // frame (default), hang, flood, exit, latebanner
+ Body string `json:"body"`
+ Code string `json:"code"`
+ Exit int `json:"exit"`
+ FloodTotal int `json:"flood_total"`
+ BannerID string `json:"banner_id"` // the id the banner names, if not the answer's
+}
+
+type record struct {
+ Argv []string `json:"argv"`
+ Env []string `json:"env"`
+ PID int `json:"pid"`
+ Child int `json:"child"`
+ SID int `json:"sid"`
+ PGID int `json:"pgid"`
+ StdinTTY bool `json:"stdin_tty"`
+ StdinEOF bool `json:"stdin_eof"`
+ Raw bool `json:"raw"`
+}
+
+var nonce = regexp.MustCompile(`([0-9a-f]{32}):BEGIN`)
+
+func main() {
+ dir := os.Getenv("TMPDIR")
+ if len(os.Args) > 1 && os.Args[1] == "child" {
+ signal.Ignore(syscall.SIGTERM)
+ for {
+ time.Sleep(time.Hour)
+ }
+ }
+ var c control
+ if raw, err := os.ReadFile(filepath.Join(dir, "fakeplugin.json")); err == nil {
+ _ = json.Unmarshal(raw, &c)
+ }
+ if len(os.Args) == 2 && os.Args[1] == "--version" {
+ f, _ := os.OpenFile(filepath.Join(dir, "fakeplugin-version.log"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
+ fmt.Fprintln(f, strings.Join(os.Environ(), "\x00"))
+ f.Close()
+ v := c.Version
+ if v == "" {
+ v = "1.2.835.0"
+ }
+ fmt.Println(v)
+ return
+ }
+
+ rec := record{Argv: os.Args[1:], Env: os.Environ(), PID: os.Getpid(), PGID: unix.Getpgrp()}
+ rec.SID, _ = unix.Getsid(0)
+ if t, err := unix.IoctlGetTermios(0, ioctlGetTermios); err == nil {
+ rec.StdinTTY = true
+ rec.Raw = t.Lflag&(unix.ICANON|unix.ECHO|unix.ISIG) == 0 && t.Oflag&unix.OPOST == 0
+ }
+ // Stdin stays open and silent: a short poll sees no data and no EOF.
+ if err := unix.SetNonblock(0, true); err == nil {
+ buf := make([]byte, 1)
+ n, err := unix.Read(0, buf)
+ rec.StdinEOF = n == 0 && err == nil
+ _ = unix.SetNonblock(0, false)
+ }
+ signal.Ignore(syscall.SIGTERM)
+ if c.Mode == "hang" {
+ self, err := os.Executable()
+ if err != nil {
+ panic(err)
+ }
+ child := exec.Command(self, "child")
+ child.Stdout, child.Stderr = os.Stdout, os.Stderr
+ if err := child.Start(); err != nil {
+ panic(err)
+ }
+ rec.Child = child.Process.Pid
+ }
+ raw, _ := json.Marshal(rec)
+ if err := os.WriteFile(filepath.Join(dir, "fakeplugin-record.json"), raw, 0o600); err != nil {
+ panic(err)
+ }
+
+ var resp struct{ SessionId string }
+ if len(os.Args) > 1 {
+ _ = json.Unmarshal([]byte(os.Getenv(os.Args[1])), &resp)
+ }
+ var request struct{ Parameters map[string][]string }
+ if len(os.Args) > 5 {
+ _ = json.Unmarshal([]byte(os.Args[5]), &request)
+ }
+ n := ""
+ if cmd := request.Parameters["command"]; len(cmd) == 1 {
+ if m := nonce.FindStringSubmatch(cmd[0]); m != nil {
+ n = m[1]
+ }
+ }
+ id := resp.SessionId
+ if c.BannerID != "" {
+ id = c.BannerID
+ }
+ banner := "\nStarting session with SessionId: " + id + "\n"
+ if c.Mode == "latebanner" {
+ banner = ""
+ }
+ code := c.Code
+ if code == "" {
+ code = "0"
+ }
+ frame := "\n" + n + ":BEGIN\n" + c.Body + "\n" + n + ":END:" + code + "\n"
+ switch c.Mode {
+ case "hang":
+ os.Stdout.WriteString(banner)
+ for {
+ time.Sleep(time.Hour)
+ }
+ case "flood":
+ pad := c.FloodTotal - len(banner) - len(frame)
+ os.Stdout.WriteString(banner + strings.Repeat("x", pad) + frame)
+ case "latebanner":
+ // The banner last, with no line end: only the whole-text scan sees it.
+ os.Stdout.WriteString(frame + "Starting session with SessionId: " + id)
+ case "exit":
+ os.Stdout.WriteString(banner + frame)
+ os.Exit(c.Exit)
+ default:
+ os.Stdout.WriteString(banner + frame + "\n\nExiting session with sessionId: " + resp.SessionId + ".\n\n")
+ }
+}
diff --git a/internal/grouprollaws/testdata/fakeplugin/termios_darwin.go b/internal/grouprollaws/testdata/fakeplugin/termios_darwin.go
new file mode 100644
index 000000000..abf975434
--- /dev/null
+++ b/internal/grouprollaws/testdata/fakeplugin/termios_darwin.go
@@ -0,0 +1,5 @@
+package main
+
+import "golang.org/x/sys/unix"
+
+const ioctlGetTermios = unix.TIOCGETA
diff --git a/internal/grouprollaws/testdata/fakeplugin/termios_linux.go b/internal/grouprollaws/testdata/fakeplugin/termios_linux.go
new file mode 100644
index 000000000..b486a6290
--- /dev/null
+++ b/internal/grouprollaws/testdata/fakeplugin/termios_linux.go
@@ -0,0 +1,5 @@
+package main
+
+import "golang.org/x/sys/unix"
+
+const ioctlGetTermios = unix.TCGETS
diff --git a/region_ha_boundary_test.go b/region_ha_boundary_test.go
index a387fea7e..2eadff9a2 100644
--- a/region_ha_boundary_test.go
+++ b/region_ha_boundary_test.go
@@ -61,6 +61,11 @@ var regionHAAdapterFiles = []string{
"internal/grouprollaws/group.go",
"internal/grouprollaws/phase.go",
"internal/grouprollaws/transport.go",
+ "internal/grouprollaws/session.go",
+ "internal/grouprollaws/pty_unix.go",
+ "internal/grouprollaws/pty_linux.go",
+ "internal/grouprollaws/pty_darwin.go",
+ "internal/grouprollaws/pty_other.go",
}
// regionHAPackages are the packages spec 2 touches. Every S3 client built