Skip to content

tagging: TagResources reports a nonexistent resource as InternalServiceException/500, the code AWS reserves for an unsupported type #845

Closed

Description

@scttfrdmn

TagResources reports "the resource does not exist" as InternalServiceException with HTTP 500
— the code AWS reserves for a failure of the tagging service, not of the request.

What substrate does

tagResources (emulator/tagging_plugin.go:711-742) resolves the ARN, then calls mergeTags
and maps any error from it to one code:

if err := p.mergeTags(goCtx, ns, key, in.Tags, nil); err != nil {
    failures[arn] = failedResourcesInfo{
        ErrorCode:    "InternalServiceException",
        ErrorMessage: err.Error(),
        StatusCode:   http.StatusInternalServerError,
    }
}

mergeResourceTags returns errors for three quite different situations
(emulator/tagging_plugin.go:988-1204):

Cause Error returned What it means
state.Get finds nothing resource not found: %s/%s the ARN names no existing resource
no arm for the namespace unsupported namespace for tag merge: %s the type is not supported
unmarshal failure unmarshal S3Bucket: … etc. substrate's own record is corrupt

All three become InternalServiceException / 500. untagResources (:756-787) does the same.

What AWS documents

FailureInfo:

InternalServiceException – This can mean that the Resource Groups Tagging API didn't
receive a response from another AWS service. It can also mean that the resource type in the
request is not supported by the Resource Groups Tagging API.

and on ErrorCode:

The code of the common error. Valid values include InternalServiceException,
InvalidParameterException, and any valid error code returned by the AWS service that hosts
the resource that you want to tag.

Valid Values: InternalServiceException | InvalidParameterException

So AWS's two meanings for InternalServiceException are (a) no response from the downstream
service and (b) the resource type is not supported. Neither is "the resource does not
exist". For that, FailureInfo explicitly admits "any valid error code returned by the AWS
service that hosts the resource" — which for a missing bucket is S3's NoSuchBucket, for a
missing queue AWS.SimpleQueueService.NonExistentQueue, and so on.

Note the second row of the table above is correct as it stands: an unsupported namespace is
exactly AWS's "resource type … is not supported" case, so #835's eleven types legitimately
answer InternalServiceException today. It is only the not-found and corrupt-record cases that
are misreported.

Why it matters

A consumer's retry logic reads these codes. AWS's own guidance on InternalServiceException is
"it's safe to retry the request and then call GetResources to verify the changes" — so
substrate is telling a caller to retry a request that will never succeed, indefinitely, for a
typo in an ARN. The 500 also makes a tagging failure look like an emulator fault in a test's
output rather than a bad input.

Acceptance criteria

  • mergeResourceTags distinguishes its failure causes rather than returning one opaque
    error — a sentinel for not-found and one for unsupported-namespace, at minimum, so the
    caller can map them without string matching.
  • A FailedResourcesMap entry for an ARN naming no existing resource carries the owning
    service's own not-found code and its status, per FailureInfo's "any valid error code
    returned by the AWS service that hosts the resource". Which code each service contributes
    is tabulated in docs/services.md.
  • An unsupported resource type keeps InternalServiceException / 500, and the reason is
    recorded as AWS's own wording rather than left looking like an oversight.
  • A malformed or unparseable ARN keeps InvalidParameterException / 400 (already correct at
    :721-726).
  • UntagResources is held to the same mapping — it has the identical block.
  • The call still answers 200 with a populated FailedResourcesMap rather than failing
    the whole request, which is what AWS does and what substrate already does.
  • Tests assert each of the three cases over the wire, including that a batch with one good
    and one bad ARN tags the good one and reports only the bad one.

