From bd1b2a7e18c988bb5efbd8b7fd2dbb988308f36e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20K=C3=A4sser?= Date: Fri, 4 Dec 2026 15:32:44 +0100 Subject: [PATCH 1/2] feat: add DescribeKey (KMS) and ListCertificates (ACM) query types DescribeKey resolves a KMS key by key ID, key ARN, alias name or alias ARN to its metadata (notably the key ARN). Cloud Control's AWS::KMS::Alias lists every alias in the account and returns a key ID, not an ARN. ListCertificates reads all ACM certificate pages, matches the domainName filter exactly client-side, defaults to ISSUED, requests every key type (ACM's default silently drops all but RSA_1024/RSA_2048) and sorts newest notAfter first, ties by ARN. Cloud Control does not model ACM certificates and the Tagging API returns no domain names. --- README.md | 16 +- aws.go | 114 +++++++++ aws_test.go | 229 +++++++++++++++++- example/Makefile | 2 + example/README.md | 2 + example/composition-acm-certificates.yaml | 31 +++ example/composition-kms-key.yaml | 32 +++ example/definition.yaml | 5 +- go.mod | 2 + go.sum | 4 + input/v1beta1/input.go | 6 +- package/crossplane.yaml | 8 +- .../input/aws.fn.crossplane.io_inputs.yaml | 6 + 13 files changed, 448 insertions(+), 9 deletions(-) create mode 100644 example/composition-acm-certificates.yaml create mode 100644 example/composition-kms-key.yaml diff --git a/README.md b/README.md index 5e29115..d6ed69e 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ existing resources by tag. It is the AWS analog of Each composition pipeline step supplies an `Input` selecting a `queryType`. The result is written to `target` (`status.` or `context.`). -**Service-metadata** (direct EC2/STS/Service Quotas calls — no account setup): +**Service-metadata** (direct EC2/STS/Service Quotas/KMS/ACM calls — no account setup): | `queryType` | Returns | |---|---| @@ -27,6 +27,8 @@ result is written to `target` (`status.` or `context.`). | `DescribeSecurityGroupRules` | `[{securityGroupRuleId, securityGroupRuleArn, groupId, groupOwnerId, isEgress, ipProtocol, fromPort, toPort, cidrIpv4, cidrIpv6, prefixListId, referencedGroupId, referencedGroupUserId, referencedGroupVpcId, description, tags{}}]`. `filters` **required**: `group-id`, `security-group-rule-id`, `tag:` - this operation does **not** accept `vpc-id`; AWS errors on it only where the region holds rules, and returns `[]` otherwise. | | `ListServiceQuotas` | `[{quotaCode, quotaName, value, unit, adjustable, globalQuota}]` (all quotas for a `serviceCode`) | | `GetServiceQuota` | `{quotaCode, quotaName, value, unit, adjustable, globalQuota}` (a single quota; needs `serviceCode`+`quotaCode`) | +| `DescribeKey` | `{keyId, arn, keyState, enabled, keyManager, keyUsage, keySpec, description, creationDate}` for one KMS key. `parameters.keyId` **required**: a key ID, key ARN, alias name (`alias/platform/eks`) or alias ARN. | +| `ListCertificates` | `[{certificateArn, domainName, status, type, keyAlgorithm, inUse, notBefore, notAfter}]` (ACM), newest `notAfter` first, so `[0]` is the certificate to use mid-rotation. `filters`: only `domainName`, an exact client-side match (values OR'd). `parameters.statuses` (csv, default `ISSUED`); `parameters.keyTypes` (csv, default all key types - ACM's own default returns only `RSA_1024`/`RSA_2048`). | **Existing-resource inventory** (generic, no Config/Resource-Explorer setup): @@ -68,6 +70,16 @@ result is written to `target` (`status.` or `context.`). gives you the groups, then `DescribeSecurityGroupRules` filtered by those `group-id`s gives you their rules, since that second operation cannot filter by VPC. +- **`DescribeKey` / `ListCertificates`** - to resolve a KMS key ARN from an + alias, or the ACM certificate for a domain. Needs `kms:DescribeKey` and + `acm:ListCertificates` respectively. Cloud Control's `AWS::KMS::Alias` lists + every alias in the account and returns a key ID, not an ARN; ACM certificates + are not in Cloud Control, and the Tagging API returns no domain names. + `domainName` matches the certificate's primary domain exactly (a wildcard + certificate is `*.example.com`), not its other subject alternative names. + Both follow AWS on every reconcile. For resolve-once semantics use a + `status.*` target with `skipQueryWhenTargetHasData: true`: then a later alias + repoint or a newer certificate does not change an already-resolved value. Rule of thumb: *IDs by tag →* `GetResources`; *attributes / full inventory of a type →* `ListResources`; *EC2 identifiers CloudFormation does not model, or an @@ -96,6 +108,8 @@ filters: # or filtersRef: (status./context parameters: # or parametersRef: ; scalar args per queryType: # allRegions, allAvailabilityZones (bool); owners, imageIds (csv) [EC2] # serviceCode, quotaCode [Service Quotas] + # keyId [KMS] + # statuses, keyTypes (csv) [ACM] # typeName, resourceModel, roleArn, hydrate (default true) [Cloud Control] # resourceTypeFilters (csv) [Tagging API] typeName: "AWS::EC2::VPC" diff --git a/aws.go b/aws.go index 86f94ff..c0f020c 100644 --- a/aws.go +++ b/aws.go @@ -1,21 +1,26 @@ package main import ( + "cmp" "context" "encoding/json" "fmt" "slices" "strconv" "strings" + "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/aws/retry" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/credentials/stscreds" + "github.com/aws/aws-sdk-go-v2/service/acm" + acmtypes "github.com/aws/aws-sdk-go-v2/service/acm/types" "github.com/aws/aws-sdk-go-v2/service/cloudcontrol" "github.com/aws/aws-sdk-go-v2/service/ec2" ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" + "github.com/aws/aws-sdk-go-v2/service/kms" "github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi" rgttypes "github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi/types" "github.com/aws/aws-sdk-go-v2/service/servicequotas" @@ -63,6 +68,8 @@ func (q *AWSQuery) registry() map[string]handler { "DescribeSecurityGroupRules": q.describeSecurityGroupRules, "ListServiceQuotas": q.listServiceQuotas, "GetServiceQuota": q.getServiceQuota, + "DescribeKey": q.describeKey, + "ListCertificates": q.listCertificates, "ListResources": q.listResources, "GetResources": q.getResources, } @@ -616,6 +623,96 @@ func quotaToMap(quota sqtypes.ServiceQuota) map[string]any { return m } +// describeKey resolves a KMS key by key ID, key ARN, alias name or alias ARN +// (KMS accepts all four as KeyId) to its metadata, notably the key ARN. +func (q *AWSQuery) describeKey(ctx context.Context, cfg aws.Config, in *v1beta1.Input) (any, error) { + if cfg.Region == "" { + return nil, errRegionRequired("DescribeKey") + } + keyID := in.Parameters["keyId"] + if keyID == "" { + return nil, errors.New("DescribeKey requires parameters.keyId (a key ID, key ARN, alias name such as \"alias/platform/eks\", or alias ARN)") + } + out, err := kms.NewFromConfig(cfg).DescribeKey(ctx, &kms.DescribeKeyInput{KeyId: aws.String(keyID)}) + if err != nil { + return nil, errors.Wrapf(err, "DescribeKey %s failed", keyID) + } + if out.KeyMetadata == nil { + return map[string]any{}, nil + } + k := out.KeyMetadata + return map[string]any{ + "keyId": aws.ToString(k.KeyId), + "arn": aws.ToString(k.Arn), + "keyState": string(k.KeyState), + "enabled": k.Enabled, + "keyManager": string(k.KeyManager), + "keyUsage": string(k.KeyUsage), + "keySpec": string(k.KeySpec), + "description": aws.ToString(k.Description), + "creationDate": rfc3339(k.CreationDate), + }, nil +} + +// listCertificates lists ACM certificates (paginated), optionally narrowed to +// exact domain names client-side: ListCertificates has no domain filter, Cloud +// Control does not model certificates, and the Tagging API returns no domain. +func (q *AWSQuery) listCertificates(ctx context.Context, cfg aws.Config, in *v1beta1.Input) (any, error) { + if cfg.Region == "" { + return nil, errRegionRequired("ListCertificates") + } + for _, f := range in.Filters { + if f.Name != "domainName" { + return nil, errors.Errorf("ListCertificates supports only the domainName filter, got %q", f.Name) + } + } + statuses := csv(in.Parameters["statuses"]) + if len(statuses) == 0 { + statuses = []string{string(acmtypes.CertificateStatusIssued)} + } + // ACM's default returns only RSA_1024/RSA_2048 certificates, which would + // silently hide an EC or RSA_4096 certificate for the domain. + keyTypes := acmtypes.KeyAlgorithm("").Values() + if v := csv(in.Parameters["keyTypes"]); len(v) > 0 { + keyTypes = toEnums[acmtypes.KeyAlgorithm](v) + } + p := acm.NewListCertificatesPaginator(acm.NewFromConfig(cfg), &acm.ListCertificatesInput{ + CertificateStatuses: toEnums[acmtypes.CertificateStatus](statuses), + Includes: &acmtypes.Filters{KeyTypes: keyTypes}, + }) + var certs []acmtypes.CertificateSummary + for p.HasMorePages() { + page, err := p.NextPage(ctx) + if err != nil { + return nil, errors.Wrap(err, "ListCertificates failed") + } + certs = append(certs, page.CertificateSummaryList...) + } + // Newest notAfter first, so mid-rotation [0] is the certificate to use; the + // ARN tie-break keeps the output stable across reconciles. + slices.SortFunc(certs, func(a, b acmtypes.CertificateSummary) int { + return cmp.Or(aws.ToTime(b.NotAfter).Compare(aws.ToTime(a.NotAfter)), + strings.Compare(aws.ToString(a.CertificateArn), aws.ToString(b.CertificateArn))) + }) + res := []any{} + for _, c := range certs { + m := map[string]any{ + "certificateArn": aws.ToString(c.CertificateArn), + "domainName": aws.ToString(c.DomainName), + "status": string(c.Status), + "type": string(c.Type), + "keyAlgorithm": string(c.KeyAlgorithm), + "inUse": aws.ToBool(c.InUse), + "notBefore": rfc3339(c.NotBefore), + "notAfter": rfc3339(c.NotAfter), + } + if matchesClientFilters(m, in.Filters) { + res = append(res, m) + } + } + return res, nil +} + // listResources lists resources of a CloudFormation-modeled type (Cloud Control, // paginated) and applies client-side filters. ListResources itself returns only // the primary identifier (plus a thin subset of properties) for most types, so @@ -799,6 +896,23 @@ func ec2TagsToMap(tags []ec2types.Tag) map[string]any { return out } +// rfc3339 formats an optional AWS timestamp; an absent one is "", not year 1. +func rfc3339(t *time.Time) string { + if t == nil { + return "" + } + return t.UTC().Format(time.RFC3339) +} + +// toEnums converts CSV-split parameter values to an SDK enum type. +func toEnums[T ~string](values []string) []T { + out := make([]T, 0, len(values)) + for _, v := range values { + out = append(out, T(v)) + } + return out +} + // putInt32 sets key only when v is set, so an absent value is not a real zero. func putInt32(m map[string]any, key string, v *int32) { if v != nil { diff --git a/aws_test.go b/aws_test.go index a0c3990..6484cd7 100644 --- a/aws_test.go +++ b/aws_test.go @@ -791,9 +791,10 @@ func TestEc2RouteTablesPaginates(t *testing.T) { } // Isolates the region guard: the shared guards table only asserts err != nil, -// which the SDK's endpoint-resolution error satisfies on its own. +// which the SDK's endpoint-resolution error satisfies on its own. DescribeKey +// and ListCertificates share the guard; it runs before their own validation. func TestEc2RegionGuard(t *testing.T) { - for _, queryType := range ec2QueryTypes { + for _, queryType := range append(ec2QueryTypes, "DescribeKey", "ListCertificates") { t.Run(queryType, func(t *testing.T) { h := newQuery().registry()[queryType] _, err := h(context.Background(), aws.Config{}, ec2Input(queryType)) @@ -959,6 +960,230 @@ func TestPutInt32(t *testing.T) { } } +// --- KMS and ACM ------------------------------------------------------------ + +const ( + describeKeyBody = `{"KeyMetadata":{"AWSAccountId":"123456789012","KeyId":"1234abcd-12ab-34cd-56ef-1234567890ab",` + + `"Arn":"arn:aws:kms:eu-central-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab",` + + `"CreationDate":1700000000,"Enabled":true,"Description":"EKS secrets","KeyUsage":"ENCRYPT_DECRYPT",` + + `"KeyState":"Enabled","Origin":"AWS_KMS","KeyManager":"CUSTOMER","KeySpec":"SYMMETRIC_DEFAULT"}}` + + // Page 1 holds the oldest wildcard certificate and one for another domain; + // page 2 holds its renewal (newer notAfter) and an apex certificate whose + // notAfter ties with the oldest one, so the ARN tie-break is exercised. + certificatesPage1 = `{"NextToken":"tok","CertificateSummaryList":[` + + `{"CertificateArn":"arn:aws:acm:eu-central-1:123456789012:certificate/a","DomainName":"*.example.com",` + + `"Status":"ISSUED","Type":"AMAZON_ISSUED","KeyAlgorithm":"RSA-2048","InUse":true,"NotBefore":1700000000,"NotAfter":1730000000},` + + `{"CertificateArn":"arn:aws:acm:eu-central-1:123456789012:certificate/b","DomainName":"api.example.org",` + + `"Status":"ISSUED","Type":"AMAZON_ISSUED","KeyAlgorithm":"RSA-2048","InUse":false,"NotBefore":1700000000,"NotAfter":1740000000}]}` + certificatesPage2 = `{"CertificateSummaryList":[` + + `{"CertificateArn":"arn:aws:acm:eu-central-1:123456789012:certificate/d","DomainName":"example.com",` + + `"Status":"ISSUED","Type":"IMPORTED","KeyAlgorithm":"RSA-2048","InUse":false,"NotBefore":1700000000,"NotAfter":1730000000},` + + `{"CertificateArn":"arn:aws:acm:eu-central-1:123456789012:certificate/c","DomainName":"*.example.com",` + + `"Status":"ISSUED","Type":"AMAZON_ISSUED","KeyAlgorithm":"EC-prime256v1","InUse":false,"NotBefore":1720000000,"NotAfter":1750000000}]}` +) + +func jsonStub(bodies ...string) *respStub { + return &respStub{bodies: bodies, contentType: "application/x-amz-json-1.1"} +} + +// TestDescribeKey resolves an alias name to the key's metadata, notably its ARN. +func TestDescribeKey(t *testing.T) { + stub := jsonStub(describeKeyBody) + in := &v1beta1.Input{Parameters: map[string]string{"keyId": "alias/platform/eks"}} + got, err := newQuery().registry()["DescribeKey"](context.Background(), stubCfg(stub), in) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + want := map[string]any{ + "keyId": "1234abcd-12ab-34cd-56ef-1234567890ab", + "arn": "arn:aws:kms:eu-central-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab", + "keyState": "Enabled", "enabled": true, "keyManager": "CUSTOMER", "keyUsage": "ENCRYPT_DECRYPT", + "keySpec": "SYMMETRIC_DEFAULT", "description": "EKS secrets", "creationDate": "2023-11-14T22:13:20Z", + } + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("-want +got:\n%s", diff) + } + if len(stub.requests) != 1 || !strings.Contains(stub.requests[0], `"KeyId":"alias/platform/eks"`) { + t.Errorf("alias not sent as KeyId: %v", stub.requests) + } +} + +// TestDescribeKeyRequiresKeyID: without a keyId there is nothing to describe, +// so a missing or empty one is fatal and names the parameter. +func TestDescribeKeyRequiresKeyID(t *testing.T) { + for name, params := range map[string]map[string]string{"Missing": nil, "Empty": {"keyId": ""}} { + t.Run(name, func(t *testing.T) { + stub := jsonStub(describeKeyBody) + _, err := newQuery().describeKey(context.Background(), stubCfg(stub), &v1beta1.Input{Parameters: params}) + if err == nil || !strings.Contains(err.Error(), "parameters.keyId") { + t.Errorf("expected an error naming parameters.keyId, got: %v", err) + } + if len(stub.requests) != 0 { + t.Errorf("expected no AWS call, got %d", len(stub.requests)) + } + }) + } +} + +// TestListCertificates reads every page, keeps only exact domainName matches +// (values OR'd), and sorts newest notAfter first, ties by ARN. +func TestListCertificates(t *testing.T) { + stub := jsonStub(certificatesPage1, certificatesPage2) + in := &v1beta1.Input{Filters: []v1beta1.Filter{{Name: "domainName", Values: []string{"*.example.com", "example.com"}}}} + got, err := newQuery().registry()["ListCertificates"](context.Background(), stubCfg(stub), in) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + cert := func(id, domain, typ, alg string, inUse bool, notBefore, notAfter string) map[string]any { + return map[string]any{ + "certificateArn": "arn:aws:acm:eu-central-1:123456789012:certificate/" + id, "domainName": domain, + "status": "ISSUED", "type": typ, "keyAlgorithm": alg, "inUse": inUse, "notBefore": notBefore, "notAfter": notAfter, + } + } + want := []any{ + cert("c", "*.example.com", "AMAZON_ISSUED", "EC-prime256v1", false, "2024-07-03T09:46:40Z", "2025-06-15T15:06:40Z"), + cert("a", "*.example.com", "AMAZON_ISSUED", "RSA-2048", true, "2023-11-14T22:13:20Z", "2024-10-27T03:33:20Z"), + cert("d", "example.com", "IMPORTED", "RSA-2048", false, "2023-11-14T22:13:20Z", "2024-10-27T03:33:20Z"), + } + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("-want +got:\n%s", diff) + } + if len(stub.requests) != 2 || !strings.Contains(stub.requests[1], `"NextToken":"tok"`) { + t.Errorf("expected a second request carrying NextToken, got: %v", stub.requests) + } +} + +// TestListCertificatesRequest pins what goes server-side: ISSUED and every key +// type by default (ACM's own default silently drops all but RSA_1024/RSA_2048), +// narrowed by parameters.statuses / parameters.keyTypes. +func TestListCertificatesRequest(t *testing.T) { + allKeyTypes := []any{"RSA_1024", "RSA_2048", "RSA_3072", "RSA_4096", "EC_prime256v1", "EC_secp384r1", "EC_secp521r1"} + cases := map[string]struct { + params map[string]string + want map[string]any + }{ + "Defaults": {want: map[string]any{ + "CertificateStatuses": []any{"ISSUED"}, "Includes": map[string]any{"keyTypes": allKeyTypes}, + }}, + "Narrowed": { + params: map[string]string{"statuses": "ISSUED, PENDING_VALIDATION", "keyTypes": "EC_prime256v1"}, + want: map[string]any{ + "CertificateStatuses": []any{"ISSUED", "PENDING_VALIDATION"}, "Includes": map[string]any{"keyTypes": []any{"EC_prime256v1"}}, + }, + }, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + stub := jsonStub(`{"CertificateSummaryList":[]}`) + if _, err := newQuery().listCertificates(context.Background(), stubCfg(stub), &v1beta1.Input{Parameters: tc.params}); err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(stub.requests) != 1 { + t.Fatalf("expected 1 request, got %d", len(stub.requests)) + } + got := map[string]any{} + if err := json.Unmarshal([]byte(stub.requests[0]), &got); err != nil { + t.Fatalf("request is not JSON: %v", err) + } + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("-want +got:\n%s", diff) + } + }) + } +} + +// TestListCertificatesRejectsUnknownFilter: domainName is the only filter, so +// any other name (e.g. the EC2-style "domain-name") is fatal, not ignored. +func TestListCertificatesRejectsUnknownFilter(t *testing.T) { + stub := jsonStub(certificatesPage1) + in := &v1beta1.Input{Filters: []v1beta1.Filter{{Name: "domain-name", Values: []string{"*.example.com"}}}} + _, err := newQuery().listCertificates(context.Background(), stubCfg(stub), in) + if err == nil || !strings.Contains(err.Error(), `"domain-name"`) { + t.Errorf("expected an error naming the unsupported filter, got: %v", err) + } + if len(stub.requests) != 0 { + t.Errorf("expected no AWS call, got %d", len(stub.requests)) + } +} + +// TestKMSACMAPIError pins that an AWS-side failure surfaces wrapped with the +// operation name (and, for DescribeKey, the keyId) and the AWS error code. +func TestKMSACMAPIError(t *testing.T) { + cases := map[string]struct { + in *v1beta1.Input + code string + want string + }{ + "DescribeKey": {in: &v1beta1.Input{Parameters: map[string]string{"keyId": "alias/platform/eks"}}, code: "NotFoundException", want: "DescribeKey alias/platform/eks failed"}, + "ListCertificates": {in: &v1beta1.Input{}, code: "AccessDeniedException", want: "ListCertificates failed"}, + } + for queryType, tc := range cases { + t.Run(queryType, func(t *testing.T) { + stub := jsonStub(fmt.Sprintf(`{"__type":%q,"message":"denied"}`, tc.code)) + stub.status = http.StatusBadRequest + got, err := newQuery().registry()[queryType](context.Background(), stubCfg(stub), tc.in) + if err == nil { + t.Fatalf("expected an error, got result %#v", got) + } + for _, want := range []string{tc.want, tc.code} { + if !strings.Contains(err.Error(), want) { + t.Errorf("expected %q in error, got: %v", want, err) + } + } + }) + } +} + +// TestRunFunctionKMSACMTargets runs the real handlers through RunFunction into +// status and context targets (keyId via parametersRef). queryIntervalMinutes +// applies to status targets only: the single DescribeKey object gets a +// lastQueryTime field, the ListCertificates list a trailing {lastQueryTime}. +func TestRunFunctionKMSACMTargets(t *testing.T) { + bodies := map[string]string{"DescribeKey": describeKeyBody, "ListCertificates": certificatesPage2} + f := &Function{log: logging.NewNopLogger(), awsQuery: &MockAWSQuery{fn: func(ctx context.Context, _ map[string][]byte, in *v1beta1.Input) (any, error) { + return newQuery().registry()[in.QueryType](ctx, stubCfg(jsonStub(bodies[in.QueryType])), in) + }}} + const keyARN = "arn:aws:kms:eu-central-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" + const certARN = "arn:aws:acm:eu-central-1:123456789012:certificate/c" + cases := map[string]struct{ queryType, target, field, want string }{ + "DescribeKeyStatus": {queryType: "DescribeKey", target: "status.kmsKey", field: "arn", want: keyARN}, + "DescribeKeyContext": {queryType: "DescribeKey", target: "context.kmsKey", field: "arn", want: keyARN}, + "ListCertificatesStatus": {queryType: "ListCertificates", target: "status.certificates", field: "certificateArn", want: certARN}, + "ListCertificatesContext": {queryType: "ListCertificates", target: "context.certificates", field: "certificateArn", want: certARN}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + rsp, err := f.RunFunction(context.Background(), &fnv1.RunFunctionRequest{ + Meta: &fnv1.RequestMeta{Tag: "test"}, + Input: resource.MustStructJSON(fmt.Sprintf(`{"apiVersion":"aws.fn.crossplane.io/v1beta1","kind":"Input", + "queryType":%q,"parametersRef":"spec.kms","target":%q,"queryIntervalMinutes":10}`, tc.queryType, tc.target)), + Observed: &fnv1.State{Composite: &fnv1.Resource{Resource: resource.MustStructJSON( + `{"apiVersion":"example.org/v1","kind":"XR","metadata":{"name":"test"},"spec":{"kms":{"keyId":"alias/platform/eks"}}}`)}}, + }) + if err != nil || hasFatal(rsp) { + t.Fatalf("unexpected failure: %v %v", err, rsp.GetResults()) + } + root, path, _ := strings.Cut(tc.target, ".") + data := rsp.GetContext().AsMap() + if root == "status" { + data, _ = rsp.GetDesired().GetComposite().GetResource().AsMap()["status"].(map[string]any) + } + v, _ := GetNestedValue(data, path) + first, last := v, v // a list's newest entry and its appended marker + if l, ok := v.([]any); ok && len(l) > 0 { + first, last = l[0], l[len(l)-1] + } + if got, _ := first.(map[string]any); got[tc.field] != tc.want { + t.Errorf("%s = %v, want %s %s first", tc.target, v, tc.field, tc.want) + } + if stamped, _ := last.(map[string]any); root == "status" && stamped["lastQueryTime"] == nil { + t.Errorf("%s = %v, want a lastQueryTime", tc.target, v) + } + }) + } +} + // --- dispatch + remaining skip paths ---------------------------------------- func TestAWSQueryUnsupportedType(t *testing.T) { diff --git a/example/Makefile b/example/Makefile index 267af14..2be28c2 100644 --- a/example/Makefile +++ b/example/Makefile @@ -43,6 +43,8 @@ ec2-route-tables|xr.yaml|composition-ec2-route-tables.yaml| ec2-subnets|xr.yaml|composition-ec2-subnets.yaml| ec2-security-groups|xr.yaml|composition-ec2-security-groups.yaml| ec2-security-group-rules|xr.yaml|composition-ec2-security-group-rules.yaml| +kms-key|xr.yaml|composition-kms-key.yaml| +acm-certificates|xr.yaml|composition-acm-certificates.yaml| dynamic-refs|xr-dynamic.yaml|composition-dynamic-refs.yaml| dynamic-context|xr.yaml|composition-dynamic-context.yaml|--context-values='$(CTX)' endef diff --git a/example/README.md b/example/README.md index c8954b9..0d0c4d4 100644 --- a/example/README.md +++ b/example/README.md @@ -52,6 +52,8 @@ status: | `composition-ec2-security-groups.yaml` | DescribeSecurityGroups | EC2 | `status.securityGroups` | | `composition-ec2-security-group-rules.yaml` | DescribeSecurityGroupRules | EC2 | `status.securityGroupRules` | | `composition-service-quotas.yaml` | ListServiceQuotas | Service Quotas | `status.ec2Quotas` | +| `composition-kms-key.yaml` | DescribeKey | KMS | `status.kmsKey` | +| `composition-acm-certificates.yaml` | ListCertificates | ACM | `context.certificates` | | `composition-cloudcontrol-vpcs.yaml` | ListResources | Cloud Control | `status.prodVpcs` | | `composition-cloudcontrol-ids.yaml` | ListResources (`hydrate=false`) | Cloud Control | `status.vpcIds` | | `composition-tagging-subnets.yaml` | GetResources | Resource Groups Tagging API | `context.subnets` | diff --git a/example/composition-acm-certificates.yaml b/example/composition-acm-certificates.yaml new file mode 100644 index 0000000..b4cb40c --- /dev/null +++ b/example/composition-acm-certificates.yaml @@ -0,0 +1,31 @@ +apiVersion: apiextensions.crossplane.io/v1 +kind: Composition +metadata: + name: function-aws-query-acm-certificates +spec: + compositeTypeRef: + apiVersion: example.io/v1alpha1 + kind: XAccount + mode: Pipeline + pipeline: + # The ISSUED wildcard certificate for an ALB listener. The domainName match is + # exact and client-side; results are newest notAfter first, so a later step + # takes [0].certificateArn from context.certificates. + - step: wildcard-certificate + functionRef: + name: function-aws-query + input: + apiVersion: aws.fn.crossplane.io/v1beta1 + kind: Input + queryType: ListCertificates + region: eu-central-1 + filters: + - name: domainName + values: ["*.example.com"] + target: context.certificates + credentials: + - name: aws-creds + source: Secret + secretRef: + namespace: crossplane-system + name: aws-creds diff --git a/example/composition-kms-key.yaml b/example/composition-kms-key.yaml new file mode 100644 index 0000000..3624270 --- /dev/null +++ b/example/composition-kms-key.yaml @@ -0,0 +1,32 @@ +apiVersion: apiextensions.crossplane.io/v1 +kind: Composition +metadata: + name: function-aws-query-kms-key +spec: + compositeTypeRef: + apiVersion: example.io/v1alpha1 + kind: XAccount + mode: Pipeline + pipeline: + # The key ARN behind a well-known alias, e.g. for EKS secrets encryption or EBS + # volumes. KMS resolves the alias server-side; a key ID, key ARN or alias ARN + # work as keyId too. skipQueryWhenTargetHasData makes it resolve-once: a later + # alias repoint does not change status.kmsKey. + - step: kms-key-by-alias + functionRef: + name: function-aws-query + input: + apiVersion: aws.fn.crossplane.io/v1beta1 + kind: Input + queryType: DescribeKey + region: eu-central-1 + parameters: + keyId: alias/platform/eks + target: status.kmsKey + skipQueryWhenTargetHasData: true + credentials: + - name: aws-creds + source: Secret + secretRef: + namespace: crossplane-system + name: aws-creds diff --git a/example/definition.yaml b/example/definition.yaml index aaaff68..6002db1 100644 --- a/example/definition.yaml +++ b/example/definition.yaml @@ -92,7 +92,10 @@ spec: items: type: object x-kubernetes-preserve-unknown-fields: true - # GetCallerIdentity returns one object, not a list. + # GetCallerIdentity and DescribeKey return one object, not a list. callerIdentity: type: object x-kubernetes-preserve-unknown-fields: true + kmsKey: + type: object + x-kubernetes-preserve-unknown-fields: true diff --git a/go.mod b/go.mod index f8e9423..6bceaa2 100644 --- a/go.mod +++ b/go.mod @@ -9,8 +9,10 @@ require ( github.com/aws/aws-sdk-go-v2 v1.48.0 github.com/aws/aws-sdk-go-v2/config v1.33.21 github.com/aws/aws-sdk-go-v2/credentials v1.21.3 + github.com/aws/aws-sdk-go-v2/service/acm v1.52.0 github.com/aws/aws-sdk-go-v2/service/cloudcontrol v1.38.12 github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0 + github.com/aws/aws-sdk-go-v2/service/kms v1.63.0 github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.42.0 github.com/aws/aws-sdk-go-v2/service/servicequotas v1.43.12 github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 diff --git a/go.sum b/go.sum index 6f94ca0..3259b08 100644 --- a/go.sum +++ b/go.sum @@ -26,6 +26,8 @@ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosIm github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI= +github.com/aws/aws-sdk-go-v2/service/acm v1.52.0 h1:jE6EjC+CeVPthk8lD0Z9H+D/hV8fFw3IPA88sSQsTHA= +github.com/aws/aws-sdk-go-v2/service/acm v1.52.0/go.mod h1:X+vU8ajhUQBywA7lCt6KDD+6jmOmYpWY/jIv/niZgRM= github.com/aws/aws-sdk-go-v2/service/cloudcontrol v1.38.12 h1:yYR4Yja/z8MmF2BOys5xc/A4B7S0BDP8l8BcfHuZsck= github.com/aws/aws-sdk-go-v2/service/cloudcontrol v1.38.12/go.mod h1:C9ZmYvltZXzDsKv0niSaxxibSdjeVecwT9wTVZQuPbM= github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.0 h1:EjAV+HmAnHedN+iYZF+b4SQYtMGlMdjURLbZc3q32fs= @@ -34,6 +36,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3 github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I= github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI= +github.com/aws/aws-sdk-go-v2/service/kms v1.63.0 h1:Ovjb0ZSWfm+hPYFgU9BX0Oy7C/ob3EXbCrUUHo9Is98= +github.com/aws/aws-sdk-go-v2/service/kms v1.63.0/go.mod h1:VMuZyNobzmV/0SRCH5p+0dziD4U5AktOi3TzFMXq1rg= github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.42.0 h1:C5MObSLa6vuu51AjmcOTwNDr1V0RWZTW57ALHSDllpM= github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.42.0/go.mod h1:j8qpULzMbJIUNh9S5aAM5SVldIxb/pYMpis+cGBhOpA= github.com/aws/aws-sdk-go-v2/service/servicequotas v1.43.12 h1:gxMPx0ZFxIOZUO30v+Lp/hpifZQC42FuTTXGe1wiVyY= diff --git a/input/v1beta1/input.go b/input/v1beta1/input.go index 8fb97fe..6a030ec 100644 --- a/input/v1beta1/input.go +++ b/input/v1beta1/input.go @@ -21,7 +21,7 @@ type Input struct { metav1.ObjectMeta `json:"metadata,omitempty"` // QueryType selects the AWS read operation to perform. - // +kubebuilder:validation:Enum=GetCallerIdentity;DescribeRegions;DescribeAvailabilityZones;DescribeImages;DescribeRouteTables;DescribeSubnets;DescribeSecurityGroups;DescribeSecurityGroupRules;ListServiceQuotas;GetServiceQuota;ListResources;GetResources + // +kubebuilder:validation:Enum=GetCallerIdentity;DescribeRegions;DescribeAvailabilityZones;DescribeImages;DescribeRouteTables;DescribeSubnets;DescribeSecurityGroups;DescribeSecurityGroupRules;ListServiceQuotas;GetServiceQuota;DescribeKey;ListCertificates;ListResources;GetResources QueryType string `json:"queryType"` // Region to target. Optional for global-ish calls (GetCallerIdentity, @@ -50,6 +50,8 @@ type Input struct { // "security-group-rule-id", "tag:". Unlike DescribeSecurityGroups, // this operation does NOT accept "vpc-id"; AWS errors on it only where // the region holds rules, and returns an empty list otherwise. + // - ListCertificates (ACM): only "domainName", an exact client-side match + // on the certificate's domain name. Any other name is fatal. // - GetResources (Tagging API): each entry is a tag filter where name is // the tag key and values are the tag values (server-side). // - ListResources (Cloud Control): client-side property match where name @@ -66,6 +68,8 @@ type Input struct { // Parameters carries scalar/string-list args specific to each QueryType: // allRegions, allAvailabilityZones (bool); owners, imageIds (csv) [EC2] // serviceCode, quotaCode [ServiceQuotas] + // keyId (key ID, key ARN, alias name or alias ARN) [KMS] + // statuses (csv, default ISSUED), keyTypes (csv, default all) [ACM] // typeName (e.g. AWS::EC2::VPC), resourceModel (json), roleArn, // hydrate (bool, default true: GetResource each item for full props) [Cloud Control] // resourceTypeFilters (csv, e.g. "ec2:vpc,ec2:subnet") [Tagging API] diff --git a/package/crossplane.yaml b/package/crossplane.yaml index 3a677cb..878e9ac 100644 --- a/package/crossplane.yaml +++ b/package/crossplane.yaml @@ -13,10 +13,10 @@ metadata: exposes the results as structured data to downstream composition steps (go-templating, patch-and-transform, etc.). It supports service-metadata queries (caller identity, regions, availability zones, AMI lookups, service - quotas) and generic existing-resource discovery (AWS Cloud Control - ListResources, the Resource Groups Tagging API GetResources, and direct - EC2 describes for route tables, subnets, security groups and security - group rules). + quotas, KMS keys by alias, ACM certificates by domain) and generic + existing-resource discovery (AWS Cloud Control ListResources, the Resource + Groups Tagging API GetResources, and direct EC2 describes for route + tables, subnets, security groups and security group rules). Authentication mirrors the Official AWS Provider: the credentials secret is a shared-credentials INI compatible with provider-upjet-aws, and the diff --git a/package/input/aws.fn.crossplane.io_inputs.yaml b/package/input/aws.fn.crossplane.io_inputs.yaml index e1068ca..9114975 100644 --- a/package/input/aws.fn.crossplane.io_inputs.yaml +++ b/package/input/aws.fn.crossplane.io_inputs.yaml @@ -48,6 +48,8 @@ spec: "security-group-rule-id", "tag:". Unlike DescribeSecurityGroups, this operation does NOT accept "vpc-id"; AWS errors on it only where the region holds rules, and returns an empty list otherwise. + - ListCertificates (ACM): only "domainName", an exact client-side match + on the certificate's domain name. Any other name is fatal. - GetResources (Tagging API): each entry is a tag filter where name is the tag key and values are the tag values (server-side). - ListResources (Cloud Control): client-side property match where name @@ -184,6 +186,8 @@ spec: Parameters carries scalar/string-list args specific to each QueryType: allRegions, allAvailabilityZones (bool); owners, imageIds (csv) [EC2] serviceCode, quotaCode [ServiceQuotas] + keyId (key ID, key ARN, alias name or alias ARN) [KMS] + statuses (csv, default ISSUED), keyTypes (csv, default all) [ACM] typeName (e.g. AWS::EC2::VPC), resourceModel (json), roleArn, hydrate (bool, default true: GetResource each item for full props) [Cloud Control] resourceTypeFilters (csv, e.g. "ec2:vpc,ec2:subnet") [Tagging API] @@ -212,6 +216,8 @@ spec: - DescribeSecurityGroupRules - ListServiceQuotas - GetServiceQuota + - DescribeKey + - ListCertificates - ListResources - GetResources type: string From b88f9803f3f8080d4292feab327e4bec7a340437 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20K=C3=A4sser?= Date: Fri, 4 Dec 2026 23:01:02 +0100 Subject: [PATCH 2/2] test: prove ListCertificates ARN tie-break and fail fast on unknown filter --- aws_test.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/aws_test.go b/aws_test.go index 6484cd7..364b639 100644 --- a/aws_test.go +++ b/aws_test.go @@ -970,9 +970,10 @@ const ( // Page 1 holds the oldest wildcard certificate and one for another domain; // page 2 holds its renewal (newer notAfter) and an apex certificate whose - // notAfter ties with the oldest one, so the ARN tie-break is exercised. + // notAfter ties with the oldest one but whose ARN sorts lower, so only the + // ARN tie-break puts it first. certificatesPage1 = `{"NextToken":"tok","CertificateSummaryList":[` + - `{"CertificateArn":"arn:aws:acm:eu-central-1:123456789012:certificate/a","DomainName":"*.example.com",` + + `{"CertificateArn":"arn:aws:acm:eu-central-1:123456789012:certificate/e","DomainName":"*.example.com",` + `"Status":"ISSUED","Type":"AMAZON_ISSUED","KeyAlgorithm":"RSA-2048","InUse":true,"NotBefore":1700000000,"NotAfter":1730000000},` + `{"CertificateArn":"arn:aws:acm:eu-central-1:123456789012:certificate/b","DomainName":"api.example.org",` + `"Status":"ISSUED","Type":"AMAZON_ISSUED","KeyAlgorithm":"RSA-2048","InUse":false,"NotBefore":1700000000,"NotAfter":1740000000}]}` @@ -1043,8 +1044,8 @@ func TestListCertificates(t *testing.T) { } want := []any{ cert("c", "*.example.com", "AMAZON_ISSUED", "EC-prime256v1", false, "2024-07-03T09:46:40Z", "2025-06-15T15:06:40Z"), - cert("a", "*.example.com", "AMAZON_ISSUED", "RSA-2048", true, "2023-11-14T22:13:20Z", "2024-10-27T03:33:20Z"), cert("d", "example.com", "IMPORTED", "RSA-2048", false, "2023-11-14T22:13:20Z", "2024-10-27T03:33:20Z"), + cert("e", "*.example.com", "AMAZON_ISSUED", "RSA-2048", true, "2023-11-14T22:13:20Z", "2024-10-27T03:33:20Z"), } if diff := cmp.Diff(want, got); diff != "" { t.Errorf("-want +got:\n%s", diff) @@ -1096,7 +1097,7 @@ func TestListCertificatesRequest(t *testing.T) { // TestListCertificatesRejectsUnknownFilter: domainName is the only filter, so // any other name (e.g. the EC2-style "domain-name") is fatal, not ignored. func TestListCertificatesRejectsUnknownFilter(t *testing.T) { - stub := jsonStub(certificatesPage1) + stub := jsonStub(`{"CertificateSummaryList":[]}`) in := &v1beta1.Input{Filters: []v1beta1.Filter{{Name: "domain-name", Values: []string{"*.example.com"}}}} _, err := newQuery().listCertificates(context.Background(), stubCfg(stub), in) if err == nil || !strings.Contains(err.Error(), `"domain-name"`) {