Compare commits

...

1 Commits

Author SHA1 Message Date
Josh Siviour 8a4ab4438c refactor(iam): move handlers/iam to domains/iam (#1249)
* refactor(iam): move handlers/iam to domains/iam

Relocate IAM's implementation and its test double to the ADR-0001 home
with git mv. The package is renamed from handlers_iam to iam and its
importers use the iamdomain alias. APIs, NATS subjects, KV buckets and
behaviour are unchanged.

The cross-domain allowlist entries now target domains/iam; the two
frozen-legacy entries and the operator/cli entry, which no longer breaks
the legacy-implementation rule, are removed. The migration record states
that per-consumer IAM capabilities remain debt but were not a
prerequisite to the move.

* docs: record the IAM move against its PR
2026-10-25 21:58:05 +10:00
196 changed files with 1091 additions and 1093 deletions
+13 -14
View File
@@ -34,7 +34,7 @@ var allowlist = []allowance{
{From: "daemon", To: "domains/ec2/awsapi/instance", Debt: "Instance adapter consumers outside EC2", Reason: "daemon/eks_cp_control.go and rds_deps.go call the instance adapter; needs an EC2 capability"},
{From: "domains/acm", To: "handlers/iam", Debt: "ACM: the IAM AES-GCM helper import (ACM relocation residual)", Reason: "IAM AES-GCM helpers; needs a shared crypto boundary"},
{From: "domains/acm", To: "domains/iam", Debt: "ACM: the IAM AES-GCM helper import (ACM relocation residual)", Reason: "IAM AES-GCM helpers; needs a shared crypto boundary"},
{From: "domains/admission/quota", To: "domains/ec2/awsapi/eip", Debt: "domains/admission/quota (dependency, moved from handlers/quota unchanged)", Reason: "describe adapter used as a counter; needs a reader capability"},
{From: "domains/admission/quota", To: "domains/ec2/awsapi/instance", Debt: "domains/admission/quota (dependency, moved from handlers/quota unchanged)", Reason: "vcpu.go counts instances through the instance adapter; needs an EC2 reader capability"},
@@ -48,17 +48,17 @@ var allowlist = []allowance{
{From: "domains/dns", To: "domains/network/reconcile", Debt: "domains/dns", Reason: "takes the reconcile lock from network's implementation"},
{From: "domains/dns", To: "runtime/compute/vm", Debt: "domains/dns", Reason: "domain-to-runtime import of VM state"},
{From: "domains/ec2/awsapi/instance", To: "handlers/iam", Debt: "domains/ec2/awsapi/instance (dependency)", Reason: "IAM edge needs an IAM capability"},
{From: "domains/ec2/awsapi/instance", To: "domains/iam", Debt: "domains/ec2/awsapi/instance (dependency)", Reason: "IAM edge needs an IAM capability"},
{From: "domains/ec2/awsapi/instance", To: "runtime/compute/cache", Debt: "domains/ec2/awsapi/instance (dependency)", Reason: "node liveness and VM state; needs an EC2-owned projection"},
{From: "domains/ec2/awsapi/instance", To: "runtime/compute/vm", Debt: "domains/ec2/awsapi/instance (dependency)", Reason: "node liveness and VM state; needs an EC2-owned projection"},
{From: "domains/ec2/awsapi/spotinstance", To: "domains/admission/quota", Debt: "domains/ec2/awsapi/spotinstance (dependency)", Reason: "RequestSpotInstances.go uses IAMService and quota.Service"},
{From: "domains/ec2/awsapi/spotinstance", To: "handlers/iam", Debt: "domains/ec2/awsapi/spotinstance (dependency)", Reason: "RequestSpotInstances.go uses IAMService and quota.Service"},
{From: "domains/ec2/awsapi/spotinstance", To: "domains/iam", Debt: "domains/ec2/awsapi/spotinstance (dependency)", Reason: "RequestSpotInstances.go uses IAMService and quota.Service"},
{From: "domains/ec2/eip", To: "domains/network/topology", Debt: "EC2 → network implementation", Reason: "EC2 reads network implementation; clears with the EC2-owned projection"},
{From: "domains/ec2/guestmetadata", To: "domains/dns", Debt: "Guest metadata: the cross-domain and runtime imports above", Reason: "guest-metadata relocation residual; needs capabilities, projections or contracts"},
{From: "domains/ec2/guestmetadata", To: "handlers/iam", Debt: "Guest metadata: the cross-domain and runtime imports above", Reason: "guest-metadata relocation residual; needs capabilities, projections or contracts"},
{From: "domains/ec2/guestmetadata", To: "domains/iam", Debt: "Guest metadata: the cross-domain and runtime imports above", Reason: "guest-metadata relocation residual; needs capabilities, projections or contracts"},
{From: "domains/ec2/guestmetadata", To: "handlers/sts", Debt: "Guest metadata: the cross-domain and runtime imports above", Reason: "guest-metadata relocation residual; needs capabilities, projections or contracts"},
{From: "domains/ec2/guestmetadata", To: "runtime/compute/vm", Debt: "Guest metadata: the cross-domain and runtime imports above", Reason: "guest-metadata relocation residual; needs capabilities, projections or contracts"},
@@ -76,7 +76,7 @@ var allowlist = []allowance{
{From: "domains/ec2/vpc", To: "domains/network/identifiers", Debt: "EC2 → network implementation", Reason: "EC2 reads network implementation; clears with the EC2-owned projection"},
{From: "domains/ec2/vpc", To: "domains/network/topology", Debt: "EC2 → network implementation", Reason: "EC2 reads network implementation; clears with the EC2-owned projection"},
{From: "domains/ecr/auth", To: "handlers/iam", Debt: "Cross-domain", Reason: "IAM implementation import; needs an IAM capability"},
{From: "domains/ecr/auth", To: "domains/iam", Debt: "Cross-domain", Reason: "IAM implementation import; needs an IAM capability"},
{From: "domains/network/host", To: "runtime/compute/vm", Debt: "domains/network", Reason: "domain-to-runtime import"},
{From: "domains/network/host", To: "runtime/host/command", Debt: "domains/network", Reason: "domain-to-runtime import"},
@@ -93,7 +93,7 @@ var allowlist = []allowance{
{From: "domains/ochre", To: "gateway/bedrock", Debt: "gateway/bedrock", Reason: "Ochre domain core still lives in gateway/bedrock; needs the recorded split"},
{From: "domains/ochre", To: "runtime/compute/gpu", Debt: "Domain → runtime", Reason: "GPU runtime state read directly; needs a domain-owned projection"},
{From: "domains/ochre/vector", To: "handlers/iam", Debt: "Cross-domain", Reason: "consumes another domain's implementation rather than a capability"},
{From: "domains/ochre/vector", To: "domains/iam", Debt: "Cross-domain", Reason: "consumes another domain's implementation rather than a capability"},
{From: "gateway", To: "domains/ec2/awsapi", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/account", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
@@ -116,17 +116,17 @@ var allowlist = []allowance{
{From: "gateway", To: "domains/ec2/awsapi/vpc", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway", To: "domains/ec2/awsapi/zone", Debt: "gateway/ec2.go (registration)", Reason: "EC2 dispatch map stays in gateway until the ingress registration seam"},
{From: "gateway/bedrock", To: "handlers/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "secret encrypt/decrypt helpers; needs a shared crypto boundary"},
{From: "gateway/bedrock", To: "domains/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "secret encrypt/decrypt helpers; needs a shared crypto boundary"},
{From: "gateway/rds", To: "domains/ec2/awsapi/instance", Debt: "Instance adapter consumers outside EC2", Reason: "enginecatalog.go calls the instance adapter; needs an EC2 capability"},
{From: "gateway/sts", To: "handlers/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "GetCallerIdentity takes IAMService; needs an IAM capability"},
{From: "gateway/sts", To: "domains/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "GetCallerIdentity takes IAMService; needs an IAM capability"},
{From: "handlers/ecs", To: "domains/ec2/ebs/metadata", Debt: "close-out: handlers/ecs (ADR-0004 blocked-dependency list; inventory-ecs boundary imports)", Reason: "legacy ECS calls another domain's implementation as an internal API"},
{From: "handlers/ecs", To: "domains/ec2/eip", Debt: "close-out: handlers/ecs (ADR-0004 blocked-dependency list; inventory-ecs boundary imports)", Reason: "legacy ECS calls another domain's implementation as an internal API"},
{From: "handlers/ecs", To: "domains/ec2/instancetypes", Debt: "close-out: handlers/ecs (ADR-0004 blocked-dependency list; inventory-ecs boundary imports)", Reason: "legacy ECS calls another domain's implementation as an internal API"},
{From: "handlers/ecs", To: "handlers/elbv2", Debt: "close-out: handlers/ecs (ADR-0004 blocked-dependency list; inventory-ecs boundary imports)", Reason: "legacy ECS calls another domain's implementation as an internal API"},
{From: "handlers/ecs", To: "handlers/iam", Debt: "close-out: handlers/ecs (ADR-0004 blocked-dependency list; inventory-ecs boundary imports)", Reason: "legacy ECS calls another domain's implementation as an internal API"},
{From: "handlers/ecs", To: "domains/iam", Debt: "close-out: handlers/ecs (ADR-0004 blocked-dependency list; inventory-ecs boundary imports)", Reason: "legacy ECS calls another domain's implementation as an internal API"},
{From: "handlers/eks", To: "domains/dns", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "domains/ec2/ebs/metadata", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
@@ -134,7 +134,7 @@ var allowlist = []allowance{
{From: "handlers/eks", To: "domains/ec2/placementgroup", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "domains/ec2/systeminstance", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "domains/network/systemvpc", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "handlers/iam", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "domains/iam", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/eks", To: "runtime/compute/vm", Debt: "close-out: handlers/eks (ADR-0004 blocked-dependency list; inventory-eks boundary imports)", Reason: "legacy EKS calls another domain's or runtime implementation directly"},
{From: "handlers/elbv2", To: "domains/acm", Debt: "handlers/elbv2 (cross-domain)", Reason: "legacy ELBv2 cross-domain import; clears when ELBv2 is extracted behind consumer-owned capabilities"},
@@ -142,7 +142,7 @@ var allowlist = []allowance{
{From: "handlers/elbv2", To: "domains/ec2/systeminstance", Debt: "handlers/elbv2 (cross-domain)", Reason: "legacy ELBv2 cross-domain import; clears when ELBv2 is extracted behind consumer-owned capabilities"},
{From: "handlers/elbv2", To: "domains/ec2/vpc", Debt: "handlers/elbv2 (cross-domain)", Reason: "legacy ELBv2 cross-domain import; clears when ELBv2 is extracted behind consumer-owned capabilities"},
{From: "handlers/elbv2", To: "domains/network/topology", Debt: "handlers/elbv2 (cross-domain)", Reason: "legacy ELBv2 cross-domain import; clears when ELBv2 is extracted behind consumer-owned capabilities"},
{From: "handlers/elbv2", To: "handlers/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "system-instance role ensurer; needs an IAM capability"},
{From: "handlers/elbv2", To: "domains/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "system-instance role ensurer; needs an IAM capability"},
{From: "handlers/elbv2", To: "lbagent", Debt: "handlers/elbv2/{agent_types,haproxy,health_checker,nginx}.go import lbagent", Reason: "health-report and cert/PID-path vocabulary; needs a guest/controller contract"},
{From: "handlers/rds", To: "domains/dns", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
@@ -150,15 +150,14 @@ var allowlist = []allowance{
{From: "handlers/rds", To: "domains/ec2/instancetypes", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/rds", To: "domains/ec2/systeminstance", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/rds", To: "domains/network/systemvpc", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/rds", To: "handlers/iam", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/rds", To: "domains/iam", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/rds", To: "runtime/compute/vm", Debt: "close-out: handlers/rds (ADR-0004 blocked-dependency list; inventory-rds boundary imports)", Reason: "legacy RDS calls another domain's or runtime implementation directly"},
{From: "handlers/sts", To: "handlers/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "STS reads IAM service, trust-policy and OIDC-provider state; needs an IAM capability"},
{From: "handlers/sts", To: "domains/iam", Debt: "IAM implementation consumers in STS, Ochre and ELBv2", Reason: "STS reads IAM service, trust-policy and OIDC-provider state; needs an IAM capability"},
{From: "operator/cli", To: "accountteardown", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "daemon", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "gateway", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "gateway/bedrock", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "handlers/eks", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
{From: "operator/cli", To: "handlers/iam", Debt: "operator/cli (dependency)", Reason: "command tree imports implementations; needs public capabilities"},
}
-2
View File
@@ -24,8 +24,6 @@ var frozenLegacyPackages = []string{
"handlers/ecs",
"handlers/eks",
"handlers/elbv2",
"handlers/iam",
"handlers/iam/mock",
"handlers/rds",
"handlers/sts",
"lbagent",
+10 -9
View File
@@ -340,6 +340,7 @@ while the branch is in flight; they do not describe the umbrella repository's
| `0d830e901` | — | `spinifex/domains/tagging` (`TaggedLister`, `TaggedResource`) | The read-only list capability for the Resource Groups Tagging aggregation, declared by its consumer per ADR-0001. `ListTagged` takes the caller's account and the lower-cased `ResourceTypeFilters` set, where an entry is a full `service:type` or a bare service, and returns ARNs with read-only tag maps. The package imports no domain, handler or contract package and the layering ratchet classifies it with no allowlist row. It carries no mutation, limit or ever-tagged surface. |
| `f3545e3ea` | `spinifex/gateway/tagging` (`listEC2`, `buildEC2Mappings`, `ec2ARN`, `elbv2Resources`, `matchesType`), copied | `spinifex/runtime/roles/awsgw` (`ec2IndexLister`, `elbv2Lister`), `spinifex/domains/tagging` (`MatchesType`) | AWSGW-side NATS client adapters implement `tagging.TaggedLister`, each with its compile-time check beside it in the composition root; no owner package carries one. The EC2 index adapter wraps `ec2.DescribeTags` and builds each ARN in the gateway's region from the stored resource type, including the unresolved-ID shapes today's code produces. The ELBv2 adapter lists load balancers and target groups admitted by the type filter, tagged or not, and reads tags in `DescribeTags` batches of 20. Both reuse existing subjects and clients, so no wire contract is added, and each call builds fresh tag maps. Type matching is exported once from `domains/tagging` so no copy survives the move. Embedded-JetStream tests cover type filters including a bare service, untagged ELBv2 resources, EC2 ARN mapping, account scoping, batch sizes and owner error propagation. |
| `aedd0b2c4` | `spinifex/gateway/tagging` (`GetResources` parsing, tag filtering, sorting, offset token, authorization, response writing) | `spinifex/domains/tagging` (`Aggregator`, `NewAggregator`, `HasScope`, `ScopedActions`), wired by `spinifex/runtime/roles/awsgw` | The aggregation moves unchanged and consumes `[]TaggedLister`: ELBv2 is called before EC2, the non-stable ARN sort is kept, lister errors propagate with the same codes, and tag maps return as key-sorted tag lists with `[]` for untagged resources. AWSGW builds the aggregator with both adapters and sets the new `GatewayConfig.TaggingResources` field; the dispatch in `gateway/tagging.go` stays and still answers `ServerInternal` when NATS or the aggregator is not wired. The `TestCurrentBehaviour_Tagging_GetResources*` tests move to `runtime/roles/awsgw` with unchanged assertions, seeding EC2 tags through the existing EC2 tags client over NATS; pure aggregator tests move to `domains/tagging` against fake listers; the gateway keeps dispatch and error-path tests. The gateway's private copies of the listing helpers and the legacy NATS lister are deleted with their tests, `gateway/tagging` is removed, and its two allowlist rows (`gateway/tagging` → `domains/ec2/tags`, `gateway/tagging` → `handlers/elbv2`) and its frozen-legacy entry go with it. |
| `spinifex#1249` | `spinifex/handlers/iam`, `spinifex/handlers/iam/mock` | `spinifex/domains/iam` (`iam`, imported as `iamdomain`), `spinifex/domains/iam/mock` | A mechanical relocation of IAM's implementation to its ADR-0001 home; APIs, NATS subjects, KV buckets and behaviour are unchanged and only the package name changed from `handlers_iam`. Per-consumer IAM capabilities remain dependency-rule debt but were not a prerequisite. The two frozen-legacy entries are removed, the cross-domain allowlist entries now target `domains/iam`, and the `operator/cli` → `handlers/iam` entry is removed because an operator import of a domain package does not break the legacy-implementation rule. |
The EC2 contract row is intentionally different from the directory moves: it creates
a compatibility boundary. `ec2.cmd.*` retains its deployed one-token NATS
subscription and permission shape, while callers use
@@ -407,7 +408,7 @@ These residuals were recorded by individual slices and must be resolved once the
- Guest metadata: the cross-domain and runtime imports above.
- EC2 → network implementation: `domains/ec2/vpc/eni.go:18` and `eni_lease_rebind.go:11` import `domains/network/topology`, `eni.go:17` also imports `domains/network/identifiers`, `external_ipam.go:10-11` imports `domains/network/external` and `domains/network/external/dhcp`, `domains/ec2/eip/service_impl.go:17` and `lease_rebind.go:11` import `domains/network/topology`, and `domains/ec2/instance/service_impl.go:31` imports `domains/network/topology`. EC2 reads network's implementation directly rather than through a capability or projection; this clears when EC2's network-facing reads and writes go through the EC2-owned projection recorded above (step 7).
- Cross-domain: `domains/ecr/auth/signingkey.go:24` and `domains/ochre/vector/appliance.go:15` import `handlers/iam`; this needs an IAM capability rather than the IAM implementation package. `domains/ochre/launch.go:17-18` and `domains/ochre/vpc.go:9` import `domains/ec2/systeminstance` and `domains/network/systemvpc`; Ochre consumes managed-service launch and system-VPC realisation as domain implementations rather than capabilities.
- Cross-domain: `domains/ecr/auth/signingkey.go:24` and `domains/ochre/vector/appliance.go:15` import `domains/iam`; this needs an IAM capability rather than the IAM implementation package. `domains/ochre/launch.go:17-18` and `domains/ochre/vpc.go:9` import `domains/ec2/systeminstance` and `domains/network/systemvpc`; Ochre consumes managed-service launch and system-VPC realisation as domain implementations rather than capabilities.
- Domain → runtime: `domains/ochre/capacity.go:9` imports `runtime/compute/gpu`; `domains/ec2/volume/service_impl.go:30` and `volume_leak_reaper.go:8` import `runtime/compute/vm`; `domains/ec2/instance/status_selection.go:9` also imports `runtime/compute/vm`. Each reads VM or GPU runtime state directly instead of through a domain-owned projection.
- STS web-identity verification never consults cluster status: tokens verify while a cluster is DELETING until teardown sweeps the prefix, and a FAILED launch keeps its JWKS. AWS behaviour must be established before calling it a divergence. Removal condition: AWS behaviour verified, and the resolver or EKS lifecycle aligned with it.
- The public `/keys` endpoint (root `gateway`, `oidc_discovery.go`) serves malformed stored JWKS bytes with HTTP 200. Removal condition: validate before serving, or record it as accepted.
@@ -448,8 +449,8 @@ These residuals were recorded by individual slices and must be resolved once the
- `gateway/requestaudit.go`: the outermost request-audit middleware records AWS fields and is updated from four places in the gateway's authentication flow through the gateway's own context key. Moving it would export about seven names used only by that flow, so it stays in `gateway` until the generic ingress registration seam defines how ingress middleware receives authentication results.
- `accountteardown` (dependency): its EC2 reapers call `domains/ec2/awsapi/*` action adapters directly, as they did under `gateway/ec2`. The ADR's `accountteardown` current-to-target map row replaces this with domain-owned cleanup capabilities before the package moves. It also holds a read-only consumer of the EC2 platform-inventory contract (`contracts/ec2/v1`, `ec2.v1.PlatformInventory`), served by `domains/ec2/accountinventory`; only the explicit dry run (`Engine.DryRun`) calls it, to log a shadow comparison, and the key-pair, placement-group and launch-template reapers still use the `awsapi` adapters. A domain-owned cleanup capability for the proven-safe subset of those three kinds (key pairs and empty placement groups no instance, spot request or live launch-template version names, and launch-template residue; never live launch templates) exists as `domains/ec2/accountcleanup` (a Go interface with injected owners and reference readers, no NATS subject); nothing calls it yet. It also holds the StageAccount settings-seal reaper, a consumer of `contracts/ec2/v1`'s `ec2.v1.SealAccountSettings` and per-node `ec2.v1.AccountSettingsSealCapability.<node>` subjects, served by `domains/ec2/account` through the daemon; the reaper reads no KV and imports no domain package, reaching both subjects only through NATS and the configured node set `NewClusterEngine` already receives.
- `domains/admission/quota` (dependency, moved from `handlers/quota` unchanged): `live.go` imports `gateway/elbv2` and `handlers/rds` for its live ELBv2 and RDS counters; `records.go` imports `runtime/compute/vm` for the instance-record vCPU sweep; `live.go`, `vcpu.go` and `storage.go` call `domains/ec2/awsapi/{vpc,eip,volume}` describe adapters to count VPCs, subnets, addresses and volumes, as they did under `gateway/ec2`. The ADR's `handlers/quota` current-to-target map row replaces these with reader capabilities once their final locations exist.
- `domains/ec2/awsapi/instance` (dependency): imports `handlers/iam` (`IAMService` in `DescribeInstances.go`, `RunInstances.go` and `IamInstanceProfileAssociation.go`; `InstanceProfile` in the latter two), `runtime/compute/cache` (`NodeState`, `NodeUnknown`, `NodeLive`) and `runtime/compute/vm` (`VM`), both in `status_synthesis.go`. The IAM edge needs an IAM capability; the runtime edges are domain-to-runtime and need the instance record and node liveness exposed through an EC2-owned projection.
- `domains/ec2/awsapi/spotinstance` (dependency): imports `handlers/iam.IAMService` and `domains/admission/quota.Service` in `RequestSpotInstances.go`.
- `domains/ec2/awsapi/instance` (dependency): imports `domains/iam` (`IAMService` in `DescribeInstances.go`, `RunInstances.go` and `IamInstanceProfileAssociation.go`; `InstanceProfile` in the latter two), `runtime/compute/cache` (`NodeState`, `NodeUnknown`, `NodeLive`) and `runtime/compute/vm` (`VM`), both in `status_synthesis.go`. The IAM edge needs an IAM capability; the runtime edges are domain-to-runtime and need the instance record and node liveness exposed through an EC2-owned projection.
- `domains/ec2/awsapi/spotinstance` (dependency): imports `domains/iam.IAMService` and `domains/admission/quota.Service` in `RequestSpotInstances.go`.
- Instance adapter consumers outside EC2: `gateway/rds/enginecatalog.go`, `daemon/eks_cp_control.go`, `daemon/rds_deps.go`, `domains/admission/quota`'s `vcpu.go` and `gateway/iam.go` (`CountInstanceProfileAssociations`) call `domains/ec2/awsapi/instance` directly; each needs an EC2 capability rather than the AWS action adapter.
Enforcement: the owner decided the layering test is blocking now, with a ratchet. Its allowlist mirrors this debt list exactly, each edge carrying its owner and removal condition; any new unrecorded forbidden edge fails local preflight and CI, and an allowlisted edge that no longer exists must be removed from the list.
@@ -463,7 +464,7 @@ Enforcement: the owner decided the layering test is blocking now, with a ratchet
- `agents/rds/agent` (dependency, narrowed): engine metadata now arrives through the agent-declared `EngineCatalog`, but the agent still imports `handlers/rds` for the command protocol, wire and record types (`Command*`, `Parameter`, `EngineHealth*`, `BootstrapMode*`) and API output types. This clears when those move behind a guest/controller wire contract.
- `gateway/rds` → `handlers/rds` (`InstanceSizing`): the gateway obtains its `Sizing` through the RDS handler package's adapter rather than its own composition root. This clears when the gateway's RDS composition moves to `runtime/roles/awsgw` and builds `Sizing` there.
- `domains/admission/quota` → `domains/ec2/instancetypes`: `reconcile.go`, `records.go` and `vcpu.go` read `DefaultVCPUs` to size instances without a recorded vCPU count. This clears when quota receives vCPU sizing through a consumer-owned capability or an EC2 projection.
- IAM implementation consumers in STS, Ochre and ELBv2: `handlers/sts` imports `handlers/iam` across five files (`IAMService`, `SessionRevoker`, `EncryptSecret`/`DecryptSecret`, `AccessKeyStatusActive`, `ValidateTrustPolicyDocument`, `PolicyEffectAllow`/`PolicyEffectDeny`, `IAMAccountBucketName`, `OIDCProviderARN`, `OIDCProviderKey`), not only `oidc_jwks.go`; `gateway/sts/GetCallerIdentity.go` takes `IAMService`; `gateway/bedrock/credentials.go` uses `EncryptSecret`/`DecryptSecret`; and `handlers/elbv2/{lb_role,service_impl}.go` use `EnsureSystemInstanceProfile` and `SystemInstanceRoleEnsurer`. Each clears when its consumer receives a narrow IAM capability, or a shared crypto boundary for the secret helpers, rather than importing the IAM implementation.
- IAM implementation consumers in STS, Ochre and ELBv2: `handlers/sts` imports `domains/iam` across five files (`IAMService`, `SessionRevoker`, `EncryptSecret`/`DecryptSecret`, `AccessKeyStatusActive`, `ValidateTrustPolicyDocument`, `PolicyEffectAllow`/`PolicyEffectDeny`, `IAMAccountBucketName`, `OIDCProviderARN`, `OIDCProviderKey`), not only `oidc_jwks.go`; `gateway/sts/GetCallerIdentity.go` takes `IAMService`; `gateway/bedrock/credentials.go` uses `EncryptSecret`/`DecryptSecret`; and `handlers/elbv2/{lb_role,service_impl}.go` use `EnsureSystemInstanceProfile` and `SystemInstanceRoleEnsurer`. Each clears when its consumer receives a narrow IAM capability, or a shared crypto boundary for the secret helpers, rather than importing the IAM implementation.
- `handlers/elbv2` (cross-domain): `service_impl.go` imports `domains/acm` (`Store`, `NewStore`), `domains/dns` (`ELBChanges`, `ELBName`, `Change`, `ActionUpsert`, `ResolveBaseDomain`), `domains/ec2/vpc` (`VPCServiceImpl`) and `domains/network/topology` (`Port`), and `launcher.go` re-exports `domains/ec2/systeminstance` launch types as aliases. These clear when ELBv2 is extracted and each edge becomes a consumer-owned capability, which ADR-0001 sequences after the ELBv2 data-plane boundary is settled.
- `docs/service-interfaces.yaml` (ECS coverage gap, closed): the traced `ecs.bus.*` family and the ECS AWS-API action subjects are both listed. The action subjects are declared as `ecs.*`, the same wildcard convention as `rds.*`: `handlers/ecs/service_nats.go` publishes them from the gateway and `daemon/daemon.go` subscribes to them. Declaring `ecs.bus.*` alone had made `ecs` a managed prefix, so `manifest-lint` failed CI on all 34 undeclared action subjects until this was added.
- `contracts/ecs/v1` (dead routes): four of five bus subjects have no producer. The scheduler leader still subscribes to `instance-register`, `instance-heartbeat` and `task-state`, which can never fire, and `assign` has neither producer nor consumer; only `service-reconcile` is live. Removal condition: an owner decision to retire these routes (a successor contract under the compatibility rules) or to adopt them in the agent.
@@ -650,13 +651,13 @@ series above; "needs decision" is open.
| Legacy path | What remains | What blocks it |
|---|---|---|
| `handlers/iam` | Private identity state and credential issuance; consumed by the EC2 instance and spot-instance AWS adapters, `handlers/sts`, `gateway/sts`, `gateway/bedrock`, the ELBv2 system-instance role path, ECR/Ochre signing-key crypto and `operator/cli`. | Deferred: the ADR's `handlers/iam` row states a shared IAM contract is not inferred from current KV readers; each cross-domain reader needs an IAM capability first. |
| `handlers/sts` | Everything except the EKS OIDC JWKS lookup, which now reaches `handlers/eks` only through the injected `ClusterJWKSResolver`. | Deferred: per-consumer IAM capabilities (dependency-rule debt above); `handlers/sts` still imports `handlers/iam` directly. |
| `handlers/iam` | — | Done. The implementation moved to `domains/iam` (package `iam`) in `spinifex#1249` with no API, NATS subject, storage or behaviour change. ADR-0001's row says a shared IAM contract is not inferred from current KV readers, and the move adds none. The cross-domain readers (the EC2 instance and spot-instance AWS adapters, `handlers/sts`, `gateway/sts`, `gateway/bedrock`, the ELBv2 system-instance role path and ECR/Ochre signing-key crypto) still import the implementation and each still needs an IAM capability; that is recorded dependency-rule debt, with its allowlist entries now targeting `domains/iam`, not a prerequisite to relocating IAM's implementation. |
| `handlers/sts` | Everything except the EKS OIDC JWKS lookup, which now reaches `handlers/eks` only through the injected `ClusterJWKSResolver`. | Deferred: per-consumer IAM capabilities (dependency-rule debt above); `handlers/sts` still imports `domains/iam` directly. |
| `handlers/ecs` | Task, service and capacity resources (`taskdefinition` already extracted to `domains/ecs/taskdefinition`). | Deferred: ADR-0004 blocked-dependency list — `iam:PassRole` in the gateway adapter and EC2/ELBv2/EIP adapters called as internal APIs. |
| `handlers/eks` | Nodegroup and cluster resources (`access` and `addon` already extracted). | Deferred: ADR-0004 blocked-dependency list — IAM role/instance-profile creation, Bluebottle `auth`, the NATS CA, and EKS identity (token review, OIDC). |
| `handlers/rds` | The RDS instance resource (subnet group, parameter group and engine catalogue already extracted). | Deferred: ADR-0004 blocked-dependency list — quota admission, the duplicated expected-node fan-out, the IAM ensurer and the Bluebottle master key. |
| `handlers/elbv2` | Everything; not yet touched. | Deferred: ADR-0001 sequences this after the ELBv2 data-plane boundary is settled. Needs decision: what evidence establishes that boundary is settled. |
| `handlers/iam/mock` | A test double for `handlers/iam`. | Moves with `handlers/iam`; it has no independent target. |
| `handlers/iam/mock` | — | Done. Moved with the implementation to `domains/iam/mock`. |
| `gateway` (root) | Generic HTTP route assembly, SigV4/registry authentication, the policy gate, request-audit middleware, request-context keys, and the legacy per-service dispatch switch for every service not yet registered. | Deferred: the ADR-0002 phases above (auth/IAM and request-context boundary design) gate moving the audit, context-key and legacy-dispatch mechanics. |
| `gateway/bedrock` | The Ochre domain core, its stores and the inference engine, together with the Bedrock action layer, in one package with internal cycles. | Deferred: needs the split plan recorded above — domain core and stores to `domains/ochre/<resource>`, inference to an Ochre-owned package, and only the action layer to `domains/ochre/awsapi`. |
| `gateway/{ecs,eks,rds,iam,sts,elbv2}` | Each service's AWS action adapters and dispatch, not yet registered through ADR-0002. | Deferred: the ADR-0002 registration contract has only reached ECR and ACM so far; each service needs its own registration slice. |
@@ -682,9 +683,9 @@ ADR-0001 completion is structural, so none of these is cleared by remediating se
| Explicitly deferred by ADR-0001 | `daemon` (Q-28), `lbagent` (Q-30) | Closed for this refactor; the ADR names the prerequisite. |
| No missing boundary (candidate moves) | `handlers/ecs/bus` → `contracts/ecs/v1` (`a130f6b8e`); `admin/images_promote.go` → `domains/ec2/image` (`263c58167`); `admin` bootstrap account identifiers → `foundation/aws/identifiers` (`3fdaa54d9`); `admin` credential-format generators → `foundation/aws/credentials` `0368e861a`, retiring `admin` | Done. |
| One narrow missing boundary | Done: `handlers/sts` EKS JWKS lookup → `handlers/eks` `ClusterJWKSResolver` (`254d898a3`); `gateway/tagging` → `domains/tagging` with AWSGW-composed listers (`0d830e901`, `f3545e3ea`, `aedd0b2c4`). Open: `gateway/spx` (owner of operator-plane dispatch registration) | Each needs one decision or one capability, then a mechanical move. |
| Broader boundary or follows another package | `handlers/iam` and `handlers/iam/mock` (per-consumer IAM capabilities); `handlers/{ecs,eks,rds}` (ADR-0004 blocked-dependency lists); `handlers/elbv2` (data-plane boundary evidence); `accountteardown` (domain cleanup capabilities); `gateway` root (ADR-0002 auth and request-context phase); `gateway/{iam,sts,ecs,eks,rds,elbv2}` (each follows its `handlers/<svc>`, because a new-path `awsapi` cannot import a legacy handler); `gateway/bedrock` (the recorded Ochre split plan) | Recorded debt with removal conditions above. |
| Broader boundary or follows another package | `handlers/{ecs,eks,rds}` (ADR-0004 blocked-dependency lists); `handlers/elbv2` (data-plane boundary evidence); `accountteardown` (domain cleanup capabilities); `gateway` root (ADR-0002 auth and request-context phase); `gateway/{iam,sts,ecs,eks,rds,elbv2}` (each follows its `handlers/<svc>`, because a new-path `awsapi` cannot import a legacy handler); `gateway/bedrock` (the recorded Ochre split plan) | Recorded debt with removal conditions above. |
Per-consumer IAM capabilities are the widest unblocker: they gate `handlers/iam` itself, STS's IAM reads, Ochre's IAM reads, the ELBv2 role path and the ECS, EKS and RDS ensurers.
Per-consumer IAM capabilities are the widest unblocker: they gate STS's IAM reads, Ochre's IAM reads, the ELBv2 role path and the ECS, EKS and RDS ensurers.
`runtime/roles/awsgw` carries two recorded residuals from its own move (`931d86d5c`
above) that are not yet re-homed: `runQuotaReconcile`/`quotaKeyFor` belong to
+1 -1
View File
@@ -76,7 +76,7 @@ services:
- spinifex/domains/ec2/vpc
- spinifex/handlers/elbv2
- spinifex/domains/acm
- spinifex/handlers/iam
- spinifex/domains/iam
- spinifex/handlers/ecs
- spinifex/handlers/rds
- spinifex/domains/rds/subnetgroup
+3 -3
View File
@@ -6,8 +6,8 @@ import (
"log/slog"
"github.com/mulgadc/spinifex/spinifex/domains/admission/quota"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvutil"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
@@ -22,7 +22,7 @@ func NewClusterEngine(
nc *nats.Conn,
expectedNodes int,
nodeIDs []string,
svc handlers_iam.IAMService,
svc iamdomain.IAMService,
buckets BucketStore,
) (*Engine, error) {
// Refused rather than skipped. A teardown missing its bucket reaper still
@@ -37,7 +37,7 @@ func NewClusterEngine(
return nil, fmt.Errorf("get JetStream context: %w", err)
}
names, err := handlers_iam.NewAccountNameIndex(ctx, js)
names, err := iamdomain.NewAccountNameIndex(ctx, js)
if err != nil {
return nil, fmt.Errorf("open account name index: %w", err)
}
+7 -7
View File
@@ -7,7 +7,7 @@ import (
"testing"
"github.com/mulgadc/spinifex/internal/testkit"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -18,9 +18,9 @@ import (
func TestNewClusterEngineCoversEveryStage(t *testing.T) {
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_iam.NewIAMServiceImpl(t.Context(), nc, masterKey)
svc, err := iamdomain.NewIAMServiceImpl(t.Context(), nc, masterKey)
require.NoError(t, err)
engine, err := NewClusterEngine(t.Context(), nc, 1, []string{"node-1"}, svc, newFakeBuckets())
@@ -47,9 +47,9 @@ func TestNewClusterEngineCoversEveryStage(t *testing.T) {
func TestNewClusterEngineRegistersTheEC2SettingsSealReaper(t *testing.T) {
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_iam.NewIAMServiceImpl(t.Context(), nc, masterKey)
svc, err := iamdomain.NewIAMServiceImpl(t.Context(), nc, masterKey)
require.NoError(t, err)
engine, err := NewClusterEngine(t.Context(), nc, 1, []string{"node-1"}, svc, newFakeBuckets())
@@ -67,9 +67,9 @@ func TestNewClusterEngineRegistersTheEC2SettingsSealReaper(t *testing.T) {
func TestClusterEnginePrechecks(t *testing.T) {
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_iam.NewIAMServiceImpl(t.Context(), nc, masterKey)
svc, err := iamdomain.NewIAMServiceImpl(t.Context(), nc, masterKey)
require.NoError(t, err)
engine, err := NewClusterEngine(t.Context(), nc, 1, []string{"node-1"}, svc, newFakeBuckets())
@@ -17,9 +17,9 @@ import (
ec2v1 "github.com/mulgadc/spinifex/contracts/ec2/v1"
"github.com/mulgadc/spinifex/internal/testkit"
"github.com/mulgadc/spinifex/spinifex/domains/ec2/accountinventory"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
awserrors "github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
natsmsg "github.com/mulgadc/spinifex/spinifex/foundation/messaging/nats"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -165,9 +165,9 @@ func TestEC2PlatformInventoryClientDistrustsAMalformedReply(t *testing.T) {
// a Teardown request marked dry run and a full teardown all leave it uncalled.
func TestOnlyTheExplicitDryRunCallsTheEC2PlatformInventory(t *testing.T) {
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_iam.NewIAMServiceImpl(t.Context(), nc, masterKey)
svc, err := iamdomain.NewIAMServiceImpl(t.Context(), nc, masterKey)
require.NoError(t, err)
cluster, err := NewClusterEngine(t.Context(), nc, 1, []string{"node-1"}, svc, newFakeBuckets())
require.NoError(t, err)
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"time"
)
// AccountStatusTerminating mirrors handlers_iam.AccountStatusTerminating.
// AccountStatusTerminating mirrors iamdomain.AccountStatusTerminating.
// Redeclared so this package does not depend on the IAM service to be tested.
const AccountStatusTerminating = "TERMINATING"
+3 -3
View File
@@ -13,7 +13,7 @@ import (
"testing"
"time"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
)
const (
@@ -129,11 +129,11 @@ func TestProtectedAccountsMatchTheRestOfTheSystem(t *testing.T) {
if _, protected := protectedAccountIDs[id]; !protected {
t.Fatalf("account %s is not protected by teardown", id)
}
if _, protected := handlers_iam.UndeletableAccountIDs[id]; !protected {
if _, protected := iamdomain.UndeletableAccountIDs[id]; !protected {
t.Fatalf("account %s is not protected by the IAM service", id)
}
}
if len(protectedAccountIDs) != len(handlers_iam.UndeletableAccountIDs) {
if len(protectedAccountIDs) != len(iamdomain.UndeletableAccountIDs) {
t.Fatal("teardown and the IAM service disagree on which accounts are protected")
}
}
+6 -6
View File
@@ -5,13 +5,13 @@ import (
"errors"
"fmt"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/nats-io/nats.go/jetstream"
)
// AccountReapers returns the final-stage reapers: the per-account counters and
// reservations that outlive every resource but must not outlive the account.
func AccountReapers(svc handlers_iam.IAMService, names *handlers_iam.AccountNameIndex, usage jetstream.KeyValue) []Reaper {
func AccountReapers(svc iamdomain.IAMService, names *iamdomain.AccountNameIndex, usage jetstream.KeyValue) []Reaper {
return []Reaper{
&quotaUsageReaper{usage: usage},
&nameReservationReaper{svc: svc, names: names},
@@ -53,8 +53,8 @@ func (r *quotaUsageReaper) Delete(ctx context.Context, _ string, resource Resour
// up again. A customer who deletes an account and returns must not be told the
// address is taken by a tenant that no longer exists.
type nameReservationReaper struct {
svc handlers_iam.IAMService
names *handlers_iam.AccountNameIndex
svc iamdomain.IAMService
names *iamdomain.AccountNameIndex
}
func (r *nameReservationReaper) Kind() string { return "name-reservation" }
@@ -92,12 +92,12 @@ func (r *nameReservationReaper) Delete(ctx context.Context, accountID string, re
// IAMAccounts adapts the IAM service to the engine's AccountStore. The engine
// declares its own Account type so its tests need no cluster; this is the one
// place the two meet.
type IAMAccounts struct{ svc handlers_iam.IAMService }
type IAMAccounts struct{ svc iamdomain.IAMService }
var _ AccountStore = (*IAMAccounts)(nil)
// NewIAMAccounts wraps svc as the engine's AccountStore.
func NewIAMAccounts(svc handlers_iam.IAMService) *IAMAccounts {
func NewIAMAccounts(svc iamdomain.IAMService) *IAMAccounts {
return &IAMAccounts{svc: svc}
}
@@ -10,8 +10,8 @@ import (
"testing"
"github.com/mulgadc/spinifex/internal/testkit"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvutil"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go/jetstream"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -22,20 +22,20 @@ import (
type accountIAM struct {
fakeIAM
account *handlers_iam.Account
account *iamdomain.Account
getErr error
deleted bool
setStatus string
}
func (f *accountIAM) GetAccount(string) (*handlers_iam.Account, error) {
func (f *accountIAM) GetAccount(string) (*iamdomain.Account, error) {
if f.getErr != nil {
return nil, f.getErr
}
return f.account, nil
}
func (f *accountIAM) SetAccountStatus(_, status string) (*handlers_iam.Account, error) {
func (f *accountIAM) SetAccountStatus(_, status string) (*iamdomain.Account, error) {
f.setStatus = status
updated := *f.account
updated.Status = status
@@ -102,12 +102,12 @@ func TestNameReservationReaperReleasesTheName(t *testing.T) {
_, js, _ := testKV(t, "spinifex-name-reaper-warmup")
ctx := testCtx(t)
names, err := handlers_iam.NewAccountNameIndex(ctx, js)
names, err := iamdomain.NewAccountNameIndex(ctx, js)
require.NoError(t, err)
require.NoError(t, names.Reserve(ctx, "tenant@example.com", "token-1"))
require.NoError(t, names.Commit(ctx, "tenant@example.com", "000000000042", "token-1"))
svc := &accountIAM{account: &handlers_iam.Account{
svc := &accountIAM{account: &iamdomain.Account{
AccountID: "000000000042", AccountName: "tenant@example.com",
}}
reaper := &nameReservationReaper{svc: svc, names: names}
@@ -130,12 +130,12 @@ func TestNameReservationReaperIgnoresAnotherAccountsName(t *testing.T) {
_, js, _ := testKV(t, "spinifex-name-reaper-other")
ctx := testCtx(t)
names, err := handlers_iam.NewAccountNameIndex(ctx, js)
names, err := iamdomain.NewAccountNameIndex(ctx, js)
require.NoError(t, err)
require.NoError(t, names.Reserve(ctx, "tenant@example.com", "token-1"))
require.NoError(t, names.Commit(ctx, "tenant@example.com", "000000000099", "token-1"))
svc := &accountIAM{account: &handlers_iam.Account{
svc := &accountIAM{account: &iamdomain.Account{
AccountID: "000000000042", AccountName: "tenant@example.com",
}}
@@ -154,7 +154,7 @@ func TestNameReservationReaperReportsAMissingAccount(t *testing.T) {
_, js, _ := testKV(t, "spinifex-name-reaper-missing")
ctx := testCtx(t)
names, err := handlers_iam.NewAccountNameIndex(ctx, js)
names, err := iamdomain.NewAccountNameIndex(ctx, js)
require.NoError(t, err)
svc := &accountIAM{getErr: errors.New("account not found")}
@@ -177,10 +177,10 @@ func TestAccountReapersRunLast(t *testing.T) {
// The adapter is the one place the engine's Account and the IAM record meet,
// so a field dropped in translation would silently break the name confirmation.
func TestIAMAccountsAdapterCarriesEveryField(t *testing.T) {
svc := &accountIAM{account: &handlers_iam.Account{
svc := &accountIAM{account: &iamdomain.Account{
AccountID: "000000000042",
AccountName: "tenant@example.com",
Status: handlers_iam.AccountStatusActive,
Status: iamdomain.AccountStatusActive,
}}
accounts := NewIAMAccounts(svc)
@@ -188,12 +188,12 @@ func TestIAMAccountsAdapterCarriesEveryField(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, "000000000042", account.AccountID)
assert.Equal(t, "tenant@example.com", account.AccountName)
assert.Equal(t, handlers_iam.AccountStatusActive, account.Status)
assert.Equal(t, iamdomain.AccountStatusActive, account.Status)
updated, err := accounts.SetAccountStatus("000000000042", AccountStatusTerminating)
require.NoError(t, err)
assert.Equal(t, AccountStatusTerminating, updated.Status)
assert.Equal(t, handlers_iam.AccountStatusTerminating, svc.setStatus)
assert.Equal(t, iamdomain.AccountStatusTerminating, svc.setStatus)
require.NoError(t, accounts.DeleteAccount("000000000042"))
assert.True(t, svc.deleted)
@@ -203,5 +203,5 @@ func TestIAMAccountsAdapterCarriesEveryField(t *testing.T) {
// two must not drift: a mismatch would mark accounts with a status the auth
// gate does not recognise, and they would keep authenticating.
func TestTerminatingStatusMatchesTheIAMRecord(t *testing.T) {
assert.Equal(t, handlers_iam.AccountStatusTerminating, AccountStatusTerminating)
assert.Equal(t, iamdomain.AccountStatusTerminating, AccountStatusTerminating)
}
+9 -9
View File
@@ -6,7 +6,7 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
)
// IAMReapers returns the identity-stage reapers in teardown order.
@@ -14,7 +14,7 @@ import (
// Access keys go first and deliberately: it is the second quiesce, and unlike
// the account-status gate it holds even against a caller that reached the
// cluster some other way.
func IAMReapers(svc handlers_iam.IAMService) []Reaper {
func IAMReapers(svc iamdomain.IAMService) []Reaper {
return []Reaper{
&accessKeyReaper{svc: svc},
&instanceProfileReaper{svc: svc},
@@ -34,7 +34,7 @@ func IAMReapers(svc handlers_iam.IAMService) []Reaper {
// They survive their cluster's deletion, so nothing else in teardown reaches
// them and an account would be left holding a trust anchor for a cluster that
// no longer exists.
type oidcProviderReaper struct{ svc handlers_iam.IAMService }
type oidcProviderReaper struct{ svc iamdomain.IAMService }
func (r *oidcProviderReaper) Kind() string { return "oidc-provider" }
func (r *oidcProviderReaper) Stage() Stage { return StagePlatform }
@@ -62,7 +62,7 @@ func (r *oidcProviderReaper) Delete(_ context.Context, accountID string, resourc
return ignoreAlreadyGone(err)
}
type accessKeyReaper struct{ svc handlers_iam.IAMService }
type accessKeyReaper struct{ svc iamdomain.IAMService }
func (r *accessKeyReaper) Kind() string { return "access-key" }
func (r *accessKeyReaper) Stage() Stage { return StageIdentity }
@@ -102,7 +102,7 @@ func (r *accessKeyReaper) Delete(_ context.Context, accountID string, resource R
return ignoreAlreadyGone(err)
}
type iamUserReaper struct{ svc handlers_iam.IAMService }
type iamUserReaper struct{ svc iamdomain.IAMService }
func (r *iamUserReaper) Kind() string { return "iam-user" }
func (r *iamUserReaper) Stage() Stage { return StageIdentity }
@@ -166,7 +166,7 @@ func (r *iamUserReaper) Delete(_ context.Context, accountID string, resource Res
return ignoreAlreadyGone(err)
}
type iamRoleReaper struct{ svc handlers_iam.IAMService }
type iamRoleReaper struct{ svc iamdomain.IAMService }
func (r *iamRoleReaper) Kind() string { return "iam-role" }
func (r *iamRoleReaper) Stage() Stage { return StageIdentity }
@@ -228,7 +228,7 @@ func (r *iamRoleReaper) Delete(_ context.Context, accountID string, resource Res
return ignoreAlreadyGone(err)
}
type iamGroupReaper struct{ svc handlers_iam.IAMService }
type iamGroupReaper struct{ svc iamdomain.IAMService }
func (r *iamGroupReaper) Kind() string { return "iam-group" }
func (r *iamGroupReaper) Stage() Stage { return StageIdentity }
@@ -254,7 +254,7 @@ func (r *iamGroupReaper) Delete(_ context.Context, accountID string, resource Re
return ignoreAlreadyGone(err)
}
type iamPolicyReaper struct{ svc handlers_iam.IAMService }
type iamPolicyReaper struct{ svc iamdomain.IAMService }
func (r *iamPolicyReaper) Kind() string { return "iam-policy" }
func (r *iamPolicyReaper) Stage() Stage { return StageIdentity }
@@ -302,7 +302,7 @@ func (r *iamPolicyReaper) Delete(_ context.Context, accountID string, resource R
return ignoreAlreadyGone(err)
}
type instanceProfileReaper struct{ svc handlers_iam.IAMService }
type instanceProfileReaper struct{ svc iamdomain.IAMService }
func (r *instanceProfileReaper) Kind() string { return "instance-profile" }
func (r *instanceProfileReaper) Stage() Stage { return StageIdentity }
+4 -4
View File
@@ -11,7 +11,7 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/mulgadc/spinifex/internal/testkit"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -21,7 +21,7 @@ import (
// stay unimplemented — calling one is a test failure by panic, which is the
// honest outcome for a reaper reaching somewhere it was not meant to.
type fakeIAM struct {
handlers_iam.IAMService
iamdomain.IAMService
calls []string
@@ -396,9 +396,9 @@ func TestPolicyReaperAsksOnlyForLocalPolicies(t *testing.T) {
// DeletePolicy refuses it until they are gone.
func TestPolicyReaperDeletesAPolicyWithSeveralVersions(t *testing.T) {
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_iam.NewIAMServiceImpl(t.Context(), nc, masterKey)
svc, err := iamdomain.NewIAMServiceImpl(t.Context(), nc, masterKey)
require.NoError(t, err)
const accountID = "000000000042"
@@ -7,8 +7,8 @@ import (
"github.com/mulgadc/spinifex/internal/testkit"
"github.com/mulgadc/spinifex/spinifex/domains/admission/quota"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvutil"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go/jetstream"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -36,7 +36,7 @@ func TestCurrentBehaviour_AccountTermination_QuotaOverridesSurviveTeardown(t *te
require.NoError(t, svc.PutAccountQuota(ctx, testAccountID, quota.Overrides{VCPUs: &unlimited}, "operator"))
accounts := newFakeAccounts()
iam := &accountIAM{account: &handlers_iam.Account{AccountID: testAccountID, AccountName: testAccountName}}
iam := &accountIAM{account: &iamdomain.Account{AccountID: testAccountID, AccountName: testAccountName}}
engine := quietEngine(accounts, AccountReapers(iam, nil, usage)...)
result, err := engine.Teardown(ctx, request())
+4 -4
View File
@@ -63,6 +63,7 @@ import (
ec2volume "github.com/mulgadc/spinifex/spinifex/domains/ec2/volume"
ec2vpc "github.com/mulgadc/spinifex/spinifex/domains/ec2/vpc"
"github.com/mulgadc/spinifex/spinifex/domains/ecr"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/domains/network/external"
"github.com/mulgadc/spinifex/spinifex/domains/network/external/dhcp"
"github.com/mulgadc/spinifex/spinifex/domains/network/external/exonet"
@@ -78,7 +79,6 @@ import (
handlers_ecs "github.com/mulgadc/spinifex/spinifex/handlers/ecs"
handlers_eks "github.com/mulgadc/spinifex/spinifex/handlers/eks"
handlers_elbv2 "github.com/mulgadc/spinifex/spinifex/handlers/elbv2"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
handlers_rds "github.com/mulgadc/spinifex/spinifex/handlers/rds"
"github.com/mulgadc/spinifex/spinifex/providers/ebs"
"github.com/mulgadc/spinifex/spinifex/providers/objectstore"
@@ -297,7 +297,7 @@ type Daemon struct {
// iamEnsurerMu guards the lazily-built system-role IAM service (systemRoleEnsurer).
iamEnsurerMu sync.Mutex
iamEnsurerCached handlers_iam.SystemInstanceRoleEnsurer
iamEnsurerCached iamdomain.SystemInstanceRoleEnsurer
mu sync.Mutex
}
@@ -2006,8 +2006,8 @@ func (d *Daemon) startCluster() error {
if err != nil {
return fmt.Errorf("jetstream handle for account status reader: %w", err)
}
var _ ec2account.AccountTerminationChecker = (*handlers_iam.AccountStatusReader)(nil)
d.accountService.SetAccountTerminationChecker(handlers_iam.NewAccountStatusReader(accountStatusJS))
var _ ec2account.AccountTerminationChecker = (*iamdomain.AccountStatusReader)(nil)
d.accountService.SetAccountTerminationChecker(iamdomain.NewAccountStatusReader(accountStatusJS))
// ELBv2 resolves listener certificate private keys through its own ACM
// Store over the same JetStream bucket the ACM service writes, so it needs
@@ -16,11 +16,11 @@ import (
ec2eip "github.com/mulgadc/spinifex/spinifex/domains/ec2/eip"
"github.com/mulgadc/spinifex/spinifex/domains/ec2/systeminstance"
ec2vpc "github.com/mulgadc/spinifex/spinifex/domains/ec2/vpc"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/domains/network/external"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/tags"
"github.com/mulgadc/spinifex/spinifex/handlers/elbv2"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/mulgadc/spinifex/spinifex/runtime/compute/vm"
"github.com/nats-io/nats.go"
"github.com/stretchr/testify/assert"
@@ -623,7 +623,7 @@ func newRefreshTestDaemon(t *testing.T) (*Daemon, *nats.Conn, string) {
tmpDir := t.TempDir()
t.Setenv("XDG_RUNTIME_DIR", tmpDir)
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_elbv2.NewELBv2ServiceImplWithNATS(nil, nc, masterKey)
require.NoError(t, err)
+3 -3
View File
@@ -7,8 +7,8 @@ import (
"github.com/mulgadc/spinifex/internal/testkit"
"github.com/mulgadc/spinifex/spinifex/bootstrap/config"
ec2eip "github.com/mulgadc/spinifex/spinifex/domains/ec2/eip"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
handlers_elbv2 "github.com/mulgadc/spinifex/spinifex/handlers/elbv2"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -20,7 +20,7 @@ func newWireLBTestDaemon(t *testing.T, cfg *config.Config) *Daemon {
t.Helper()
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_elbv2.NewELBv2ServiceImplWithNATS(nil, nc, masterKey)
require.NoError(t, err)
@@ -203,7 +203,7 @@ func TestWireLBAgentConfig_GatewayURL_SingleNodeBindMatchesAdvertise(t *testing.
// newSubscribeTestDaemon creates a minimal Daemon wired enough for subscribeAll.
func newSubscribeTestDaemon(t *testing.T, nc *nats.Conn, gatewayURL, accessKey string) *Daemon {
t.Helper()
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_elbv2.NewELBv2ServiceImplWithNATS(nil, nc, masterKey)
require.NoError(t, err)
+2 -2
View File
@@ -9,10 +9,10 @@ import (
"testing"
"github.com/mulgadc/spinifex/internal/testkit"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvstore"
handlers_eks "github.com/mulgadc/spinifex/spinifex/handlers/eks"
handlers_elbv2 "github.com/mulgadc/spinifex/spinifex/handlers/elbv2"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
handlers_rds "github.com/mulgadc/spinifex/spinifex/handlers/rds"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -81,7 +81,7 @@ func TestElbv2WatchBuckets_NoStoreIsNilSafe(t *testing.T) {
func TestElbv2WatchBuckets_WithStoreReturnsWatchBucket(t *testing.T) {
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_elbv2.NewELBv2ServiceImplWithNATS(nil, nc, masterKey)
require.NoError(t, err)
+3 -3
View File
@@ -6,8 +6,8 @@ import (
"path/filepath"
"github.com/mulgadc/bluebottle/pkg/masterkey"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
handlers_ecs "github.com/mulgadc/spinifex/spinifex/handlers/ecs"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
)
// buildECSServiceDeps assembles the ECS service Deps for ProvisionCapacity: the
@@ -47,8 +47,8 @@ func (d *Daemon) buildECSServiceDeps() handlers_ecs.Deps {
// to have responders. A daemon that started first got one attempt, failed
// it, and had capacity provisioning off for the life of the process with no
// symptom but a 500 from ProvisionCapacity.
iamSvc, iamErr := initServiceWithRetry("ECS IAM service", func() (*handlers_iam.IAMServiceImpl, error) {
return handlers_iam.NewIAMServiceImpl(d.ctx, d.natsConn, masterKey)
iamSvc, iamErr := initServiceWithRetry("ECS IAM service", func() (*iamdomain.IAMServiceImpl, error) {
return iamdomain.NewIAMServiceImpl(d.ctx, d.natsConn, masterKey)
})
if iamErr != nil {
// Off rather than fatal: ECS CRUD, EKS and EC2 do not need this, and a
+3 -3
View File
@@ -10,8 +10,8 @@ import (
"github.com/mulgadc/bluebottle/pkg/masterkey"
"github.com/mulgadc/spinifex/spinifex/bootstrap/config"
ec2placementgroup "github.com/mulgadc/spinifex/spinifex/domains/ec2/placementgroup"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
handlers_eks "github.com/mulgadc/spinifex/spinifex/handlers/eks"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/mulgadc/spinifex/spinifex/providers/objectstore"
)
@@ -24,7 +24,7 @@ import (
// first-use (an LB/cluster create) the backend is up. Returns nil (caller falls
// back to static creds) until a build succeeds; retried on each call until then,
// cached once it works.
func (d *Daemon) systemRoleEnsurer() handlers_iam.SystemInstanceRoleEnsurer {
func (d *Daemon) systemRoleEnsurer() iamdomain.SystemInstanceRoleEnsurer {
d.iamEnsurerMu.Lock()
defer d.iamEnsurerMu.Unlock()
if d.iamEnsurerCached != nil {
@@ -36,7 +36,7 @@ func (d *Daemon) systemRoleEnsurer() handlers_iam.SystemInstanceRoleEnsurer {
"err", err)
return nil
}
iamSvc, iamErr := handlers_iam.NewIAMServiceImpl(d.ctx, d.natsConn, masterKey)
iamSvc, iamErr := iamdomain.NewIAMServiceImpl(d.ctx, d.natsConn, masterKey)
if iamErr != nil {
slog.Warn("System role ensurer: IAM service init failed (retried on next launch); system VMs fall back to baked static creds",
"err", iamErr)
+4 -4
View File
@@ -21,9 +21,9 @@ import (
"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
"github.com/aws/aws-sdk-go/service/acm"
"github.com/mulgadc/spinifex/internal/testkit"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/arn"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -33,7 +33,7 @@ const testAccountID = "000000000001"
func setupACMService(t *testing.T) *ACMServiceImpl {
t.Helper()
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := NewACMServiceImplWithNATS(t.Context(), nil, nc, masterKey)
require.NoError(t, err)
@@ -307,7 +307,7 @@ func TestImportCertificate_PrivateKeyEncryptedAtRest(t *testing.T) {
// TestDescribeCertificate_DoesNotLeakPrivateKey asserts the public
// CertificateDetail response can never carry key material, however the
// record is stored. Precedent: TestSensitiveDataNotLogged_MasterKey in
// handlers/iam/service_impl_test.go.
// domains/iam/service_impl_test.go.
func TestDescribeCertificate_DoesNotLeakPrivateKey(t *testing.T) {
t.Parallel()
svc := setupACMService(t)
@@ -331,7 +331,7 @@ func TestDescribeCertificate_DoesNotLeakPrivateKey(t *testing.T) {
// TestSensitiveDataNotLogged_ACMPrivateKey asserts ImportCertificate and
// DescribeCertificate never place the raw private key PEM in log output.
// Precedent: TestSensitiveDataNotLogged_MasterKey in
// handlers/iam/service_impl_test.go.
// domains/iam/service_impl_test.go.
// fakeCertAuthority is a minimal CertAuthority for testing RequestCertificate's
// PRIVATE_CA path without the real tenant CA implementation (domains/acm/privateca.go
// lives on a separate branch).
+4 -4
View File
@@ -11,10 +11,10 @@ import (
"strings"
"time"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/arn"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvstore"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvutil"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
@@ -161,7 +161,7 @@ type CertRecord struct {
type Store struct {
store *kvstore.Store[CertRecord]
// masterKey encrypts/decrypts CertRecord.PrivateKey at rest (AES-256-GCM via
// handlers_iam.EncryptSecret/DecryptSecret). Every Store over the ACM bucket
// iamdomain.EncryptSecret/DecryptSecret). Every Store over the ACM bucket
// — the ACM service and ELBv2's independent read-only Store alike — must be
// constructed with the same deployment key: a keyed writer and an unkeyed (or
// differently keyed) reader of the same bucket disagree silently, with the
@@ -221,7 +221,7 @@ func certKey(certArn string) string {
// via the legacy-passthrough path in decryptPrivateKey is therefore
// re-encrypted the next time it is put.
func (s *Store) PutCert(ctx context.Context, rec *CertRecord) error {
ciphertext, err := handlers_iam.EncryptSecret(rec.PrivateKey, s.masterKey)
ciphertext, err := iamdomain.EncryptSecret(rec.PrivateKey, s.masterKey)
if err != nil {
return fmt.Errorf("encrypt private key: %w", err)
}
@@ -324,7 +324,7 @@ func isPlaintextPrivateKeyPEM(raw string) bool {
// ciphertext, garbage) is a hard error rather than a silent plaintext
// fallback.
func (s *Store) decryptPrivateKey(rec *CertRecord) error {
if plaintext, err := handlers_iam.DecryptSecret(rec.PrivateKey, s.masterKey); err == nil {
if plaintext, err := iamdomain.DecryptSecret(rec.PrivateKey, s.masterKey); err == nil {
rec.PrivateKey = plaintext
return nil
}
+2 -2
View File
@@ -8,8 +8,8 @@ import (
"time"
"github.com/mulgadc/spinifex/internal/testkit"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvstore"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go/jetstream"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -21,7 +21,7 @@ import (
func setupACMStore(t *testing.T) *Store {
t.Helper()
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
store, err := NewStore(t.Context(), nc, masterKey)
require.NoError(t, err)
@@ -14,8 +14,8 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
)
@@ -477,7 +477,7 @@ func judgeIdentityCompleteness(ctx context.Context, frames []natsmsg.Frame, sum
// that carries only an ARN. Results are cached per ARN to avoid repeated RPCs.
// Misses are warn-logged and leave Id empty (graceful degradation for deleted profiles).
// Safe to call with a nil output or nil IAMService (no-op).
func EnrichInstanceProfileIDs(out *ec2.DescribeInstancesOutput, iamSvc handlers_iam.IAMService, accountID string) {
func EnrichInstanceProfileIDs(out *ec2.DescribeInstancesOutput, iamSvc iamdomain.IAMService, accountID string) {
if out == nil || iamSvc == nil {
return
}
@@ -11,8 +11,8 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -751,9 +751,9 @@ func TestEnrichInstanceProfileIDs_CachesPerARN(t *testing.T) {
arn := "arn:aws:iam::123456789012:instance-profile/shared"
var calls int
svc := &fakeIAMService{
resolveFn: func(_, nameOrARN string) (*handlers_iam.InstanceProfile, error) {
resolveFn: func(_, nameOrARN string) (*iamdomain.InstanceProfile, error) {
calls++
return &handlers_iam.InstanceProfile{ARN: nameOrARN, InstanceProfileID: "AIPAEXAMPLE"}, nil
return &iamdomain.InstanceProfile{ARN: nameOrARN, InstanceProfileID: "AIPAEXAMPLE"}, nil
},
}
@@ -771,11 +771,11 @@ func TestEnrichInstanceProfileIDs_ResolveErrorLeavesIdEmpty(t *testing.T) {
failingARN := "arn:aws:iam::123456789012:instance-profile/missing"
okARN := "arn:aws:iam::123456789012:instance-profile/present"
svc := &fakeIAMService{
resolveFn: func(_, nameOrARN string) (*handlers_iam.InstanceProfile, error) {
resolveFn: func(_, nameOrARN string) (*iamdomain.InstanceProfile, error) {
if nameOrARN == failingARN {
return nil, errors.New(awserrors.ErrorIAMNoSuchEntity)
}
return &handlers_iam.InstanceProfile{ARN: nameOrARN, InstanceProfileID: "AIPAOK"}, nil
return &iamdomain.InstanceProfile{ARN: nameOrARN, InstanceProfileID: "AIPAOK"}, nil
},
}
@@ -12,9 +12,9 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/mulgadc/spinifex/contracts/ec2/v1"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/arn"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
)
@@ -24,7 +24,7 @@ const fanOutTimeout = 3 * time.Second
// resolveAndAuthorizeProfile resolves a profile (name or ARN) and enforces iam:PassRole.
// Profiles without a role skip PassRole; missing profile → InvalidIamInstanceProfile.NotFound.
func resolveAndAuthorizeProfile(spec *ec2.IamInstanceProfileSpecification, iamSvc handlers_iam.IAMService, accountID string, passRoleCheck PassRoleChecker) (*handlers_iam.InstanceProfile, error) {
func resolveAndAuthorizeProfile(spec *ec2.IamInstanceProfileSpecification, iamSvc iamdomain.IAMService, accountID string, passRoleCheck PassRoleChecker) (*iamdomain.InstanceProfile, error) {
nameOrARN := profileNameOrARN(spec)
if nameOrARN == "" {
return nil, errors.New(awserrors.ErrorMissingParameter)
@@ -55,7 +55,7 @@ func resolveAndAuthorizeProfile(spec *ec2.IamInstanceProfileSpecification, iamSv
// AssociateIamInstanceProfile attaches a profile to a running instance.
// The gateway resolves the profile and enforces PassRole; the daemon validates
// no existing profile and generates a fresh iip-assoc-… ID.
func AssociateIamInstanceProfile(ctx context.Context, input *ec2.AssociateIamInstanceProfileInput, natsConn *nats.Conn, iamSvc handlers_iam.IAMService, accountID string, passRoleCheck PassRoleChecker) (*ec2.AssociateIamInstanceProfileOutput, error) {
func AssociateIamInstanceProfile(ctx context.Context, input *ec2.AssociateIamInstanceProfileInput, natsConn *nats.Conn, iamSvc iamdomain.IAMService, accountID string, passRoleCheck PassRoleChecker) (*ec2.AssociateIamInstanceProfileOutput, error) {
if input == nil || input.InstanceId == nil || *input.InstanceId == "" {
return nil, errors.New(awserrors.ErrorMissingParameter)
}
@@ -107,7 +107,7 @@ func DisassociateIamInstanceProfile(ctx context.Context, input *ec2.Disassociate
// ReplaceIamInstanceProfileAssociation swaps the profile for an existing association.
// The gateway resolves the new profile and enforces PassRole; the daemon swaps atomically.
func ReplaceIamInstanceProfileAssociation(ctx context.Context, input *ec2.ReplaceIamInstanceProfileAssociationInput, natsConn *nats.Conn, iamSvc handlers_iam.IAMService, expectedNodes int, accountID string, passRoleCheck PassRoleChecker) (*ec2.ReplaceIamInstanceProfileAssociationOutput, error) {
func ReplaceIamInstanceProfileAssociation(ctx context.Context, input *ec2.ReplaceIamInstanceProfileAssociationInput, natsConn *nats.Conn, iamSvc iamdomain.IAMService, expectedNodes int, accountID string, passRoleCheck PassRoleChecker) (*ec2.ReplaceIamInstanceProfileAssociationOutput, error) {
if input == nil || input.AssociationId == nil || *input.AssociationId == "" {
return nil, errors.New(awserrors.ErrorMissingParameter)
}
@@ -173,7 +173,7 @@ func DescribeIamInstanceProfileAssociations(ctx context.Context, input *ec2.Desc
// enrichProfileID fills IamInstanceProfile.Id from the resolved profile.
// Daemons have no IAM access. Safe to call with a nil association.
func enrichProfileID(assoc *ec2.IamInstanceProfileAssociation, profile *handlers_iam.InstanceProfile) {
func enrichProfileID(assoc *ec2.IamInstanceProfileAssociation, profile *iamdomain.InstanceProfile) {
if assoc == nil || profile == nil {
return
}
@@ -11,10 +11,10 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/mulgadc/spinifex/contracts/ec2/v1"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/arn"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
awsidentifiers "github.com/mulgadc/spinifex/spinifex/foundation/aws/identifiers"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -35,13 +35,13 @@ const (
// fakeIAMService implements profile and canonical role lookups.
// Other methods nil-panic to surface unexpected calls.
type fakeIAMService struct {
handlers_iam.IAMService
iamdomain.IAMService
resolveFn func(accountID, nameOrARN string) (*handlers_iam.InstanceProfile, error)
resolveFn func(accountID, nameOrARN string) (*iamdomain.InstanceProfile, error)
canonicalFn func(accountID string, kind arn.IAMResourceType, name string) (string, error)
}
func (f *fakeIAMService) ResolveInstanceProfile(accountID, nameOrARN string) (*handlers_iam.InstanceProfile, error) {
func (f *fakeIAMService) ResolveInstanceProfile(accountID, nameOrARN string) (*iamdomain.InstanceProfile, error) {
if f.resolveFn != nil {
return f.resolveFn(accountID, nameOrARN)
}
@@ -58,11 +58,11 @@ func (f *fakeIAMService) CanonicalResourceARN(accountID string, kind arn.IAMReso
return "", errors.New(awserrors.ErrorIAMNoSuchEntity)
}
var _ handlers_iam.IAMService = (*fakeIAMService)(nil)
var _ iamdomain.IAMService = (*fakeIAMService)(nil)
// profileWithRole builds a resolved profile fixture pointing at the test role.
func profileWithRole() *handlers_iam.InstanceProfile {
return &handlers_iam.InstanceProfile{
func profileWithRole() *iamdomain.InstanceProfile {
return &iamdomain.InstanceProfile{
InstanceProfileName: testProfileNameApp,
InstanceProfileID: testProfileIDApp,
AccountID: testGwAccountID,
@@ -73,8 +73,8 @@ func profileWithRole() *handlers_iam.InstanceProfile {
// profileNoRole builds a resolved profile fixture with no role attached.
// resolveAndAuthorizeProfile must NOT invoke PassRole for this profile.
func profileNoRole() *handlers_iam.InstanceProfile {
return &handlers_iam.InstanceProfile{
func profileNoRole() *iamdomain.InstanceProfile {
return &iamdomain.InstanceProfile{
InstanceProfileName: testProfileNameOther,
InstanceProfileID: testProfileIDOther,
AccountID: testGwAccountID,
@@ -88,7 +88,7 @@ func profileNoRole() *handlers_iam.InstanceProfile {
func TestResolveAndAuthorizeProfile_NameForm(t *testing.T) {
t.Parallel()
gotNameOrARN := ""
svc := &fakeIAMService{resolveFn: func(_, nameOrARN string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(_, nameOrARN string) (*iamdomain.InstanceProfile, error) {
gotNameOrARN = nameOrARN
return profileWithRole(), nil
}}
@@ -112,7 +112,7 @@ func TestResolveAndAuthorizeProfile_NameForm(t *testing.T) {
func TestResolveAndAuthorizeProfile_ArnForm(t *testing.T) {
t.Parallel()
gotNameOrARN := ""
svc := &fakeIAMService{resolveFn: func(_, nameOrARN string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(_, nameOrARN string) (*iamdomain.InstanceProfile, error) {
gotNameOrARN = nameOrARN
return profileWithRole(), nil
}}
@@ -144,7 +144,7 @@ func TestResolveAndAuthorizeProfile_NilIAMService(t *testing.T) {
func TestResolveAndAuthorizeProfile_NotFoundMapsToEC2Error(t *testing.T) {
t.Parallel()
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return nil, errors.New(awserrors.ErrorIAMNoSuchEntity)
}}
_, err := resolveAndAuthorizeProfile(
@@ -157,7 +157,7 @@ func TestResolveAndAuthorizeProfile_NotFoundMapsToEC2Error(t *testing.T) {
func TestResolveAndAuthorizeProfile_PassthroughOtherIAMError(t *testing.T) {
t.Parallel()
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return nil, errors.New(awserrors.ErrorAccessDenied)
}}
_, err := resolveAndAuthorizeProfile(
@@ -170,7 +170,7 @@ func TestResolveAndAuthorizeProfile_PassthroughOtherIAMError(t *testing.T) {
func TestResolveAndAuthorizeProfile_PassRoleDenied(t *testing.T) {
t.Parallel()
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileWithRole(), nil
}}
check := func(string) error { return errors.New(awserrors.ErrorAccessDenied) }
@@ -183,7 +183,7 @@ func TestResolveAndAuthorizeProfile_PassRoleDenied(t *testing.T) {
func TestResolveAndAuthorizeProfile_NoRoleSkipsPassRole(t *testing.T) {
t.Parallel()
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileNoRole(), nil
}}
checkCalled := false
@@ -265,7 +265,7 @@ func TestAssociateIamInstanceProfile_ProfileNotFound(t *testing.T) {
func TestAssociateIamInstanceProfile_PassRoleDenied(t *testing.T) {
t.Parallel()
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileWithRole(), nil
}}
in := &ec2.AssociateIamInstanceProfileInput{
@@ -281,7 +281,7 @@ func TestAssociateIamInstanceProfile_PassRoleDenied(t *testing.T) {
func TestAssociateIamInstanceProfile_NoResponders(t *testing.T) {
t.Parallel()
_, nc := startTestNATSServer(t)
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileNoRole(), nil
}}
in := &ec2.AssociateIamInstanceProfileInput{
@@ -299,7 +299,7 @@ func TestAssociateIamInstanceProfile_NoResponders(t *testing.T) {
func TestAssociateIamInstanceProfile_Success(t *testing.T) {
t.Parallel()
_, nc := startTestNATSServer(t)
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileWithRole(), nil
}}
const instanceID = "i-assoc-success"
@@ -345,7 +345,7 @@ func TestAssociateIamInstanceProfile_Success(t *testing.T) {
func TestAssociateIamInstanceProfile_DaemonAlreadyAssociated(t *testing.T) {
t.Parallel()
_, nc := startTestNATSServer(t)
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileNoRole(), nil
}}
const instanceID = "i-already-bound"
@@ -474,7 +474,7 @@ func TestReplaceIamInstanceProfileAssociation_MissingProfileSpec(t *testing.T) {
func TestReplaceIamInstanceProfileAssociation_PassRoleDeniedBeforeBroadcast(t *testing.T) {
t.Parallel()
// nc=nil proves the call is rejected before any NATS dispatch.
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileWithRole(), nil
}}
check := func(string) error { return errors.New(awserrors.ErrorAccessDenied) }
@@ -489,7 +489,7 @@ func TestReplaceIamInstanceProfileAssociation_PassRoleDeniedBeforeBroadcast(t *t
func TestReplaceIamInstanceProfileAssociation_Success(t *testing.T) {
t.Parallel()
_, nc := startTestNATSServer(t)
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileWithRole(), nil
}}
const oldID = "iip-assoc-old00000000001"
@@ -530,7 +530,7 @@ func TestReplaceIamInstanceProfileAssociation_Success(t *testing.T) {
func TestReplaceIamInstanceProfileAssociation_NoSuchAssociation(t *testing.T) {
t.Parallel()
_, nc := startTestNATSServer(t)
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileNoRole(), nil
}}
_, err := nc.Subscribe("ec2.IamProfileAssociation.replace", func(msg *nats.Msg) {
@@ -700,7 +700,7 @@ func TestResolveAndAuthorizeProfile_CanonicalRoleARN(t *testing.T) {
t.Parallel()
storedARN := "arn:aws:iam::111122223333:role" + path + "app-role"
svc := &fakeIAMService{
resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileWithRole(), nil
},
canonicalFn: func(accountID string, kind arn.IAMResourceType, name string) (string, error) {
@@ -729,7 +729,7 @@ func TestResolveAndAuthorizeProfile_CanonicalLookupError(t *testing.T) {
t.Run(lookupErr.Error(), func(t *testing.T) {
t.Parallel()
svc := &fakeIAMService{
resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileWithRole(), nil
},
canonicalFn: func(string, arn.IAMResourceType, string) (string, error) {
@@ -20,8 +20,8 @@ import (
ec2key "github.com/mulgadc/spinifex/spinifex/domains/ec2/key"
ec2launchtemplate "github.com/mulgadc/spinifex/spinifex/domains/ec2/launchtemplate"
ec2placementgroup "github.com/mulgadc/spinifex/spinifex/domains/ec2/placementgroup"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
)
@@ -131,7 +131,7 @@ func hasPinnedPrivateIP(input *ec2.RunInstancesInput) bool {
// passRoleCheck may be nil to skip PassRole enforcement.
// launchQuotaCheck may be nil to skip quota enforcement; when present it runs
// after validation and PassRole authorization, but before any launch dispatch.
func RunInstances(ctx context.Context, input *ec2.RunInstancesInput, natsConn *nats.Conn, iamSvc handlers_iam.IAMService, accountID string, passRoleCheck PassRoleChecker, launchQuotaCheck LaunchQuotaChecker, expectedNodes int) (reservation ec2.Reservation, err error) {
func RunInstances(ctx context.Context, input *ec2.RunInstancesInput, natsConn *nats.Conn, iamSvc iamdomain.IAMService, accountID string, passRoleCheck PassRoleChecker, launchQuotaCheck LaunchQuotaChecker, expectedNodes int) (reservation ec2.Reservation, err error) {
// Expand a referenced launch template before validation so validation, quota,
// and downstream routing all see the effective (post-merge) parameters.
if err = ExpandLaunchTemplate(ctx, natsConn, input, accountID); err != nil {
@@ -163,7 +163,7 @@ func RunInstances(ctx context.Context, input *ec2.RunInstancesInput, natsConn *n
// runInstancesInner performs the actual launch: profile resolution, placement
// routing, and capacity-aware distribution. Wrapped by RunInstances for idempotency.
func runInstancesInner(ctx context.Context, input *ec2.RunInstancesInput, natsConn *nats.Conn, iamSvc handlers_iam.IAMService, accountID string, passRoleCheck PassRoleChecker, launchQuotaCheck LaunchQuotaChecker, expectedNodes int) (reservation ec2.Reservation, err error) {
func runInstancesInner(ctx context.Context, input *ec2.RunInstancesInput, natsConn *nats.Conn, iamSvc iamdomain.IAMService, accountID string, passRoleCheck PassRoleChecker, launchQuotaCheck LaunchQuotaChecker, expectedNodes int) (reservation ec2.Reservation, err error) {
resolvedProfile, err := resolveAndAuthorizeInstanceProfile(input, iamSvc, accountID, passRoleCheck)
if err != nil {
return reservation, err
@@ -236,7 +236,7 @@ func runInstancesInner(ctx context.Context, input *ec2.RunInstancesInput, natsCo
// resolveAndAuthorizeInstanceProfile resolves an optional instance profile,
// enforces PassRole, and normalises input to the canonical ARN only.
func resolveAndAuthorizeInstanceProfile(input *ec2.RunInstancesInput, iamSvc handlers_iam.IAMService, accountID string, passRoleCheck PassRoleChecker) (*handlers_iam.InstanceProfile, error) {
func resolveAndAuthorizeInstanceProfile(input *ec2.RunInstancesInput, iamSvc iamdomain.IAMService, accountID string, passRoleCheck PassRoleChecker) (*iamdomain.InstanceProfile, error) {
if input.IamInstanceProfile == nil {
return nil, nil
}
@@ -261,7 +261,7 @@ func profileNameOrARN(spec *ec2.IamInstanceProfileSpecification) string {
// enrichReservationWithProfileID fills IamInstanceProfile.Id on every instance.
// Daemons emit Arn only (no IAM access); the gateway adds Id from the resolved profile.
func enrichReservationWithProfileID(reservation *ec2.Reservation, profile *handlers_iam.InstanceProfile) {
func enrichReservationWithProfileID(reservation *ec2.Reservation, profile *iamdomain.InstanceProfile) {
if reservation == nil || profile == nil {
return
}
@@ -9,8 +9,8 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/mulgadc/spinifex/spinifex/domains/ec2/ebs/metadata"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -385,7 +385,7 @@ func TestResolveAndAuthorizeInstanceProfile_Absent(t *testing.T) {
func TestResolveAndAuthorizeInstanceProfile_NameForm_NormalisesToARN(t *testing.T) {
t.Parallel()
svc := &fakeIAMService{resolveFn: func(_, nameOrARN string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(_, nameOrARN string) (*iamdomain.InstanceProfile, error) {
assert.Equal(t, testProfileNameApp, nameOrARN)
return profileWithRole(), nil
}}
@@ -404,7 +404,7 @@ func TestResolveAndAuthorizeInstanceProfile_NameForm_NormalisesToARN(t *testing.
func TestResolveAndAuthorizeInstanceProfile_ArnForm(t *testing.T) {
t.Parallel()
svc := &fakeIAMService{resolveFn: func(_, nameOrARN string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(_, nameOrARN string) (*iamdomain.InstanceProfile, error) {
assert.Equal(t, testProfileARNApp, nameOrARN)
return profileWithRole(), nil
}}
@@ -433,7 +433,7 @@ func TestResolveAndAuthorizeInstanceProfile_NilIAMService(t *testing.T) {
func TestResolveAndAuthorizeInstanceProfile_NotFoundMapsToEC2Error(t *testing.T) {
t.Parallel()
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return nil, errors.New(awserrors.ErrorIAMNoSuchEntity)
}}
in := runValidInputWithProfile(&ec2.IamInstanceProfileSpecification{Name: aws.String("ghost")})
@@ -445,7 +445,7 @@ func TestResolveAndAuthorizeInstanceProfile_NotFoundMapsToEC2Error(t *testing.T)
func TestResolveAndAuthorizeInstanceProfile_CrossAccountARNPassthrough(t *testing.T) {
t.Parallel()
// IAM service rejects cross-account; gateway surfaces the AccessDenied verbatim.
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return nil, errors.New(awserrors.ErrorAccessDenied)
}}
in := runValidInputWithProfile(&ec2.IamInstanceProfileSpecification{Arn: aws.String(testCrossAccountARN)})
@@ -456,7 +456,7 @@ func TestResolveAndAuthorizeInstanceProfile_CrossAccountARNPassthrough(t *testin
func TestResolveAndAuthorizeInstanceProfile_PassRoleDenied(t *testing.T) {
t.Parallel()
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileWithRole(), nil
}}
check := func(roleARN string) error {
@@ -471,7 +471,7 @@ func TestResolveAndAuthorizeInstanceProfile_PassRoleDenied(t *testing.T) {
func TestResolveAndAuthorizeInstanceProfile_NoRoleSkipsPassRole(t *testing.T) {
t.Parallel()
svc := &fakeIAMService{resolveFn: func(string, string) (*handlers_iam.InstanceProfile, error) {
svc := &fakeIAMService{resolveFn: func(string, string) (*iamdomain.InstanceProfile, error) {
return profileNoRole(), nil
}}
checkCalled := false
@@ -17,10 +17,10 @@ import (
admissionquota "github.com/mulgadc/spinifex/spinifex/domains/admission/quota"
ec2instanceapi "github.com/mulgadc/spinifex/spinifex/domains/ec2/awsapi/instance"
ec2spotinstance "github.com/mulgadc/spinifex/spinifex/domains/ec2/spotinstance"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
awsidentifiers "github.com/mulgadc/spinifex/spinifex/foundation/aws/identifiers"
awstags "github.com/mulgadc/spinifex/spinifex/foundation/aws/tags"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
)
@@ -64,7 +64,7 @@ func ValidateRequestSpotInstancesInput(input *ec2.RequestSpotInstancesInput) err
// ClientToken passed through, same vCPU quota gate), then builds and persists one
// active/fulfilled SpotInstanceRequest per launched instance. On a launch failure
// (including InsufficientInstanceCapacity) it returns the error and persists nothing.
func RequestSpotInstances(ctx context.Context, input *ec2.RequestSpotInstancesInput, natsConn *nats.Conn, iamSvc handlers_iam.IAMService, accountID, az string, passRoleCheck ec2instanceapi.PassRoleChecker, quota *admissionquota.Service, expectedNodes int) (ec2.RequestSpotInstancesOutput, error) {
func RequestSpotInstances(ctx context.Context, input *ec2.RequestSpotInstancesInput, natsConn *nats.Conn, iamSvc iamdomain.IAMService, accountID, az string, passRoleCheck ec2instanceapi.PassRoleChecker, quota *admissionquota.Service, expectedNodes int) (ec2.RequestSpotInstancesOutput, error) {
var output ec2.RequestSpotInstancesOutput
if err := ValidateRequestSpotInstancesInput(input); err != nil {
@@ -13,8 +13,8 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/sts"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -62,13 +62,13 @@ func (f *fakeResolver) resolveVPCCIDR(_ context.Context, _, _ string) (string, e
}
type fakeIAM struct {
profile *handlers_iam.InstanceProfile
profile *iamdomain.InstanceProfile
profileErr error
roleARN string
roleErr error
}
func (f *fakeIAM) ResolveInstanceProfile(_ context.Context, _, _ string) (*handlers_iam.InstanceProfile, error) {
func (f *fakeIAM) ResolveInstanceProfile(_ context.Context, _, _ string) (*iamdomain.InstanceProfile, error) {
return f.profile, f.profileErr
}
@@ -991,8 +991,8 @@ func TestHTTP_PublicKeysInstanceBackendError500(t *testing.T) {
// ----- IAM / credentials -------------------------------------------------
func profileFixture() *handlers_iam.InstanceProfile {
return &handlers_iam.InstanceProfile{
func profileFixture() *iamdomain.InstanceProfile {
return &iamdomain.InstanceProfile{
InstanceProfileName: "app-profile",
InstanceProfileID: "AIPAEXAMPLE",
AccountID: "111122223333",
@@ -10,7 +10,7 @@ import (
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/sts"
ec2key "github.com/mulgadc/spinifex/spinifex/domains/ec2/key"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
handlers_sts "github.com/mulgadc/spinifex/spinifex/handlers/sts"
"github.com/nats-io/nats.go"
)
@@ -50,7 +50,7 @@ func (a *NATSSTSAssumer) AssumeRoleForInstance(ctx context.Context, accountID, r
// NATSProfileLookup is the NATS-backed profileLookup with a short-TTL cache.
type NATSProfileLookup struct {
nc *nats.Conn
profiles *ttlCache[*handlers_iam.InstanceProfile]
profiles *ttlCache[*iamdomain.InstanceProfile]
roles *ttlCache[*iam.GetRoleOutput]
}
@@ -60,17 +60,17 @@ var _ profileLookup = (*NATSProfileLookup)(nil)
func NewNATSProfileLookup(nc *nats.Conn) *NATSProfileLookup {
return &NATSProfileLookup{
nc: nc,
profiles: newTTLCache[*handlers_iam.InstanceProfile](profileCacheTTL),
profiles: newTTLCache[*iamdomain.InstanceProfile](profileCacheTTL),
roles: newTTLCache[*iam.GetRoleOutput](profileCacheTTL),
}
}
func (p *NATSProfileLookup) ResolveInstanceProfile(ctx context.Context, accountID, nameOrARN string) (*handlers_iam.InstanceProfile, error) {
func (p *NATSProfileLookup) ResolveInstanceProfile(ctx context.Context, accountID, nameOrARN string) (*iamdomain.InstanceProfile, error) {
key := accountID + "\x00" + nameOrARN
if v, ok := p.profiles.get(key); ok {
return v, nil
}
out, err := natsmsg.NATSRequest[handlers_iam.InstanceProfile](ctx, p.nc, handlers_iam.SubjectResolveInstanceProfile, handlers_iam.ResolveInstanceProfileRequest{
out, err := natsmsg.NATSRequest[iamdomain.InstanceProfile](ctx, p.nc, iamdomain.SubjectResolveInstanceProfile, iamdomain.ResolveInstanceProfileRequest{
AccountID: accountID,
NameOrARN: nameOrARN,
}, imdsRPCTimeout, accountID)
@@ -86,7 +86,7 @@ func (p *NATSProfileLookup) GetRole(ctx context.Context, accountID string, input
if v, ok := p.roles.get(key); ok {
return v, nil
}
out, err := natsmsg.NATSRequest[iam.GetRoleOutput](ctx, p.nc, handlers_iam.SubjectGetRole, handlers_iam.GetRoleRequest{
out, err := natsmsg.NATSRequest[iam.GetRoleOutput](ctx, p.nc, iamdomain.SubjectGetRole, iamdomain.GetRoleRequest{
AccountID: accountID,
Input: input,
}, imdsRPCTimeout, accountID)
@@ -13,8 +13,8 @@ import (
"github.com/aws/aws-sdk-go/service/sts"
"github.com/mulgadc/spinifex/internal/testkit"
ec2key "github.com/mulgadc/spinifex/spinifex/domains/ec2/key"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
handlers_sts "github.com/mulgadc/spinifex/spinifex/handlers/sts"
"github.com/nats-io/nats.go"
"github.com/stretchr/testify/assert"
@@ -72,9 +72,9 @@ func TestNATSSTSAssumer_RoundTrip(t *testing.T) {
func TestNATSProfileLookup_CachesProfile(t *testing.T) {
_, nc := testutil.StartTestNATS(t)
calls := serveCounted(t, nc, handlers_iam.SubjectResolveInstanceProfile,
func(req *handlers_iam.ResolveInstanceProfileRequest) (*handlers_iam.InstanceProfile, error) {
return &handlers_iam.InstanceProfile{
calls := serveCounted(t, nc, iamdomain.SubjectResolveInstanceProfile,
func(req *iamdomain.ResolveInstanceProfileRequest) (*iamdomain.InstanceProfile, error) {
return &iamdomain.InstanceProfile{
InstanceProfileName: "app",
AccountID: req.AccountID,
RoleName: "app-role",
@@ -94,8 +94,8 @@ func TestNATSProfileLookup_CachesProfile(t *testing.T) {
func TestNATSProfileLookup_CachesRole(t *testing.T) {
_, nc := testutil.StartTestNATS(t)
calls := serveCounted(t, nc, handlers_iam.SubjectGetRole,
func(req *handlers_iam.GetRoleRequest) (*iam.GetRoleOutput, error) {
calls := serveCounted(t, nc, iamdomain.SubjectGetRole,
func(req *iamdomain.GetRoleRequest) (*iam.GetRoleOutput, error) {
return &iam.GetRoleOutput{Role: &iam.Role{
RoleName: req.Input.RoleName,
Arn: aws.String("arn:aws:iam::123456789012:role/app-role"),
@@ -114,8 +114,8 @@ func TestNATSProfileLookup_CachesRole(t *testing.T) {
func TestNATSProfileLookup_PropagatesError(t *testing.T) {
_, nc := testutil.StartTestNATS(t)
serveCounted(t, nc, handlers_iam.SubjectResolveInstanceProfile,
func(_ *handlers_iam.ResolveInstanceProfileRequest) (*handlers_iam.InstanceProfile, error) {
serveCounted(t, nc, iamdomain.SubjectResolveInstanceProfile,
func(_ *iamdomain.ResolveInstanceProfileRequest) (*iamdomain.InstanceProfile, error) {
return nil, assert.AnError
})
@@ -11,8 +11,8 @@ import (
"testing"
"time"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -47,7 +47,7 @@ func TestProfileForReportsWhyTheRoleIsMissing(t *testing.T) {
{
name: "role resolved",
res: &fakeResolver{eni: testENI(), inst: &instanceFacts{iamInstanceProfileArn: "arn:aws:iam::111122223333:instance-profile/app"}},
iam: &fakeIAM{profile: &handlers_iam.InstanceProfile{ARN: "arn", InstanceProfileID: "AIPA", RoleName: "app"}},
iam: &fakeIAM{profile: &iamdomain.InstanceProfile{ARN: "arn", InstanceProfileID: "AIPA", RoleName: "app"}},
want: roleMissNone,
},
}
@@ -13,9 +13,9 @@ import (
"time"
"github.com/aws/aws-sdk-go/service/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvstore"
"github.com/mulgadc/spinifex/spinifex/foundation/telemetry"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
)
@@ -35,7 +35,7 @@ type listTapsFunc func(ctx context.Context) (map[string]string, error)
// profileLookup is the IAMService slice needed for credential + iam/* paths.
type profileLookup interface {
ResolveInstanceProfile(ctx context.Context, accountID, nameOrARN string) (*handlers_iam.InstanceProfile, error)
ResolveInstanceProfile(ctx context.Context, accountID, nameOrARN string) (*iamdomain.InstanceProfile, error)
GetRole(ctx context.Context, accountID string, input *iam.GetRoleInput) (*iam.GetRoleOutput, error)
}
+3 -3
View File
@@ -20,8 +20,8 @@ import (
"strings"
"time"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvutil"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go/jetstream"
)
@@ -176,7 +176,7 @@ func deleteSigningKey(ctx context.Context, kv jetstream.KeyValue, kid string) er
// decodeSigningKey decrypts and parses one stored signing key's encrypted PKCS#8
// PEM bytes into a SigningKey under kid.
func decodeSigningKey(kid string, ciphertext []byte, masterKey []byte) (*SigningKey, error) {
pemStr, err := handlers_iam.DecryptSecret(string(ciphertext), masterKey)
pemStr, err := iamdomain.DecryptSecret(string(ciphertext), masterKey)
if err != nil {
return nil, fmt.Errorf("decrypt signing key %s: %w", kid, err)
}
@@ -203,7 +203,7 @@ func generateSigningKey(ctx context.Context, kv jetstream.KeyValue, masterKey []
return nil, fmt.Errorf("marshal pkcs8 private key: %w", err)
}
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8})
ciphertext, err := handlers_iam.EncryptSecret(string(pemBytes), masterKey)
ciphertext, err := iamdomain.EncryptSecret(string(pemBytes), masterKey)
if err != nil {
return nil, fmt.Errorf("encrypt signing key: %w", err)
}
@@ -1,22 +1,22 @@
package handlers_iam_test
package iam_test
import (
"testing"
"github.com/mulgadc/spinifex/internal/testkit"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newLifecycleService(t *testing.T) handlers_iam.IAMService {
func newLifecycleService(t *testing.T) iamdomain.IAMService {
t.Helper()
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_iam.NewIAMServiceImpl(t.Context(), nc, masterKey)
svc, err := iamdomain.NewIAMServiceImpl(t.Context(), nc, masterKey)
require.NoError(t, err)
return svc
}
@@ -27,18 +27,18 @@ func TestSetAccountStatusMovesBetweenStates(t *testing.T) {
account, err := svc.CreateAccount("tenant@example.com")
require.NoError(t, err)
suspended, err := svc.SetAccountStatus(account.AccountID, handlers_iam.AccountStatusSuspended)
suspended, err := svc.SetAccountStatus(account.AccountID, iamdomain.AccountStatusSuspended)
require.NoError(t, err)
assert.Equal(t, handlers_iam.AccountStatusSuspended, suspended.Status)
assert.Equal(t, iamdomain.AccountStatusSuspended, suspended.Status)
// An operator hold is reversible, unlike a teardown.
restored, err := svc.SetAccountStatus(account.AccountID, handlers_iam.AccountStatusActive)
restored, err := svc.SetAccountStatus(account.AccountID, iamdomain.AccountStatusActive)
require.NoError(t, err)
assert.Equal(t, handlers_iam.AccountStatusActive, restored.Status)
assert.Equal(t, iamdomain.AccountStatusActive, restored.Status)
stored, err := svc.GetAccount(account.AccountID)
require.NoError(t, err)
assert.Equal(t, handlers_iam.AccountStatusActive, stored.Status)
assert.Equal(t, iamdomain.AccountStatusActive, stored.Status)
}
// There is no path back from TERMINATING. A half-torn-down account that
@@ -50,17 +50,17 @@ func TestTerminatingIsAOneWayDoor(t *testing.T) {
account, err := svc.CreateAccount("tenant@example.com")
require.NoError(t, err)
_, err = svc.SetAccountStatus(account.AccountID, handlers_iam.AccountStatusTerminating)
_, err = svc.SetAccountStatus(account.AccountID, iamdomain.AccountStatusTerminating)
require.NoError(t, err)
for _, status := range []string{handlers_iam.AccountStatusActive, handlers_iam.AccountStatusSuspended} {
for _, status := range []string{iamdomain.AccountStatusActive, iamdomain.AccountStatusSuspended} {
_, err = svc.SetAccountStatus(account.AccountID, status)
require.Error(t, err)
}
stored, err := svc.GetAccount(account.AccountID)
require.NoError(t, err)
assert.Equal(t, handlers_iam.AccountStatusTerminating, stored.Status)
assert.Equal(t, iamdomain.AccountStatusTerminating, stored.Status)
}
func TestSetAccountStatusRejectsAnUnknownStatus(t *testing.T) {
@@ -88,7 +88,7 @@ func TestDeleteAccountRequiresTerminating(t *testing.T) {
require.Error(t, svc.DeleteAccount(account.AccountID))
_, err = svc.SetAccountStatus(account.AccountID, handlers_iam.AccountStatusTerminating)
_, err = svc.SetAccountStatus(account.AccountID, iamdomain.AccountStatusTerminating)
require.NoError(t, err)
require.NoError(t, svc.DeleteAccount(account.AccountID))
@@ -102,16 +102,16 @@ func TestProtectedAccountsCanNeverBeDeleted(t *testing.T) {
t.Parallel()
svc := newLifecycleService(t)
for accountID := range handlers_iam.UndeletableAccountIDs {
for accountID := range iamdomain.UndeletableAccountIDs {
t.Run(accountID, func(t *testing.T) {
t.Parallel()
// Even a status that would otherwise permit deletion must not.
_, _ = svc.SetAccountStatus(accountID, handlers_iam.AccountStatusTerminating)
_, _ = svc.SetAccountStatus(accountID, iamdomain.AccountStatusTerminating)
err := svc.DeleteAccount(accountID)
require.Error(t, err)
assert.ErrorIs(t, err, handlers_iam.ErrAccountUndeletable)
assert.ErrorIs(t, err, iamdomain.ErrAccountUndeletable)
})
}
}
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,21 +1,21 @@
package handlers_iam_test
package iam_test
import (
"strings"
"testing"
"github.com/mulgadc/spinifex/internal/testkit"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/nats-io/nats.go/jetstream"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newAccountNameIndex(t *testing.T) (*handlers_iam.AccountNameIndex, jetstream.JetStream) {
func newAccountNameIndex(t *testing.T) (*iamdomain.AccountNameIndex, jetstream.JetStream) {
t.Helper()
_, _, js := testutil.StartTestJetStream(t)
index, err := handlers_iam.NewAccountNameIndex(t.Context(), js)
index, err := iamdomain.NewAccountNameIndex(t.Context(), js)
require.NoError(t, err)
return index, js
}
@@ -55,12 +55,12 @@ func TestAccountNameIndexReserveConflicts(t *testing.T) {
require.NoError(t, index.Reserve(ctx, "ben@example.com", "token-a"))
err := index.Reserve(ctx, "ben@example.com", "token-b")
assert.ErrorIs(t, err, handlers_iam.ErrNameInFlight)
assert.ErrorIs(t, err, iamdomain.ErrNameInFlight)
require.NoError(t, index.Commit(ctx, "ben@example.com", "000000000042", "token-a"))
err = index.Reserve(ctx, "ben@example.com", "token-b")
assert.ErrorIs(t, err, handlers_iam.ErrNameTaken)
assert.ErrorIs(t, err, iamdomain.ErrNameTaken)
}
// Case and whitespace must not create a second account for the same person.
@@ -77,7 +77,7 @@ func TestAccountNameIndexNormalizesName(t *testing.T) {
assert.True(t, found)
assert.Equal(t, "000000000042", accountID)
assert.ErrorIs(t, index.Reserve(ctx, "BEN@EXAMPLE.COM", "token-b"), handlers_iam.ErrNameTaken)
assert.ErrorIs(t, index.Reserve(ctx, "BEN@EXAMPLE.COM", "token-b"), iamdomain.ErrNameTaken)
}
func TestAccountNameIndexRelease(t *testing.T) {
@@ -89,7 +89,7 @@ func TestAccountNameIndexRelease(t *testing.T) {
// A reservation belongs to its owner; another token cannot drop it.
require.NoError(t, index.Release(ctx, "ben@example.com", "token-b"))
assert.ErrorIs(t, index.Reserve(ctx, "ben@example.com", "token-b"), handlers_iam.ErrNameInFlight)
assert.ErrorIs(t, index.Reserve(ctx, "ben@example.com", "token-b"), iamdomain.ErrNameInFlight)
require.NoError(t, index.Release(ctx, "ben@example.com", "token-a"))
require.NoError(t, index.Reserve(ctx, "ben@example.com", "token-b"))
@@ -119,7 +119,7 @@ func TestAccountNameIndexKeysCarryNoEmailAddress(t *testing.T) {
require.NoError(t, index.Reserve(ctx, "ben@example.com", "token-a"))
kv, err := js.KeyValue(ctx, handlers_iam.KVBucketAccountNames)
kv, err := js.KeyValue(ctx, iamdomain.KVBucketAccountNames)
require.NoError(t, err)
keys, err := kv.Keys(ctx)
require.NoError(t, err)
@@ -138,12 +138,12 @@ func TestFindAccountByName(t *testing.T) {
created, err := svc.CreateAccount("ben@example.com")
require.NoError(t, err)
found, err := handlers_iam.FindAccountByName(svc, " BEN@Example.com ")
found, err := iamdomain.FindAccountByName(svc, " BEN@Example.com ")
require.NoError(t, err)
require.NotNil(t, found)
assert.Equal(t, created.AccountID, found.AccountID)
missing, err := handlers_iam.FindAccountByName(svc, "nobody@example.com")
missing, err := iamdomain.FindAccountByName(svc, "nobody@example.com")
require.NoError(t, err)
assert.Nil(t, missing)
}
@@ -157,7 +157,7 @@ func TestAccountNameIndexRejectsCorruptEntry(t *testing.T) {
require.NoError(t, index.Reserve(ctx, "ben@example.com", "token-a"))
kv, err := js.KeyValue(ctx, handlers_iam.KVBucketAccountNames)
kv, err := js.KeyValue(ctx, iamdomain.KVBucketAccountNames)
require.NoError(t, err)
keys, err := kv.Keys(ctx)
require.NoError(t, err)
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,10 +1,10 @@
package handlers_iam_test
package iam_test
import (
"testing"
"github.com/mulgadc/spinifex/internal/testkit"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/nats-io/nats.go/jetstream"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -12,16 +12,16 @@ import (
// newStatusReaderFixture starts a real IAM service (which creates and
// migrates spinifex-accounts) and a reader attached to the same JetStream.
func newStatusReaderFixture(t *testing.T) (handlers_iam.IAMService, *handlers_iam.AccountStatusReader, jetstream.JetStream) {
func newStatusReaderFixture(t *testing.T) (iamdomain.IAMService, *iamdomain.AccountStatusReader, jetstream.JetStream) {
t.Helper()
_, nc, js := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_iam.NewIAMServiceImpl(t.Context(), nc, masterKey)
svc, err := iamdomain.NewIAMServiceImpl(t.Context(), nc, masterKey)
require.NoError(t, err)
return svc, handlers_iam.NewAccountStatusReader(js), js
return svc, iamdomain.NewAccountStatusReader(js), js
}
func TestAccountStatusReader_TerminatingIsTrue(t *testing.T) {
@@ -29,7 +29,7 @@ func TestAccountStatusReader_TerminatingIsTrue(t *testing.T) {
svc, reader, _ := newStatusReaderFixture(t)
account, err := svc.CreateAccount("tenant@example.com")
require.NoError(t, err)
_, err = svc.SetAccountStatus(account.AccountID, handlers_iam.AccountStatusTerminating)
_, err = svc.SetAccountStatus(account.AccountID, iamdomain.AccountStatusTerminating)
require.NoError(t, err)
terminating, err := reader.AccountTerminating(t.Context(), account.AccountID)
@@ -48,7 +48,7 @@ func TestAccountStatusReader_ActiveAndSuspendedAreFalse(t *testing.T) {
suspended, err := svc.CreateAccount("suspended@example.com")
require.NoError(t, err)
_, err = svc.SetAccountStatus(suspended.AccountID, handlers_iam.AccountStatusSuspended)
_, err = svc.SetAccountStatus(suspended.AccountID, iamdomain.AccountStatusSuspended)
require.NoError(t, err)
terminating, err = reader.AccountTerminating(t.Context(), suspended.AccountID)
require.NoError(t, err)
@@ -68,12 +68,12 @@ func TestAccountStatusReader_MissingRecordIsFalseNotError(t *testing.T) {
func TestAccountStatusReader_MissingBucketIsErrorAndNeverCreated(t *testing.T) {
t.Parallel()
_, nc, js := testutil.StartTestJetStream(t)
reader := handlers_iam.NewAccountStatusReader(js)
reader := iamdomain.NewAccountStatusReader(js)
_, err := reader.AccountTerminating(t.Context(), "111111111111")
require.Error(t, err)
_, bucketErr := js.KeyValue(t.Context(), handlers_iam.KVBucketAccounts)
_, bucketErr := js.KeyValue(t.Context(), iamdomain.KVBucketAccounts)
assert.ErrorIs(t, bucketErr, jetstream.ErrBucketNotFound)
_ = nc
}
@@ -81,22 +81,22 @@ func TestAccountStatusReader_MissingBucketIsErrorAndNeverCreated(t *testing.T) {
func TestAccountStatusReader_UndecodableValueIsError(t *testing.T) {
t.Parallel()
_, nc, js := testutil.StartTestJetStream(t)
_, err := handlers_iam.NewIAMServiceImpl(t.Context(), nc, mustMasterKey(t))
_, err := iamdomain.NewIAMServiceImpl(t.Context(), nc, mustMasterKey(t))
require.NoError(t, err)
kv, err := js.KeyValue(t.Context(), handlers_iam.KVBucketAccounts)
kv, err := js.KeyValue(t.Context(), iamdomain.KVBucketAccounts)
require.NoError(t, err)
_, err = kv.Put(t.Context(), "222222222222", []byte(`{"status":`))
require.NoError(t, err)
reader := handlers_iam.NewAccountStatusReader(js)
reader := iamdomain.NewAccountStatusReader(js)
_, err = reader.AccountTerminating(t.Context(), "222222222222")
require.Error(t, err)
}
func mustMasterKey(t *testing.T) []byte {
t.Helper()
key, err := handlers_iam.GenerateMasterKey()
key, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
return key
}
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"testing"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"encoding/json"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,6 +1,6 @@
//test:in-package — uses setupTestIAMService and testAccountID, unexported fixtures shared with the other handler tests.
package handlers_iam
package iam
import (
"testing"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"crypto/rand"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"encoding/json"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"encoding/json"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"github.com/aws/aws-sdk-go/service/iam"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"testing"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"errors"
@@ -1,5 +1,5 @@
// Package mock provides an in-memory implementation of
// handlers_iam.SystemInstanceRoleEnsurer for tests.
// iamdomain.SystemInstanceRoleEnsurer for tests.
package mock
import (
@@ -8,12 +8,12 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
)
// SystemInstanceRoleEnsurer is an in-memory
// handlers_iam.SystemInstanceRoleEnsurer. Roles and instance profiles are
// iamdomain.SystemInstanceRoleEnsurer. Roles and instance profiles are
// stored keyed by name; Get* miss with NoSuchEntity until the matching
// Create* call, and a repeat Create* reports EntityAlreadyExists, mirroring
// the live IAM API. Every method is safe for concurrent use, so callers that
@@ -59,7 +59,7 @@ type SystemInstanceRoleEnsurer struct {
EmptyInstanceProfileARN bool
}
var _ handlers_iam.SystemInstanceRoleEnsurer = (*SystemInstanceRoleEnsurer)(nil)
var _ iamdomain.SystemInstanceRoleEnsurer = (*SystemInstanceRoleEnsurer)(nil)
// New returns an empty SystemInstanceRoleEnsurer ready for use.
func New() *SystemInstanceRoleEnsurer {
@@ -6,8 +6,8 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/mulgadc/spinifex/spinifex/domains/iam/mock"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
"github.com/mulgadc/spinifex/spinifex/handlers/iam/mock"
)
func TestGetRole_MissingReturnsNoSuchEntity(t *testing.T) {
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"net/url"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"fmt"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"cmp"
@@ -1,6 +1,6 @@
//test:in-package — writes raw records to policiesBucket and reads resolveAttachedPolicy, both unexported.
package handlers_iam
package iam
import (
"fmt"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"errors"
@@ -1,4 +1,4 @@
package handlers_iam_test
package iam_test
import (
"testing"
@@ -6,21 +6,21 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/mulgadc/spinifex/internal/testkit"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const provisionAccountID = "000000000042"
func newIAMService(t *testing.T) *handlers_iam.IAMServiceImpl {
func newIAMService(t *testing.T) *iamdomain.IAMServiceImpl {
t.Helper()
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_iam.NewIAMServiceImpl(t.Context(), nc, masterKey)
svc, err := iamdomain.NewIAMServiceImpl(t.Context(), nc, masterKey)
require.NoError(t, err)
return svc
}
@@ -39,7 +39,7 @@ func TestNormalizeAccountName(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
assert.Equal(t, tc.want, handlers_iam.NormalizeAccountName(tc.in))
assert.Equal(t, tc.want, iamdomain.NormalizeAccountName(tc.in))
})
}
}
@@ -48,20 +48,20 @@ func TestProvisionAccountCreatesAdminIdentity(t *testing.T) {
t.Parallel()
svc := newIAMService(t)
got, err := handlers_iam.ProvisionAccount(svc, provisionAccountID, "ben@example.com")
got, err := iamdomain.ProvisionAccount(svc, provisionAccountID, "ben@example.com")
require.NoError(t, err)
assert.Equal(t, provisionAccountID, got.AccountID)
assert.Equal(t, handlers_iam.AdminUserName, got.AdminUser)
assert.Equal(t, iamdomain.AdminUserName, got.AdminUser)
assert.NotEmpty(t, got.AccessKeyID)
assert.NotEmpty(t, got.SecretAccessKey)
attached, err := svc.ListAttachedUserPolicies(provisionAccountID, &iam.ListAttachedUserPoliciesInput{
UserName: aws.String(handlers_iam.AdminUserName),
UserName: aws.String(iamdomain.AdminUserName),
})
require.NoError(t, err)
require.Len(t, attached.AttachedPolicies, 1)
assert.Equal(t, handlers_iam.AdminPolicyName, aws.StringValue(attached.AttachedPolicies[0].PolicyName))
assert.Equal(t, iamdomain.AdminPolicyName, aws.StringValue(attached.AttachedPolicies[0].PolicyName))
}
// A retry must finish the job rather than fail on the steps that already ran:
@@ -70,26 +70,26 @@ func TestProvisionAccountResumesPartialState(t *testing.T) {
t.Parallel()
tests := []struct {
name string
prepare func(t *testing.T, svc handlers_iam.IAMService)
prepare func(t *testing.T, svc iamdomain.IAMService)
}{
{
name: "admin user already exists",
prepare: func(t *testing.T, svc handlers_iam.IAMService) {
prepare: func(t *testing.T, svc iamdomain.IAMService) {
_, err := svc.CreateUser(provisionAccountID, &iam.CreateUserInput{
UserName: aws.String(handlers_iam.AdminUserName),
UserName: aws.String(iamdomain.AdminUserName),
})
require.NoError(t, err)
},
},
{
name: "admin user and policy already exist",
prepare: func(t *testing.T, svc handlers_iam.IAMService) {
prepare: func(t *testing.T, svc iamdomain.IAMService) {
_, err := svc.CreateUser(provisionAccountID, &iam.CreateUserInput{
UserName: aws.String(handlers_iam.AdminUserName),
UserName: aws.String(iamdomain.AdminUserName),
})
require.NoError(t, err)
_, err = svc.CreatePolicy(provisionAccountID, &iam.CreatePolicyInput{
PolicyName: aws.String(handlers_iam.AdminPolicyName),
PolicyName: aws.String(iamdomain.AdminPolicyName),
PolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"*","Resource":"*"}]}`),
})
require.NoError(t, err)
@@ -103,7 +103,7 @@ func TestProvisionAccountResumesPartialState(t *testing.T) {
svc := newIAMService(t)
tc.prepare(t, svc)
got, err := handlers_iam.ProvisionAccount(svc, provisionAccountID, "ben@example.com")
got, err := iamdomain.ProvisionAccount(svc, provisionAccountID, "ben@example.com")
require.NoError(t, err)
assert.NotEmpty(t, got.AccessKeyID)
})
@@ -116,15 +116,15 @@ func TestProvisionAccountLeavesExactlyOneAccessKey(t *testing.T) {
t.Parallel()
svc := newIAMService(t)
first, err := handlers_iam.ProvisionAccount(svc, provisionAccountID, "ben@example.com")
first, err := iamdomain.ProvisionAccount(svc, provisionAccountID, "ben@example.com")
require.NoError(t, err)
second, err := handlers_iam.ProvisionAccount(svc, provisionAccountID, "ben@example.com")
second, err := iamdomain.ProvisionAccount(svc, provisionAccountID, "ben@example.com")
require.NoError(t, err)
assert.NotEqual(t, first.AccessKeyID, second.AccessKeyID)
listed, err := svc.ListAccessKeys(provisionAccountID, &iam.ListAccessKeysInput{
UserName: aws.String(handlers_iam.AdminUserName),
UserName: aws.String(iamdomain.AdminUserName),
})
require.NoError(t, err)
require.Len(t, listed.AccessKeyMetadata, 1)
@@ -135,12 +135,12 @@ func TestProvisionAccountRejectsEmptyInput(t *testing.T) {
t.Parallel()
svc := newIAMService(t)
_, err := handlers_iam.ProvisionAccount(svc, "", "ben@example.com")
_, err := iamdomain.ProvisionAccount(svc, "", "ben@example.com")
assert.Error(t, err)
_, err = handlers_iam.ProvisionAccount(svc, provisionAccountID, "")
_, err = iamdomain.ProvisionAccount(svc, provisionAccountID, "")
assert.Error(t, err)
_, err = handlers_iam.ProvisionAccount(nil, provisionAccountID, "ben@example.com")
_, err = iamdomain.ProvisionAccount(nil, provisionAccountID, "ben@example.com")
assert.Error(t, err)
}
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"testing"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,12 +1,12 @@
package handlers_iam_test
package iam_test
import (
"testing"
"time"
"github.com/mulgadc/spinifex/internal/testkit"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/state/clustersize"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/stretchr/testify/require"
)
@@ -23,11 +23,11 @@ func TestNewIAMServiceWithRetry_StopsOnAConfigFault(t *testing.T) {
_, nc, _ := testutil.StartTestJetStream(t)
clustersize.RedeclareForTest(t, 0)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
start := time.Now()
_, err = handlers_iam.NewIAMServiceWithRetry(t.Context(), nc, masterKey)
_, err = iamdomain.NewIAMServiceWithRetry(t.Context(), nc, masterKey)
elapsed := time.Since(start)
require.Error(t, err, "an undeclared cluster size must not look like a working IAM service")
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"encoding/json"
@@ -1,7 +1,7 @@
// Package handlers_iam implements IAM: users, groups, roles, policies, access
// Package iam implements IAM: users, groups, roles, policies, access
// keys, instance profiles and OIDC providers, persisted in JetStream KV with
// secrets sealed under the deployment master key.
package handlers_iam
package iam
import (
"github.com/aws/aws-sdk-go/service/iam"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"context"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"fmt"
@@ -1,13 +1,13 @@
// package handlers_iam_test, not handlers_iam: an in-package test importing
// package iam_test, not iam: an in-package test importing
// the shared mock package would create an import cycle, since the mock
// package itself imports handlers_iam for the interface compile check.
package handlers_iam_test
// package itself imports iam for the interface compile check.
package iam_test
import (
"testing"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iammock "github.com/mulgadc/spinifex/spinifex/handlers/iam/mock"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
iammock "github.com/mulgadc/spinifex/spinifex/domains/iam/mock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -24,7 +24,7 @@ const (
func TestEnsureSystemInstanceProfile_CreatesAll(t *testing.T) {
t.Parallel()
f := iammock.New()
arn, err := handlers_iam.EnsureSystemInstanceProfile(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
arn, err := iamdomain.EnsureSystemInstanceProfile(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
require.NoError(t, err)
assert.Equal(t, "arn:aws:iam::"+testRoleAcct+":instance-profile/"+testRoleName, arn)
@@ -42,10 +42,10 @@ func TestEnsureSystemInstanceProfile_CreatesAll(t *testing.T) {
func TestEnsureSystemInstanceProfile_Idempotent(t *testing.T) {
t.Parallel()
f := iammock.New()
_, err := handlers_iam.EnsureSystemInstanceProfile(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
_, err := iamdomain.EnsureSystemInstanceProfile(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
require.NoError(t, err)
_, err = handlers_iam.EnsureSystemInstanceProfile(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
_, err = iamdomain.EnsureSystemInstanceProfile(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
require.NoError(t, err)
assert.Equal(t, 1, f.CreateRoleCalls, "role created once")
assert.Equal(t, 1, f.CreateInstanceProfileCalls, "profile created once")
@@ -57,11 +57,11 @@ func TestEnsureSystemInstanceProfile_Idempotent(t *testing.T) {
func TestConvergeSystemRolePolicy_RewritesExistingRole(t *testing.T) {
t.Parallel()
f := iammock.New()
_, err := handlers_iam.EnsureSystemInstanceProfile(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
_, err := iamdomain.EnsureSystemInstanceProfile(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
require.NoError(t, err)
const updated = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["svc:DoThing","sts:AssumeRole"],"Resource":"*"}]}`
require.NoError(t, handlers_iam.ConvergeSystemRolePolicy(f, testRoleAcct, testRoleName, testPolicyName, updated))
require.NoError(t, iamdomain.ConvergeSystemRolePolicy(f, testRoleAcct, testRoleName, testPolicyName, updated))
assert.Equal(t, updated, f.RolePolicies[testRoleName])
}
@@ -71,7 +71,7 @@ func TestConvergeSystemRolePolicy_RewritesExistingRole(t *testing.T) {
func TestConvergeSystemRolePolicy_AbsentRoleIsNotProvisioned(t *testing.T) {
t.Parallel()
f := iammock.New()
require.NoError(t, handlers_iam.ConvergeSystemRolePolicy(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc))
require.NoError(t, iamdomain.ConvergeSystemRolePolicy(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc))
assert.Zero(t, f.CreateRoleCalls)
assert.Zero(t, f.CreateInstanceProfileCalls)
@@ -84,11 +84,11 @@ func TestConvergeSystemRolePolicy_AbsentRoleIsNotProvisioned(t *testing.T) {
func TestConvergeSystemRolePolicy_PropagatesPutFailure(t *testing.T) {
t.Parallel()
f := iammock.New()
_, err := handlers_iam.EnsureSystemInstanceProfile(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
_, err := iamdomain.EnsureSystemInstanceProfile(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
require.NoError(t, err)
f.PutRolePolicyErr = assert.AnError
err = handlers_iam.ConvergeSystemRolePolicy(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
err = iamdomain.ConvergeSystemRolePolicy(f, testRoleAcct, testRoleName, testPolicyName, testPolicyDoc)
require.Error(t, err)
assert.ErrorIs(t, err, assert.AnError)
}
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"testing"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"fmt"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"encoding/json"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"encoding/json"
@@ -1,4 +1,4 @@
package handlers_iam
package iam
import (
"encoding/json"
+4 -4
View File
@@ -11,8 +11,8 @@ import (
"sync"
"time"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvstore"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go/jetstream"
)
@@ -73,7 +73,7 @@ const appliancePasswordAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrs
// ApplianceRecord is the persisted singleton record for the platform Postgres
// appliance. EncryptedPassword is AES-256-GCM ciphertext (base64, via
// handlers_iam.EncryptSecret/DecryptSecret) — the plaintext master password
// iamdomain.EncryptSecret/DecryptSecret) — the plaintext master password
// is never stored, logged, or held anywhere outside a launch/Connect call.
//
// No exported Appliance method ever returns an ApplianceRecord: Ensure
@@ -496,7 +496,7 @@ func (a *Appliance) getRecord(ctx context.Context) (*ApplianceRecord, uint64, er
// decryptPassword resolves rec's encrypted master password to plaintext. The
// error path never includes the ciphertext or any decrypted material.
func (a *Appliance) decryptPassword(rec *ApplianceRecord) (string, error) {
plaintext, err := handlers_iam.DecryptSecret(rec.EncryptedPassword, a.masterKey)
plaintext, err := iamdomain.DecryptSecret(rec.EncryptedPassword, a.masterKey)
if err != nil {
return "", fmt.Errorf("ochrevector: decrypt appliance master password: %w", err)
}
@@ -511,7 +511,7 @@ func newApplianceRecord(masterKey []byte) (ApplianceRecord, string, error) {
if err != nil {
return ApplianceRecord{}, "", err
}
encrypted, err := handlers_iam.EncryptSecret(password, masterKey)
encrypted, err := iamdomain.EncryptSecret(password, masterKey)
if err != nil {
return ApplianceRecord{}, "", fmt.Errorf("ochrevector: encrypt appliance master password: %w", err)
}
@@ -15,7 +15,7 @@ import (
"time"
"github.com/mulgadc/spinifex/internal/testkit"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/nats-io/nats.go/jetstream"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -110,7 +110,7 @@ func TestCredentialRoundTrip(t *testing.T) {
require.NoError(t, err)
assert.Len(t, password, appliancePasswordLength)
encrypted, err := handlers_iam.EncryptSecret(password, masterKey)
encrypted, err := iamdomain.EncryptSecret(password, masterKey)
require.NoError(t, err)
assert.NotEqual(t, password, encrypted)
assert.NotContains(t, encrypted, password)
@@ -196,7 +196,7 @@ func TestEnsure_StaleProvisioningIsResumed(t *testing.T) {
seedPassword, err := generateMasterPassword()
require.NoError(t, err)
encrypted, err := handlers_iam.EncryptSecret(seedPassword, masterKey)
encrypted, err := iamdomain.EncryptSecret(seedPassword, masterKey)
require.NoError(t, err)
stale := time.Now().UTC().Add(-2 * applianceStaleAfter)
@@ -236,7 +236,7 @@ func TestEnsure_FreshProvisioningIsWaitedNotResumed(t *testing.T) {
seedPassword, err := generateMasterPassword()
require.NoError(t, err)
encrypted, err := handlers_iam.EncryptSecret(seedPassword, masterKey)
encrypted, err := iamdomain.EncryptSecret(seedPassword, masterKey)
require.NoError(t, err)
fresh := time.Now().UTC()
@@ -328,7 +328,7 @@ func TestResume_LaunchFailureLeavesRecordProvisioning(t *testing.T) {
seedPassword, err := generateMasterPassword()
require.NoError(t, err)
encrypted, err := handlers_iam.EncryptSecret(seedPassword, masterKey)
encrypted, err := iamdomain.EncryptSecret(seedPassword, masterKey)
require.NoError(t, err)
stale := time.Now().UTC().Add(-2 * applianceStaleAfter)
@@ -379,7 +379,7 @@ func TestConnect_NotAvailable(t *testing.T) {
password, err := generateMasterPassword()
require.NoError(t, err)
encrypted, err := handlers_iam.EncryptSecret(password, masterKey)
encrypted, err := iamdomain.EncryptSecret(password, masterKey)
require.NoError(t, err)
now := time.Now().UTC()
@@ -418,7 +418,7 @@ func seedAvailableAppliance(t *testing.T, appliance *Appliance, masterKey []byte
t.Helper()
password, err := generateMasterPassword()
require.NoError(t, err)
encrypted, err := handlers_iam.EncryptSecret(password, masterKey)
encrypted, err := iamdomain.EncryptSecret(password, masterKey)
require.NoError(t, err)
now := time.Now().UTC()
@@ -800,7 +800,7 @@ func TestDecryptPassword_WrongKeyErrors(t *testing.T) {
password, err := generateMasterPassword()
require.NoError(t, err)
encrypted, err := handlers_iam.EncryptSecret(password, rightKey)
encrypted, err := iamdomain.EncryptSecret(password, rightKey)
require.NoError(t, err)
appliance := &Appliance{masterKey: wrongKey}
@@ -5,22 +5,22 @@ import (
"testing"
"github.com/mulgadc/bluebottle/pkg/iampolicy"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
)
// doc builds a single-statement policy document.
func doc(effect, action, resource string) handlers_iam.PolicyDocument {
return handlers_iam.PolicyDocument{
func doc(effect, action, resource string) iamdomain.PolicyDocument {
return iamdomain.PolicyDocument{
Version: "2012-10-17",
Statement: []handlers_iam.Statement{
{Effect: effect, Action: handlers_iam.StringOrArr{action}, Resource: handlers_iam.StringOrArr{resource}},
Statement: []iamdomain.Statement{
{Effect: effect, Action: iamdomain.StringOrArr{action}, Resource: iamdomain.StringOrArr{resource}},
},
}
}
// The deny-wins algorithm and wildcard matcher are unit-tested in predastore's
// pkg/iampolicy. These tests pin spinifex's own action-string conventions end to
// end through iampolicy.Evaluate, exercising the aliased handlers_iam DTOs.
// end through iampolicy.Evaluate, exercising the aliased domains/iam DTOs.
// TestEvaluate_IAMInstanceProfileActionStrings pins the action strings for
// iam:PassRole + the four EC2 instance-profile association actions so a rename of
@@ -34,7 +34,7 @@ func TestEvaluate_IAMInstanceProfileActionStrings(t *testing.T) {
"ec2:ReplaceIamInstanceProfileAssociation",
"ec2:DescribeIamInstanceProfileAssociations",
}
policies := []handlers_iam.PolicyDocument{
policies := []iamdomain.PolicyDocument{
doc("Allow", "*", "*"),
}
for _, a := range actions {
@@ -43,7 +43,7 @@ func TestEvaluate_IAMInstanceProfileActionStrings(t *testing.T) {
}
}
scoped := []handlers_iam.PolicyDocument{
scoped := []iamdomain.PolicyDocument{
doc("Allow", "ec2:*IamInstanceProfile*", "*"),
doc("Allow", "iam:PassRole", "arn:aws:iam::*:role/*"),
}
@@ -80,8 +80,8 @@ func TestEvaluate_STSActionStrings(t *testing.T) {
"sts:GetCallerIdentity",
}
wildcard := []handlers_iam.PolicyDocument{doc("Allow", "*", "*")}
scoped := []handlers_iam.PolicyDocument{doc("Allow", "sts:*", "*")}
wildcard := []iamdomain.PolicyDocument{doc("Allow", "*", "*")}
scoped := []iamdomain.PolicyDocument{doc("Allow", "sts:*", "*")}
for _, a := range actions {
if got := iampolicy.EvaluateWithKeys(a, "*", wildcard, nil); got != iampolicy.Allow {
@@ -119,7 +119,7 @@ func TestEvaluate_ResourceScopedStatementsNeedARealARN(t *testing.T) {
const prod = "arn:aws:ec2:ap-southeast-2:123456789012:instance/i-prod"
const dev = "arn:aws:ec2:ap-southeast-2:123456789012:instance/i-dev"
fenced := []handlers_iam.PolicyDocument{
fenced := []iamdomain.PolicyDocument{
doc("Allow", "ec2:*", "*"),
doc("Deny", "ec2:TerminateInstances", "arn:aws:ec2:*:*:instance/i-prod"),
}
@@ -133,7 +133,7 @@ func TestEvaluate_ResourceScopedStatementsNeedARealARN(t *testing.T) {
t.Errorf("fenced policy against an unfenced instance: got %v, want Allow", got)
}
scopedAllow := []handlers_iam.PolicyDocument{
scopedAllow := []iamdomain.PolicyDocument{
doc("Allow", "ec2:*", "arn:aws:ec2:*:*:instance/i-dev"),
}
if got := iampolicy.EvaluateWithKeys("ec2:TerminateInstances", "*", scopedAllow, nil); got != iampolicy.Deny {
@@ -161,7 +161,7 @@ func TestEvaluate_IAMResourceARNs(t *testing.T) {
"arn:aws:iam::123456789012:oidc-provider/issuer.example/id/cluster",
}
for _, resource := range resources {
policies := []handlers_iam.PolicyDocument{doc("Allow", "iam:Delete*", resource)}
policies := []iamdomain.PolicyDocument{doc("Allow", "iam:Delete*", resource)}
if got := iampolicy.EvaluateWithKeys("iam:DeleteRole", resource, policies, nil); got != iampolicy.Allow {
t.Errorf("IAM scoped policy against %q: got %v, want Allow", resource, got)
}
@@ -176,7 +176,7 @@ func TestEvaluate_PassingARealARNCannotWithdrawAccess(t *testing.T) {
"arn:aws:ec2:ap-southeast-2:123456789012:instance/i-abc/admin",
"not-an-arn",
}
policies := [][]handlers_iam.PolicyDocument{
policies := [][]iamdomain.PolicyDocument{
{doc("Allow", "ec2:*", "*")},
{doc("Allow", "*", "*")},
}
@@ -287,7 +287,7 @@ func TestNATSRequest_ErrorResponse(t *testing.T) {
}
// TestNATSRequest_DecodedErrorContainsCode pins the shape strings.Contains(err.Error(), code)
// classifiers depend on (e.g. handlers/iam/provision.go's isAlreadyExists,
// classifiers depend on (e.g. domains/iam/provision.go's isAlreadyExists,
// gateway/auth.go's IAM-not-found branch): the decoded error's Error() text
// must still contain the wire code even when a message rides alongside it.
func TestNATSRequest_DecodedErrorContainsCode(t *testing.T) {
+13 -13
View File
@@ -17,8 +17,8 @@ import (
"github.com/mulgadc/bluebottle/pkg/sigv4"
"github.com/mulgadc/spinifex/internal/testkit"
acmawsapi "github.com/mulgadc/spinifex/spinifex/domains/acm/awsapi"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/telemetry"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/mulgadc/spinifex/spinifex/ingress/aws/envelope"
"github.com/nats-io/nats.go"
"github.com/stretchr/testify/assert"
@@ -31,9 +31,9 @@ import (
// acmPipelineApp wires SigV4AuthMiddleware -> Request as SetupRoutes does, on
// live test NATS, with docs as every principal's policy. The region is
// testRegion because signTestRequestAs always signs for it.
func acmPipelineApp(t *testing.T, docs []handlers_iam.PolicyDocument) (*GatewayConfig, http.Handler) {
func acmPipelineApp(t *testing.T, docs []iamdomain.PolicyDocument) (*GatewayConfig, http.Handler) {
t.Helper()
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
require.NoError(t, err)
_, nc := testutil.StartTestNATS(t)
@@ -44,7 +44,7 @@ func acmPipelineApp(t *testing.T, docs []handlers_iam.PolicyDocument) (*GatewayC
IAMService: &policyMockIAMService{
mockIAMService: mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -54,7 +54,7 @@ func acmPipelineApp(t *testing.T, docs []handlers_iam.PolicyDocument) (*GatewayC
},
},
},
getUserPoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) { return docs, nil },
getUserPoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) { return docs, nil },
},
}
@@ -68,11 +68,11 @@ func acmPipelineApp(t *testing.T, docs []handlers_iam.PolicyDocument) (*GatewayC
// allowAllACMDocs is the policy acmPipelineApp uses when the test is not
// exercising authorization itself.
func allowAllACMDocs() []handlers_iam.PolicyDocument {
return []handlers_iam.PolicyDocument{{
func allowAllACMDocs() []iamdomain.PolicyDocument {
return []iamdomain.PolicyDocument{{
Version: "2012-10-17",
Statement: []handlers_iam.Statement{
{Effect: "Allow", Action: handlers_iam.StringOrArr{"*"}, Resource: handlers_iam.StringOrArr{"*"}},
Statement: []iamdomain.Statement{
{Effect: "Allow", Action: iamdomain.StringOrArr{"*"}, Resource: iamdomain.StringOrArr{"*"}},
},
}}
}
@@ -209,13 +209,13 @@ func TestACMPipeline_OversizedBody_413OverHTTP(t *testing.T) {
// dispatch runs, and denies, before the NATS-backed action handler is ever
// invoked, through the full pipeline.
func TestACMPipeline_AuthzGateBlocksAction(t *testing.T) {
scopedDocs := []handlers_iam.PolicyDocument{{
scopedDocs := []iamdomain.PolicyDocument{{
Version: "2012-10-17",
Statement: []handlers_iam.Statement{
Statement: []iamdomain.Statement{
{
Effect: "Allow",
Action: handlers_iam.StringOrArr{"acm:DeleteCertificate"},
Resource: handlers_iam.StringOrArr{"arn:aws:acm:" + testRegion + ":" + authzAccountID + ":certificate/other"},
Action: iamdomain.StringOrArr{"acm:DeleteCertificate"},
Resource: iamdomain.StringOrArr{"arn:aws:acm:" + testRegion + ":" + authzAccountID + ":certificate/other"},
},
},
}}
+3 -3
View File
@@ -9,8 +9,8 @@ import (
"github.com/mulgadc/spinifex/internal/testkit"
admissionquota "github.com/mulgadc/spinifex/spinifex/domains/admission/quota"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go/jetstream"
"github.com/stretchr/testify/require"
)
@@ -25,11 +25,11 @@ type quotaIAMService struct {
known string
}
func (m *quotaIAMService) GetAccount(accountID string) (*handlers_iam.Account, error) {
func (m *quotaIAMService) GetAccount(accountID string) (*iamdomain.Account, error) {
if accountID != m.known {
return nil, errors.New(awserrors.ErrorIAMNoSuchEntity)
}
return &handlers_iam.Account{AccountID: accountID, Status: handlers_iam.AccountStatusActive}, nil
return &iamdomain.Account{AccountID: accountID, Status: iamdomain.AccountStatusActive}, nil
}
// quotaTestGateway wires a real quota Service over a real JetStream KV bucket,
+11 -11
View File
@@ -13,9 +13,9 @@ import (
"time"
"github.com/mulgadc/spinifex/contracts/ec2/v1"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvutil"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go/jetstream"
)
@@ -141,7 +141,7 @@ func (gw *GatewayConfig) adminCreateAccount(ctx context.Context, body []byte) (a
record, err := json.Marshal(adminIdemRecord{
State: adminIdemDone,
Name: handlers_iam.NormalizeAccountName(req.Name),
Name: iamdomain.NormalizeAccountName(req.Name),
Response: &stored,
StartedAt: time.Now().UTC().Format(time.RFC3339),
})
@@ -163,12 +163,12 @@ func (gw *GatewayConfig) adminCreateAccount(ctx context.Context, body []byte) (a
// admin identity and waits for the default VPC.
func (gw *GatewayConfig) provisionNewAccount(
ctx context.Context,
names *handlers_iam.AccountNameIndex,
names *iamdomain.AccountNameIndex,
req *CreateAccountRequest,
) (*CreateAccountResponse, error) {
// Accounts that predate the reservation index have no entry to collide
// with, so they are found by name scan. The same listing bounds the cap.
existing, err := handlers_iam.FindAccountByName(gw.IAMService, req.Name)
existing, err := iamdomain.FindAccountByName(gw.IAMService, req.Name)
if err != nil {
slog.Error("CreateAccount: failed to list accounts", "err", err)
return nil, errors.New(awserrors.ErrorInternalError)
@@ -181,16 +181,16 @@ func (gw *GatewayConfig) provisionNewAccount(
}
switch err := names.Reserve(ctx, req.Name, req.ClientToken); {
case errors.Is(err, handlers_iam.ErrNameTaken):
case errors.Is(err, iamdomain.ErrNameTaken):
return nil, errors.New(awserrors.ErrorAccountAlreadyExists)
case errors.Is(err, handlers_iam.ErrNameInFlight):
case errors.Is(err, iamdomain.ErrNameInFlight):
return nil, errors.New(awserrors.ErrorOperationInProgress)
case err != nil:
slog.Error("CreateAccount: failed to reserve account name", "err", err)
return nil, errors.New(awserrors.ErrorInternalError)
}
account, err := gw.IAMService.CreateAccount(handlers_iam.NormalizeAccountName(req.Name))
account, err := gw.IAMService.CreateAccount(iamdomain.NormalizeAccountName(req.Name))
if err != nil {
if relErr := names.Release(ctx, req.Name, req.ClientToken); relErr != nil {
slog.Error("CreateAccount: failed to release name reservation", "err", relErr)
@@ -208,7 +208,7 @@ func (gw *GatewayConfig) provisionNewAccount(
return nil, errors.New(awserrors.ErrorInternalError)
}
provisioned, err := handlers_iam.ProvisionAccount(gw.IAMService, account.AccountID, account.AccountName)
provisioned, err := iamdomain.ProvisionAccount(gw.IAMService, account.AccountID, account.AccountName)
if err != nil {
slog.Error("CreateAccount: failed to provision account",
"accountID", account.AccountID, "err", err)
@@ -239,7 +239,7 @@ func (gw *GatewayConfig) provisionNewAccount(
// response when the token has already completed, meaning the caller should
// replay it rather than provision again.
func claimClientToken(ctx context.Context, idem jetstream.KeyValue, clientToken, name string) (*CreateAccountResponse, error) {
normalized := handlers_iam.NormalizeAccountName(name)
normalized := iamdomain.NormalizeAccountName(name)
claim, err := json.Marshal(adminIdemRecord{
State: adminIdemInProgress,
Name: normalized,
@@ -340,14 +340,14 @@ func (gw *GatewayConfig) ensureDefaultVPC(ctx context.Context, accountID string)
// adminStores opens the name index and the idempotency bucket. Both are opened
// per request rather than cached on the gateway so a bucket created after
// startup (a cluster upgraded into this feature) is picked up without a restart.
func (gw *GatewayConfig) adminStores(ctx context.Context) (*handlers_iam.AccountNameIndex, jetstream.KeyValue, error) {
func (gw *GatewayConfig) adminStores(ctx context.Context) (*iamdomain.AccountNameIndex, jetstream.KeyValue, error) {
js, err := jetstream.New(gw.NATSConn)
if err != nil {
slog.Error("CreateAccount: failed to get JetStream context", "err", err)
return nil, nil, errors.New(awserrors.ErrorServiceUnavailable)
}
names, err := handlers_iam.NewAccountNameIndex(ctx, js)
names, err := iamdomain.NewAccountNameIndex(ctx, js)
if err != nil {
slog.Error("CreateAccount: failed to open account name index", "err", err)
return nil, nil, errors.New(awserrors.ErrorServiceUnavailable)
+7 -7
View File
@@ -14,9 +14,9 @@ import (
"github.com/mulgadc/spinifex/contracts/ec2/v1"
"github.com/mulgadc/spinifex/internal/testkit"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvutil"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"github.com/stretchr/testify/assert"
@@ -27,17 +27,17 @@ const testClientToken = "0123456789abcdef0123456789abcdef"
// capMockIAMService reports a fixed account count for the cap check.
type capMockIAMService struct {
handlers_iam.IAMService
iamdomain.IAMService
accounts int
err error
}
func (m *capMockIAMService) ListAccounts() ([]*handlers_iam.Account, error) {
func (m *capMockIAMService) ListAccounts() ([]*iamdomain.Account, error) {
if m.err != nil {
return nil, m.err
}
return make([]*handlers_iam.Account, m.accounts), nil
return make([]*iamdomain.Account, m.accounts), nil
}
func TestValidateCreateAccountRequest(t *testing.T) {
@@ -239,9 +239,9 @@ func newCreateAccountGateway(t *testing.T) *GatewayConfig {
t.Helper()
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_iam.NewIAMServiceImpl(t.Context(), nc, masterKey)
svc, err := iamdomain.NewIAMServiceImpl(t.Context(), nc, masterKey)
require.NoError(t, err)
sub, err := nc.Subscribe(ec2v1.EnsureDefaultVpcSubject, func(msg *nats.Msg) {
@@ -276,7 +276,7 @@ func TestAdminCreateAccountProvisionsAndReplays(t *testing.T) {
assert.NotEmpty(t, created.AccountID)
assert.Equal(t, "ben@example.com", created.AccountName)
assert.Equal(t, handlers_iam.AdminUserName, created.AdminUser)
assert.Equal(t, iamdomain.AdminUserName, created.AdminUser)
assert.NotEmpty(t, created.AccessKeyID)
assert.NotEmpty(t, created.SecretAccessKey)
assert.Equal(t, "vpc-0a1b2c3d", created.DefaultVpcID)
@@ -13,7 +13,7 @@ import (
"testing"
"github.com/mulgadc/spinifex/spinifex/accountteardown"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -23,14 +23,14 @@ const dryRunShadowMessage = "Account teardown dry-run EC2 platform shadow compar
// deleteAccountGrant is the real IAM service with a policy granting
// spinifex:DeleteAccount, so a request clears the admin gates.
type deleteAccountGrant struct {
handlers_iam.IAMService
iamdomain.IAMService
}
func (deleteAccountGrant) GetUserPolicies(string, string) ([]handlers_iam.PolicyDocument, error) {
return []handlers_iam.PolicyDocument{{
func (deleteAccountGrant) GetUserPolicies(string, string) ([]iamdomain.PolicyDocument, error) {
return []iamdomain.PolicyDocument{{
Version: "2012-10-17",
Statement: []handlers_iam.Statement{{
Effect: "Allow", Action: handlers_iam.StringOrArr{"spinifex:DeleteAccount"}, Resource: handlers_iam.StringOrArr{"*"},
Statement: []iamdomain.Statement{{
Effect: "Allow", Action: iamdomain.StringOrArr{"spinifex:DeleteAccount"}, Resource: iamdomain.StringOrArr{"*"},
}},
}}, nil
}
@@ -15,9 +15,9 @@ import (
ec2v1 "github.com/mulgadc/spinifex/contracts/ec2/v1"
"github.com/mulgadc/spinifex/internal/testkit"
"github.com/mulgadc/spinifex/spinifex/accountteardown"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
"github.com/mulgadc/spinifex/spinifex/foundation/messaging/nats"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/mulgadc/spinifex/spinifex/providers/objectstore"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
@@ -44,9 +44,9 @@ func newDeleteAccountGateway(t *testing.T) *GatewayConfig {
t.Helper()
_, nc, _ := testutil.StartTestJetStream(t)
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
svc, err := handlers_iam.NewIAMServiceImpl(t.Context(), nc, masterKey)
svc, err := iamdomain.NewIAMServiceImpl(t.Context(), nc, masterKey)
require.NoError(t, err)
for _, subject := range teardownSubjects {
@@ -139,7 +139,7 @@ func (emptyBucketStore) DeleteBucket(context.Context, string) error { return nil
// newTenantAccount creates an account that is safe to delete. Account ids are
// sequential and the first belongs to the super admin, which is protected, so
// the tenant under test can never be the first one created.
func newTenantAccount(t *testing.T, gw *GatewayConfig, name string) *handlers_iam.Account {
func newTenantAccount(t *testing.T, gw *GatewayConfig, name string) *iamdomain.Account {
t.Helper()
if accounts, err := gw.IAMService.ListAccounts(); err == nil && len(accounts) == 0 {
_, err := gw.IAMService.CreateAccount("super-admin@example.com")
@@ -207,7 +207,7 @@ func TestAdminDeleteAccountDryRunChangesNothing(t *testing.T) {
stored, err := gw.IAMService.GetAccount(account.AccountID)
require.NoError(t, err)
assert.Equal(t, handlers_iam.AccountStatusActive, stored.Status)
assert.Equal(t, iamdomain.AccountStatusActive, stored.Status)
// No job record means a later real delete is not answered as a replay.
_, err = gw.adminDescribeAccountDeletion(t.Context(),
@@ -428,7 +428,7 @@ func TestAdminDeleteAccountRefusesAMismatchedName(t *testing.T) {
stored, err := gw.IAMService.GetAccount(account.AccountID)
require.NoError(t, err)
assert.Equal(t, handlers_iam.AccountStatusActive, stored.Status)
assert.Equal(t, iamdomain.AccountStatusActive, stored.Status)
}
func TestAdminDeleteAccountRejectsAnUnknownAccount(t *testing.T) {
+8 -8
View File
@@ -13,8 +13,8 @@ import (
"time"
"github.com/mulgadc/spinifex/spinifex/accountteardown"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -23,11 +23,11 @@ import (
type listAccountsIAMService struct {
policyMockIAMService
accounts []*handlers_iam.Account
accounts []*iamdomain.Account
err error
}
func (m *listAccountsIAMService) ListAccounts() ([]*handlers_iam.Account, error) {
func (m *listAccountsIAMService) ListAccounts() ([]*iamdomain.Account, error) {
return m.accounts, m.err
}
@@ -177,10 +177,10 @@ func TestTeardownErrorMapping(t *testing.T) {
// that is how a stuck TERMINATING account is noticed — and no key material.
func TestAdminListAccountsReportsStatus(t *testing.T) {
gw := &GatewayConfig{DisableLogging: true, IAMService: &listAccountsIAMService{
accounts: []*handlers_iam.Account{
{AccountID: "000000000042", AccountName: "t@example.com", Status: handlers_iam.AccountStatusActive},
accounts: []*iamdomain.Account{
{AccountID: "000000000042", AccountName: "t@example.com", Status: iamdomain.AccountStatusActive},
nil,
{AccountID: "000000000043", AccountName: "u@example.com", Status: handlers_iam.AccountStatusTerminating},
{AccountID: "000000000043", AccountName: "u@example.com", Status: iamdomain.AccountStatusTerminating},
},
}}
@@ -190,8 +190,8 @@ func TestAdminListAccountsReportsStatus(t *testing.T) {
response, ok := output.(*ListAccountsResponse)
require.True(t, ok)
assert.Equal(t, 2, response.Count)
assert.Equal(t, handlers_iam.AccountStatusActive, response.Accounts[0].Status)
assert.Equal(t, handlers_iam.AccountStatusTerminating, response.Accounts[1].Status)
assert.Equal(t, iamdomain.AccountStatusActive, response.Accounts[0].Status)
assert.Equal(t, iamdomain.AccountStatusTerminating, response.Accounts[1].Status)
}
// Failing closed matters here: an empty listing reads as "no accounts", which
+7 -7
View File
@@ -14,9 +14,9 @@ import (
"testing"
"github.com/go-chi/chi/v5"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
awsidentifiers "github.com/mulgadc/spinifex/spinifex/foundation/aws/identifiers"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -47,19 +47,19 @@ func TestAdminPathMethod(t *testing.T) {
// createAccountPolicy grants exactly the action the signup principal holds.
func createAccountPolicy() *policyMockIAMService {
allow := []handlers_iam.PolicyDocument{{
allow := []iamdomain.PolicyDocument{{
Version: "2012-10-17",
Statement: []handlers_iam.Statement{
Statement: []iamdomain.Statement{
{
Effect: "Allow",
Action: handlers_iam.StringOrArr{"spinifex:CreateAccount"},
Resource: handlers_iam.StringOrArr{"*"},
Action: iamdomain.StringOrArr{"spinifex:CreateAccount"},
Resource: iamdomain.StringOrArr{"*"},
},
},
}}
return &policyMockIAMService{
getUserPoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) { return allow, nil },
getRolePoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) { return allow, nil },
getUserPoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) { return allow, nil },
getRolePoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) { return allow, nil },
}
}
+2 -2
View File
@@ -13,9 +13,9 @@ import (
"uuid"
"github.com/mulgadc/bluebottle/pkg/sigv4"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
telemetry "github.com/mulgadc/spinifex/spinifex/foundation/telemetry"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
handlers_sts "github.com/mulgadc/spinifex/spinifex/handlers/sts"
"github.com/mulgadc/spinifex/spinifex/ingress/aws/dispatch"
"github.com/mulgadc/spinifex/spinifex/ingress/aws/envelope"
@@ -383,7 +383,7 @@ func (gw *GatewayConfig) resolveLongLivedAKID(accessKeyID string, src authSource
slog.Error("IAM lookup failed", "accessKeyID", accessKeyID, "err", err)
return "", principalContext{}, awserrors.ErrorInternalError
}
if ak.Status != handlers_iam.AccessKeyStatusActive {
if ak.Status != iamdomain.AccessKeyStatusActive {
slog.Warn("Auth failure: access key inactive", "accessKeyID", accessKeyID, "sourceIP", src.logIP)
gw.RateLimiter.RecordFailure(src.limitKey, authlimit.Fingerprint("akid-inactive", accessKeyID))
return "", principalContext{}, awserrors.ErrorInvalidClientTokenId
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"sync"
"time"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
)
// accountActiveTTL bounds how long an account is trusted to still be ACTIVE
@@ -86,7 +86,7 @@ func (gw *GatewayConfig) checkAccountActive(accountID string, src authSource) st
return awserrors.ErrorInternalError
}
if account.Status != handlers_iam.AccountStatusActive {
if account.Status != iamdomain.AccountStatusActive {
slog.Warn("Auth failure: account is not active",
"accountID", accountID, "status", account.Status, "sourceIP", src.logIP)
return awserrors.ErrorAccessDenied
+11 -11
View File
@@ -11,12 +11,12 @@ import (
"time"
"github.com/go-chi/chi/v5"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
)
// statusGateRouter builds a signed-request harness whose only job is to report
// whether the auth middleware let the request through.
func statusGateRouter(t *testing.T, svc handlers_iam.IAMService) (chi.Router, *http.Request) {
func statusGateRouter(t *testing.T, svc iamdomain.IAMService) (chi.Router, *http.Request) {
t.Helper()
gw := &GatewayConfig{DisableLogging: true, Region: testRegion, IAMService: svc}
@@ -35,29 +35,29 @@ func statusGateRouter(t *testing.T, svc handlers_iam.IAMService) (chi.Router, *h
func statusGateService(t *testing.T, accountID, status string) *mockIAMService {
t.Helper()
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("encrypt secret: %v", err)
}
return &mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
UserName: "alice",
AccountID: accountID,
Status: handlers_iam.AccessKeyStatusActive,
Status: iamdomain.AccessKeyStatusActive,
},
},
accounts: map[string]*handlers_iam.Account{
accounts: map[string]*iamdomain.Account{
accountID: {AccountID: accountID, Status: status},
},
}
}
func TestAuthAllowsAnActiveAccount(t *testing.T) {
r, req := statusGateRouter(t, statusGateService(t, "123456789012", handlers_iam.AccountStatusActive))
r, req := statusGateRouter(t, statusGateService(t, "123456789012", iamdomain.AccountStatusActive))
if resp := doRequest(r, req); resp.StatusCode != http.StatusOK {
t.Fatalf("expected 200 for an ACTIVE account, got %d", resp.StatusCode)
@@ -67,7 +67,7 @@ func TestAuthAllowsAnActiveAccount(t *testing.T) {
// Until this gate existed, account status was enforced only in ECR's principal
// resolution, so suspending an account left EC2, S3 and STS wide open.
func TestAuthDeniesASuspendedAccount(t *testing.T) {
r, req := statusGateRouter(t, statusGateService(t, "123456789012", handlers_iam.AccountStatusSuspended))
r, req := statusGateRouter(t, statusGateService(t, "123456789012", iamdomain.AccountStatusSuspended))
if resp := doRequest(r, req); resp.StatusCode != http.StatusForbidden {
t.Fatalf("expected 403 for a SUSPENDED account, got %d", resp.StatusCode)
@@ -77,7 +77,7 @@ func TestAuthDeniesASuspendedAccount(t *testing.T) {
// The quiesce that makes teardown converge: a terminating account must not be
// able to create resources the cascade has already walked past.
func TestAuthDeniesATerminatingAccount(t *testing.T) {
r, req := statusGateRouter(t, statusGateService(t, "123456789012", handlers_iam.AccountStatusTerminating))
r, req := statusGateRouter(t, statusGateService(t, "123456789012", iamdomain.AccountStatusTerminating))
if resp := doRequest(r, req); resp.StatusCode != http.StatusForbidden {
t.Fatalf("expected 403 for a TERMINATING account, got %d", resp.StatusCode)
@@ -89,13 +89,13 @@ type unreadableAccountService struct {
*mockIAMService
}
func (s *unreadableAccountService) GetAccount(string) (*handlers_iam.Account, error) {
func (s *unreadableAccountService) GetAccount(string) (*iamdomain.Account, error) {
return nil, errors.New("account store unavailable")
}
// An account we cannot read is not evidence of an account in good standing.
func TestAuthFailsClosedWhenTheAccountCannotBeRead(t *testing.T) {
svc := &unreadableAccountService{statusGateService(t, "123456789012", handlers_iam.AccountStatusActive)}
svc := &unreadableAccountService{statusGateService(t, "123456789012", iamdomain.AccountStatusActive)}
r, req := statusGateRouter(t, svc)
if resp := doRequest(r, req); resp.StatusCode == http.StatusOK {
+18 -18
View File
@@ -28,11 +28,11 @@ import (
"github.com/stretchr/testify/require"
"github.com/mulgadc/spinifex/internal/testkit"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
awserrors "github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
awsidentifiers "github.com/mulgadc/spinifex/spinifex/foundation/aws/identifiers"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvutil"
handlers_eks "github.com/mulgadc/spinifex/spinifex/handlers/eks"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
handlers_sts "github.com/mulgadc/spinifex/spinifex/handlers/sts"
)
@@ -56,7 +56,7 @@ type cbCreds struct {
// cbDecryptCounter is the real IAM service with DecryptSecret counted, so a test
// can observe whether the door decrypted a secret before rejecting a request.
type cbDecryptCounter struct {
*handlers_iam.IAMServiceImpl
*iamdomain.IAMServiceImpl
decrypts atomic.Int32
}
@@ -79,7 +79,7 @@ type cbEnv struct {
nc *nats.Conn // the gateway's connection
iamNC *nats.Conn // IAM/STS connection; == nc unless separateIAMConn
js jetstream.JetStream
iam *handlers_iam.IAMServiceImpl
iam *iamdomain.IAMServiceImpl
sts *handlers_sts.STSServiceImpl
counter *cbDecryptCounter
h http.Handler
@@ -100,9 +100,9 @@ func newCBEnv(t *testing.T, opts cbEnvOpts) *cbEnv {
e.iamNC = iamNC
}
masterKey, err := handlers_iam.GenerateMasterKey()
masterKey, err := iamdomain.GenerateMasterKey()
require.NoError(t, err)
e.iam, err = handlers_iam.NewIAMServiceImpl(t.Context(), e.iamNC, masterKey)
e.iam, err = iamdomain.NewIAMServiceImpl(t.Context(), e.iamNC, masterKey)
require.NoError(t, err)
iamJS := testutil.NewJetStream(t, e.iamNC)
e.sts, err = handlers_sts.NewSTSServiceImpl(t.Context(), e.iamNC, e.iam, masterKey, handlers_eks.NewOIDCJWKSReader(iamJS))
@@ -111,9 +111,9 @@ func newCBEnv(t *testing.T, opts cbEnvOpts) *cbEnv {
e.iam.SetSessionRevoker(e.sts)
}
encrypted, err := handlers_iam.EncryptSecret(cbRootSecret, masterKey)
encrypted, err := iamdomain.EncryptSecret(cbRootSecret, masterKey)
require.NoError(t, err)
require.NoError(t, e.iam.SeedBootstrap(&handlers_iam.BootstrapData{
require.NoError(t, e.iam.SeedBootstrap(&iamdomain.BootstrapData{
AccessKeyID: cbRootAKID, EncryptedSecret: encrypted, AccountID: awsidentifiers.GlobalAccountID,
}))
@@ -365,7 +365,7 @@ func TestCurrentBehaviour_Auth_LongLivedRejections(t *testing.T) {
creds := e.newKey(t, "alice")
require.Equal(t, http.StatusOK, e.callerIdentity(t, creds).Code)
_, err := e.iam.UpdateAccessKey(e.accountID, &iam.UpdateAccessKeyInput{
UserName: aws.String("alice"), AccessKeyId: aws.String(creds.akid), Status: aws.String(handlers_iam.AccessKeyStatusInactive),
UserName: aws.String("alice"), AccessKeyId: aws.String(creds.akid), Status: aws.String(iamdomain.AccessKeyStatusInactive),
})
require.NoError(t, err)
assert.Equal(t, cbRegistry(awserrors.ErrorInvalidClientTokenId), cbOutcomeOf(e.callerIdentity(t, creds)))
@@ -462,7 +462,7 @@ func TestCurrentBehaviour_Session_GetSessionTokenOutlivesMintingKey(t *testing.T
assert.Equal(t, e.aliceID, cbXML(rec.Body.String(), "UserId"))
_, err := e.iam.UpdateAccessKey(e.accountID, &iam.UpdateAccessKeyInput{
UserName: aws.String("alice"), AccessKeyId: aws.String(mintKey.akid), Status: aws.String(handlers_iam.AccessKeyStatusInactive),
UserName: aws.String("alice"), AccessKeyId: aws.String(mintKey.akid), Status: aws.String(iamdomain.AccessKeyStatusInactive),
})
require.NoError(t, err)
_, err = e.iam.DeleteAccessKey(e.accountID, &iam.DeleteAccessKeyInput{
@@ -486,9 +486,9 @@ func TestCurrentBehaviour_Session_WebIdentityCredentials(t *testing.T) {
issuer := testDiscIssuer
iamKV, err := kvutil.GetOrCreateBucket(t.Context(), e.js,
handlers_iam.IAMAccountBucketName(e.accountID), handlers_iam.KVBucketIAMAccountVersion)
iamdomain.IAMAccountBucketName(e.accountID), iamdomain.KVBucketIAMAccountVersion)
require.NoError(t, err)
_, err = iamKV.Put(t.Context(), handlers_iam.OIDCProviderKey(issuer), []byte(`{"registered":true}`))
_, err = iamKV.Put(t.Context(), iamdomain.OIDCProviderKey(issuer), []byte(`{"registered":true}`))
require.NoError(t, err)
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
@@ -506,7 +506,7 @@ func TestCurrentBehaviour_Session_WebIdentityCredentials(t *testing.T) {
_, err = eksKV.Put(t.Context(), handlers_eks.OIDCJWKSKey(testDiscCluster), jwks)
require.NoError(t, err)
federated := handlers_iam.OIDCProviderARN(e.accountID, strings.TrimPrefix(issuer, "https://"))
federated := iamdomain.OIDCProviderARN(e.accountID, strings.TrimPrefix(issuer, "https://"))
role, err := e.iam.CreateRole(e.accountID, &iam.CreateRoleInput{
RoleName: aws.String("irsa"),
AssumeRolePolicyDocument: aws.String(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Federated":"` +
@@ -640,11 +640,11 @@ func TestCurrentBehaviour_Revocation_OrphanedKeyAuthenticatesAsRecreatedUser(t *
// access-key records in place, the state an interrupted DeleteAccessKey leaves.
func (e *cbEnv) orphanKeys(t *testing.T, user string) {
t.Helper()
usersKV, err := e.js.KeyValue(t.Context(), handlers_iam.KVBucketUsers)
usersKV, err := e.js.KeyValue(t.Context(), iamdomain.KVBucketUsers)
require.NoError(t, err)
entry, err := usersKV.Get(t.Context(), e.accountID+"."+user)
require.NoError(t, err)
var u handlers_iam.User
var u iamdomain.User
require.NoError(t, json.Unmarshal(entry.Value(), &u))
u.AccessKeys = []string{}
data, err := json.Marshal(u)
@@ -744,7 +744,7 @@ func TestCurrentBehaviour_Auth_BackingStateUnavailable(t *testing.T) {
t.Run("access_key_bucket_deleted", func(t *testing.T) {
e := newCBEnv(t, cbEnvOpts{})
require.NoError(t, e.js.DeleteKeyValue(t.Context(), handlers_iam.KVBucketAccessKeys))
require.NoError(t, e.js.DeleteKeyValue(t.Context(), iamdomain.KVBucketAccessKeys))
for name, c := range map[string]cbCreds{"known": e.alice, "unknown": {akid: cbUnknownKey, secret: cbBadSecret}} {
assert.Equal(t, internal, cbOutcomeOf(e.request(t, e.h, c, "sts", gci)), name)
}
@@ -760,7 +760,7 @@ func TestCurrentBehaviour_Auth_BackingStateUnavailable(t *testing.T) {
t.Run("accounts_bucket_deleted", func(t *testing.T) {
e := newCBEnv(t, cbEnvOpts{})
require.NoError(t, e.js.DeleteKeyValue(t.Context(), handlers_iam.KVBucketAccounts))
require.NoError(t, e.js.DeleteKeyValue(t.Context(), iamdomain.KVBucketAccounts))
// Fails closed only once the signature holds; a bad one still reads as such.
assert.Equal(t, internal, cbOutcomeOf(e.callerIdentity(t, e.alice)))
assert.Equal(t, cbRegistry(awserrors.ErrorSignatureDoesNotMatch),
@@ -812,7 +812,7 @@ func TestCurrentBehaviour_AntiEnumeration_RejectionShapes(t *testing.T) {
e := newCBEnv(t, cbEnvOpts{})
bobKey, _ := e.newUser(t, "bob")
_, err := e.iam.UpdateAccessKey(e.accountID, &iam.UpdateAccessKeyInput{
UserName: aws.String("bob"), AccessKeyId: aws.String(bobKey.akid), Status: aws.String(handlers_iam.AccessKeyStatusInactive),
UserName: aws.String("bob"), AccessKeyId: aws.String(bobKey.akid), Status: aws.String(iamdomain.AccessKeyStatusInactive),
})
require.NoError(t, err)
carolKey, _ := e.newUser(t, "carol")
@@ -858,7 +858,7 @@ func TestCurrentBehaviour_AntiEnumeration_RejectionShapes(t *testing.T) {
func TestCurrentBehaviour_Cache_AccountStatusIsTheOnlyAuthCache(t *testing.T) {
require.Equal(t, 5*time.Second, accountActiveTTL)
for _, status := range []string{handlers_iam.AccountStatusSuspended, handlers_iam.AccountStatusTerminating} {
for _, status := range []string{iamdomain.AccountStatusSuspended, iamdomain.AccountStatusTerminating} {
t.Run(status, func(t *testing.T) {
e := newCBEnv(t, cbEnvOpts{})
require.Equal(t, http.StatusOK, e.callerIdentity(t, e.alice).Code)
+104 -104
View File
@@ -30,8 +30,8 @@ import (
"github.com/go-chi/chi/v5"
"github.com/mulgadc/bluebottle/pkg/sigv4"
"github.com/mulgadc/spinifex/internal/testkit"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
handlers_sts "github.com/mulgadc/spinifex/spinifex/handlers/sts"
"github.com/nats-io/nats.go"
"github.com/stretchr/testify/assert"
@@ -45,27 +45,27 @@ const (
testService = "ec2"
)
// mockIAMService implements handlers_iam.IAMService for auth tests. It embeds
// mockIAMService implements iamdomain.IAMService for auth tests. It embeds
// the interface so it satisfies the full contract; the SigV4 middleware drives
// LookupAccessKey, DecryptSecret and GetUser, so those are the methods wired.
// Any other method nil-panics, surfacing an unexpected call.
type mockIAMService struct {
handlers_iam.IAMService
iamdomain.IAMService
accessKeys map[string]*handlers_iam.AccessKey
accessKeys map[string]*iamdomain.AccessKey
masterKey []byte
// accounts overrides the status the auth gate reads. An empty map means
// every account is ACTIVE, which is what most tests here are asserting
// around rather than asserting about.
accounts map[string]*handlers_iam.Account
accounts map[string]*iamdomain.Account
// getUserFn overrides the synthetic user record below, for a test that cares
// what aws:userid resolves to or that it fails to resolve at all.
getUserFn func(accountID string, input *iam.GetUserInput) (*iam.GetUserOutput, error)
}
func (m *mockIAMService) LookupAccessKey(accessKeyID string) (*handlers_iam.AccessKey, error) {
func (m *mockIAMService) LookupAccessKey(accessKeyID string) (*iamdomain.AccessKey, error) {
ak, ok := m.accessKeys[accessKeyID]
if !ok {
return nil, errors.New(awserrors.ErrorIAMNoSuchEntity)
@@ -74,14 +74,14 @@ func (m *mockIAMService) LookupAccessKey(accessKeyID string) (*handlers_iam.Acce
}
func (m *mockIAMService) DecryptSecret(ciphertext string) (string, error) {
return handlers_iam.DecryptSecret(ciphertext, m.masterKey)
return iamdomain.DecryptSecret(ciphertext, m.masterKey)
}
func (m *mockIAMService) GetAccount(accountID string) (*handlers_iam.Account, error) {
func (m *mockIAMService) GetAccount(accountID string) (*iamdomain.Account, error) {
if account, ok := m.accounts[accountID]; ok {
return account, nil
}
return &handlers_iam.Account{AccountID: accountID, Status: handlers_iam.AccountStatusActive}, nil
return &iamdomain.Account{AccountID: accountID, Status: iamdomain.AccountStatusActive}, nil
}
// GetUser answers with a unique ID derived from the name, so aws:userid resolves
@@ -102,7 +102,7 @@ var testMasterKey []byte
func init() {
var err error
testMasterKey, err = handlers_iam.GenerateMasterKey()
testMasterKey, err = iamdomain.GenerateMasterKey()
if err != nil {
panic("failed to generate test master key: " + err.Error())
}
@@ -136,14 +136,14 @@ func signTestRequestAs(t *testing.T, req *http.Request, body []byte, accessKey,
}
func setupTestApp(accessKey, secretKey string) http.Handler {
encryptedSecret, err := handlers_iam.EncryptSecret(secretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(secretKey, testMasterKey)
if err != nil {
panic("failed to encrypt test secret: " + err.Error())
}
mockSvc := &mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
accessKey: {
AccessKeyID: accessKey,
SecretAccessKey: encryptedSecret,
@@ -172,10 +172,10 @@ func setupTestApp(accessKey, secretKey string) http.Handler {
// the aws:userid branch that a user principal reaches in production.
func userIDApp(t *testing.T, svc *mockIAMService) (http.Handler, *string) {
t.Helper()
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
require.NoError(t, err)
svc.masterKey = testMasterKey
svc.accessKeys = map[string]*handlers_iam.AccessKey{
svc.accessKeys = map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -371,14 +371,14 @@ func TestSigV4Auth_ValidSignatureWithQueryString(t *testing.T) {
}
func TestSigV4Auth_InactiveAccessKey(t *testing.T) {
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
mockSvc := &mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -480,18 +480,18 @@ func TestParseAWSQueryArgs_URLDecoding(t *testing.T) {
func TestSigV4Auth_DecryptFailure(t *testing.T) {
// Secret encrypted under a rotated master key — unverifiable credential must
// return 403 InvalidClientTokenId, not 500, so the client re-authenticates.
otherKey, err := handlers_iam.GenerateMasterKey()
otherKey, err := iamdomain.GenerateMasterKey()
if err != nil {
t.Fatalf("GenerateMasterKey() error: %v", err)
}
encryptedWithOther, err := handlers_iam.EncryptSecret(testSecretKey, otherKey)
encryptedWithOther, err := iamdomain.EncryptSecret(testSecretKey, otherKey)
if err != nil {
t.Fatalf("EncryptSecret() error: %v", err)
}
mockSvc := &mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedWithOther, // encrypted with wrong key
@@ -832,14 +832,14 @@ func TestSigV4Auth_S3ScopeReturnsFlatS3Error(t *testing.T) {
// --- Context Propagation Tests ---
func TestSigV4Auth_ContextPropagation(t *testing.T) {
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
mockSvc := &mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -902,20 +902,20 @@ func TestSigV4Auth_ContextPropagation(t *testing.T) {
}
func TestSigV4Auth_ContextDoesNotLeakBetweenRequests(t *testing.T) {
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
secondKey := "AKIAIOSFODNN7SECOND0"
encryptedSecret2, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret2, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
mockSvc := &mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -1034,14 +1034,14 @@ func TestSigV4Auth_PathWithSpecialCharacters(t *testing.T) {
func TestSigV4Auth_SignedContentType(t *testing.T) {
// Verify signature works when content-type is included in signed headers.
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
mockSvc := &mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -1146,18 +1146,18 @@ func TestSigV4Auth_QueryStringEdgeCases(t *testing.T) {
type policyMockIAMService struct {
mockIAMService
getUserPoliciesFn func(accountID, userName string) ([]handlers_iam.PolicyDocument, error)
getRolePoliciesFn func(accountID, roleName string) ([]handlers_iam.PolicyDocument, error)
getUserPoliciesFn func(accountID, userName string) ([]iamdomain.PolicyDocument, error)
getRolePoliciesFn func(accountID, roleName string) ([]iamdomain.PolicyDocument, error)
}
func (m *policyMockIAMService) GetUserPolicies(accountID, userName string) ([]handlers_iam.PolicyDocument, error) {
func (m *policyMockIAMService) GetUserPolicies(accountID, userName string) ([]iamdomain.PolicyDocument, error) {
if m.getUserPoliciesFn != nil {
return m.getUserPoliciesFn(accountID, userName)
}
return nil, nil
}
func (m *policyMockIAMService) GetRolePolicies(accountID, roleName string) ([]handlers_iam.PolicyDocument, error) {
func (m *policyMockIAMService) GetRolePolicies(accountID, roleName string) ([]iamdomain.PolicyDocument, error) {
if m.getRolePoliciesFn != nil {
return m.getRolePoliciesFn(accountID, roleName)
}
@@ -1171,7 +1171,7 @@ type errorLookupMockIAMService struct {
err error
}
func (m *errorLookupMockIAMService) LookupAccessKey(_ string) (*handlers_iam.AccessKey, error) {
func (m *errorLookupMockIAMService) LookupAccessKey(_ string) (*iamdomain.AccessKey, error) {
return nil, m.err
}
@@ -1190,7 +1190,7 @@ func setupPolicyTestHandler(gw *GatewayConfig) http.Handler {
}
func TestCheckPolicy_NonRootNoPolicies_Denied(t *testing.T) {
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
@@ -1198,7 +1198,7 @@ func TestCheckPolicy_NonRootNoPolicies_Denied(t *testing.T) {
mockSvc := &policyMockIAMService{
mockIAMService: mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -1208,7 +1208,7 @@ func TestCheckPolicy_NonRootNoPolicies_Denied(t *testing.T) {
},
},
},
getUserPoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
getUserPoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return nil, nil // no policies
},
}
@@ -1239,7 +1239,7 @@ func TestCheckPolicy_NonRootNoPolicies_Denied(t *testing.T) {
}
func TestCheckPolicy_NonRootWithAllow_Passes(t *testing.T) {
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
@@ -1247,7 +1247,7 @@ func TestCheckPolicy_NonRootWithAllow_Passes(t *testing.T) {
mockSvc := &policyMockIAMService{
mockIAMService: mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -1257,15 +1257,15 @@ func TestCheckPolicy_NonRootWithAllow_Passes(t *testing.T) {
},
},
},
getUserPoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
return []handlers_iam.PolicyDocument{
getUserPoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return []iamdomain.PolicyDocument{
{
Version: "2012-10-17",
Statement: []handlers_iam.Statement{
Statement: []iamdomain.Statement{
{
Effect: "Allow",
Action: handlers_iam.StringOrArr{"ec2:RunInstances"},
Resource: handlers_iam.StringOrArr{"*"},
Action: iamdomain.StringOrArr{"ec2:RunInstances"},
Resource: iamdomain.StringOrArr{"*"},
},
},
},
@@ -1294,7 +1294,7 @@ func TestCheckPolicy_NonRootWithAllow_Passes(t *testing.T) {
}
func TestCheckPolicy_NonRootWithExplicitDeny_Denied(t *testing.T) {
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
@@ -1302,7 +1302,7 @@ func TestCheckPolicy_NonRootWithExplicitDeny_Denied(t *testing.T) {
mockSvc := &policyMockIAMService{
mockIAMService: mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -1312,20 +1312,20 @@ func TestCheckPolicy_NonRootWithExplicitDeny_Denied(t *testing.T) {
},
},
},
getUserPoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
return []handlers_iam.PolicyDocument{
getUserPoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return []iamdomain.PolicyDocument{
{
Version: "2012-10-17",
Statement: []handlers_iam.Statement{
Statement: []iamdomain.Statement{
{
Effect: "Allow",
Action: handlers_iam.StringOrArr{"ec2:*"},
Resource: handlers_iam.StringOrArr{"*"},
Action: iamdomain.StringOrArr{"ec2:*"},
Resource: iamdomain.StringOrArr{"*"},
},
{
Effect: "Deny",
Action: handlers_iam.StringOrArr{"ec2:RunInstances"},
Resource: handlers_iam.StringOrArr{"*"},
Action: iamdomain.StringOrArr{"ec2:RunInstances"},
Resource: iamdomain.StringOrArr{"*"},
},
},
},
@@ -1359,7 +1359,7 @@ func TestCheckPolicy_NonRootWithExplicitDeny_Denied(t *testing.T) {
}
func TestCheckPolicy_RootGlobalAccount_Bypasses(t *testing.T) {
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
@@ -1367,7 +1367,7 @@ func TestCheckPolicy_RootGlobalAccount_Bypasses(t *testing.T) {
mockSvc := &policyMockIAMService{
mockIAMService: mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -1377,16 +1377,16 @@ func TestCheckPolicy_RootGlobalAccount_Bypasses(t *testing.T) {
},
},
},
getUserPoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
getUserPoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) {
// Return explicit deny — root should bypass anyway
return []handlers_iam.PolicyDocument{
return []iamdomain.PolicyDocument{
{
Version: "2012-10-17",
Statement: []handlers_iam.Statement{
Statement: []iamdomain.Statement{
{
Effect: "Deny",
Action: handlers_iam.StringOrArr{"*"},
Resource: handlers_iam.StringOrArr{"*"},
Action: iamdomain.StringOrArr{"*"},
Resource: iamdomain.StringOrArr{"*"},
},
},
},
@@ -1415,7 +1415,7 @@ func TestCheckPolicy_RootGlobalAccount_Bypasses(t *testing.T) {
}
func TestCheckPolicy_MissingAccountID_InternalError(t *testing.T) {
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
@@ -1424,7 +1424,7 @@ func TestCheckPolicy_MissingAccountID_InternalError(t *testing.T) {
mockSvc := &policyMockIAMService{
mockIAMService: mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -1457,7 +1457,7 @@ func TestCheckPolicy_MissingAccountID_InternalError(t *testing.T) {
}
func TestCheckPolicy_GetUserPoliciesError_InternalError(t *testing.T) {
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
@@ -1465,7 +1465,7 @@ func TestCheckPolicy_GetUserPoliciesError_InternalError(t *testing.T) {
mockSvc := &policyMockIAMService{
mockIAMService: mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -1475,7 +1475,7 @@ func TestCheckPolicy_GetUserPoliciesError_InternalError(t *testing.T) {
},
},
},
getUserPoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
getUserPoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return nil, errors.New("nats: timeout")
},
}
@@ -1503,7 +1503,7 @@ func TestCheckPolicy_GetUserPoliciesError_InternalError(t *testing.T) {
func TestCheckPolicy_RootNonGlobalAccount_StillEvaluated(t *testing.T) {
// A user named "root" but on a non-global account should still have
// policies evaluated (only root + GlobalAccountID bypasses).
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
if err != nil {
t.Fatalf("Failed to encrypt secret: %v", err)
}
@@ -1511,7 +1511,7 @@ func TestCheckPolicy_RootNonGlobalAccount_StillEvaluated(t *testing.T) {
mockSvc := &policyMockIAMService{
mockIAMService: mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -1521,7 +1521,7 @@ func TestCheckPolicy_RootNonGlobalAccount_StillEvaluated(t *testing.T) {
},
},
},
getUserPoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
getUserPoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return nil, nil // no policies → should deny
},
}
@@ -1728,7 +1728,7 @@ const (
// real AES-GCM so the SigV4 verify path exercises the actual decrypt code.
func setupSessionTestApp(t *testing.T, expiresAt time.Time) (http.Handler, *mockSTSService) {
t.Helper()
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
require.NoError(t, err)
cred := &handlers_sts.SessionCredential{
@@ -1752,7 +1752,7 @@ func setupSessionTestApp(t *testing.T, expiresAt time.Time) (http.Handler, *mock
// principal context; varies cred to drive the principal-type branch in resolveSessionAKID.
func mountSessionGateway(t *testing.T, cred *handlers_sts.SessionCredential) (http.Handler, *mockSTSService) {
t.Helper()
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
require.NoError(t, err)
stsMock := &mockSTSService{
@@ -1762,7 +1762,7 @@ func mountSessionGateway(t *testing.T, cred *handlers_sts.SessionCredential) (ht
iamMock := &mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -1824,7 +1824,7 @@ func TestSigV4Auth_Session_ValidSignature(t *testing.T) {
func TestSigV4Auth_Session_UserPrincipal(t *testing.T) {
// GetSessionToken session (PrincipalType "user") must resolve back to the IAM
// user with no assumed-role fields, so buildCallerARN yields arn:aws:iam::A:user/N.
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
require.NoError(t, err)
cred := &handlers_sts.SessionCredential{
AccessKeyID: testSessionAKID,
@@ -1856,7 +1856,7 @@ func TestSigV4Auth_Session_UserPrincipal(t *testing.T) {
func TestSigV4Auth_Session_EmptyPrincipalType_ResolvesAssumedRole(t *testing.T) {
// Pre-PrincipalType records have an empty value and must still resolve as assumed-role.
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
require.NoError(t, err)
cred := &handlers_sts.SessionCredential{
AccessKeyID: testSessionAKID,
@@ -2111,12 +2111,12 @@ func TestSigV4Auth_UnknownAKIDPrefix_NoLookup(t *testing.T) {
func TestSigV4Auth_AKIA_PrincipalTypeUser(t *testing.T) {
// Long-lived AKIA path must set ctxPrincipalType=user for correct policy gating.
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
require.NoError(t, err)
iamMock := &mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -2150,11 +2150,11 @@ func TestSigV4Auth_AKIA_PrincipalTypeUser(t *testing.T) {
func TestSigV4Auth_Session_STSServiceNil(t *testing.T) {
// Session AKID with nil STSService is a misconfiguration — must fail with InternalError.
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
require.NoError(t, err)
iamMock := &mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{},
accessKeys: map[string]*iamdomain.AccessKey{},
}
_ = encryptedSecret
gw := &GatewayConfig{
@@ -2184,7 +2184,7 @@ func TestSigV4Auth_Session_STSServiceNil(t *testing.T) {
// that grants nothing. The enforcement path must resolve the underlying role —
// never the SessionName — so the request is denied and GetUserPolicies is never called.
func TestCheckPolicy_SessionNameCollision(t *testing.T) {
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
require.NoError(t, err)
var userPoliciesCalled bool
@@ -2195,7 +2195,7 @@ func TestCheckPolicy_SessionNameCollision(t *testing.T) {
iamMock := &policyMockIAMService{
mockIAMService: mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
@@ -2205,11 +2205,11 @@ func TestCheckPolicy_SessionNameCollision(t *testing.T) {
},
},
},
getUserPoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
getUserPoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) {
userPoliciesCalled = true
return allowPolicy("ec2:*"), nil
},
getRolePoliciesFn: func(_, roleName string) ([]handlers_iam.PolicyDocument, error) {
getRolePoliciesFn: func(_, roleName string) ([]iamdomain.PolicyDocument, error) {
resolvedRoleName = roleName
return nil, nil
},
@@ -2254,18 +2254,18 @@ func TestCheckPolicy_SessionNameCollision(t *testing.T) {
}
// allowPolicy returns a single-statement Allow policy granting action on "*".
func allowPolicy(action string) []handlers_iam.PolicyDocument {
func allowPolicy(action string) []iamdomain.PolicyDocument {
return allowPolicyResource(action, "*")
}
// allowPolicyResource returns a single-statement Allow policy for action on resource.
func allowPolicyResource(action, resource string) []handlers_iam.PolicyDocument {
return []handlers_iam.PolicyDocument{{
func allowPolicyResource(action, resource string) []iamdomain.PolicyDocument {
return []iamdomain.PolicyDocument{{
Version: "2012-10-17",
Statement: []handlers_iam.Statement{{
Statement: []iamdomain.Statement{{
Effect: "Allow",
Action: handlers_iam.StringOrArr{action},
Resource: handlers_iam.StringOrArr{resource},
Action: iamdomain.StringOrArr{action},
Resource: iamdomain.StringOrArr{resource},
}},
}}
}
@@ -2288,16 +2288,16 @@ func assumedRoleSessionCred(sessionName, underlyingRoleARN, accountID string) *h
// newAssumedRoleEnforcementGateway wires a gateway for assumed-role checkPolicy tests.
// The user resolver fails the test if called — an assumed-role must never be evaluated as a user.
func newAssumedRoleEnforcementGateway(t *testing.T, cred *handlers_sts.SessionCredential,
getRoleFn func(accountID, roleName string) ([]handlers_iam.PolicyDocument, error),
getRoleFn func(accountID, roleName string) ([]iamdomain.PolicyDocument, error),
) *GatewayConfig {
t.Helper()
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
require.NoError(t, err)
cred.SecretEncrypted = encryptedSecret
iamMock := &policyMockIAMService{
mockIAMService: mockIAMService{masterKey: testMasterKey},
getUserPoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
getUserPoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) {
t.Errorf("priv-esc: assumed-role principal must not consult GetUserPolicies")
return nil, nil
},
@@ -2344,7 +2344,7 @@ func doSessionPolicyRequest(t *testing.T, handler http.Handler, akid string) *ht
// predastore's assumed-role S3 enforcement.
func TestCheckPolicy_AssumedRole_AllowedByRolePolicy(t *testing.T) {
cred := assumedRoleSessionCred("app", "arn:aws:iam::123456789012:role/app-role", "123456789012")
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, roleName string) ([]handlers_iam.PolicyDocument, error) {
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, roleName string) ([]iamdomain.PolicyDocument, error) {
require.Equal(t, "app-role", roleName)
return allowPolicy("ec2:RunInstances"), nil
})
@@ -2358,7 +2358,7 @@ func TestCheckPolicy_AssumedRole_AllowedByRolePolicy(t *testing.T) {
// action nor an explicit Deny, so the default deny applies.
func TestCheckPolicy_AssumedRole_ImplicitDeny(t *testing.T) {
cred := assumedRoleSessionCred("app", "arn:aws:iam::123456789012:role/app-role", "123456789012")
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return allowPolicy("ec2:DescribeInstances"), nil // does not cover RunInstances
})
@@ -2372,12 +2372,12 @@ func TestCheckPolicy_AssumedRole_ImplicitDeny(t *testing.T) {
// overrides any Allow.
func TestCheckPolicy_AssumedRole_ExplicitDeny(t *testing.T) {
cred := assumedRoleSessionCred("app", "arn:aws:iam::123456789012:role/app-role", "123456789012")
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
return []handlers_iam.PolicyDocument{{
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return []iamdomain.PolicyDocument{{
Version: "2012-10-17",
Statement: []handlers_iam.Statement{
{Effect: "Allow", Action: handlers_iam.StringOrArr{"ec2:*"}, Resource: handlers_iam.StringOrArr{"*"}},
{Effect: "Deny", Action: handlers_iam.StringOrArr{"ec2:RunInstances"}, Resource: handlers_iam.StringOrArr{"*"}},
Statement: []iamdomain.Statement{
{Effect: "Allow", Action: iamdomain.StringOrArr{"ec2:*"}, Resource: iamdomain.StringOrArr{"*"}},
{Effect: "Deny", Action: iamdomain.StringOrArr{"ec2:RunInstances"}, Resource: iamdomain.StringOrArr{"*"}},
},
}}, nil
})
@@ -2393,7 +2393,7 @@ func TestCheckPolicy_AssumedRole_ExplicitDeny(t *testing.T) {
// permissions.
func TestCheckPolicy_AssumedRole_ZeroPolicyRole_DenyAll(t *testing.T) {
cred := assumedRoleSessionCred("app", "arn:aws:iam::123456789012:role/app-role", "123456789012")
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return nil, nil // role exists, zero attached policies
})
@@ -2411,7 +2411,7 @@ func TestCheckPolicy_AssumedRole_SessionNamedRoot_NoBypass(t *testing.T) {
cred := assumedRoleSessionCred("root",
"arn:aws:iam::"+awsidentifiers.GlobalAccountID+":role/sneaky-role", awsidentifiers.GlobalAccountID)
var roleResolved bool
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, roleName string) ([]handlers_iam.PolicyDocument, error) {
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, roleName string) ([]iamdomain.PolicyDocument, error) {
roleResolved = true
require.Equal(t, "sneaky-role", roleName)
return nil, nil // role grants nothing
@@ -2440,7 +2440,7 @@ func TestCheckPolicy_AssumedRole_EdgeARNs_Denied(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cred := assumedRoleSessionCred("app", tc.underlyingRoleARN, "123456789012")
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]iamdomain.PolicyDocument, error) {
t.Errorf("role resolver must not be consulted for an edge-case ARN (%s)", tc.name)
return nil, nil
})
@@ -2457,7 +2457,7 @@ func TestCheckPolicy_AssumedRole_EdgeARNs_Denied(t *testing.T) {
// resolve error fails closed — never an allow-on-error.
func TestCheckPolicy_AssumedRole_ResolveError_InternalError(t *testing.T) {
cred := assumedRoleSessionCred("app", "arn:aws:iam::123456789012:role/app-role", "123456789012")
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return nil, errors.New(awserrors.ErrorIAMNoSuchEntity) // role deleted after mint
})
@@ -2473,7 +2473,7 @@ func TestCheckPolicy_AssumedRole_TransientNATS_RetriesThenFails(t *testing.T) {
shortenPolicyResolveRetry(t)
cred := assumedRoleSessionCred("app", "arn:aws:iam::123456789012:role/app-role", "123456789012")
var calls int
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]iamdomain.PolicyDocument, error) {
calls++
return nil, nats.ErrNoResponders
})
@@ -2491,7 +2491,7 @@ func TestCheckPolicy_AssumedRole_TransientNATS_RetriesThenFails(t *testing.T) {
func TestCheckPolicy_AssumedRole_PassRole_ScopedToTargetARN_Allowed(t *testing.T) {
const targetRoleARN = "arn:aws:iam::123456789012:role/instance-role"
cred := assumedRoleSessionCred("app", "arn:aws:iam::123456789012:role/launcher-role", "123456789012")
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return allowPolicyResource("iam:PassRole", targetRoleARN), nil
})
@@ -2506,7 +2506,7 @@ func TestCheckPolicy_AssumedRole_PassRole_ScopedToTargetARN_Allowed(t *testing.T
func TestCheckPolicy_AssumedRole_PassRole_ScopedToOtherARN_Denied(t *testing.T) {
const targetRoleARN = "arn:aws:iam::123456789012:role/instance-role"
cred := assumedRoleSessionCred("app", "arn:aws:iam::123456789012:role/launcher-role", "123456789012")
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return allowPolicyResource("iam:PassRole", "arn:aws:iam::123456789012:role/some-other-role"), nil
})
@@ -2523,7 +2523,7 @@ func TestCheckPolicy_AssumedRole_PassRole_ScopedToOtherARN_Denied(t *testing.T)
func TestCheckPolicy_AssumedRole_PassRole_WildcardResource_Allowed(t *testing.T) {
const targetRoleARN = "arn:aws:iam::123456789012:role/instance-role"
cred := assumedRoleSessionCred("app", "arn:aws:iam::123456789012:role/launcher-role", "123456789012")
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]handlers_iam.PolicyDocument, error) {
gw := newAssumedRoleEnforcementGateway(t, cred, func(_, _ string) ([]iamdomain.PolicyDocument, error) {
return allowPolicyResource("iam:PassRole", "*"), nil
})
@@ -2737,12 +2737,12 @@ func TestSigV4Auth_ServedScopeSignatureMismatchStillSignatureDoesNotMatch(t *tes
// so before the fix ctxAction stayed empty and every such request shared the
// throttle bucket "<account>:unknown", which no per-action limit can match.
func TestSigV4Auth_ResolvesCtxActionForNonQueryServices(t *testing.T) {
encryptedSecret, err := handlers_iam.EncryptSecret(testSecretKey, testMasterKey)
encryptedSecret, err := iamdomain.EncryptSecret(testSecretKey, testMasterKey)
require.NoError(t, err)
mockSvc := &mockIAMService{
masterKey: testMasterKey,
accessKeys: map[string]*handlers_iam.AccessKey{
accessKeys: map[string]*iamdomain.AccessKey{
testAccessKey: {
AccessKeyID: testAccessKey,
SecretAccessKey: encryptedSecret,
+3 -3
View File
@@ -5,8 +5,8 @@ import (
"errors"
"fmt"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/state/kvstore"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/nats-io/nats.go/jetstream"
)
@@ -63,7 +63,7 @@ func (s *CredentialStore) Resolve(ctx context.Context, accountID, vendor string)
entry, err := kv.Get(ctx, credentialKey(accountID, vendor))
switch {
case err == nil:
plaintext, err := handlers_iam.DecryptSecret(string(entry.Value()), s.masterKey)
plaintext, err := iamdomain.DecryptSecret(string(entry.Value()), s.masterKey)
if err != nil {
return "", false, fmt.Errorf("decrypt credential for %s/%s: %w", accountID, vendor, err)
}
@@ -84,7 +84,7 @@ func (s *CredentialStore) PutCredential(ctx context.Context, accountID, vendor,
if err != nil {
return err
}
ciphertext, err := handlers_iam.EncryptSecret(key, s.masterKey)
ciphertext, err := iamdomain.EncryptSecret(key, s.masterKey)
if err != nil {
return fmt.Errorf("encrypt credential for %s/%s: %w", accountID, vendor, err)
}
+3 -3
View File
@@ -6,7 +6,7 @@ import (
"testing"
"github.com/mulgadc/spinifex/internal/testkit"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -106,11 +106,11 @@ func TestEncryptDecryptSecret_RoundTrip(t *testing.T) {
key := fixedMasterKey()
plaintext := "sk-ant-test-secret"
ciphertext, err := handlers_iam.EncryptSecret(plaintext, key)
ciphertext, err := iamdomain.EncryptSecret(plaintext, key)
require.NoError(t, err)
assert.NotEqual(t, plaintext, ciphertext)
decrypted, err := handlers_iam.DecryptSecret(ciphertext, key)
decrypted, err := iamdomain.DecryptSecret(ciphertext, key)
require.NoError(t, err)
assert.Equal(t, plaintext, decrypted)
}
@@ -14,7 +14,7 @@ import (
"testing"
"github.com/mulgadc/bluebottle/pkg/iampolicy"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -176,7 +176,7 @@ func TestValidatePolicyDocument_AcceptsExactlyTheSupportedConditions(t *testing.
for _, key := range allConditionKeys {
for op, value := range withIfExists(operatorValues) {
doc := conditionDocument(t, op, key, value)
_, err := handlers_iam.ValidatePolicyDocument(doc)
_, err := iamdomain.ValidatePolicyDocument(doc)
if iampolicy.SupportedCondition(op, key) {
assert.NoError(t, err,
@@ -204,7 +204,7 @@ func TestValidatePolicyDocument_AcceptsExactlyTheSubstitutableVariables(t *testi
resourceDocument(t, "arn:aws:s3:::reports/"+reference+"/*"),
conditionDocument(t, iampolicy.OpStringLike, iampolicy.KeyS3Prefix, reference+"/*"),
} {
_, err := handlers_iam.ValidatePolicyDocument(doc)
_, err := iamdomain.ValidatePolicyDocument(doc)
if unresolvable {
assert.Error(t, err,
"the write path accepts %s, which the evaluator cannot resolve: the policy would "+
@@ -220,7 +220,7 @@ func TestValidatePolicyDocument_AcceptsExactlyTheSubstitutableVariables(t *testi
// A malformed reference resolves nowhere and is rejected on every path.
func TestValidatePolicyDocument_RejectsUnterminatedVariable(t *testing.T) {
_, err := handlers_iam.ValidatePolicyDocument(
_, err := iamdomain.ValidatePolicyDocument(
resourceDocument(t, "arn:aws:s3:::reports/"+iampolicy.VariablePrefix+iampolicy.KeyUsername))
assert.ErrorContains(t, err, "unterminated policy variable reference")
}
+11 -11
View File
@@ -16,8 +16,8 @@ import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/mulgadc/bluebottle/pkg/iampolicy"
iamdomain "github.com/mulgadc/spinifex/spinifex/domains/iam"
"github.com/mulgadc/spinifex/spinifex/foundation/aws/errors"
handlers_iam "github.com/mulgadc/spinifex/spinifex/handlers/iam"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -279,15 +279,15 @@ func TestRequestConditionKeys_SourceIPWithoutAuthMiddleware(t *testing.T) {
// conditionedPolicyIAMService serves one statement carrying cond, so a test can
// drive a real condition through checkPolicyResources.
func conditionedPolicyIAMService(effect string, cond map[string]map[string]handlers_iam.ConditionValue) *policyMockIAMService {
docs := []handlers_iam.PolicyDocument{{
func conditionedPolicyIAMService(effect string, cond map[string]map[string]iamdomain.ConditionValue) *policyMockIAMService {
docs := []iamdomain.PolicyDocument{{
Version: "2012-10-17",
Statement: []handlers_iam.Statement{
{Effect: "Allow", Action: handlers_iam.StringOrArr{"*"}, Resource: handlers_iam.StringOrArr{"*"}},
Statement: []iamdomain.Statement{
{Effect: "Allow", Action: iamdomain.StringOrArr{"*"}, Resource: iamdomain.StringOrArr{"*"}},
{
Effect: effect,
Action: handlers_iam.StringOrArr{"ec2:*"},
Resource: handlers_iam.StringOrArr{"*"},
Action: iamdomain.StringOrArr{"ec2:*"},
Resource: iamdomain.StringOrArr{"*"},
Condition: cond,
},
},
@@ -296,8 +296,8 @@ func conditionedPolicyIAMService(effect string, cond map[string]map[string]handl
docs[0].Statement = docs[0].Statement[1:]
}
return &policyMockIAMService{
getUserPoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) { return docs, nil },
getRolePoliciesFn: func(_, _ string) ([]handlers_iam.PolicyDocument, error) { return docs, nil },
getUserPoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) { return docs, nil },
getRolePoliciesFn: func(_, _ string) ([]iamdomain.PolicyDocument, error) { return docs, nil },
}
}
@@ -307,7 +307,7 @@ func conditionedPolicyIAMService(effect string, cond map[string]map[string]handl
func TestCheckPolicyResources_ConditionalAllowHonoursSourceIP(t *testing.T) {
gw := &GatewayConfig{
DisableLogging: true,
IAMService: conditionedPolicyIAMService("Allow", map[string]map[string]handlers_iam.ConditionValue{
IAMService: conditionedPolicyIAMService("Allow", map[string]map[string]iamdomain.ConditionValue{
iampolicy.OpIPAddress: {iampolicy.KeySourceIP: {"10.0.0.0/8"}},
}),
}
@@ -346,7 +346,7 @@ func TestCheckPolicyResources_ConditionalAllowHonoursSourceIP(t *testing.T) {
func TestCheckPolicyResources_ConditionalDenyHonoursSourceIP(t *testing.T) {
gw := &GatewayConfig{
DisableLogging: true,
IAMService: conditionedPolicyIAMService("Deny", map[string]map[string]handlers_iam.ConditionValue{
IAMService: conditionedPolicyIAMService("Deny", map[string]map[string]iamdomain.ConditionValue{
iampolicy.OpIPAddress: {iampolicy.KeySourceIP: {"203.0.113.0/24"}},
}),
}

Some files were not shown because too many files have changed in this diff Show More