Activity

  1. added this to the v0.115.0 milestone on Sep 13, 2026
  2. added
    type: bug
    on Sep 13, 2026
  3. scttfrdmn commented on Sep 14, 2026

    @scttfrdmn
    OwnerAuthor

    Premise corrections before implementing

    Research at v0.114.0 (8c4fec1) verified the defect but found the issue's two error codes are the wrong way round, and found the underlying cause is larger than the issue states. Recording that here before the PR rather than letting a diff imply it.

    1. The error codes are inverted relative to what the issue asserts

    The issue says "#835's eleven types legitimately answer InternalServiceException today". They do not. tagResources (emulator/tagging_plugin.go:710-742) maps a resolver failure to InvalidParameterException/400:

    		ns, key, err := p.resolveARN(arn, reqCtx)
    		if err != nil {
    			failures[arn] = failedResourcesInfo{
    				ErrorCode:    "InvalidParameterException",
    				ErrorMessage: err.Error(),
    				StatusCode:   http.StatusBadRequest,
    			}
    			continue
    		}

    untagResources (:756-787) is identical. AWS's FailureInfo documents InternalServiceException as covering "the resource type in the request is not supported by the Resource Groups Tagging API", with the guidance "it's safe to retry the request and then call GetResources to verify the changes". So the fix is the opposite direction from the issue's framing: unsupported type moves from InvalidParameterException/400 to InternalServiceException/500, and InvalidParameterException/400 is kept for an ARN that is not an ARN.

    Three qualifications, all of which go in the release's Provenance section rather than being presented as AWS's rule:

    • The overlap is real. The same page's InvalidParameterException bullets say "the target ID is invalid, unsupported, or doesn't exist", so both codes can be read to cover an unsupported type. Substrate splits them on whether the ARN parses, because that is the only distinction a caller can act on differently. Substrate's reading, not AWS's.
    • FailureInfo.ErrorCode's enum is closed at two values (InternalServiceException | InvalidParameterException) while the same page's prose says "any valid error code returned by the AWS service" and its bullets document a third, AccessDeniedException, absent from the enum. That inconsistency is AWS's; substrate emits only the two enumerated values.
    • InvalidParameterException's bullets describe a top-level request exception, not a FailedResourcesMap entry, and AWS does not say which path a malformed ARN takes. Substrate keeps it in FailedResourcesMap; moving it would be a larger break than the defect warrants. Also substrate's reading.

    And AWS publishes no structural validation to appeal to: ResourceARNList's documented pattern is [\s\S]*, which matches any string including the empty one. Every refusal added here is substrate's choice, stated as such.

    2. The actual cause is eight arms that never check the prefix they strip

    resolveARN switches on the ARN's service and then derives a state key with strings.TrimPrefix. TrimPrefix returns its input unchanged when the prefix does not match, so an ARN naming a different resource type under the same service produces a well-formed key for the wrong kind of resource instead of an error. Eight of sixteen arms do this:

    Arm Line Unguarded strip What a different type becomes
    s3 :806 TrimPrefix(resource, "") — an empty prefix, a no-op an access-point ARN is rejected as an "object ARN"
    lambda :815 "function:" a layer ARN → function:layer:my-layer:1; a versioned ARN function:name:1 → a key the function is not stored at
    dynamodb :832 "table/" a stream or index ARN → table:<acct>/<name>/stream/…
    apigateway :861 "/restapis/" an HTTP API ARN /apis/{id} → api:<acct>/<region>//apis/{id}
    states :867 "stateMachine:" an activity ARN → statemachine:<acct>/<region>/activity:<name>
    ecr :875 "repository/" any other ECR resource → an ecrrepo: key
    cognito-idp :892 "userpool/" any other Cognito resource → a userpool: key
    kinesis :899 "stream/" a consumer ARN → a stream: key

    Seven arms in the same function already guard with strings.HasPrefix (ec2 :837, iam :847, ecs :882, rds :906, elasticache :916, elasticfilesystem :926, glue :940), so the pattern to copy is already there.

    Three guards need more than a prefix test, and each is that way because AWS's own ARN format makes it so — all three formats from the Service Authorization Reference's Resource types tables:

    • lambda — a version ARN function:${Name}:${Version} and an alias ARN function:${Name}:${Alias} are lexically identical; only numeric-ness distinguishes them and AWS does not resolve the ambiguity. So any qualified function ARN is refused rather than guessed at, which costs nothing because tags belong to the function.
    • dynamodb — index and stream ARNs nest under the table prefix (table/${Name}/index/${IndexName}, table/${Name}/stream/${StreamLabel}), so HasPrefix "table/" alone is not sufficient; a remaining / is not a table.
    • states — the two taggable types are distinguished by literal case: activity:${ActivityName} versus stateMachine:${StateMachineName}, capital M. That check is case-sensitive on purpose, and it confirms the activity mis-keying independently of reading substrate's code.

    3. A live recurrence of #826 that its own audit missed

    The DynamoDB arm builds the key from reqCtx.AccountID, not from the ARN's account (tagging_plugin.go:835):

    	case "dynamodb":
    		// arn:aws:dynamodb:{region}:{acct}:table/{name}
    		name := strings.TrimPrefix(resource, "table/")
    		return dynamodbNamespace, "table:" + reqCtx.AccountID + "/" + name, nil

    The arm immediately above it — SQS, rewritten by #826 in v0.114.0 — carries the reason this is wrong verbatim: "The account comes from the ARN rather than from reqCtx, as it does for the IAM and EC2 arms: an ARN naming another account must resolve that account's queue or none." DynamoDB is the outlier that pass missed. So TagResources with another account's table ARN tags the caller's own same-named table, and UntagResources strips tags from it.

    The fix makes the invariant structural rather than advisory: resolveARN no longer takes a *RequestContext at all, so no arm can reach for the caller's account again.

    Cross-account behaviour is undocumented and the release says so. TagResources states only that "you can only tag resources that are located in the specified AWS Region for the AWS account", and AWS documents an explicit refusal for a partition mismatch but publishes nothing for an account mismatch. Refusing is substrate's reading, consistent with what #826 already shipped for SQS. A useful contrast: GetResources' own ResourceARNList says "if a resource specified by this parameter doesn't exist, it doesn't generate an error; it simply isn't included in the response" — and TagResources carries no equivalent sentence, which is the documented warrant for the two operations behaving differently.

    4. ErrorMessage was publishing substrate's state-key layout

    The mapping passed err.Error() straight to the caller, so a FailedResourcesMap entry disclosed the internal key shape. The detail now goes to the log and the response carries AWS's documented sentence.

    5. ECS answered HTTP 200 for a tag it never wrote — folded in here

    Not in this issue as filed, found while guarding the ECS arm, and fixed in the same PR because the two share a key builder. ECSPlugin.resourceStateKey (ecs_plugin.go:1117-1158) returned ("", "") in its default arm and applyTagsToResource (:1035-1038) then reported success — so TagResource against a task definition answered the exact response AWS documents for a successful tag ("an HTTP 200 response with an empty HTTP body") having written nothing, and UntagResource did the same. A nonexistent resource behaved identically. Meanwhile ListTagsForResource refused the same ARN: the two sides of one tag disagreed and the write side was the one that lied.

    Both write sides now refuse, with the codes ECS publishes — InvalidParameterException for an ARN that keys nothing, which is the code API_TagResource's own resourceArn description names for the one bad-ARN case AWS spells out ("if you try to tag a service with a short ARN, you receive an InvalidParameterException error"), and ResourceNotFoundException for a well-formed ARN naming no stored resource.

    Two further findings inside that:

    The plan's instruction to refuse a task definition was wrong and is reversed: API_TagResource states task definitions are taggable — AWS lists six taggable ECS types, "capacity providers, tasks, services, task definitions, clusters, and container instances" — and substrate already stores them with a Tags field. So a task-definition arm was added instead. Substrate keys four of the six; a capacity provider and a container instance are refused rather than silently accepted, because substrate stores neither, so there is no record a tag could land on or be read back from.

    Routing the tagging API to those new types surfaced one more latent defect: mergeResourceTags' ECS arm decoded every key into ECSCluster, so a service or task definition would have been re-marshalled with every member ECSCluster lacks silently dropped. It now edits the stored record's tags member as raw JSON through the same function ECS's own TagResource writes with.

    6. One item of the plan reversed: the mergeResourceTags guards stay

    The plan said mergeResourceTags' default arm and its three unsupported <SVC> resource key arms were "dead from every caller once the resolver guards". They are not: the writer has three callers, and two are CloudFormation paths that build the namespace and key themselves rather than from an ARN (cfnStampResourceTags, cfnPropagateRecordStackTags). For those, the arms are the only thing between a stamp aimed at an unhandled namespace and a silent success — which is the defect class this issue exists to remove, not to relocate. The arms are kept, with a doc paragraph saying why.

    7. An unfiled determinism defect, fixed here

    All four slice-returning tag merge helpers — EC2, IAM, ECS, EFS — built their result by ranging over a Go map, so two identical runs stored one resource's tags in different orders. That made ListTagsForResource, DescribeTags and GetResources report a different order each run for the same state, and it made a hash over the record differ when nothing about the record had changed — which an event-sourced emulator cannot afford, because a replay has to be able to compare state it did not change and find it equal. All four now sort by key, which is the answer DescribeStacks already gives for a stack's own tags.

    Scope of the PR

    Closes this issue. Advances the resolver half of #835 (its eleven mergeResourceTags arms stay open; see the comment there). Two findings are filed separately rather than fixed here: resolveARN has no elasticloadbalancing arm at all, so the Resource Groups Tagging API reaches no ELB resource today, v2 included — that needs the classic/v2 ARN-arity discrimination from #844 first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: taggingtype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions