package awsjob import ( "context" "errors" "fmt" "net/netip" "slices" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/isolatedjob" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/lambdacore" vms "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms" "github.com/aws/aws-sdk-go-v2/service/lambdamicrovms/types" "github.com/aws/smithy-go/middleware" ) // MicroVMAPI is the part of the Lambda MicroVMs client the runner calls. // *lambdamicrovms.Client satisfies it. type MicroVMAPI interface { RunMicrovm(context.Context, *vms.RunMicrovmInput, ...func(*vms.Options)) (*vms.RunMicrovmOutput, error) GetMicrovm(context.Context, *vms.GetMicrovmInput, ...func(*vms.Options)) (*vms.GetMicrovmOutput, error) SuspendMicrovm(context.Context, *vms.SuspendMicrovmInput, ...func(*vms.Options)) (*vms.SuspendMicrovmOutput, error) ResumeMicrovm(context.Context, *vms.ResumeMicrovmInput, ...func(*vms.Options)) (*vms.ResumeMicrovmOutput, error) TerminateMicrovm(context.Context, *vms.TerminateMicrovmInput, ...func(*vms.Options)) (*vms.TerminateMicrovmOutput, error) ListMicrovms(context.Context, *vms.ListMicrovmsInput, ...func(*vms.Options)) (*vms.ListMicrovmsOutput, error) GetMicrovmImageVersion(context.Context, *vms.GetMicrovmImageVersionInput, ...func(*vms.Options)) (*vms.GetMicrovmImageVersionOutput, error) } // EC2API is the part of the EC2 client the network audit calls. // *ec2.Client satisfies it. type EC2API interface { DescribeVpcAttribute(context.Context, *ec2.DescribeVpcAttributeInput, ...func(*ec2.Options)) (*ec2.DescribeVpcAttributeOutput, error) DescribeSubnets(context.Context, *ec2.DescribeSubnetsInput, ...func(*ec2.Options)) (*ec2.DescribeSubnetsOutput, error) DescribeRouteTables(context.Context, *ec2.DescribeRouteTablesInput, ...func(*ec2.Options)) (*ec2.DescribeRouteTablesOutput, error) DescribeSecurityGroups(context.Context, *ec2.DescribeSecurityGroupsInput, ...func(*ec2.Options)) (*ec2.DescribeSecurityGroupsOutput, error) } // ConnectorAPI is the part of the Lambda core client the network audit // calls to read the egress connector. *lambdacore.Client satisfies it. type ConnectorAPI interface { GetNetworkConnector(context.Context, *lambdacore.GetNetworkConnectorInput, ...func(*lambdacore.Options)) (*lambdacore.GetNetworkConnectorOutput, error) } // API is every provider call the runner makes. type API interface { MicroVMAPI EC2API ConnectorAPI } // NewAPI joins the three clients into an API, for example // NewAPI(lambdamicrovms.NewFromConfig(cfg), ec2.NewFromConfig(cfg), // lambdacore.NewFromConfig(cfg)). func NewAPI(m MicroVMAPI, e EC2API, c ConnectorAPI) API { return clients{m, e, c} } type clients struct { MicroVMAPI EC2API ConnectorAPI } // Image is one certified base image: its MicroVM image ARN and the image // version to run for each size. Memory, CPU and OS capabilities are set on // an image version, and one version has one memory size, so each size needs // a version of its own. type Image struct { ARN string Versions map[isolatedjob.Size]string } // Config is where hosted VMs launch and what they may reach. type Config struct { Region string // ConnectorID is the version-qualified ARN of the VPC_EGRESS network // connector, the VMs' only egress: // arn:aws:lambda:REGION:ACCOUNT:network-connector:ID:VERSION. The // version pins the connector's subnets and groups, so an update to the // connector cannot change what launched VMs use without a config change. ConnectorID string VPCID string // the VPC of the connector's subnet VMSubnetID string // the connector's only subnet VMSecurityGroupID string // the connector's only security group // Images are the certified images, by digest. They also bound what // List sees (ruling R32): only VMs running one of these image ARNs are // listed, so VMs of other images in a shared account are never taken // for orphans and stopped by the reaper. Images map[isolatedjob.ImageDigest]Image // Egress is every destination the security group should let VMs // reach: the shared proxies. Empty means none: the group has no // outbound rules, as in slice 1a, which has no egress stack. Egress []netip.AddrPort } // Runner is the isolatedjob.Runner and isolatedjob.NetworkAuditor for AWS // Lambda MicroVMs. It is safe for concurrent use. type Runner struct { cfg Config api API mu sync.Mutex verified map[imageVersion]int // memory in MiB of each version that passed the image check } type imageVersion struct{ arn, version string } var ( _ isolatedjob.Runner = (*Runner)(nil) _ isolatedjob.NetworkAuditor = (*Runner)(nil) ) // New checks cfg and returns a Runner that calls api. Every config error // wraps isolatedjob.ErrInvalid. func New(cfg Config, api API) (*Runner, error) { if err := cfg.check(); err != nil { return nil, fmt.Errorf("%w: awsjob config: %v", isolatedjob.ErrInvalid, err) } if api == nil { return nil, fmt.Errorf("%w: awsjob: no API", isolatedjob.ErrInvalid) } return &Runner{cfg: cfg, api: api, verified: map[imageVersion]int{}}, nil } func (c Config) check() error { for name, v := range map[string]string{"region": c.Region, "connector": c.ConnectorID, "vpc": c.VPCID, "subnet": c.VMSubnetID, "security group": c.VMSecurityGroupID} { if v == "" { return fmt.Errorf("%s is empty", name) } } if !qualifiedConnector(c.ConnectorID, c.Region) { return fmt.Errorf("connector %q is not a version-qualified network connector ARN in %s", c.ConnectorID, c.Region) } if len(c.Images) == 0 { return errors.New("no images") } for d, img := range c.Images { if img.ARN == "" || len(img.Versions) == 0 { return fmt.Errorf("image %s needs an ARN and at least one version", d) } for size, v := range img.Versions { if size.MemoryMiB() == 0 || v == "" { return fmt.Errorf("image %s: size %q, version %q", d, size, v) } } } for _, e := range c.Egress { if !e.IsValid() || e.Port() == 0 { return fmt.Errorf("egress %v is not an address and port", e) } } return nil } // qualifiedConnector reports whether arn has the form // arn:PARTITION:lambda:region:ACCOUNT:network-connector:ID:VERSION with a // numeric version. func qualifiedConnector(arn, region string) bool { f := strings.Split(arn, ":") if len(f) != 8 || f[0] != "arn" || f[1] == "" || f[2] != "lambda" || f[3] != region || f[4] == "" || f[5] != "network-connector" || f[6] == "" || f[7] == "" { return false } for _, c := range f[7] { if c < '0' || c > '9' { return false } } return true } // Fingerprint names what a launch of image d at size s sends to AWS beyond // the spec: the region (and with it the NO_INGRESS connector), the egress // connector, and the image ARN and version. The controller keeps it with // each launch intent and refuses to replay an intent under another one // (hostedctl Config.ProviderFingerprint). An image or size with no version // gives a fingerprint with empty fields, which a configured one never // matches. func (c Config) Fingerprint(d isolatedjob.ImageDigest, s isolatedjob.Size) string { img := c.Images[d] return fmt.Sprintf("region=%q connector=%q image=%q version=%q", c.Region, c.ConnectorID, img.ARN, img.Versions[s]) } // NoIngressConnectorARN is the Lambda-provided NO_INGRESS connector in // region, in the form the developer guide prints for the managed ingress // connectors (doc.go, Connectors). The guide does not print this one; the // live check confirms it. func NoIngressConnectorARN(region string) string { return "arn:aws:lambda:" + region + ":aws:network-connector:aws-network-connector:NO_INGRESS" } // Limits are the spike's findings and doc.go's: 8 hours including suspended // time, a 4096-byte run hook payload, and connections dropped by suspend. func (r *Runner) Limits() isolatedjob.Limits { return isolatedjob.Limits{ MaxLifetime: 28800 * time.Second, MaxBootstrapBytes: 4096, SuspendUsesLifetime: true, ConnectionsSurvive: false, } } // Launch runs one VM with NO_INGRESS, the configured connector as its only // egress, no execution role, no idle policy, the spec's lifetime as the // maximum duration and the attempt ID as the client token. It refuses with // isolatedjob.ErrInvalid, before any run call, a spec that fails Validate, // a bootstrap that is not ASCII, an image or size with no configured // version, and an image version that is not x86_64 with all OS capabilities // and the size's memory. func (r *Runner) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { if err := s.Validate(r.Limits()); err != nil { return "", err } // runHookPayload is a JSON string: the SDK would turn invalid UTF-8 // into U+FFFD, and AWS does not say whether its limit counts bytes or // characters. The bootstrap is an enrolment code, so ASCII is enough // and every ASCII byte survives JSON unchanged. for i, b := range s.Bootstrap { if b >= 0x80 { return "", fmt.Errorf("%w: bootstrap byte %d is 0x%02x; only ASCII survives the run hook payload unchanged", isolatedjob.ErrInvalid, i, b) } } img, ok := r.cfg.Images[s.Image] if !ok { return "", fmt.Errorf("%w: image %s is not configured", isolatedjob.ErrInvalid, s.Image) } version, ok := img.Versions[s.Size] if !ok { return "", fmt.Errorf("%w: image %s has no version for size %s", isolatedjob.ErrInvalid, s.Image, s.Size) } seconds := int64(s.MaxLifetime / time.Second) if seconds < 1 || seconds > 28800 { return "", fmt.Errorf("%w: lifetime %v is not 1 to 28800 whole seconds", isolatedjob.ErrInvalid, s.MaxLifetime) } if err := r.checkImageVersion(ctx, img.ARN, version, s.Size); err != nil { return "", err } out, err := r.api.RunMicrovm(ctx, &vms.RunMicrovmInput{ ImageIdentifier: aws.String(img.ARN), ImageVersion: aws.String(version), ClientToken: aws.String(s.AttemptID), // always set: the SDK invents one when it is nil IngressNetworkConnectors: []string{NoIngressConnectorARN(r.cfg.Region)}, EgressNetworkConnectors: []string{r.cfg.ConnectorID}, MaximumDurationInSeconds: aws.Int32(int32(seconds)), RunHookPayload: aws.String(string(s.Bootstrap)), }) if err != nil { return "", mapErr("run", err) } id := isolatedjob.Ref(aws.ToString(out.MicrovmId)) if !id.Valid() { // The text is fixed: a malformed ID is never echoed (R36). return "", fmt.Errorf("awsjob: run %s: the reply's microvm id is missing or malformed", s.AttemptID) } return id, nil } // checkImageVersion reads the image version once and refuses it unless it // has exactly the "ALL" OS capability, one x86_64 CPU configuration and // one memory setting equal to the size's. A pass is kept for the life of // the Runner; a failure is not, so a fixed version passes on the next try. func (r *Runner) checkImageVersion(ctx context.Context, arn, version string, size isolatedjob.Size) error { key := imageVersion{arn, version} want := size.MemoryMiB() r.mu.Lock() mem, seen := r.verified[key] r.mu.Unlock() if seen { if mem != want { return fmt.Errorf("%w: image version %s:%s has %d MiB, size %s needs %d", isolatedjob.ErrInvalid, arn, version, mem, size, want) } return nil } out, err := r.api.GetMicrovmImageVersion(ctx, &vms.GetMicrovmImageVersionInput{ ImageIdentifier: aws.String(arn), ImageVersion: aws.String(version), }) if err != nil { err = mapErr("get image version", err) if errors.Is(err, isolatedjob.ErrNotFound) { return fmt.Errorf("%w: image version %s:%s: %w", isolatedjob.ErrInvalid, arn, version, err) } return err } if !slices.Equal(out.AdditionalOsCapabilities, []types.Capability{types.CapabilityAll}) { return fmt.Errorf("%w: image version %s:%s has OS capabilities %v, want [ALL]", isolatedjob.ErrInvalid, arn, version, out.AdditionalOsCapabilities) } if len(out.CpuConfigurations) != 1 || out.CpuConfigurations[0].Architecture != types.ArchitectureX8664 { return fmt.Errorf("%w: image version %s:%s has CPU configurations %v, want one X86_64", isolatedjob.ErrInvalid, arn, version, out.CpuConfigurations) } if len(out.Resources) != 1 || out.Resources[0].MinimumMemoryInMiB == nil || int(*out.Resources[0].MinimumMemoryInMiB) != want { return fmt.Errorf("%w: image version %s:%s has memory %v, size %s needs one setting of %d MiB", isolatedjob.ErrInvalid, arn, version, memories(out.Resources), size, want) } r.mu.Lock() r.verified[key] = want r.mu.Unlock() return nil } func memories(rs []types.Resources) []int32 { var out []int32 for _, r := range rs { out = append(out, aws.ToInt32(r.MinimumMemoryInMiB)) } return out } // Get reads one VM. func (r *Runner) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) { if !ref.Valid() { return isolatedjob.Job{}, fmt.Errorf("%w: empty or malformed ref", isolatedjob.ErrInvalid) } out, err := r.api.GetMicrovm(ctx, &vms.GetMicrovmInput{MicrovmIdentifier: aws.String(string(ref))}) if err != nil { return isolatedjob.Job{}, mapErr("get", err) } // The reply must name a valid ID (R36, R38): a missing one is an error, // never the asked-for ref, so a malformed reply cannot become stop proof. id := isolatedjob.Ref(aws.ToString(out.MicrovmId)) if !id.Valid() { return isolatedjob.Job{}, errors.New("awsjob: get: the reply's microvm id is missing or malformed") } return job(id, out.State, out.StateReason, out.StartedAt, out.ResultMetadata), nil } // Suspend asks AWS to suspend the VM. func (r *Runner) Suspend(ctx context.Context, ref isolatedjob.Ref) error { if !ref.Valid() { return fmt.Errorf("%w: empty or malformed ref", isolatedjob.ErrInvalid) } _, err := r.api.SuspendMicrovm(ctx, &vms.SuspendMicrovmInput{MicrovmIdentifier: aws.String(string(ref))}) return mapErr("suspend", err) } // Resume asks AWS to resume the VM. AWS refuses to resume a VM that is not // suspended with a ConflictException; Resume then reads the VM once and // returns nil only if it is running, so resuming a running VM is a no-op. func (r *Runner) Resume(ctx context.Context, ref isolatedjob.Ref) error { if !ref.Valid() { return fmt.Errorf("%w: empty or malformed ref", isolatedjob.ErrInvalid) } _, err := r.api.ResumeMicrovm(ctx, &vms.ResumeMicrovmInput{MicrovmIdentifier: aws.String(string(ref))}) var conflict *types.ConflictException if !errors.As(err, &conflict) { return mapErr("resume", err) } j, getErr := r.Get(ctx, ref) if getErr != nil { return fmt.Errorf("%w: resume %s refused (%v) and its state is unreadable: %v", isolatedjob.ErrConflict, ref, err, getErr) } if j.State == isolatedjob.StateRunning { return nil } return fmt.Errorf("%w: resume %s refused in state %s: %w", isolatedjob.ErrConflict, ref, j.State, err) } // Stop terminates the VM. AWS has no field for the reason, so it is not // sent. A VM AWS no longer knows is already gone, which is success. func (r *Runner) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error { if !ref.Valid() { return fmt.Errorf("%w: empty or malformed ref", isolatedjob.ErrInvalid) } _, err := r.api.TerminateMicrovm(ctx, &vms.TerminateMicrovmInput{MicrovmIdentifier: aws.String(string(ref))}) if err = mapErr("terminate", err); errors.Is(err, isolatedjob.ErrNotFound) { return nil } return err } // listPageSize is the most ListMicrovms returns in one page. const listPageSize = 50 // List reads the VMs of the configured images in the account and region // (ruling R32): one ListMicrovms walk per configured image ARN, in ARN // order, filtered by that image, every page of each. An item whose imageArn // is not the ARN asked for is dropped, so a VM from another image is never // returned even if the filter were ignored; the account may be shared, and // the reaper stops listed VMs no job owns. If any page fails, repeats a // token or holds a VM whose ID is missing or fails isolatedjob.Ref.Valid // (R36), List returns no jobs and an error wrapping // isolatedjob.ErrIncomplete. func (r *Runner) List(ctx context.Context) ([]isolatedjob.Job, error) { var jobs []isolatedjob.Job for _, arn := range r.imageARNs() { got, err := r.listImage(ctx, arn) if err != nil { return nil, err } jobs = append(jobs, got...) } return jobs, nil } // imageARNs is every configured image ARN once, sorted. func (r *Runner) imageARNs() []string { var arns []string for _, img := range r.cfg.Images { arns = append(arns, img.ARN) } slices.Sort(arns) return slices.Compact(arns) } // listImage walks every page of ListMicrovms filtered by image arn. func (r *Runner) listImage(ctx context.Context, arn string) ([]isolatedjob.Job, error) { var jobs []isolatedjob.Job var token *string seen := map[string]bool{} for page := 1; ; page++ { out, err := r.api.ListMicrovms(ctx, &vms.ListMicrovmsInput{ImageIdentifier: aws.String(arn), MaxResults: aws.Int32(listPageSize), NextToken: token}) if err != nil { return nil, fmt.Errorf("%w: list image %s page %d: %w", isolatedjob.ErrIncomplete, arn, page, mapErr("list", err)) } for _, it := range out.Items { if aws.ToString(it.ImageArn) != arn { continue } id := isolatedjob.Ref(aws.ToString(it.MicrovmId)) if !id.Valid() { return nil, fmt.Errorf("%w: list image %s page %d holds a VM with a missing or malformed id", isolatedjob.ErrIncomplete, arn, page) } jobs = append(jobs, job(id, it.State, nil, it.StartedAt, out.ResultMetadata)) } next := aws.ToString(out.NextToken) if next == "" { return jobs, nil } if seen[next] { return nil, fmt.Errorf("%w: list image %s page %d repeats a page token", isolatedjob.ErrIncomplete, arn, page) } seen[next] = true token = aws.String(next) } } // job builds a Job from one response. ProviderAge is the response's server // time minus the VM's start time, both from AWS; with either missing, or a // start after the server time, AgeKnown is false. func job(ref isolatedjob.Ref, raw types.MicrovmState, reason *string, started *time.Time, meta middleware.Metadata) isolatedjob.Job { j := isolatedjob.Job{Ref: ref} j.State, j.Reason = state(raw, aws.ToString(reason)) if started != nil { j.StartedAt = *started } if server, ok := awsmiddleware.GetServerTime(meta); ok && started != nil && !server.Before(*started) { j.ProviderAge, j.AgeKnown = server.Sub(*started), true } return j } // state maps an AWS MicroVM state. A state this package does not know is // unknown, with the raw value in the reason; AWS says the set can grow. func state(raw types.MicrovmState, reason string) (isolatedjob.State, string) { switch raw { case types.MicrovmStatePending: return isolatedjob.StateStarting, reason case types.MicrovmStateRunning: return isolatedjob.StateRunning, reason case types.MicrovmStateSuspending: return isolatedjob.StateSuspending, reason case types.MicrovmStateSuspended: return isolatedjob.StateSuspended, reason case types.MicrovmStateTerminating: return isolatedjob.StateStopping, reason case types.MicrovmStateTerminated: return isolatedjob.StateStopped, reason } why := fmt.Sprintf("provider state %q", string(raw)) if reason != "" { why += ": " + reason } return isolatedjob.StateUnknown, why }