Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<field>` or `context.<field>`).

**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 |
|---|---|
Expand All @@ -27,6 +27,8 @@ result is written to `target` (`status.<field>` or `context.<field>`).
| `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:<key>` - 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):

Expand Down Expand Up @@ -68,6 +70,16 @@ result is written to `target` (`status.<field>` or `context.<field>`).
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
Expand Down Expand Up @@ -96,6 +108,8 @@ filters: # or filtersRef: <path> (status./context
parameters: # or parametersRef: <path>; 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"
Expand Down
114 changes: 114 additions & 0 deletions aws.go
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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,
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading