Skip to content

fix(local-apigw): treat authorizer resource ARNs as literals, not regex - #9155

Merged
reedham-aws merged 3 commits into
aws:developfrom
devteamaegis:fix/local-authorizer-arn-regex-escape
Nov 10, 2026
Merged

reedham-aws merged 3 commits into
aws:developfrom
devteamaegis:fix/local-authorizer-arn-regex-escape

Conversation

@devteamaegis

Copy link
Copy Markdown
Contributor

What's broken

sam local start-api returns 403 for requests a Lambda authorizer explicitly allows, whenever the resource ARN contains a regex metacharacter. The everyday case is the HTTP API $default stage:

# authorizer handler
return {"principalId": "user", "policyDocument": {"Statement": [{
    "Action": "execute-api:Invoke", "Effect": "Allow",
    "Resource": "arn:aws:execute-api:us-east-1:123456789012:abc123/$default/*",
}]}}
$ sam local start-api
$ curl localhost:3000/hello
{"message":"User is not authorized to access this resource"}

It fails even when the authorizer echoes back the exact methodArn it was handed — the most common example in AWS's own docs. Deployed API Gateway allows the same request, so this is a pure local/deployed divergence.

A [ or ( in the path is worse — the request dies with re.PatternError: unterminated character set.

Why it happens

_is_resource_authorized builds a regex directly from the ARN, escaping nothing but the wildcards:

regex_method_arn = resource_arn.replace("*", ".*").replace("?", ".")
regex_method_arn += "$"

So $ becomes an end-of-string anchor, . matches any character, and [ / ( are unbalanced syntax.

The fix

re.escape() the ARN first, then translate the two IAM wildcards:

regex_method_arn = re.escape(resource_arn).replace(r"\*", ".*").replace(r"\?", ".")

* and ? keep working; everything else in the ARN is matched literally. This also stops . from over-matching — .../GET/a.c no longer authorizes .../GET/abc.

The test

test_is_resource_authorized_treats_arn_as_literal in tests/unit/local/apigw/test_lambda_authorizer.py — six cases covering $default, an echoed method ARN, [, (, literal ., and a stage that should still be denied. Five of six fail on develop:

$ pytest tests/unit/local/apigw/test_lambda_authorizer.py -k treats_arn_as_literal   # before
5 failed, 1 passed

$ pytest tests/unit/local/apigw                                                      # after
286 passed

black --check clean on both files.

_is_resource_authorized built a regular expression straight from the
Lambda authorizer's Resource ARN, escaping nothing but the wildcards.
Any regex metacharacter in the ARN was therefore interpreted as syntax.

The common case is the HTTP API '$default' stage: '$' is an end-of-string
anchor, so an Allow statement for
'arn:aws:execute-api:...:api/$default/*' never matched the method ARN and
sam local start-api returned 403 for a request that succeeds when
deployed - even when the authorizer echoed back the exact methodArn it
was handed.  A '[' or '(' in the path raised re.PatternError outright.

Escape the ARN first, then translate the '*' and '?' wildcards.

Signed-off-by: devteamaegis <[email protected]>
@github-actions github-actions Bot added area/local/start-api sam local start-api command area/local/invoke sam local invoke command area/local/start-invoke pr/external stage/needs-triage Automatically applied to new issues and PRs, indicating they haven't been looked at. labels Aug 2, 2026
@devteamaegis
devteamaegis marked this pull request as ready for review August 3, 2026 16:45
@devteamaegis
devteamaegis requested a review from a team as a code owner August 3, 2026 16:45
@roger-zhangg

Copy link
Copy Markdown
Member

Thanks for this, and sorry for the long silence — 30 days is too long for a fix this small.

I reviewed it on a local worktree of pull/9155/head and verified the claims rather than taking them on faith. Short version: the change is correct and minimally scoped, and I could not find a second site that needs the same treatment.

The escaping covers every ARN comparison site. samcli/local/apigw/authorizers/lambda_authorizer.py:393 is the only place in the repo that builds a regex out of a resource ARN. Grepping samcli/local/apigw/ for re.match|re.search|re.fullmatch|re.compile|re.sub returns only two other hits, neither an ARN comparison:

  • lambda_authorizer.py:110 — matches an identity source against the authorizer's ValidationExpression, which is a caller-supplied regex by design.
  • path_converter.py:30-31 — path-template conversion, not ARNs.

method_arn reaches exactly one comparison, lambda_authorizer.py:396 (via is_valid_response at :355), so there is no second path left unescaped.

Both failure directions are real. With develop's version of the file and this PR's tests, 5 of 6 new cases fail:

  • the a[b case raises re.PatternError: unterminated character set at position 64 — a 500, not a 403;
  • case 4 (resource .../GET/a.c, request .../GET/abc) returns True on develop, i.e. a false allow. That is the security-relevant direction, and it is easy to hit by accident since dots in paths (/report.pdf, /v1.0/...) are ordinary.

The $default scenario is reachable end to end, worth recording for whoever backports this: _create_method_arn interpolates self.api.stage_name (samcli/local/apigw/local_apigw_service.py:261-264), and stage_name is taken verbatim from the template's StageName (samcli/lib/providers/sam_api_provider.py:370, assigned at :390). So with StageName: $default the methodArn/routeArn that SAM itself hands the authorizer contains a $, and echoing it straight back as Resource — the pattern in AWS's own examples — could never match under the old code.

Wildcards still translate. re.escape emits \* and \? on every Python we support (checked on 3.13.7), so .replace(r"\*", ".*").replace(r"\?", ".") preserves both IAM wildcards. arn:...:abc/$default/* matches arn:...:abc/$default/GET/hello after the change, and the pre-existing he?lo single-character-wildcard case at tests/unit/local/apigw/test_lambda_authorizer.py:383 still passes.

Tests run (worktree of 91f23c6e1, Python 3.13.7):

  • python -m pytest tests/unit/local/apigw -q → 286 passed
  • same command after merging current develop into the head locally (merged clean, no conflicts) → 286 passed
  • black --check clean on both changed files; mypy on lambda_authorizer.py surfaces only a pre-existing, unrelated error in samcli/lib/utils/graphql_api.py:27

Non-blocking notes, none of which I would hold the merge for:

  1. lambda_authorizer.py:394 appends "$", and $ also matches just before a trailing newline, so .../GET/hello\n would still match. Pre-existing, and method_arn is built from flask_request.path, so I don't believe it is reachable — but re.fullmatch(pattern, method_arn) or \Z would be strictly tighter if you're already touching the line.
  2. The six cases could be appended to the existing test_validate_is_resource_authorized parameterized list instead of a new method — that test already accepts an optional method_arn override (tests/unit/local/apigw/test_lambda_authorizer.py:438-442) and test_is_resource_authorized_treats_arn_as_literal (:492) duplicates its LambdaAuthorizer(...) setup verbatim. Purely cosmetic; I'm fine as-is.
  3. Unrelated to this PR, noticed while reading: _is_resource_authorized skips every non-Allow statement (lambda_authorizer.py:377-378), so an explicit Deny never overrides an Allow locally the way it does in deployed API Gateway. That's a separate issue — please don't expand this PR to cover it.

This looks good to me as it stands. Note that only 3 checks have reported so far; the remaining fork workflows need a maintainer approval to run before it can go in.

@devteamaegis

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @roger-zhangg, and for verifying it on a worktree rather than taking it on faith — that write-up is more careful than the fix deserved. Agreed on leaving the scope as-is; the Deny-override behavior is a separate issue and I won't pull it in here.

On note 1: since I'm already touching that line, I'm happy to switch the trailing $ to \Z (or re.fullmatch) for the strictly-tighter match if you'd prefer it — but equally fine leaving it, given method_arn comes from flask_request.path. Your call. Otherwise it's ready whenever you can approve the fork workflows. Thanks again!

@devteamaegis

Copy link
Copy Markdown
Contributor Author

@roger-zhangg gentle ping on this one: I've updated the branch with the latest base. Is there anything else you'd like changed before it can be approved and the fork workflows run?

@aws-sam-tooling-bot

aws-sam-tooling-bot Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

🧪 Hands-on test plan (not run: external contributor)

Commit 39e4ee1. This plan was not run, so nothing in it has been tested.

Summary: Runs the apigw unit suite, then calls the authorizer resource matcher directly on ARNs with regex metacharacters ($, ., [, (, +, {}, backslash, spaces, unicode) and on existing IAM wildcard patterns (*, ?, prod/*/*), so before/after results can be compared. Then runs sam local start-api on an HttpApi with StageName $default and an IAM-policy Lambda authorizer to confirm end to end that echoed method ARNs and $default wildcards now return 200, that '[' and '(' paths no longer crash, and that '.' and other-stage policies are still denied.

Why: The fix changes how sam local start-api matches Lambda authorizer IAM policy resources against the method ARN. This is runtime behavior a user hits locally: an HttpApi with StageName $default plus an authorizer that echoes methodArn/routeArn currently gets 403, and '[' or '(' in the path crashes the matcher. Both are easy to reproduce with a small SAM app and Docker, and comparing against the merge base shows the fix. The diff is two files (a one-line logic change plus unit tests) with no new dependencies, hooks, network code or agent-directed text, so running it is low risk.

Needs Docker: yes

Needs cloud resources (would not be run):

  • Checking that deployed API Gateway (HTTP API, $default stage) allows the same authorizer policies the fixed local emulator now allows, including resources with '.', '[' or '(' in the path

Risk notes:

  • No risky content in the diff: samcli/local/apigw/authorizers/lambda_authorizer.py only adds re.escape() before translating the IAM wildcards; tests/unit/local/apigw/test_lambda_authorizer.py only adds a parameterized unit test.
  • The run pulls public AWS Lambda emulation images (public.ecr.aws/lambda/python) through sam local start-api. This is normal SAM CLI behavior, not something the PR adds.
  • Setup installs the repo's dev extras from PyPI with pip install -e '.[dev]', the same as the Makefile init target. The PR does not change dependencies.

Setup:

python3 -m venv .venv
. .venv/bin/activate && SAM_CLI_DEV=1 pip install -e '.[dev]'
mkdir -p /tmp/authz-app/src && cat > /tmp/authz-app/template.yaml <<'EOF'
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Globals:
  Function:
    Timeout: 10
    MemorySize: 128
Resources:
  MyHttpApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      StageName: '$default'
      Auth:
        DefaultAuthorizer: LambdaAuth
        Authorizers:
          LambdaAuth:
            AuthorizerPayloadFormatVersion: "2.0"
            EnableSimpleResponses: false
            FunctionArn: !GetAtt AuthFunction.Arn
            Identity:
              Headers:
                - Authorization
  HelloFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: app.hello
      Runtime: python3.12
      Architectures:
        - x86_64
      Events:
        Proxy:
          Type: HttpApi
          Properties:
            ApiId: !Ref MyHttpApi
            Path: /{proxy+}
            Method: ANY
  AuthFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: app.auth
      Runtime: python3.12
      Architectures:
        - x86_64
EOF
cat > /tmp/authz-app/src/app.py <<'EOF'
import json


def auth(event, context):
    arn = event.get('routeArn') or event.get('methodArn')
    print('AUTHZ_ARN', arn)
    headers = {k.lower(): v for k, v in (event.get('headers') or {}).items()}
    resource = he
… (truncated)

Scenarios (5)

S1: Check that the PR's new unit test and the existing apigw unit tests pass, so the existing wildcard cases (*, ?, prod/*/* on the root URL) still work after re.escape.

. .venv/bin/activate && python -m pytest tests/unit/local/apigw -q -p no:cacheprovider

Expected: Exit code 0. All tests pass, including the 6 parameterized cases of test_is_resource_authorized_treats_arn_as_literal and all cases of test_validate_is_resource_authorized. The PR description says 286 passed; small count differences are fine as long as nothing fails or errors.

S2: Call LambdaAuthorizer._is_resource_authorized directly on ARNs with regex metacharacters and on existing IAM wildcard patterns, to show before/after behavior and catch compatibility breaks (?, multiple *, anchoring, unicode, spaces, +, {}, backslash). (compared with the base branch)

. .venv/bin/activate && python - <<'EOF'
from unittest.mock import Mock
from samcli.local.apigw.authorizers.lambda_authorizer import LambdaAuthorizer
a = LambdaAuthorizer('a', Mock(), Mock(), [], Mock(), Mock(), Mock())
P = 'arn:aws:execute-api:us-east-1:123456789012:1234567890/'
cases = [
 ('dollar_wild', P+'$default/*', P+'$default/GET/hello'),
 ('dollar_echo', P+'$default/GET/hello', P+'$default/GET/hello'),
 ('bracket_echo', P+'prod/GET/a[b', P+'prod/GET/a[b'),
 ('paren_echo', P+'prod/GET/x(y', P+'prod/GET/x(y'),
 ('dot_literal', P+'prod/GET/a.c', P+'prod/GET/abc'),
 ('dot_echo', P+'prod/GET/a.c', P+'prod/GET/a.c'),
 ('other_stage', P+'$default/*', P+'prod/GET/hello'),
 ('star_root', P+'prod/*/*', P+'prod/GET/'),
 ('qmark', P+'prod/GET/he?lo', P+'prod/GET/hello'),
 ('qmark_short', P+'prod/GET/he?lo', P+'prod/GET/helo'),
 ('multi_star', 'arn:aws:execute-api:*:*:*/prod/GET/*', P+'prod/GET/hello'),
 ('star_only', '*', P+'prod/GET/hello'),
 ('prefix_only', P+'prod/GET/hel', P+'prod/GET/hello'),
 ('plus_brace_echo', P+'prod/GET/a+b{c}', P+'prod/GET/a+b{c}'),
 ('unicode_echo', P+'prod/GET/caf\u00e9', P+'prod/GET/caf\u00e9'),
 ('space_echo', P+'prod/GET/a b', P+'prod/GET/a b'),
 ('hyphen_tilde_echo', P+'prod/GET/a-b~c', P+'prod/GET/a-b~c'),
 ('backslash_echo', P+'prod/GET/a\\b', P+'prod/GET/a\\b'),
]
for name, res, arn in cases:
    doc = {'policyDocument': {'Statement': [{'Action': 'execute-api:Invoke', 'Effect': 'Allow', 'Resource': res}]}}
    try:
        r = a
… (truncated)

Expected: Exit code 0, one RESULT line per case. With the PR: dollar_wild True, dollar_echo True, bracket_echo True, paren_echo True, dot_literal False, dot_echo True, other_stage False, star_root True, qmark True, qmark_short False, multi_star True, star_only True, prefix_only False, plus_brace_echo True, u…

S3: Reproduce the PR's main claim end to end: on an HttpApi with StageName $default, an authorizer that echoes the routeArn it receives, or allows .../$default/*, should get 200 from sam local start-api instead of 403. (compared with the base branch)

. .venv/bin/activate && /tmp/authz-app/probe.sh 'echo_get|GET|/hello|' 'echo_post|POST|/hello|' 'default_wild|GET|/hello|arn:aws:execute-api:us-east-1:123456789012:1234567890/$default/*' 'default_get_wild|GET|/items/42|arn:aws:execute-api:us-east-1:123456789012:1234567890/$default/GET/*'

Expected: The sam log shows AUTHZ_ARN lines like arn:aws:execute-api:us-east-1:123456789012:1234567890/$default/GET/hello, which confirms '$default' is in the method ARN. With the PR, all four cases print HTTP 200 with a body containing "ok": true. On the merge base, all four print HTTP 403 with a body like …

S4: Error path: a request path containing '[' or '(' that the authorizer echoes back should no longer crash the authorizer check; the request should be allowed. (compared with the base branch)

. .venv/bin/activate && /tmp/authz-app/probe.sh 'bracket|GET|/a[b|' 'paren|GET|/x(y|' 'bracket_header|GET|/ok|arn:aws:execute-api:us-east-1:123456789012:1234567890/$default/GET/ok[' 'plain_after|GET|/hello|'

Expected: With the PR: bracket and paren print HTTP 200 with "ok": true; bracket_header prints HTTP 403 (the literal resource '.../GET/ok[' does not match '.../GET/ok'); plain_after prints HTTP 200 (the server keeps working). The sam log has no Traceback, PatternError or re.error lines. On the merge base: br…

S5: Check that policies that should deny still deny: '.' is literal, other stages and other methods are denied, a prefix without a wildcard does not match, and a normal '*' wildcard still allows. (compared with the base branch)

. .venv/bin/activate && /tmp/authz-app/probe.sh 'dot_overmatch|GET|/abc|arn:aws:execute-api:us-east-1:123456789012:1234567890/$default/GET/a.c' 'dot_exact|GET|/a.c|arn:aws:execute-api:us-east-1:123456789012:1234567890/$default/GET/a.c' 'other_stage|GET|/hello|arn:aws:execute-api:us-east-1:123456789012:1234567890/prod/*' 'other_method|POST|/hello|arn:aws:execute-api:us-east-1:123456789012:1234567890/$default/GET/*' 'prefix_only|GET|/hello|arn:aws:execute-api:us-east-1:123456789012:1234567890/$default/GET/hel' 'global_star|GET|/hello|*'

Expected: With the PR: dot_overmatch 403, dot_exact 200, other_stage 403, other_method 403, prefix_only 403, global_star 200. On the merge base: dot_overmatch returns 200 (the '.' over-match the PR removes), other_method/prefix_only/global_star are the same as with the PR, and the $default-based dot_exact re…

🤖 Automated hands-on test — not a review approval · model claude-opus-5.5 · commit 39e4ee1

History (2)
Commit Result When (UTC) Build
39e4ee1 Plan only (not run) 2026-10-28 20:22
62cde3a Plan only (not run) 2026-10-27 20:34

@devteamaegis

Copy link
Copy Markdown
Contributor Author

Thanks @reedham-aws! The failing durable-functions integ job is unrelated to this change: every test there fails while pulling the emulator image (toomanyrequests: Data limit exceeded from public.ecr.aws), so a re-run should clear it.

@devteamaegis

Copy link
Copy Markdown
Contributor Author

@reedham-aws thanks again for the approval. Is there anyone else who needs to review before this can merge? Happy to make any changes.

@reedham-aws

Copy link
Copy Markdown
Contributor

Yes, I'll get another maintainer and then we can merge. Thanks for the contribution!

@reedham-aws
reedham-aws merged commit d8e632b into aws:develop Nov 10, 2026
100 of 102 checks passed
@devteamaegis

Copy link
Copy Markdown
Contributor Author

Thanks @reedham-aws for the review and for getting a second maintainer on it.

This was investigated and written with an AI coding agent (Claude) working on my behalf.

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

Labels

area/local/invoke sam local invoke command area/local/start-api sam local start-api command area/local/start-invoke pr/external stage/needs-triage Automatically applied to new issues and PRs, indicating they haven't been looked at.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants