mirror of
https://github.com/mulgadc/spinifex.git
synced 2026-10-19 10:52:04 +00:00
b5879f44ff
* refactor: move telemetry file naming to contract
* docs: record telemetry contract move
* refactor: move aws xml response helpers
* docs: record aws xml helper move
* refactor: move aws tag projections to foundation
* docs: record aws tag projection move
* refactor: move account key to state foundation
* docs: record account key state move
* refactor: move host privilege escalation to runtime
* docs: record host privilege move
* chore: resolve lint findings from package-boundary moves
* refactor: move process supervision helpers to runtime host
* docs: record process supervision move
* refactor: move nbd endpoint helpers to compute runtime
* docs: record nbd endpoint move
* refactor: move image catalogue to operator
* docs: record image catalogue move
* refactor: move resource id generation to aws foundation
* docs: record resource id move
* refactor: move predastore role to runtime roles
* docs: point service manifest at acm domain
* docs: record predastore role move
* refactor: move northstar role to runtime roles
* docs: record northstar role move
* refactor: move awsgw role to runtime roles
* docs: record awsgw role move
* refactor: move error payload helpers to aws errors
* docs: record error payload move
* refactor: move account identifiers to aws identifiers
* docs: record account identifier move
* refactor: move NATS transport to messaging foundation
* docs: record NATS transport move
* refactor: move system instance contract to EC2 domain
* docs: record system instance move
* refactor: move system VPC builder to network domain
* docs: record system VPC move
* refactor: move instance metadata service to EC2 domain
* docs: record guest metadata move and dependency-rule debt
* refactor: move DNS control plane to DNS domain
* docs: record DNS domain move
* refactor: move base zone bootstrap to DNS domain
* docs: record base zone bootstrap move
* refactor: replace SystemAccountID with GlobalAccountID
* docs: record SystemAccountID removal
* refactor: extract CA key-pair loader to foundation pki
* docs: record foundation pki extraction
* refactor: move tenant CA paths to ACM domain
* docs: record tenant CA path move
* refactor: move IPsec certificate handling to network host
* docs: record IPsec certificate move
* refactor: move Ochre serving lifecycle to the Ochre domain
handlers/bedrock becomes domains/ochre. Ochre is the platform service;
Bedrock names only its AWS API surface. Persisted and observable
identifiers keep their bedrock names.
* docs: record Ochre domain move
* refactor: move Ochre vector store to the Ochre domain
handlers/ochrevector becomes domains/ochre/vector. Callers import it as
ochrevector because vector is a common local name in the gateway.
* docs: record Ochre vector store move
* refactor: move Hugging Face Hub client to the Ochre domain
gateway/bedrock/hfhub becomes domains/ochre/hfhub. Its only caller is
the spx admin ochre weights pull.
* docs: record Hugging Face Hub client move and Ochre gateway debt
* refactor: move EC2 tag mutation helpers to the EC2 domain
utils/tagmirror.go becomes domains/ec2/tagmirror. It is EC2-wide tag
mutation behaviour, and the tags resource package cannot host it
without a resource-to-resource import cycle.
* docs: record EC2 tag mutation move and migrate split finding
* refactor: move network packages under the network domain
Move spinifex/network/* to spinifex/domains/network/* as one enclosing
move so the L0-L5 layer invariants keep classifying every package from
a single root. Package names and dependency direction are unchanged;
invariant scan roots, the RG-10 sudo allow-list path, CODEOWNERS and
the repo-root walk in the IMDS netns unit test follow the new path.
* docs: record network domain move
* refactor: move standalone EC2 resource packages to the EC2 domain
Move handlers/ec2/{account,key,launchtemplate,placementgroup,
spotinstance,volumestate} to domains/ec2/<resource>. Each package is
named after its directory and callers import it as ec2<resource>;
volumestate already carried its directory name.
* docs: record standalone EC2 resource moves
* refactor: move EC2 VPC networking packages to the EC2 domain
Move handlers/ec2/{vpc,eigw,eip,igw,natgw,routetable} to
domains/ec2/<resource>, each named after its directory and imported as
ec2<resource>. The reconcile drift-watch source scan now matches the
ec2<resource> bucket qualifiers; its rule is unchanged.
* docs: record EC2 VPC networking moves
* refactor: move EC2 compute and storage packages to the EC2 domain
Move handlers/ec2/{instance,volume,snapshot,image,tags} to
domains/ec2/<resource>, each named after its directory and imported as
ec2<resource>, which empties handlers/ec2. The daemon's e2e suite
selection now lists the moved EC2 resource paths in place of
handlers/ec2, so EC2-only changes select the daemon suites again.
* docs: record EC2 compute and storage moves
* refactor: move ECR credential provider to the EKS agent tree
Move the kubelet exec credential provider implementation from
cmd/ecr-credential-provider to agents/eks/credentialprovider, exposing
one Main(in, out) entry point. The binary keeps its name and FIPS boot
import as a thin main. Moving out of cmd/ brings the code under gosec;
the one G101 hit on the kubelet API version constant is annotated.
* docs: record ECR credential provider move
* refactor: move EKS gateway publish helper to the EKS agent tree
Move the eks-gateway-publish implementation to agents/eks/gatewaypublish
behind Run(ctx, Config) error. The binary keeps flag definitions,
environment defaults, parsing, its log prefix and exit code; each former
fatal site returns an error with the same text. The retry wait now also
honours context cancellation, which the binary never triggers.
* docs: record EKS gateway publish move
* refactor: move EKS gateway fetch helper to the EKS agent tree
Move the eks-gateway-fetch implementation to agents/eks/gatewayfetch
behind Run(ctx, Config) error, writing its TSV to Config.Out. The binary
keeps flag definitions, environment defaults, parsing, its log prefix and
exit code; each former fatal site returns an error with the same text.
* docs: record EKS gateway fetch move
* refactor: move EKS webhook cert helper to the EKS agent tree
cmd/eks-webhook-cert keeps flag parsing, the log prefix and the exit;
agents/eks/webhookcert owns Config and Run. Output, error text, file
modes and exit codes are unchanged.
* docs: record EKS webhook cert move
* refactor: move EKS konnectivity cert helper to the EKS agent tree
cmd/eks-konnectivity-cert keeps flag parsing, the log prefix and the
exit; agents/eks/konnectivitycert owns Config and Run. Output, error
text, file modes and exit codes are unchanged.
* docs: record EKS konnectivity cert move
* refactor: move EKS token webhook to the EKS agent tree
cmd/eks-token-webhook keeps the -addr flag, environment-derived
config, logging setup and exits; agents/eks/tokenwebhook owns Config
and Run. The handlers/eks TokenReview result type stays as recorded
temporary debt.
* docs: record EKS token webhook move
* refactor: move ECS agent runtime and credentials packages to the ECS agent tree
* docs: record ECS agent subpackage move
* refactor: move ECS agent implementation to the ECS agent tree
cmd/ecs-agent keeps process lifecycle: signal context, the separate New
and Run calls, both failure log lines, the exit and the ldflags-set
build version, now passed in through Config.AgentVersion.
agents/ecs/agent owns Config, LoadConfig and the agent.
* docs: record ECS agent move
* refactor: move RDS guest agent to agents/rds/agent
* docs: record RDS guest agent move
* refactor: move installer packages to operator/installer
* docs: record installer move
* refactor: move spx command tree to operator/cli
Moving the command tree out of cmd/ brings it under errcheck and gosec.
Flag and config wiring now fails loudly instead of silently dropping a
binding, listing commands fail when they cannot write their table, and
the formation server's unauthenticated TLS is annotated as a known gap.
* docs: record spx command tree move
* chore: accept known vulnerabilities with an expiry
The vulnerability scan failed preflight on a containerd advisory that dev
already carries and that is deferred to a separate dependency update. The
gate now passes only reachable findings listed with an expiry date, fails
on any new one or on an expired acceptance, and warns when an acceptance
is no longer needed.
* refactor: move EC2 account action adapters to domains/ec2/awsapi
* refactor: move EC2 capacityreservation action adapters to domains/ec2/awsapi
* refactor: move EC2 key action adapters to domains/ec2/awsapi
* refactor: move EC2 launchtemplate action adapters to domains/ec2/awsapi
* refactor: move EC2 placementgroup action adapters to domains/ec2/awsapi
* docs: record EC2 standalone action adapter moves
* refactor: move EC2 zone action adapters to domains/ec2/awsapi
* refactor: move EC2 vpc action adapters to domains/ec2/awsapi
* refactor: move EC2 eigw action adapters to domains/ec2/awsapi
* refactor: move EC2 eip action adapters to domains/ec2/awsapi
* refactor: move EC2 igw action adapters to domains/ec2/awsapi
* refactor: move EC2 natgw action adapters to domains/ec2/awsapi
* refactor: move EC2 routetable action adapters to domains/ec2/awsapi
* docs: record EC2 VPC networking action adapter moves
* refactor: move EC2 image action adapters to domains/ec2/awsapi
* refactor: move EC2 snapshot action adapters to domains/ec2/awsapi
* refactor: move EC2 volume action adapters to domains/ec2/awsapi
* refactor: move EC2 tags action adapters to domains/ec2/awsapi
* docs: record EC2 storage and tag action adapter moves
* refactor: move EC2 resource authorization scopes to domains/ec2/awsapi
* refactor: move EC2 idempotency adapter to domains/ec2/awsapi
* refactor: move EC2 instance action adapters to domains/ec2/awsapi
* refactor: move EC2 spotinstance action adapters to domains/ec2/awsapi
* docs: record EC2 instance action adapter moves
* refactor: move AWS REST-JSON router to ingress/aws/rest
* refactor: move SigV4 auth-failure rate limiter to ingress/aws/ratelimit
* docs: record AWS ingress helper moves and tooling conformance
* docs: correct historical lifecycle references
* test: characterize ECR control-plane dispatch before registration seam
* feat: add AWS ingress service registration contract
* docs: record ingress registration phases 0 and 1
* refactor: route registered AWS services through the ingress dispatch registry
The gateway now consumes ingress/aws/dispatch. A registered service is
accepted by the auth gate, resolves its own action label, renders errors in
its declared envelope and is dispatched with an authenticated Invocation
(account, region, policy authorisation and a lazy verified actor). Every
other service keeps the existing switch, now named as the legacy path.
The awsgw role wires an empty registry and refuses to start if a registered
name is also served by the legacy table. No service is registered yet, so
behaviour for every existing service is unchanged.
* docs: record ingress dispatch registry consumption
* refactor: register the ECR control plane from its domain
domains/ecr/awsapi now registers the "ecr" AWS JSON 1.1 surface with the
ingress dispatch registry: action resolution, resource scope, authorisation
through the invocation, the composed capabilities and the success writer all
live with the domain. The awsgw role is the only serving composition point;
the gateway no longer imports the ECR API package and ECR leaves the legacy
service table, JSON error table and dispatch switch. The OCI /v2 route is
unchanged.
Operation coverage reads ECR's declared inventory, which the registration
uses verbatim; coverage.json is byte-identical.
* docs: record ECR control-plane registration
* fix: compose the ECR control plane in the integration harness
The harness stopped wiring ECR's composed capabilities when the
authorization-token action was composed, so every integration test that
creates a repository or mints a token got ServerInternal. It now composes
ECR as the awsgw role does, sharing the OCI registry, meta store and token
issuer the /v2 data plane uses.
* docs: record ingress pipeline deferral
* refactor: extract AWS error envelope rendering to ingress
ingress/aws/envelope owns the EC2, IAM-style and S3 XML error envelopes, the
AWS JSON 1.1 error body and X-Amzn-Errortype value, the JSON-protocol header
detector and the two error content types. Each shape keeps its own builder.
The gateway error writers, ErrorHandler and the legacy per-service envelope
selection stay in gateway and call the new package; gateway/eks renders its
JSON errors through it directly. A 140-case status/header/body golden
comparison across services and error writers was identical before and after.
* docs: record error envelope extraction
* refactor: move AWS service selection into ingress dispatch
Selector answers served, action, error protocol, registered entry and
startup overlap. The gateway supplies its legacy tables through the
dispatch.Legacy interface; legacy dispatch and invocation building stay
in gateway.
* docs: record ingress service selection move
* test: characterize ACM control-plane dispatch before registration
Pins full-pipeline error envelopes, a successful action, target parsing
agreement between dispatch and telemetry, authorization before the NATS
call, 413 and 503 paths, throttle/trace/audit action and the inventory.
* refactor: register ACM control plane from its domain
domains/acm/awsapi registers the acm JSON 1.1 surface through the
ingress dispatch registry, wired by the awsgw role. The gateway drops
ACM_Request, the ACM action table and every legacy acm entry; the
import invariant now covers each registered domain.
* docs: record ACM registration
* docs: record ECS, EKS and RDS source inventory and first-resource ranking
* docs: record EKS control-plane secrets persisted in the cluster record
* chore: drop containerd advisory acceptance now that dev ships v2.4.1
* test: characterize RDS DB subnet group lifecycle before extraction
* docs: record RDS DB subnet group lifecycle contract
* refactor: extract the RDS DB subnet group lifecycle owner
domains/rds/subnetgroup owns the db-subnet-groups/{name} record, member
subnet validation and the delete in-use guard. handlers/rds keeps AWS
validation, projection and paging and binds two consumer-owned
capabilities: the owner's Dependants (instances naming the group) and the
instance side's subnetGroupPlacement. Stored shape and behaviour are
unchanged.
* docs: record RDS DB subnet group owner extraction
* docs: correct RDS subnet group tagging debt and conformance scope
* test: characterize ECS task definition lifecycle before extraction
* docs: record ECS task definition lifecycle contract
* refactor: extract ECS task definition owner into domains/ecs/taskdefinition
Move the task definition record, container types, keys, reference parsing,
ARN helpers and the register/deregister/resolve/list logic into a resource
owner package. Stored JSON field names and KV keys are unchanged, and
revision allocation keeps its existing non-atomic read-then-write.
The owner declares its own PortMapping and SystemControl persisted types so
it no longer depends on handlers/ecs/bus; the handler translates them onto
the assign payload. Task and service launches reach task definitions only
through a launch-side taskDefinitionResolver. AWS conversion, the guest
projection and tags stay in handlers/ecs, and gateway authz only switches to
the moved reference/ARN helpers.
List handlers/ecs and the new package under spinifex_daemon so ECS-only
changes select e2e-ecs.
* docs: record ECS task definition owner extraction
* test: characterize EKS access entry lifecycle before extraction
* docs: record EKS access entry lifecycle contract
* refactor: extract EKS access entry owner into domains/eks/access
Move the access entry record, associated policy and scope types, keys,
PrincipalARNHash, the policy catalogue and group mapping into a resource
owner package. Stored JSON field names and KV keys are unchanged.
Owner is the only writer: Create, SeedCreatorAdmin, Update, Associate,
Disassociate and Delete carry the existing logic verbatim, and the put,
compare-and-set and delete primitives are private. The handler keeps AWS
validation, the cluster existence check, error mapping and projection.
Token review still reads records through the exported Get, and the cluster
prefix purge still sweeps entry keys.
List handlers/eks and the new package under spinifex_daemon so EKS-only
changes select the EKS suites.
* docs: record EKS access entry owner extraction
* test: characterize RDS engine catalogue before extraction
* fix: return InvalidParameterValue for a missing RDS master password
ValidateMasterUserPassword built the empty-password error with a bare
errors.New carrying the code only in its text, which awserrors does not
resolve, so CreateDBInstance without MasterUserPassword returned HTTP 500
ServerInternal. Build it with awserrors.Errorf like the other branches so
the gateway returns 400 InvalidParameterValue, and cover the full gateway
to RDS service path with a regression test.
* docs: record RDS engine catalogue boundary and evidence
* refactor: extract RDS engine catalogue into domains/rds/engine
Move engine identity and validation, the per-engine parameter catalogues,
effective-parameter resolution, db.* instance classes and engine/orderable
selection into an engine package. Behaviour, error codes and ordering are
unchanged.
The package imports no EC2 package: instance-class memory comes from an
immutable Sizing value built from an engine-declared InstanceTypes
interface, backed by the fixed instance-type table in handlers/rds.
Effective parameters leave as an engine-owned Setting, converted to
Parameter in handlers/rds. AWS output building, paging, apply-method
mapping, storage limits and the gateway runnable check stay in the
adapter path.
The RDS agent declares its own EngineCatalog interface and types and
receives an engine-backed implementation from cmd/rds-agent, so agent
code does not import the catalogue. Cross-engine tests use the two real
engines instead of a registered fake.
* docs: record RDS engine catalogue owner move
* test: characterize RDS DB parameter group lifecycle before extraction
* docs: record RDS DB parameter group lifecycle contract
* refactor: extract RDS DB parameter group owner
Move the parameter group and override records, keys and listing into
domains/rds/parametergroup behind an Owner. Delete asks an owner-declared
Dependants interface; instance-side resolution reads through its own
parameterGroupValues interface. SetOverrides refuses an unknown group so
no override key is written without its group. Stored shape, keys, public
errors and propagation are unchanged.
* docs: record RDS DB parameter group owner extraction
* test: characterize EKS add-on lifecycle and guest wire
Pin the persisted record and manifest layout, create/update/delete and
status-report transitions, the ignored client token and report version,
the missing serviceAccountRoleArn PassRole check, and the exact internal
add-ons HTTP body and agent TSV output as they stand today.
* docs: record EKS add-on lifecycle contract
* fix: require iam:PassRole for EKS add-on service account role
CreateAddon and UpdateAddon now pass serviceAccountRoleArn through the
existing EKS PassedRoleARNs path, so the caller needs iam:PassRole on the
role for eks.amazonaws.com, matching CreateCluster and CreateNodegroup.
* docs: record EKS add-on PassRole check
* refactor: extract EKS add-on owner
Move the add-on catalogue, record and manifest keys, CAS, status
transitions and staging into domains/eks/addon behind an Owner that is
the sole writer. The handler keeps AWS validation, error mapping and
projection; the cluster reconciler delegates reports through the narrow
addonReports interface; node groups call EnsureGPUDevicePlugin. Stored
keys, JSON shape, wire types and lifecycle behaviour are unchanged.
* docs: record EKS add-on owner extraction
* refactor: extract EKS add-on guest wire contract
Move the add-on status subject, delivery phase, status report, staged
manifest and internal add-ons response into contracts/eks/v1 and use it
from the handler, gateway and gatewayfetch, replacing the agent's
duplicate. Wire bytes are unchanged, including the internal add-ons body
that the SDK renderer emits with Go field names; compatibility tests pin
the JSON, the guest printf form and the TSV.
* docs: record EKS add-on wire contract extraction
* docs: update EKS add-on inventory and remaining edges
* docs: draft EKS add-on lifecycle correction design for review
* chore: run contracts tests in the default test, coverage and race targets
* docs: apply review decisions to EKS add-on lifecycle design
* test: characterize EKS add-on v1 compatibility with added fields
Pin which owner writes drop unknown record and manifest fields, that
reads and deletes ignore or erase them, that one undecodable entry fails
a listing, and that v1 wire consumers ignore extra fields.
* docs: add EKS add-on executor, bundle, v1 compatibility and release inventories
* docs: draft EKS add-on v2 guest contract design for review
* docs: qualify historical architecture references
* docs: apply review decisions and ADR-0006 to EKS add-on v2 design
* fix(eks): bind internal report publishing to the caller's cluster
PublishInternal was authorised by IAM policy alone, with its resource
built from the body accountId and the URL cluster. The control-plane
role grants it on "*", so any control-plane VM session, any tenant
holding eks:*, or static system credentials could publish cluster
state, bootstrap and add-on reports for another cluster or account.
PublishInternal now passes the existing internal-route gate: the caller
must be a control-plane instance-role session that is a member of the
URL cluster in the body account. The gate and the handler decode the
body through one shared decoder, so the account checked is the account
the subject is built from. Every unauthorised target returns the same
AccessDenied, and invalid account or cluster names are treated as not
found. Valid publishes keep their subjects and payload bytes.
* fix(eks): bind webhook token review to the caller's cluster
WebhookTokenReview took its account from the request body and was
authorised by IAM policy alone, with the control-plane role granting it
on "*". A control-plane VM, any tenant holding eks:*, or static system
credentials could resolve a token against another cluster or account
and learn the Kubernetes groups it maps to there. Error responses also
distinguished absent accounts from absent clusters.
WebhookTokenReview now passes the same internal-route gate as
PublishInternal: a control-plane instance-role session that is a member
of the URL cluster in the body account. The gate and the handler share
one body decoder, each body-scoped internal route must declare its
reader, and every unauthorised target returns the same AccessDenied
without reaching STS verification. Same-cluster responses are unchanged.
* fix(eks): validate add-on serviceAccountRoleArn syntax
CreateAddon and UpdateAddon stored serviceAccountRoleArn without
checking it was an ARN, and the guest renders the value into the
add-on's manifests. A non-empty value must now be syntactically an IAM
role ARN (12-digit account, no region, role resource, IAM name and path
rules); anything else returns InvalidParameterException before any
record is written or manifest staged.
The syntax check is foundation/aws/arn.ValidateRoleARN. iam:PassRole at
the gateway remains the permission and existence check. Stored values
are not rewritten, and an UpdateAddon that omits the field still
succeeds on a record holding a legacy value.
* docs: record EKS internal-route and role-ARN security corrections
* docs: add EKS add-on release membership and activation case study
* fix: point UI build, CI and lint rules at moved package paths
* docs: record EKS add-on activation review decisions
* refactor: move quota admission to domains/admission/quota
Relocate the quota service, live counters and vCPU records from
handlers/quota to domains/admission/quota. Package renamed from
handlers_quota to quota; callers with a local quota identifier import it
as admissionquota. KV buckets, subjects and error codes are unchanged, and
the package's existing debt edges move with it unchanged.
* docs: reconcile package-boundary record for ADR-0001 close-out
Add the missing slice rows (the commits that dissolved spinifex/types, the
ECR repository projection, the stale-path fix and the quota move), correct
stale entries, record the dependency-rule breaks found in the import graph
with removal conditions, add the close-out table of remaining legacy paths
with their decided target owners, recount the mulga-side follow-ups, and
fix stale old-path references in docs and comments.
* test: move KV migration engine tests to foundation/state/migrate
The Registry and RunKV tests exercise foundation/state/migrate exclusively
but lived in spinifex/migrate's test file. Relocate them, with their NATS
helpers, to the package that owns the engine. No test name, assertion or
behaviour changes.
* refactor: move config and object-store upgrade workflow to operator/upgrade
Relocate spinifex/migrate, the operator-driven config-file and object-store
upgrade workflow behind spx admin upgrade, to operator/upgrade. Package
renamed to upgrade (imported as opupgrade where a local upgrade identifier
exists). It stays distinct from foundation/state/migrate, the generic KV
migration engine; no registry types, migration names, versions, file
formats or command names change.
* docs: record migrate move to operator/upgrade
* test: enforce ADR-0001 layering with a blocking ratchet
Add spinifex/architecture/layering, a test-only package that parses the
module's import graph, maps every production package to an ADR-0001
layer and checks each dependency rule as its own subtest. Existing
violations are allow-listed against their recorded debt; a new forbidden
edge, an unmapped package, a stale allowlist entry or a new package
under a frozen legacy root fails local preflight and CI.
Record the nine edges the test found missing from the migration record
(quota -> EC2 instance types, STS/Ochre/ELBv2 -> IAM, ELBv2
cross-domain, installer UI -> admin), name the importers of the utils
residuals and gateway/ec2_idempotency.go, and correct the handlers/iam
consumer list.
* refactor: drop the legacy handlers_ecr import alias
Import domains/ecr under its package name, or as ecrdomain where the
file also imports the AWS SDK ecr package, matching acmdomain. Also fix
a stale daemon file reference in the integration ECR daemon comment.
* chore: mark spf13/pflag as a direct dependency
operator/cli/wiring.go imports pflag directly. Same version; no upgrade.
* docs: record test-package-check and nilaway as unverified gates
* refactor: move the layering test to module-root architecture/
The ADR-0001 layering ratchet is repository governance tooling, not
Spinifex product code, so it sits beside tests/ rather than under the
spinifex/ product tree. make test, test-cover and test-race now include
./architecture/..., and the graph walk excludes architecture/.
* fix: update paths left stale by the package moves
The MariaDB image stamp test read the RDS engine from
handlers/rds/engine_mariadb.go, so test-images failed in CI; it now reads
domains/rds/engine/mariadb.go. Comments citing moved files now name
their new locations.
* refactor: move the default-VPC subject into contracts/ec2/v1
utils.SubjectEnsureDefaultVpc becomes ec2v1.EnsureDefaultVpcSubject, the
request/reply route between gateway account creation and the daemon.
Only the subject moves; the request and reply bodies are still anonymous
structs on each side and are recorded as such in the contract README.
The layering freeze now allows two utils files.
* docs: qualify the migrate split and record admin and Viperblock findings
The migrate row is a split, not an exact ADR-0001 map row, and needs a map
clarification. Correct the stale admin consumers, record the operator-only
admin files as movable, the vbwire prerequisite for the Viperblock adapter
and the capability decision encryption.go needs.
* refactor: move operator-only admin code to operator/admin
Config generation, certificate issuance, host discovery, telemetry,
email validation and image import/removal/orphan-volume tooling move
to operator/admin. Legacy admin keeps only the symbols with
non-operator consumers: default account identifiers, AWS credential
generators and system image promotion.
foundation/pki and the tenant ACM CA are unchanged. The readAMI
helper and the removal test fixtures are duplicated privately in
legacy admin rather than shared across the split. The now-stale
operator/installer/ui -> admin layering allowlist entry is removed.
* docs: record operator/admin split in package-boundary migration
* test: pin viperblockd fence, abandon and dirty-marker wire shapes
Characterization tests against the current vbwire package, before it
moves to contracts/viperblockd/legacy/v1: both subject forms for the
fenced and abandon routes, golden JSON for VolumeFencedEvent,
VolumeAbandonRequest, VolumeAbandonResponse and DirtyRecord, the dirty
bucket name, and the volume-key pattern shared by the lease and dirty
stores.
* refactor: move viperblockd fence, abandon and dirty-marker vocabulary to contracts
Move the fence and abandon subjects/DTOs, the dirty bucket name,
DirtyRecord and the shared volume-key pattern out of vbwire and into
contracts/viperblockd/legacy/v1, alongside the package's existing
mount/unmount/delete/sync/config-update routes. vbwire keeps only the
I/O helpers (BindDirtyBucket, ListUnsealedVolumes), now built on the
contract vocabulary instead of defining it.
Record the approved dirty-marker ownership boundary in the contract
README: the Viperblock adapter is the sole producer, viperblockd was
only its transitional custodian. Document the fence and abandon routes
and the dirty bucket in docs/service-interfaces.yaml.
* refactor: split the Viperblock EBS adapter out of services/viperblockd
Move the EBS provider adapter (volume lease, fence, dirty marker,
nbdkit recovery, provider handlers, encryption key loading) to
providers/ebs/viperblock. services/viperblockd keeps only process
lifecycle and the NATS subscription wiring that starts and stops it.
The dirty-bucket read path moves to providers/ebs/viperblock/dirty as
a read-only ListUnsealedVolumes capability; the adapter's write, clear
and purge logic stays unexported in the adapter package. Delete
services/viperblockd/vbwire now that its vocabulary lives in
contracts/viperblockd/legacy/v1 and its I/O helpers live in dirty.
Update operator/cli, the runtime service registry, qemunbdd's config
comment and the integration test harness to the new import paths, and
drop the now-stale architecture/layering allowlist and frozen-package
entries for the deleted package. Behaviour, persisted keys and NATS
subjects are unchanged.
* refactor: move the viperblockd role to runtime/roles/viperblockd
With the EBS adapter in providers/ebs/viperblock, services/viperblockd
holds only role supervision and the opt-in live data-path tests, so it
joins the other runtime roles. It was the last package under services/;
the frozen legacy list drops it.
* docs: record viperblockd contract, adapter and role moves
* test: characterise vpc.* network-realisation routes
Pin every vpc.* subject, JSON payload shape and the request/reply
{success,error} ack envelope exactly as they exist today, ahead of
introducing contracts/network/v1. Covers the 22 subjects registered
by domains/network/subscribers, the vpc.igw-attach/detach subjects
and InternetGatewayEvent already owned by contracts/ec2/v1, the
utils.AddNAT/PublishNATEvent client wire behaviour including the
delete-nat retry-on-ErrNoResponders budget, and the EC2-side NATEvent
and SGEvent/SGRule duplicates in domains/ec2/vpc.
Also adds the six vpc.* route-table and system-egress subjects that
were missing from service-interfaces.yaml despite being live
production routes (vpc.add/delete-igw-route, vpc.gate/ungate-subnet-
egress, vpc.add/delete-system-egress).
* feat: add contracts/network/v1 for vpc.* realisation routes
Declare the versioned wire vocabulary for the vpc.* control-plane-to-
network-realisation boundary: subjects, payload types, the shared
{success,error} ack envelope and the vpcd-workers queue group, one
file per route family. No NATS I/O, no consumer switched over yet;
the package coexists with the fragmented originals pinned in the
prior characterization commit until slice 3 migrates call sites.
* refactor: use contracts/network/v1 for vpc.* producers and consumers
Switch every vpc.* producer (domains/ec2/vpc, eip, instance, natgw,
routetable, igw, handlers/elbv2, handlers/eks, daemon, systemvpc) and the
network/subscribers consumer onto contracts/network/v1 subjects, event
types and the shared AckEnvelope. contracts/network/v1 becomes the sole
owner of vpc.igw-attach/detach, replacing the duplicate definitions in
contracts/ec2/v1.
Deletes the duplicated local subject constants and event structs:
subscribers' Topic* consts and event structs, vpc.NATEvent and SGEvent,
eip's natEvent, natgw's natGatewayEvent, and eks's systemEgressEvent.
domains/ec2/vpc.SGRule survives because EC2 persists it directly in
SecurityGroupRecord; contracts/network/v1.SecurityGroupRule was expanded
in slice 2 to match it field-for-field so wire bytes are unchanged.
No lifecycle or reliability changes: the NAT add barrier, delete
retry-on-ErrNoResponders, and the inconsistent per-call-site NAT
delivery modes (EIP AssociateAddress and DeleteNetworkInterface both stay
fire-and-forget with no ack) are preserved exactly, as are the golden
wire literals pinned in the characterization tests.
* refactor: replace utils/vpcd_event.go with a typed network projection client
Every vpc.* call site now goes through domains/network/projection's
operation-specific methods instead of utils.AddNAT, utils.PublishNATEvent
or utils.RequestEvent, so no caller passes a bare subject string. Each
method states today's delivery mode by name: AddNAT stays strict,
AddNATBestEffort and AnnounceNATAdd/AnnounceNATDelete keep the gaps those
call sites already had, and RemoveNAT keeps the ErrNoResponders retry.
utils/vpcd_event.go and its tests are deleted; the behaviour they pinned
(wire shape, ack envelope, retry-on-no-responders) moved into the
projection package's own golden and nat tests, unchanged. utils/ now
holds only encryption.go, which this does not touch.
* refactor: route the remaining fire-and-forget vpc.* producers through projection
CreateVPC/DeleteVPC, CreateSubnet/DeleteSubnet, AttachInternetGateway/
DetachInternetGateway, AddNATGateway/RemoveNATGateway, AddIGWRoute/
RemoveIGWRoute, GateSubnetEgress/UngateSubnetEgress and RemoveSystemEgress
were still publishing through natsmsg.PublishEvent or a raw nc.Publish
call with a bare subject string, left over from the mechanical slice 3
pass. Each now goes through its named projection.Client method instead,
so every vpc.* producer in the tree uses the typed client.
* refactor: move EBS encryption posture to domains/ec2/ebs/encryption and delete utils
The master-key loader was used only by EC2 image, instance and volume to
derive the AWS-visible Encrypted flag. It becomes ebsencryption.Enabled,
EC2's temporary reading of the provider's key-file setting; the cache,
empty-path meaning, error text and each caller's error handling are
unchanged (image still reports unencrypted when the key will not load).
Its successor is a providers/ebs capability reporting volume encryption
posture.
utils/ is now empty and deleted. The layering test drops utils and
services from the legacy roots, removes their allowlist entries and fails
if either retired root regains files. The S7 subject scan follows the
vpc.* literals from utils to contracts/network so its gap list stays
complete.
* docs: record the network contract, projection client and utils removal
* test: characterise instance-state persistence, recovery and generation handling
Pin the current local-file bytes and schema failure modes, the instance
bucket configuration, record key and wire form, the bucket version gate,
generation preservation across every KV writer and the VM conversion, and
what a returning node does for a missing, foreign, terminal or unreadable
canonical record. These describe current behaviour, not the ADR-0007 target.
* test: freeze direct instance-state consumers
Add an AST ratchet over production code that fails when a new file names
the daemon's instance-state bucket, record keys, local-file API, the raw
vm.InstanceRecord or its conversion, or a JetStreamManager instance-state
method. Today's 73 uses form a shrink-only allowlist keyed to the slice 0
inventory; stale entries fail, and a synthetic-source self-test proves the
matcher detects each kind of use and ignores declarations.
* docs: record ADR-0007 slice 0 instance-state inventory
Record the instance-state persistence formats, the nineteen direct
consumers by process and access kind, the characterised recovery and
schema outcomes, the generation-preservation matrix and the ratchet that
freezes the consumer set. Nothing conforms to ADR-0007 yet and vpcd stays
blocked.
* test: narrow the instance-state ratchet to instance-state access
Stop freezing the JetStreamManager type and constructor, which also serve
cluster state; flag only instance-state methods, bucket and key identifiers,
record codecs and local-state access. The cluster-state-only consumers in
daemon_mgmt_ip.go and operator/cli/cluster.go leave the allowlist (73 to 67).
The self-test now proves a cluster-state use is ignored and an instance-state
method call is caught. Record the owner's disposition of the KV-unavailable
restore result in the migration record.
* docs: record the narrowed instance-state ratchet commit
* docs: design the instance-state transition record and activation gate
* docs: record the instance-state transition-record design commit
* docs: record slice 1a activation-gate decisions
* feat: add instance transition-record codec with format marker
Adds DecodeTransitionRecord and TransitionRecord.Encode in the record's owner
package. A top-level format member selects the shape: absent or 1 decodes the
legacy record and is never given a marker on write; 2 also decodes the new
assignment and observation sections; an integer above 2 decodes its legacy
fields read-only and Encode refuses it; anything else is refused on decode.
Encode applies only the typed paths that differ from the decode-time snapshot
onto the input, so unknown members at every object level and unchanged known
fields keep their read form. A changed array is replaced whole. Decode refuses
malformed JSON, duplicate keys at any depth, keys that alias a known field by
case, trailing data and a non-object record, each with its own sentinel.
No production reader or writer uses the codec yet; the new types are not
part of vm.InstanceRecord, so every existing record encodes unchanged. The
codec file is registered as an owner file of the instance-state ratchet.
* docs: record slice 1b step 1 codec and awsgw rollout qualification
Records the codec added in e62f921d2 as design Section 10 (C1 to C7): its
surface, preservation at every object level, the changed-array limitation,
marker handling, the rejection classes and its capable-writers-only scope. C2
supersedes P1's top-level-only preservation for the codec. G19 records that
old read-only gateway consumers remain safe but DescribeInstanceStatus gains
unconfirmed/degraded visibility only after awsgw upgrades. The migration record
gains the commit row and states that no production path uses the codec yet.
* refactor: move the instance transition-record codec to domains/ec2/instance/state
The codec defines how the canonical persisted instance record evolves, with
its assignment and observation sections, which is EC2 instance ownership rather
than node-local VM supervision. It moves unchanged into its own package and
keeps wrapping the legacy vm.InstanceRecord alias and its spec and status
types, which stay in runtime/compute/vm for now.
The domain-to-runtime import is recorded as new dependency-rule debt with its
removal condition and allow-listed against that entry. The instance-state
ratchet now names the new file as an owner file; its allowlist is unchanged.
* fix: refuse array changes that would drop element extensions
A changed array is replaced whole by the writer's value, which silently lost
any member a newer writer had added inside its elements. Encode now inspects
the array as read: if any element carries a member its typed schema does not
know, at any depth, it returns ErrRecordExtensionConflict naming the array and
the first such member. Arrays without such members are still replaced whole,
unchanged arrays are still kept verbatim, and arrays inside unknown members are
never inspected.
* docs: record the codec move and the array extension-conflict rule
Records 8db9771fb and c617914a1. T1 and Section 10 now name
domains/ec2/instance/state as the eventual owner of the persisted instance
record and its evolution, with vm.InstanceRecord as the temporary legacy type
it wraps. C3 replaces the changed-array limitation with the refusal: a changed
array with element extensions fails with ErrRecordExtensionConflict and is never
silently dropped. P2 stays a conservative rule until finalisation.
* fix: refuse removals that would drop record extension fields
A capable writer may no longer remove or replace a known object, map entry or
array when its stored value carries members the writer's schema does not know.
The check that guarded changed arrays now runs wherever the merge drops or
overwrites a stored value instead of merging into it: a known member deleted or
set to null, a map entry removed or stored under a key the typed decode
rewrote, a value of another JSON kind, and a changed array. Encode returns
ErrRecordExtensionConflict naming the changed container and the first unknown
member. Removal stays allowed when the stored value has no extensions, and a
change merged member by member still keeps unknown members.
* docs: record the uniform extension-conflict rule
Adds design clause C8 for 0d7b4266d: a capable writer may not remove or
replace a known object, map entry or array whose stored value carries unknown
structured extension fields; removal without extensions stays allowed. C3 and
C5 point at it. The migration record gains the commit row, updated subsection
wording and a pointer-bump follow-up deferring make docs-portal to the Mulga
gitlink PR so the portal evaluates the proposed Spinifex revision.
* refactor: inject vpcd's IMDS instance-state readers from the instance state boundary
* docs: cite the vpcd reader injection commit in the migration record
* refactor: move vpcd to runtime/roles/vpcd
* docs: cite the vpcd move commit in the migration record
* refactor: move the ECS agent wire vocabulary to contracts/ecs/v1
Move handlers/ecs/bus to contracts/ecs/v1 (package ecsv1) with no legacy
shim. Subject strings, JSON fields and types are byte-identical; the old-agent
compatibility test moves unchanged and golden pins cover the remaining
message types. The README route table records that only service-reconcile
has a live producer today; the agent reuses these payload types through the
gateway actions. service-interfaces.yaml lists ecs.bus.* under the daemon.
* refactor: move system-image promotion to domains/ec2/image
Move images_promote.go and its tests from admin to domains/ec2/image:
SystemOwnerAlias, PromoteImageOpts/PromoteImageResult, PromoteSystemImage,
GetAMIMetadata and the private snapshot reader. Storage, ordering, errors and
promotion behaviour are unchanged; the daemon, gateway/spx and operator CLI
callers import ec2image. admin now holds only account IDs and key generators.
* docs: record the ECS contract and image-promotion moves and the remaining-roots matrix
* refactor: move the bootstrap account identifiers to foundation/aws/identifiers
DefaultAccountID and DefaultAccountName join GlobalAccountID as the fixed,
platform-reserved identity of the first human-facing bootstrap account.
Names and values are unchanged and stay fixed. Callers in daemon, gateway,
awsgw, accountteardown and the operator CLI use awsidentifiers; admin now
holds only the IAM credential generators.
* docs: cite the bootstrap account identifier move in the migration record
* refactor: inject the STS cluster JWKS lookup from handlers/eks
handlers/sts declares ClusterJWKSResolver and keeps JWKS decoding and
InvalidIdentityToken mapping; handlers/eks implements it as
OIDCJWKSReader beside the bucket and key layout helpers. awsgw and the
integration harness inject the reader. STS no longer imports any EKS
package, including tests, and the handlers/sts -> handlers/eks layering
exception is removed.
* docs: cite the STS JWKS resolver cut in the migration record
* refactor: move the AWS credential-format generators to foundation/aws/credentials and retire admin
GenerateAWSAccessKey and GenerateAWSSecretKey move unchanged to
foundation/aws/credentials as a stateless format primitive. handlers/iam
and operator/cli import it directly. The admin legacy root is deleted
and joins the retired roots so it cannot return.
* docs: cite the admin retirement in the migration record
* revert: remove the uncalled ADR-0007 codec and design stack from the ADR-0001 checkpoint
The instance transition-record codec, its tests and the slice 1a design
had no production caller. They leave this package-boundary checkpoint
and will be reapplied on a dedicated ADR-0007 branch. Slice 0
characterisation and the vpcd IMDS readers in
domains/ec2/instance/state stay.
* docs: cite the ADR-0007 codec revert in the migration record
* fix: declare the ECS action subjects in service-interfaces.yaml
Declaring ecs.bus.* made ecs a managed prefix for manifest-lint, which then
failed on the 34 ECS action subjects the daemon registers. Declare them as
ecs.*, the same wildcard convention as rds.*.
* chore: run manifest-check and manifest-lint in preflight
CI runs both, but preflight did not, so manifest drift could pass local
checks and still fail Build and Test.
* docs: record resumed preflight enforcement and dev merge ports
* fix: restore dev changes dropped by earlier merges
Reapplies the slices.ContainsFunc rewrite in nodeFitsCustomerInstance and the DeleteDBSubnetGroup doc comment, both lost when their files were refactored.
* docs: record accountteardown as a frozen legacy root pending cleanup capabilities
---------
Co-authored-by: Julian Sommer <115516918+juliansommer@users.noreply.github.com>
848 lines
41 KiB
Go
848 lines
41 KiB
Go
//go:build e2e
|
|
|
|
package iam
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"fmt"
|
|
"hash/fnv"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/aws/aws-sdk-go/aws"
|
|
"github.com/aws/aws-sdk-go/service/ec2"
|
|
"github.com/aws/aws-sdk-go/service/iam"
|
|
"github.com/aws/aws-sdk-go/service/sts"
|
|
"github.com/mulgadc/spinifex/spinifex/domains/dns"
|
|
"github.com/mulgadc/spinifex/tests/e2e/harness"
|
|
"github.com/stretchr/testify/require"
|
|
"golang.org/x/crypto/ssh"
|
|
)
|
|
|
|
// IMDS E2E identifiers. The role/profile carry an imds-e2e- prefix so they
|
|
// never collide with the IAM-roles suite ("app-role"/"app-profile") or the
|
|
// STS suite ("sts-e2e-role").
|
|
const (
|
|
imdsRoleName = "imds-e2e-role"
|
|
imdsProfileName = "imds-e2e-profile"
|
|
|
|
// imdsAdminPolicyName is the bootstrap managed policy attached to the IMDS
|
|
// role so the minted instance-role creds round-trip a real API call.
|
|
imdsAdminPolicyName = "AdministratorAccess"
|
|
// imdsTrustPolicyEC2 lets ec2.amazonaws.com assume the IMDS instance role.
|
|
imdsTrustPolicyEC2 = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}`
|
|
|
|
// metaURL is the AWS-compatible link-local IMDS endpoint, answered at the
|
|
// guest's own host tap by the per-tap responder: the tap rides the OVN-
|
|
// unmanaged br-imds bridge, where a demux flow steers 169.254.169.254 to a
|
|
// SO_BINDTODEVICE-bound responder and a patch carries everything else to
|
|
// br-int. Identity is the tap (→ ENI), not the source IP; no per-subnet
|
|
// localport, no netns, no in-guest route.
|
|
metaURL = "http://169.254.169.254"
|
|
|
|
// imdsUserData is a #cloud-config carrying a unique marker, used two ways: the
|
|
// /latest/user-data round-trip asserts the body the guest sees matches what
|
|
// RunInstances was given, and its runcmd writes imdsUDMarker to imdsUDDoneFile
|
|
// so the boot-from-IMDS guard can prove cloud-init actually RAN user-data from
|
|
// the Ec2 datasource, not just that the responder served it.
|
|
imdsUserData = "#cloud-config\n" +
|
|
"# imds-e2e-userdata-marker-7f3a91\n" +
|
|
"runcmd:\n" +
|
|
" - [ sh, -c, \"echo imds-e2e-userdata-marker-7f3a91 > /run/imds-e2e-userdata.done\" ]\n"
|
|
imdsUDMarker = "imds-e2e-userdata-marker-7f3a91"
|
|
imdsUDDoneFile = "/run/imds-e2e-userdata.done"
|
|
|
|
// imdsProbeVPCCIDR / imdsProbeSubnetCIDR are shared by BOTH isolation VPCs.
|
|
// Overlapping CIDRs across VPCs are legal (each VPC is its own routing
|
|
// domain); using identical subnets makes IPAM hand the first VM in each the
|
|
// SAME private IP (network+4, deterministic per ipam.go). With a shared
|
|
// source IP the only thing that can tell the two VMs apart is their tap, so
|
|
// this is exactly the case the per-tap tap→ENI identity must resolve.
|
|
imdsProbeVPCCIDR = "10.211.0.0/16"
|
|
imdsProbeSubnetCIDR = "10.211.7.0/24"
|
|
)
|
|
|
|
// imdsCredDoc mirrors the AWS credential JSON served at
|
|
// /latest/meta-data/iam/security-credentials/<role>. Only the fields the test
|
|
// asserts on are decoded.
|
|
type imdsCredDoc struct {
|
|
Code string `json:"Code"`
|
|
Type string `json:"Type"`
|
|
AccessKeyId string `json:"AccessKeyId"`
|
|
SecretAccessKey string `json:"SecretAccessKey"`
|
|
Token string `json:"Token"`
|
|
Expiration string `json:"Expiration"`
|
|
AccountId string `json:"AccountId"`
|
|
}
|
|
|
|
// runIMDS exercises the host-served IMDSv2 surface end-to-end against real guest
|
|
// VMs over the per-tap datapath. It stands up two VPCs with identical subnet
|
|
// CIDRs and one VM in each so the two VMs share a private IP:
|
|
//
|
|
// - VM X (profile-bound, user-data) drives the full surface: IMDSv2 token
|
|
// issuance, the v2-only stance (tokenless / garbage-token GET → 401), the
|
|
// metadata fields, the instance-role credential path + a wire round-trip
|
|
// proving the ASIA creds resolve to the instance assumed-role ARN, and the
|
|
// /latest/user-data round-trip — all reached from the guest with no in-guest
|
|
// route, since the responder intercepts at the tap regardless of addressing.
|
|
// - The per-tap datapath shape: the guest's tap + the ime-/imp- endpoint and
|
|
// patch live on the OVN-unmanaged br-imds bridge, the imi- patch end on
|
|
// br-int carries the guest's OVN iface-id, and br-imds carries the demux
|
|
// (priority=200, capturing 169.254.169.254) and forward (priority=100) flow
|
|
// tiers. Host-local; skipped when the VM landed on another chassis.
|
|
// - The file-capability proof: the live vpcd serves under the restored sandbox
|
|
// with CAP_NET_ADMIN/NET_RAW/NET_BIND_SERVICE and no CAP_SYS_ADMIN.
|
|
// - Cross-VPC isolation: VM X and VM Y share the same source IP in different
|
|
// VPCs, yet each IMDS returns its OWN instance-id — the tap→ENI identity
|
|
// boundary, which a source-IP lookup could not disambiguate.
|
|
//
|
|
// OVN + SSH gated: the IMDS datapath needs ovn-controller to bind the guest LSP
|
|
// to the patch per chassis, and every guest-facing assertion runs via SSH.
|
|
func runIMDS(t *testing.T, fix *Fixture) {
|
|
harness.Phase(t, "Single — IMDSv2 Host-Served Instance Metadata")
|
|
harness.SkipIfNoOVN(t)
|
|
sshHealth.Require(t)
|
|
|
|
adminAccount := harness.IAMAccountID(t, fix.AWS)
|
|
keyName, keyPath := needKeyPair(t, fix)
|
|
imdsEnsureRoleProfile(t, fix, adminAccount)
|
|
|
|
// Two VPCs, identical subnet CIDR → the first VM in each gets the same IP.
|
|
// The VPC IDs are logged inside imdsEnsureProbeVPC; the L2 datapath and the
|
|
// isolation assertions key off the subnet and the instance identity, not the
|
|
// VPC ID, so they aren't bound here.
|
|
_, subX, sgX := imdsEnsureProbeVPC(t, fix, imdsProbeVPCCIDR, imdsProbeSubnetCIDR)
|
|
_, subY, sgY := imdsEnsureProbeVPC(t, fix, imdsProbeVPCCIDR, imdsProbeSubnetCIDR)
|
|
|
|
// VM X — profile-bound + user-data; drives the full surface. eniX builds the
|
|
// guest LSP name (port-<eni>) for the ovn-trace datapath assertion.
|
|
idX, privX, eniX, tgtX := imdsProbe(t, fix, keyPath, imdsVMSpec{
|
|
subnetID: subX,
|
|
sgID: sgX,
|
|
profileName: imdsProfileName,
|
|
userData: imdsUserData,
|
|
})
|
|
// VM Y — isolation peer; no profile needed for the instance-id probe.
|
|
idY, privY, _, tgtY := imdsProbe(t, fix, keyPath, imdsVMSpec{
|
|
subnetID: subY,
|
|
sgID: sgY,
|
|
})
|
|
require.NotEqual(t, idX, idY, "the two probe VMs must be distinct instances")
|
|
require.Equalf(t, privX, privY,
|
|
"isolation premise: both first-in-subnet VMs must share a private IP "+
|
|
"(IPAM is deterministic at network+4) — got %s vs %s", privX, privY)
|
|
harness.Detail(t, "vm_x", idX, "vm_y", idY, "shared_priv", privX)
|
|
|
|
// --- Per-tap datapath shape (host-local) + file-capability proof ---------
|
|
// The per-tap successor to the retired per-subnet ovn-trace L2 assertion:
|
|
// the guest's tap rides br-imds with the endpoint/patch ports and flow tiers,
|
|
// and the live vpcd serves it without CAP_SYS_ADMIN.
|
|
imdsAssertPerTapDatapath(t, eniX)
|
|
imdsAssertVpcdFileCaps(t)
|
|
|
|
// --- IMDSv2 token issuance ----------------------------------------------
|
|
harness.Step(t, "PUT /latest/api/token (IMDSv2)")
|
|
tokenX := imdsAwaitToken(t, fix, tgtX, subX, privX)
|
|
harness.Detail(t, "token_len", len(tokenX))
|
|
|
|
// --- v2-only stance: tokenless + garbage-token GET → 401 -----------------
|
|
harness.Step(t, "tokenless GET /latest/meta-data/instance-id → 401")
|
|
require.Equal(t, "401", imdsCode(tgtX, "", "/latest/meta-data/instance-id"),
|
|
"IMDSv1 (tokenless) GET must be rejected with 401")
|
|
harness.Step(t, "garbage-token GET → 401")
|
|
require.Equal(t, "401",
|
|
imdsCode(tgtX, `-H "X-aws-ec2-metadata-token: not-a-real-token"`, "/latest/meta-data/instance-id"),
|
|
"unknown token must be rejected with 401 (no token-exists leak)")
|
|
|
|
// --- SSRF defence: X-Forwarded-For → 403 even with a valid token ---------
|
|
// A forwarded request is a proxied SSRF attempt; the host refuses it before
|
|
// the token is consulted, so a valid token does not rescue it.
|
|
harness.Step(t, "X-Forwarded-For GET with valid token → 403")
|
|
require.Equal(t, "403",
|
|
imdsCode(tgtX, fmt.Sprintf(`-H "X-aws-ec2-metadata-token: %s" -H "X-Forwarded-For: 10.0.0.1"`, tokenX),
|
|
"/latest/meta-data/instance-id"),
|
|
"X-Forwarded-For must be rejected with 403 even with a valid token (SSRF defence)")
|
|
|
|
// --- Token-TTL validation: missing / 0 / over-max / non-numeric → 400 ----
|
|
// PUT /latest/api/token requires X-aws-ec2-metadata-token-ttl-seconds in
|
|
// [1,21600]; anything outside that mints no token and returns 400.
|
|
for _, tc := range []struct{ label, header string }{
|
|
{"missing", `-X PUT`},
|
|
{"zero", `-X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 0"`},
|
|
{"over-max", `-X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21601"`},
|
|
{"non-numeric", `-X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: abc"`},
|
|
} {
|
|
harness.Step(t, "PUT token with %s TTL → 400", tc.label)
|
|
require.Equalf(t, "400", imdsCode(tgtX, tc.header, "/latest/api/token"),
|
|
"PUT token with %s TTL must be 400", tc.label)
|
|
}
|
|
|
|
// --- Method-not-allowed: token is PUT-only, metadata is GET-only → 405 ---
|
|
// The method check precedes token validation, so neither probe needs a token.
|
|
harness.Step(t, "GET /latest/api/token → 405; PUT metadata path → 405")
|
|
require.Equal(t, "405", imdsCode(tgtX, "", "/latest/api/token"),
|
|
"GET on the PUT-only token endpoint must be 405")
|
|
require.Equal(t, "405", imdsCode(tgtX, `-X PUT`, "/latest/meta-data/instance-id"),
|
|
"PUT on a GET-only metadata path must be 405")
|
|
|
|
// --- Metadata surface ----------------------------------------------------
|
|
harness.Step(t, "GET metadata surface")
|
|
require.Equal(t, idX, imdsGet(t, tgtX, tokenX, "/latest/meta-data/instance-id"),
|
|
"instance-id mismatch")
|
|
require.Equal(t, privX, imdsGet(t, tgtX, tokenX, "/latest/meta-data/local-ipv4"),
|
|
"local-ipv4 must equal the request source IP")
|
|
require.NotEmpty(t, imdsGet(t, tgtX, tokenX, "/latest/meta-data/instance-type"),
|
|
"instance-type must be populated")
|
|
require.NotEmpty(t, imdsGet(t, tgtX, tokenX, "/latest/meta-data/mac"),
|
|
"mac must be populated")
|
|
azX := imdsGet(t, tgtX, tokenX, "/latest/meta-data/placement/availability-zone")
|
|
require.NotEmpty(t, azX, "placement/availability-zone must be populated")
|
|
|
|
// Cheap one-field/static leaves: a real reservation id, the static
|
|
// instance-life-cycle, and the services subtree.
|
|
require.True(t, strings.HasPrefix(imdsGet(t, tgtX, tokenX, "/latest/meta-data/reservation-id"), "r-"),
|
|
"reservation-id must be served as an r-… identifier")
|
|
require.Equal(t, "on-demand", imdsGet(t, tgtX, tokenX, "/latest/meta-data/instance-life-cycle"),
|
|
"instance-life-cycle must be on-demand (Spot not modelled)")
|
|
require.Equal(t, "aws", imdsGet(t, tgtX, tokenX, "/latest/meta-data/services/partition"),
|
|
"services/partition must be aws")
|
|
require.Equal(t, harness.NorthstarAWSInternalSuffix(fix.Env), imdsGet(t, tgtX, tokenX, "/latest/meta-data/services/domain"),
|
|
"services/domain must be the cluster's configured services domain, never amazonaws.com")
|
|
|
|
// public-hostname needs a public IP, else 404. In pool mode the probe subnet
|
|
// maps one on launch; in dev_networking it has none, so the two modes
|
|
// exercise the two branches.
|
|
if fix.PoolMode {
|
|
pubIP := imdsGet(t, tgtX, tokenX, "/latest/meta-data/public-ipv4")
|
|
require.NotEmpty(t, pubIP, "pool-mode VM must have a public IP")
|
|
gotHost := imdsGet(t, tgtX, tokenX, "/latest/meta-data/public-hostname")
|
|
|
|
// A pool-mode fixture provides Northstar, so the responder must serve the
|
|
// AWS-shaped EC2 name built from the ENI's public IP and its AZ's region.
|
|
base := harness.RequireDNSEnabled(t, fix.Env)
|
|
want := dns.EC2PublicName(pubIP, imdsRegionFromAZ(azX), base)
|
|
require.Equal(t, want, gotHost,
|
|
"public-hostname must be the AWS-shaped EC2 name for public-ipv4")
|
|
|
|
harness.Step(t, "resolve IMDS public-hostname %s from the guest", gotHost)
|
|
resolved := harness.RunSSH(t, tgtX, "getent ahostsv4 "+gotHost)
|
|
require.Containsf(t, strings.Fields(resolved), pubIP,
|
|
"public-hostname %s did not resolve to public-ipv4 %s: %s", gotHost, pubIP, resolved)
|
|
} else {
|
|
require.Equal(t, "404",
|
|
imdsCode(tgtX, fmt.Sprintf(`-H "X-aws-ec2-metadata-token: %s"`, tokenX),
|
|
"/latest/meta-data/public-hostname"),
|
|
"no public IP → public-hostname must 404")
|
|
}
|
|
|
|
// VM X is profile-bound, so meta-data/ lists iam/ and cloud-init descends.
|
|
require.Contains(t, imdsGet(t, tgtX, tokenX, "/latest/meta-data/"), "iam/",
|
|
"profile-bound meta-data/ listing must include iam/")
|
|
// iam/info → InstanceProfileArn ends with the bound profile.
|
|
iamInfo := imdsGet(t, tgtX, tokenX, "/latest/meta-data/iam/info")
|
|
require.Containsf(t, iamInfo, ":instance-profile/"+imdsProfileName,
|
|
"iam/info must carry the bound InstanceProfileArn (got %q)", iamInfo)
|
|
// security-credentials/ lists the role name (not the profile name).
|
|
require.Equal(t, imdsRoleName, imdsGet(t, tgtX, tokenX, "/latest/meta-data/iam/security-credentials/"),
|
|
"security-credentials/ must list the resolved role name")
|
|
|
|
// --- public-keys ---------------------------------------------------------
|
|
// The launch key injection path cloud-init's Ec2 datasource queries: the two
|
|
// directory listings plus the material leaf, served live from the key store.
|
|
harness.Step(t, "GET /latest/meta-data/public-keys/ subtree")
|
|
require.Equal(t, "0="+keyName, imdsGet(t, tgtX, tokenX, "/latest/meta-data/public-keys/"),
|
|
"public-keys/ must list 0=<keyName>")
|
|
require.Equal(t, "openssh-key", imdsGet(t, tgtX, tokenX, "/latest/meta-data/public-keys/0/"),
|
|
"public-keys/0/ must list the openssh-key format")
|
|
gotKey := imdsGet(t, tgtX, tokenX, "/latest/meta-data/public-keys/0/openssh-key")
|
|
wantType, wantB64 := imdsExpectedPubKey(t, keyPath)
|
|
gotFields := strings.Fields(gotKey)
|
|
require.GreaterOrEqualf(t, len(gotFields), 2,
|
|
"public-keys/0/openssh-key must serve <type> <base64> (got %q)", gotKey)
|
|
require.Equal(t, wantType, gotFields[0], "public key type mismatch")
|
|
require.Equal(t, wantB64, gotFields[1],
|
|
"public-keys/0/openssh-key material must match the launch key pair")
|
|
|
|
// --- user-data round-trip ------------------------------------------------
|
|
harness.Step(t, "GET /latest/user-data round-trips launch user-data")
|
|
require.Contains(t, imdsGet(t, tgtX, tokenX, "/latest/user-data"), imdsUDMarker,
|
|
"user-data must round-trip the launch user-data")
|
|
|
|
// --- Boot-from-IMDS cutover guards ---------------------------------------
|
|
// The rest of this suite proves the guest can READ IMDS; this proves it BOOTED
|
|
// from it. The NoCloud seed is retired, so every guest now self-configures from
|
|
// the Ec2 datasource — and every other assertion here still passes if the seed
|
|
// silently comes back, so this is the only guard against that regression.
|
|
imdsAssertBootFromIMDS(t, tgtX, privX)
|
|
|
|
// --- Version discovery + dated-version alias (cloud-init parity) ----------
|
|
// cloud-init's EC2 datasource probes its OWN hardcoded dated versions
|
|
// (e.g. 2021-03-23), not the GET / listing, so any dated prefix must alias to
|
|
// /latest. Prove that aliasing resolves in-guest.
|
|
harness.Step(t, "version discovery: GET /, GET /latest, dated-version alias")
|
|
require.Contains(t, imdsGet(t, tgtX, tokenX, "/"), "latest",
|
|
"GET / must advertise the supported version list")
|
|
require.Equal(t, "dynamic\nmeta-data\nuser-data", imdsGet(t, tgtX, tokenX, "/latest"),
|
|
"GET /latest must list the top-level tree")
|
|
require.Equal(t, idX, imdsGet(t, tgtX, tokenX, "/2021-03-23/meta-data/instance-id"),
|
|
"a dated API version must alias to /latest (cloud-init parity)")
|
|
|
|
// --- Dynamic instance-identity document ----------------------------------
|
|
// The unsigned document is consumed by real SDKs in-guest; assert the fields
|
|
// resolved from ENI + instance facts, including the launch-time architecture.
|
|
harness.Step(t, "GET /latest/dynamic/instance-identity/document")
|
|
_, wantArch := needInstanceTypeArch(t, fix)
|
|
docBody := imdsGet(t, tgtX, tokenX, "/latest/dynamic/instance-identity/document")
|
|
var idDoc struct {
|
|
InstanceID string `json:"instanceId"`
|
|
AccountID string `json:"accountId"`
|
|
Region string `json:"region"`
|
|
Architecture string `json:"architecture"`
|
|
}
|
|
require.NoError(t, json.Unmarshal([]byte(docBody), &idDoc),
|
|
"identity document must be valid JSON: %s", docBody)
|
|
require.Equal(t, idX, idDoc.InstanceID, "identity document instanceId mismatch")
|
|
require.Equal(t, adminAccount, idDoc.AccountID, "identity document accountId mismatch")
|
|
require.NotEmpty(t, idDoc.Region, "identity document region must be populated")
|
|
require.Equal(t, wantArch, idDoc.Architecture,
|
|
"identity document architecture must match the launch instance type")
|
|
|
|
// --- Instance-role credentials + wire round-trip -------------------------
|
|
harness.Step(t, "GET security-credentials/%s → ASIA creds", imdsRoleName)
|
|
credBody := imdsGet(t, tgtX, tokenX, "/latest/meta-data/iam/security-credentials/"+imdsRoleName)
|
|
var cred imdsCredDoc
|
|
require.NoError(t, json.Unmarshal([]byte(credBody), &cred),
|
|
"credential body must be valid JSON: %s", credBody)
|
|
require.Equal(t, "Success", cred.Code, "credential Code must be Success (body=%s)", credBody)
|
|
require.True(t, strings.HasPrefix(cred.AccessKeyId, "ASIA"),
|
|
"instance-role AKID must start with ASIA, got %q", cred.AccessKeyId)
|
|
require.NotEmpty(t, cred.SecretAccessKey, "empty SecretAccessKey")
|
|
require.NotEmpty(t, cred.Token, "empty session Token")
|
|
require.Equal(t, adminAccount, cred.AccountId, "credential AccountId mismatch")
|
|
harness.Detail(t, "cred_akid", cred.AccessKeyId)
|
|
|
|
// Prove the minted creds verify on the gateway and resolve to the instance-
|
|
// bound assumed-role identity. The session name is the instance ID, so the
|
|
// ARN is .../assumed-role/<role>/<instance-id>.
|
|
harness.Step(t, "get-caller-identity with the IMDS-minted creds (ASIA path)")
|
|
sessionCli := harness.NewAWSClientWithSessionCreds(t, fix.Env,
|
|
cred.AccessKeyId, cred.SecretAccessKey, cred.Token)
|
|
who, err := sessionCli.STS.GetCallerIdentity(&sts.GetCallerIdentityInput{})
|
|
require.NoError(t, err, "get-caller-identity with instance-role creds")
|
|
expectedARN := "arn:aws:sts::" + adminAccount + ":assumed-role/" + imdsRoleName + "/" + idX
|
|
require.Equal(t, expectedARN, aws.StringValue(who.Arn),
|
|
"IMDS-minted creds must resolve to the instance assumed-role ARN")
|
|
|
|
// --- Cross-VPC isolation -------------------------------------------------
|
|
// VM X and VM Y query 169.254.169.254 from the IDENTICAL source IP, in
|
|
// different VPCs (hence different subnets). Each must get its own instance-id;
|
|
// a leak here means the responder consulted the source IP instead of the tap —
|
|
// the tap→ENI identity boundary is broken.
|
|
harness.Step(t, "cross-VPC isolation: shared IP %s, distinct identities", privX)
|
|
tokenY := imdsAwaitToken(t, fix, tgtY, subY, privY)
|
|
gotY := imdsGet(t, tgtY, tokenY, "/latest/meta-data/instance-id")
|
|
require.Equalf(t, idY, gotY, "VM Y IMDS must return VM Y's instance-id (got %q)", gotY)
|
|
require.NotEqualf(t, idX, gotY,
|
|
"cross-VPC leak: VM Y (source IP %s) resolved to VM X — the tap→ENI "+
|
|
"identity boundary is broken (source IP is not identity)", privX)
|
|
// And VM X still resolves to itself (not Y) after Y came up on the same IP.
|
|
require.Equal(t, idX, imdsGet(t, tgtX, tokenX, "/latest/meta-data/instance-id"),
|
|
"VM X IMDS must still return VM X's instance-id")
|
|
harness.Detail(t, "isolation", "ok")
|
|
|
|
// --- Cross-instance token binding + no-profile surface -------------------
|
|
// Re-mint a fresh VM X token so the binding rejection below is unambiguously
|
|
// about ENI binding rather than TTL expiry of the token minted early above.
|
|
freshTokenX := imdsAwaitToken(t, fix, tgtX, subX, privX)
|
|
|
|
harness.Step(t, "VM Y presents VM X's token → 401 (ENI-bound)")
|
|
require.Equal(t, "401",
|
|
imdsCode(tgtY, fmt.Sprintf(`-H "X-aws-ec2-metadata-token: %s"`, freshTokenX),
|
|
"/latest/meta-data/instance-id"),
|
|
"a token bound to VM X's ENI must not authorise VM Y")
|
|
|
|
// VM Y has no instance profile, so the whole iam/ subtree is absent: real EC2
|
|
// omits iam/ from the meta-data/ listing and 404s the iam/ directory, so
|
|
// cloud-init never descends and never trips on a 404ing iam/info that would fail
|
|
// its metadata crawl and zombie the guest.
|
|
harness.Step(t, "VM Y meta-data/ omits iam/; iam/ directory 404s")
|
|
require.NotContains(t, imdsGet(t, tgtY, tokenY, "/latest/meta-data/"), "iam/",
|
|
"no-profile meta-data/ listing must omit iam/")
|
|
for _, p := range []string{"/latest/meta-data/iam", "/latest/meta-data/iam/"} {
|
|
require.Equalf(t, "404",
|
|
imdsCode(tgtY, fmt.Sprintf(`-H "X-aws-ec2-metadata-token: %s"`, tokenY), p),
|
|
"no-profile %s must 404 (real-EC2 parity)", p)
|
|
}
|
|
|
|
// VM Y has no instance profile: iam/info is 404 and the credential listing is
|
|
// an empty 200 (absence is not an error, matching AWS).
|
|
harness.Step(t, "VM Y iam/info → 404; security-credentials/ → empty 200")
|
|
require.Equal(t, "404",
|
|
imdsCode(tgtY, fmt.Sprintf(`-H "X-aws-ec2-metadata-token: %s"`, tokenY),
|
|
"/latest/meta-data/iam/info"),
|
|
"an instance with no profile must 404 on iam/info")
|
|
require.Equal(t, "200",
|
|
imdsCode(tgtY, fmt.Sprintf(`-H "X-aws-ec2-metadata-token: %s"`, tokenY),
|
|
"/latest/meta-data/iam/security-credentials/"),
|
|
"no-profile security-credentials/ listing must be an empty 200")
|
|
require.Empty(t, imdsGet(t, tgtY, tokenY, "/latest/meta-data/iam/security-credentials/"),
|
|
"no-profile security-credentials/ body must be empty")
|
|
|
|
// VM X is profile-bound: a credential request for a role it isn't bound to
|
|
// is a 404, not a leak of the bound role's creds.
|
|
harness.Step(t, "VM X credential request for an unbound role name → 404")
|
|
require.Equal(t, "404",
|
|
imdsCode(tgtX, fmt.Sprintf(`-H "X-aws-ec2-metadata-token: %s"`, freshTokenX),
|
|
"/latest/meta-data/iam/security-credentials/wrong-role-name"),
|
|
"a credential request for a role the instance isn't bound to must 404")
|
|
}
|
|
|
|
// imdsVMSpec parameterises a launch for the IMDS suite. profileName / userData
|
|
// are optional.
|
|
type imdsVMSpec struct {
|
|
subnetID string
|
|
sgID string
|
|
profileName string
|
|
userData string
|
|
}
|
|
|
|
// imdsProbe launches a VM per spec, waits for it to run + become SSH-reachable,
|
|
// and returns (instanceID, privateIP, eniID, sshTarget). eniID drives the per-tap
|
|
// datapath shape assertion (its tap/endpoint/patch port names). Registers
|
|
// terminate cleanup so the VM is torn down before its VPC/subnet are deleted (LIFO).
|
|
func imdsProbe(t *testing.T, fix *Fixture, keyPath string, spec imdsVMSpec) (string, string, string, harness.SSHTarget) {
|
|
t.Helper()
|
|
id := imdsRunVM(t, fix, spec)
|
|
t.Cleanup(func() {
|
|
_, _ = fix.AWS.EC2.TerminateInstances(&ec2.TerminateInstancesInput{
|
|
InstanceIds: []*string{aws.String(id)},
|
|
})
|
|
_ = harness.WaitForInstanceStateSoft(fix.AWS, id, "terminated", 5*time.Minute)
|
|
})
|
|
|
|
inst := harness.WaitForInstanceState(t, fix.AWS, id, "running")
|
|
priv := aws.StringValue(inst.PrivateIpAddress)
|
|
require.NotEmptyf(t, priv, "instance %s has no PrivateIpAddress", id)
|
|
eni := primaryENI(t, inst)
|
|
|
|
host, port := harness.InstancePublicSSHHost(t, inst)
|
|
harness.Step(t, "wait for %s SSH at %s:%d", id, host, port)
|
|
sshHealth.WaitReady(t, host, port, keyPath)
|
|
return id, priv, eni, harness.SSHTarget{User: "ubuntu", Host: host, Port: port, KeyPath: keyPath}
|
|
}
|
|
|
|
// imdsAssertPerTapDatapath asserts the per-tap IMDS datapath is realised on the
|
|
// LOCAL chassis for the guest's ENI. It is the per-tap successor to the retired
|
|
// per-subnet ovn-trace L2 assertion and guards the steering bug the runtime smoke
|
|
// caught: the primary tap must be a port on the OVN-unmanaged br-imds (not br-int)
|
|
// so the demux flows meet its egress. Checks:
|
|
//
|
|
// - the tap + the ime-/imp- endpoint and patch ports are on br-imds;
|
|
// - the imi- patch end on br-int carries the guest's OVN iface-id, so
|
|
// ovn-controller binds the guest LSP to the patch exactly as to the tap;
|
|
// - br-imds carries the demux (priority=200, capturing 169.254.169.254) and the
|
|
// transparent forward (priority=100) flow tiers.
|
|
//
|
|
// br-imds ports are per-chassis OVS state, so this is host-local: it skips when
|
|
// the guest landed on another chassis (multinode) or the runner is remote.
|
|
func imdsAssertPerTapDatapath(t *testing.T, eniID string) {
|
|
t.Helper()
|
|
short := imdsShortENI(eniID)
|
|
tap := imdsTapName(eniID)
|
|
endpoint := "ime-" + short // host.IMDSEndpointName
|
|
patchIMDS := "imp-" + short // host.IMDSPatchPort (br-imds end)
|
|
patchInt := "imi-" + short // host.IMDSIntPatchPort (br-int end)
|
|
|
|
harness.Step(t, "per-tap datapath: tap %s + endpoint/patch on br-imds", tap)
|
|
brimdsPorts := harness.OvsVsctl(t, "list-ports", "br-imds")
|
|
if !strings.Contains(brimdsPorts, tap) {
|
|
t.Skipf("guest tap %s not on local br-imds (ports=%q) — VM on another chassis "+
|
|
"or remote runner; per-tap datapath shape is host-local", tap, brimdsPorts)
|
|
}
|
|
require.Containsf(t, brimdsPorts, endpoint,
|
|
"per-tap endpoint %s must be a br-imds port (the SO_BINDTODEVICE target the responder binds)", endpoint)
|
|
require.Containsf(t, brimdsPorts, patchIMDS,
|
|
"per-tap patch %s must be a br-imds port (the transparent hop to br-int)", patchIMDS)
|
|
|
|
// The br-int patch end carries the OVN iface-id so ovn-controller binds the
|
|
// guest LSP to it exactly as it bound the tap before the move to br-imds.
|
|
wantIface := "port-" + eniID // vm.OVSIfaceID == topology.Port
|
|
gotIface := harness.OvsVsctl(t, "--bare", "--columns=external_ids",
|
|
"find", "Interface", "name="+patchInt)
|
|
require.Containsf(t, gotIface, "iface-id="+wantIface,
|
|
"br-int patch end %s must carry external_ids:iface-id=%s so ovn-controller binds the "+
|
|
"guest LSP to the patch (got %q)", patchInt, wantIface, gotIface)
|
|
|
|
// Both flow tiers must be present: the demux captures 169.254.169.254 at
|
|
// priority 200, the forward bridges everything else to br-int at 100.
|
|
harness.Step(t, "per-tap datapath: br-imds demux + forward flow tiers")
|
|
flows := harness.OvsOfctl(t, "dump-flows", "br-imds")
|
|
require.Containsf(t, flows, "priority=200",
|
|
"br-imds must carry the demux flow tier (priority=200); flows:\n%s", flows)
|
|
require.Containsf(t, flows, "nw_dst=169.254.169.254",
|
|
"br-imds demux must capture 169.254.169.254; flows:\n%s", flows)
|
|
require.Containsf(t, flows, "priority=100",
|
|
"br-imds must carry the transparent forward flow tier (priority=100) so non-IMDS "+
|
|
"traffic still reaches br-int; flows:\n%s", flows)
|
|
}
|
|
|
|
// imdsAssertVpcdFileCaps proves the per-tap cutover's capability claim against the
|
|
// live daemon: vpcd serves IMDS under the restored sandbox with CAP_NET_ADMIN /
|
|
// CAP_NET_RAW / CAP_NET_BIND_SERVICE and WITHOUT CAP_SYS_ADMIN — the setns/netns
|
|
// path that required CAP_SYS_ADMIN is gone. Reads the live vpcd CapEff; skips
|
|
// where vpcd is not local.
|
|
func imdsAssertVpcdFileCaps(t *testing.T) {
|
|
t.Helper()
|
|
// Capability bit positions (linux/capability.h).
|
|
const (
|
|
capNetBindService = 10
|
|
capNetAdmin = 12
|
|
capNetRaw = 13
|
|
capSysAdmin = 21
|
|
)
|
|
caps, ok := harness.EffectiveCapsForUnit(t, "spinifex-vpcd")
|
|
if !ok {
|
|
t.Skip("spinifex-vpcd MainPID/CapEff not readable on this host; the file-cap proof " +
|
|
"requires a local vpcd (single-node chassis)")
|
|
}
|
|
harness.Step(t, "vpcd CapEff=0x%x: CAP_SYS_ADMIN dropped, net caps retained", caps)
|
|
require.Zerof(t, caps&(uint64(1)<<capSysAdmin),
|
|
"vpcd must NOT hold CAP_SYS_ADMIN after the per-tap cutover (CapEff=0x%x) — the "+
|
|
"setns/netns path that required it is gone", caps)
|
|
for _, c := range []struct {
|
|
bit uint
|
|
name string
|
|
}{
|
|
{capNetAdmin, "CAP_NET_ADMIN"},
|
|
{capNetRaw, "CAP_NET_RAW"},
|
|
{capNetBindService, "CAP_NET_BIND_SERVICE"},
|
|
} {
|
|
require.NotZerof(t, caps&(uint64(1)<<c.bit),
|
|
"vpcd must retain %s to serve the per-tap datapath (CapEff=0x%x)", c.name, caps)
|
|
}
|
|
}
|
|
|
|
// imdsAssertBootFromIMDS proves VM X bootstrapped from the Ec2 IMDS datasource
|
|
// with the NoCloud seed retired — a regression guard the rest of the suite can't
|
|
// give: every other assertion still passes if the seed silently comes back and
|
|
// cloud-init boots from NoCloud instead. Checks, all in-guest:
|
|
//
|
|
// - cloud-init reports the aws platform / an Ec2 datasource (not NoCloud);
|
|
// - no cidata-labelled block device is attached (the seed ISO is gone);
|
|
// - the login is the AMI's stock default user (no Spinifex-forced account);
|
|
// - the hostname is the AWS form ip-<dashed-ip>;
|
|
// - the primary NIC carries the VPC IP rendered from IMDS;
|
|
// - the user-data runcmd executed (cloud-init processed user-data from IMDS).
|
|
func imdsAssertBootFromIMDS(t *testing.T, tgt harness.SSHTarget, privIP string) {
|
|
t.Helper()
|
|
harness.Step(t, "boot-from-IMDS: cloud-init selected the aws (Ec2) datasource")
|
|
ds := strings.ToLower(strings.TrimSpace(
|
|
harness.RunSSH(t, tgt, "cloud-id 2>/dev/null || cloud-init query --format '{{datasource}}'")))
|
|
require.Truef(t, strings.Contains(ds, "aws") || strings.Contains(ds, "ec2"),
|
|
"cloud-init must report the aws/Ec2 datasource (got %q) — not the retired NoCloud seed", ds)
|
|
|
|
harness.Step(t, "boot-from-IMDS: no NoCloud cidata seed device attached")
|
|
labels := strings.ToLower(harness.RunSSH(t, tgt, "lsblk -no LABEL"))
|
|
require.NotContainsf(t, labels, "cidata",
|
|
"no cidata-labelled device may be attached — the seed ISO is retired (lsblk LABELs: %q)", labels)
|
|
|
|
harness.Step(t, "boot-from-IMDS: login is the AMI stock default user %q", tgt.User)
|
|
require.Equal(t, tgt.User, strings.TrimSpace(harness.RunSSH(t, tgt, "id -un")),
|
|
"in-guest login must be the AMI stock default user, not a Spinifex-forced account")
|
|
|
|
harness.Step(t, "boot-from-IMDS: AWS-form hostname ip-<dashed-ip>")
|
|
wantHost := "ip-" + strings.ReplaceAll(privIP, ".", "-")
|
|
gotHost := strings.TrimSpace(harness.RunSSH(t, tgt, "hostname"))
|
|
require.Truef(t, strings.HasPrefix(gotHost, wantHost),
|
|
"hostname must be the AWS form %q rendered from IMDS local-hostname (got %q)", wantHost, gotHost)
|
|
|
|
harness.Step(t, "boot-from-IMDS: primary NIC up with the VPC IP %s", privIP)
|
|
addrs := harness.RunSSH(t, tgt, "ip -4 -o addr show scope global")
|
|
require.Containsf(t, addrs, privIP,
|
|
"the Ec2 datasource must render the primary NIC with the VPC IP %s from IMDS (ip addr: %q)", privIP, addrs)
|
|
|
|
harness.Step(t, "boot-from-IMDS: user-data runcmd executed")
|
|
deadline := time.Now().Add(90 * time.Second)
|
|
for {
|
|
out, _ := harness.RunSSHCombined(tgt, "cat "+imdsUDDoneFile+" 2>/dev/null")
|
|
if strings.Contains(out, imdsUDMarker) {
|
|
break
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatalf("user-data runcmd marker %s never appeared within 90s — "+
|
|
"cloud-init did not run user-data from the Ec2 datasource", imdsUDDoneFile)
|
|
}
|
|
time.Sleep(3 * time.Second)
|
|
}
|
|
}
|
|
|
|
// imdsShortENI mirrors host.shortENIID: the FNV-32a hash of the full ENI ID as 8
|
|
// hex chars, which the per-tap port names key off (inlined, as this suite inlines
|
|
// the other OVS/OVN names). A hash, NOT a truncation — suffix-sharing ENIs differ.
|
|
func imdsShortENI(eniID string) string {
|
|
h := fnv.New32a()
|
|
_, _ = h.Write([]byte(eniID))
|
|
return fmt.Sprintf("%08x", h.Sum32())
|
|
}
|
|
|
|
// imdsTapName mirrors vm.TapDeviceName: "tap" + the ENI (sans eni- prefix),
|
|
// truncated to the 15-char IFNAMSIZ limit.
|
|
func imdsTapName(eniID string) string {
|
|
name := "tap" + strings.TrimPrefix(eniID, "eni-")
|
|
if len(name) > 15 {
|
|
name = name[:15]
|
|
}
|
|
return name
|
|
}
|
|
|
|
// imdsRegionFromAZ mirrors the responder's own AZ→region derivation: strip the
|
|
// trailing AZ letter ("ap-southeast-2a" → "ap-southeast-2"). Deriving the region
|
|
// from the AZ the responder reports — rather than the client's configured region
|
|
// — keeps the expected hostname self-consistent with the instance under test.
|
|
func imdsRegionFromAZ(az string) string {
|
|
if az == "" {
|
|
return ""
|
|
}
|
|
if last := az[len(az)-1]; last >= 'a' && last <= 'z' {
|
|
return az[:len(az)-1]
|
|
}
|
|
return az
|
|
}
|
|
|
|
// imdsRunVM launches a single instance per spec and returns its ID. AMI / type /
|
|
// key come from the suite discovery helpers.
|
|
func imdsRunVM(t *testing.T, fix *Fixture, spec imdsVMSpec) string {
|
|
t.Helper()
|
|
amiID := needAMI(t, fix)
|
|
instType, _ := needInstanceTypeArch(t, fix)
|
|
keyName, _ := needKeyPair(t, fix)
|
|
|
|
in := &ec2.RunInstancesInput{
|
|
ImageId: aws.String(amiID),
|
|
InstanceType: aws.String(instType),
|
|
KeyName: aws.String(keyName),
|
|
SubnetId: aws.String(spec.subnetID),
|
|
SecurityGroupIds: []*string{aws.String(spec.sgID)},
|
|
MinCount: aws.Int64(1),
|
|
MaxCount: aws.Int64(1),
|
|
}
|
|
if spec.profileName != "" {
|
|
in.IamInstanceProfile = &ec2.IamInstanceProfileSpecification{Name: aws.String(spec.profileName)}
|
|
}
|
|
if spec.userData != "" {
|
|
in.UserData = aws.String(base64.StdEncoding.EncodeToString([]byte(spec.userData)))
|
|
}
|
|
out, err := fix.AWS.EC2.RunInstances(in)
|
|
require.NoError(t, err, "run-instances subnet=%s", spec.subnetID)
|
|
require.NotEmpty(t, out.Instances, "run-instances returned no Instances")
|
|
id := aws.StringValue(out.Instances[0].InstanceId)
|
|
require.True(t, strings.HasPrefix(id, "i-"), "unexpected InstanceId %q", id)
|
|
return id
|
|
}
|
|
|
|
// imdsEnsureProbeVPC creates a VPC + subnet wired for SSH reachability and
|
|
// returns (vpcID, subnetID, sgID). In pool mode it adds the public-IP path
|
|
// (MapPublicIpOnLaunch + IGW + 0.0.0.0/0 route) so the runner reaches the guest
|
|
// by public IP; in dev_networking mode SSH lands via the per-VM qemu hostfwd, so
|
|
// the IGW plumbing is skipped. All resources are torn down LIFO via t.Cleanup.
|
|
func imdsEnsureProbeVPC(t *testing.T, fix *Fixture, vpcCIDR, subnetCIDR string) (string, string, string) {
|
|
t.Helper()
|
|
c := fix.AWS
|
|
|
|
vpcOut, err := c.EC2.CreateVpc(&ec2.CreateVpcInput{CidrBlock: aws.String(vpcCIDR)})
|
|
require.NoError(t, err, "create-vpc %s", vpcCIDR)
|
|
vpcID := aws.StringValue(vpcOut.Vpc.VpcId)
|
|
require.NotEmpty(t, vpcID, "VpcId empty")
|
|
t.Cleanup(func() { _, _ = c.EC2.DeleteVpc(&ec2.DeleteVpcInput{VpcId: aws.String(vpcID)}) })
|
|
|
|
subOut, err := c.EC2.CreateSubnet(&ec2.CreateSubnetInput{
|
|
VpcId: aws.String(vpcID),
|
|
CidrBlock: aws.String(subnetCIDR),
|
|
})
|
|
require.NoError(t, err, "create-subnet %s", subnetCIDR)
|
|
subnetID := aws.StringValue(subOut.Subnet.SubnetId)
|
|
require.NotEmpty(t, subnetID, "SubnetId empty")
|
|
t.Cleanup(func() { _, _ = c.EC2.DeleteSubnet(&ec2.DeleteSubnetInput{SubnetId: aws.String(subnetID)}) })
|
|
|
|
if fix.PoolMode {
|
|
imdsAttachInternet(t, c, vpcID, subnetID)
|
|
}
|
|
|
|
sgID := imdsDefaultSG(t, c, vpcID)
|
|
harness.AuthorizeSSHIngress(t, c, sgID)
|
|
harness.Detail(t, "probe_vpc", vpcID, "subnet", subnetID, "sg", sgID)
|
|
return vpcID, subnetID, sgID
|
|
}
|
|
|
|
// imdsAttachInternet gives subnetID a public-IP egress path (pool mode only):
|
|
// MapPublicIpOnLaunch + a fresh IGW + a 0.0.0.0/0 route table. Cleanups unwind
|
|
// LIFO before the subnet/VPC are deleted by the caller's earlier-registered
|
|
// cleanups.
|
|
func imdsAttachInternet(t *testing.T, c *harness.AWSClient, vpcID, subnetID string) {
|
|
t.Helper()
|
|
_, err := c.EC2.ModifySubnetAttribute(&ec2.ModifySubnetAttributeInput{
|
|
SubnetId: aws.String(subnetID),
|
|
MapPublicIpOnLaunch: &ec2.AttributeBooleanValue{Value: aws.Bool(true)},
|
|
})
|
|
require.NoError(t, err, "modify-subnet-attribute MapPublicIpOnLaunch")
|
|
|
|
igwOut, err := c.EC2.CreateInternetGateway(&ec2.CreateInternetGatewayInput{})
|
|
require.NoError(t, err, "create-internet-gateway")
|
|
igwID := aws.StringValue(igwOut.InternetGateway.InternetGatewayId)
|
|
require.NotEmpty(t, igwID, "InternetGatewayId empty")
|
|
t.Cleanup(func() {
|
|
_, _ = c.EC2.DetachInternetGateway(&ec2.DetachInternetGatewayInput{
|
|
InternetGatewayId: aws.String(igwID), VpcId: aws.String(vpcID),
|
|
})
|
|
_, _ = c.EC2.DeleteInternetGateway(&ec2.DeleteInternetGatewayInput{InternetGatewayId: aws.String(igwID)})
|
|
})
|
|
_, err = c.EC2.AttachInternetGateway(&ec2.AttachInternetGatewayInput{
|
|
InternetGatewayId: aws.String(igwID), VpcId: aws.String(vpcID),
|
|
})
|
|
require.NoError(t, err, "attach-internet-gateway")
|
|
|
|
rtOut, err := c.EC2.CreateRouteTable(&ec2.CreateRouteTableInput{VpcId: aws.String(vpcID)})
|
|
require.NoError(t, err, "create-route-table")
|
|
rtbID := aws.StringValue(rtOut.RouteTable.RouteTableId)
|
|
require.NotEmpty(t, rtbID, "RouteTableId empty")
|
|
t.Cleanup(func() { _, _ = c.EC2.DeleteRouteTable(&ec2.DeleteRouteTableInput{RouteTableId: aws.String(rtbID)}) })
|
|
|
|
assocOut, err := c.EC2.AssociateRouteTable(&ec2.AssociateRouteTableInput{
|
|
RouteTableId: aws.String(rtbID), SubnetId: aws.String(subnetID),
|
|
})
|
|
require.NoError(t, err, "associate-route-table")
|
|
assocID := aws.StringValue(assocOut.AssociationId)
|
|
t.Cleanup(func() {
|
|
_, _ = c.EC2.DisassociateRouteTable(&ec2.DisassociateRouteTableInput{AssociationId: aws.String(assocID)})
|
|
})
|
|
|
|
_, err = c.EC2.CreateRoute(&ec2.CreateRouteInput{
|
|
RouteTableId: aws.String(rtbID),
|
|
DestinationCidrBlock: aws.String("0.0.0.0/0"),
|
|
GatewayId: aws.String(igwID),
|
|
})
|
|
require.NoError(t, err, "create-route 0.0.0.0/0 -> IGW")
|
|
}
|
|
|
|
// imdsEnsureRoleProfile creates the EC2-trusted role + instance profile the
|
|
// IMDS credential path resolves, attaching AdministratorAccess so the minted
|
|
// session creds round-trip a real call. Registers fixture-teardown cleanup and
|
|
// sweeps any residue from a prior run first.
|
|
func imdsEnsureRoleProfile(t *testing.T, fix *Fixture, adminAccount string) {
|
|
t.Helper()
|
|
adminPolicyARN := harness.IAMPolicyARN(adminAccount, imdsAdminPolicyName)
|
|
harness.IAMDeleteRoleAndProfilesBestEffort(fix.AWS, imdsRoleName, []string{imdsProfileName}, adminPolicyARN)
|
|
fix.Harness.RegisterCleanup(func() {
|
|
harness.IAMDeleteRoleAndProfilesBestEffort(fix.AWS, imdsRoleName, []string{imdsProfileName}, adminPolicyARN)
|
|
})
|
|
|
|
harness.Step(t, "create-role %q (trust=ec2.amazonaws.com) + profile %q", imdsRoleName, imdsProfileName)
|
|
_, err := fix.AWS.IAM.CreateRole(&iam.CreateRoleInput{
|
|
RoleName: aws.String(imdsRoleName),
|
|
AssumeRolePolicyDocument: aws.String(imdsTrustPolicyEC2),
|
|
Description: aws.String("E2E IMDS instance-role credentials"),
|
|
})
|
|
require.NoError(t, err, "create-role")
|
|
|
|
_, err = fix.AWS.IAM.AttachRolePolicy(&iam.AttachRolePolicyInput{
|
|
RoleName: aws.String(imdsRoleName),
|
|
PolicyArn: aws.String(adminPolicyARN),
|
|
})
|
|
require.NoError(t, err, "attach AdministratorAccess to role")
|
|
|
|
_, err = fix.AWS.IAM.CreateInstanceProfile(&iam.CreateInstanceProfileInput{
|
|
InstanceProfileName: aws.String(imdsProfileName),
|
|
})
|
|
require.NoError(t, err, "create-instance-profile")
|
|
_, err = fix.AWS.IAM.AddRoleToInstanceProfile(&iam.AddRoleToInstanceProfileInput{
|
|
InstanceProfileName: aws.String(imdsProfileName),
|
|
RoleName: aws.String(imdsRoleName),
|
|
})
|
|
require.NoError(t, err, "add-role-to-instance-profile")
|
|
}
|
|
|
|
// imdsAwaitToken PUTs an IMDSv2 token from inside the guest, retrying to ride
|
|
// out the cold-start window before vpcd's reconcile-from-taps binds the per-tap
|
|
// responder. Returns the token. On timeout it dumps the per-tap IMDS datapath
|
|
// (br-imds flows/ports + reply routing + listener + conntrack) before failing,
|
|
// so a reachability timeout (exit 28) is triaged as request-path vs reply-path
|
|
// rather than a bare "condition not met".
|
|
func imdsAwaitToken(t *testing.T, fix *Fixture, tgt harness.SSHTarget, subnetID, guestIP string) string {
|
|
t.Helper()
|
|
deadline := time.Now().Add(90 * time.Second)
|
|
var lastErr error
|
|
for {
|
|
cmd := fmt.Sprintf(
|
|
`curl -sf -X PUT "%s/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 120"`, metaURL)
|
|
out, err := harness.RunSSHCombined(tgt, cmd)
|
|
switch {
|
|
case err != nil:
|
|
lastErr = fmt.Errorf("token PUT failed: %w (out=%q)", err, out)
|
|
case strings.TrimSpace(out) == "":
|
|
lastErr = fmt.Errorf("token PUT returned empty body")
|
|
default:
|
|
return strings.TrimSpace(out)
|
|
}
|
|
if time.Now().After(deadline) {
|
|
harness.DumpIMDSDatapathDiagnostics(t, subnetID, guestIP, fix.ArtifactDir(t))
|
|
t.Fatalf("imdsAwaitToken: token never minted within 90s (subnet=%s guest=%s): %v "+
|
|
"(see IMDS datapath diagnostics above)", subnetID, guestIP, lastErr)
|
|
}
|
|
time.Sleep(3 * time.Second)
|
|
}
|
|
}
|
|
|
|
// imdsGet fetches a token-gated path from inside the guest and returns the
|
|
// trimmed body. -sf turns any HTTP >= 400 into a non-zero exit, so a 4xx/5xx
|
|
// fails the test loudly with the server status visible via harness.RunSSH's stderr.
|
|
func imdsGet(t *testing.T, tgt harness.SSHTarget, token, path string) string {
|
|
t.Helper()
|
|
cmd := fmt.Sprintf(`curl -sf -H "X-aws-ec2-metadata-token: %s" %s%s`, token, metaURL, path)
|
|
return strings.TrimSpace(harness.RunSSH(t, tgt, cmd))
|
|
}
|
|
|
|
// imdsExpectedPubKey derives the OpenSSH public key (type + base64) the IMDS
|
|
// material path must serve, from the launch key pair's PEM. CreateKeyPair returns
|
|
// only the private PEM, so the public key is recomputed from it via ssh.Signer.
|
|
// The stored key carries an empty comment (ssh-keygen -C ""), so callers compare
|
|
// on the type + base64 fields, not the full line.
|
|
func imdsExpectedPubKey(t *testing.T, pemPath string) (keyType, base64Key string) {
|
|
t.Helper()
|
|
pem, err := os.ReadFile(pemPath)
|
|
require.NoErrorf(t, err, "read key PEM %s", pemPath)
|
|
signer, err := ssh.ParsePrivateKey(pem)
|
|
require.NoError(t, err, "parse key PEM")
|
|
authorized := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(signer.PublicKey())))
|
|
fields := strings.Fields(authorized)
|
|
require.GreaterOrEqualf(t, len(fields), 2, "derived public key malformed: %q", authorized)
|
|
return fields[0], fields[1]
|
|
}
|
|
|
|
// imdsCode returns the HTTP status code (as a string) the guest sees for a GET,
|
|
// without failing on non-2xx. headerArg is an optional pre-formatted curl -H
|
|
// argument (empty for the tokenless probe).
|
|
func imdsCode(tgt harness.SSHTarget, headerArg, path string) string {
|
|
cmd := fmt.Sprintf(`curl -s -o /dev/null -w '%%{http_code}' %s %s%s`, headerArg, metaURL, path)
|
|
out, _ := harness.RunSSHCombined(tgt, cmd)
|
|
return strings.TrimSpace(out)
|
|
}
|
|
|
|
// imdsDefaultSG returns the auto-created default security group ID for a VPC.
|
|
func imdsDefaultSG(t *testing.T, c *harness.AWSClient, vpcID string) string {
|
|
t.Helper()
|
|
out, err := c.EC2.DescribeSecurityGroups(&ec2.DescribeSecurityGroupsInput{
|
|
Filters: []*ec2.Filter{
|
|
{Name: aws.String("vpc-id"), Values: []*string{aws.String(vpcID)}},
|
|
{Name: aws.String("group-name"), Values: []*string{aws.String("default")}},
|
|
},
|
|
})
|
|
require.NoError(t, err, "describe-security-groups default (vpc=%s)", vpcID)
|
|
require.NotEmpty(t, out.SecurityGroups, "no default SG for vpc=%s", vpcID)
|
|
id := aws.StringValue(out.SecurityGroups[0].GroupId)
|
|
require.NotEmpty(t, id, "default SG GroupId empty (vpc=%s)", vpcID)
|
|
return id
|
|
}
|