Skip to content

feat(mcp): Expose the bounded-context APIs through an MCP gateway - #188

Merged
raphaho merged 14 commits into
mainfrom
feat/mcp-gateway
Nov 13, 2026
Merged

raphaho merged 14 commits into
mainfrom
feat/mcp-gateway

Conversation

@raphaho

@raphaho raphaho commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

What does this change do?

Puts one Amazon Bedrock AgentCore Gateway in front of the projects, packaging, publishing
and provisioning APIs as MCP tool targets, so an agent can drive the workbench from any MCP
client.

  • A bounded context opts in with enable_mcp=True on its BackendAppOpenApi.
  • infra/helpers/mcp_openapi_transform turns each context's OpenAPI document into the
    shape the gateway accepts. At synth time it rejects a tool with a missing, short or
    duplicate description, an undocumented parameter or request property, a duplicate tool
    name, or a broken $ref.
  • A REQUEST interceptor Lambda forwards the caller's Authorization header to the target
    API, so the existing Cedar authorizer still makes every authorization decision. The
    gateway role can invoke the interceptor and read the spec bucket, and holds no
    execute-api:Invoke.
  • The gateway authenticates callers with CUSTOM_JWT against the user pool, accepting only
    its own app client.
  • The gateway role trust policy and the interceptor's invoke permission require
    aws:SourceAccount and an aws:SourceArn matching this stack's gateway. The gateway log
    key grants the regional CloudWatch Logs principal, limited to its own log group.
  • The stack is deployed only when the mcp-gateway-agentcore app client is configured, as
    feat(cli): Add the vew command-line client #187 does for its router. deploy.sh deletes a gateway stack left over once it is no
    longer configured.

The four API schemas gain operation and parameter descriptions. The gateway publishes them
as its tool descriptions, which is what an agent reasons over to choose a tool.

Type of change

  • Bug fix
  • New feature
  • Refactor / tech debt
  • Documentation
  • Infrastructure / CI

How was this tested?

  • pytest app: 2685 passed.
  • pytest infra/backend/tests infra/helpers/tests: 110 passed, 1 xfail.
  • Synth with and without the MCP client: 16 stacks with the gateway, 15 without.
  • The frontend's generated clients were regenerated and compared. They differ only in
    description text. vitest: 28 passed.
  • Deployed to a fresh hub and spoke pair:
    • A deploy without the MCP client succeeds, and removes the gateway stack left by an
      earlier run.
    • With the client, the gateway deploys.
    • The deployed gateway's tools/list (with feat(packaging): Import images from an AMI or Marketplace subscription #200's operations on top) returned 104
      tools. None has an empty, short or duplicate description, no names are duplicated,
      and none exposes an Authorization input.
    • A tools/call through an MCP client completed the auth-code flow and returned data.

Checklist

  • Follows the guidance in CONTRIBUTING.md
  • Tests added/updated and passing locally
  • Lint / type checks pass locally
  • No secrets, credentials, or account IDs committed
  • Docs updated if behavior or usage changed (API schema descriptions, README.md)
  • Linked the related issue (if any): closes #

Notes for reviewers

Where to focus. mcp_gateway_agentcore_app_stack.py for the gateway, its role and the
authorizer; infra/helpers/mcp_openapi_transform.py for what becomes a tool; and the
interceptor handler, the only new code on the request path. The schema changes are
description text.

Setting it up. Add an mcp-gateway-agentcore entry to ADDITIONAL_APP_CLIENTS. It is
a public client, with no secret and auth-code with PKCE. Its callback URLs are
constants.MCP_GATEWAY_OAUTH_REDIRECT_URIS, i.e. http://localhost:<port> and
http://localhost:<port>/callback for ports 19876–19880. Cognito accepts plain http only
for localhost, so there is no 127.0.0.1 entry. The stack prints ready-to-paste MCP
client configs.

The gateway creates no Cognito client of its own. It reads the client id that
ADDITIONAL_APP_CLIENTS publishes, so the authorizer's accepted-client list stays a single
mechanism. A test asserts no client is created.

release_component_version now accepts a request with no body, matching the schema
change that made the body optional.

Tool names. x-mcp-operation-id gives two provisioning tools clearer names
(ListProvisionableProducts, ListProvisionableProductVersions).

Acknowledgment

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

raphaho added 4 commits November 8, 2026 22:42
A Rust CLI that logs in against the workbench's OIDC provider and calls
the workbench APIs from a terminal, for scripting and CI use where the
web app is not practical.

- `vew login` runs an authorization-code flow with PKCE against the
  configured provider, receiving the callback on a loopback port, and
  stores the tokens per profile. `vew logout` revokes the refresh token
  where the provider exposes a revocation endpoint.
- Commands are derived at runtime from each bounded context's OpenAPI
  document, so the CLI follows the APIs without being regenerated.
  Internal and documentation paths are skipped.
- Configuration is a per-profile file holding the issuer, the OIDC client
  id and the API endpoints. Nothing is discovered from AWS, so the CLI
  needs no AWS credentials.
- Install scripts for Unix shells and PowerShell, and a GitHub Actions
  workflow running fmt, clippy with warnings as errors, the test suite
  and a dependency audit, all pinned to Rust 1.95.

Diagnostics are off unless --verbose is passed. The token-endpoint
response body and the OAuth callback query string are never logged,
since they carry tokens and the authorization code; only their sizes and
the request path are. OAuth error bodies and JWKS documents are logged,
as neither contains a credential.

To use it, register an additional Cognito app client through the
deployment's ADDITIONAL_APP_CLIENTS setting and put that client id in the
CLI's config file.
The CLI's config holds one `api_endpoint`, but a deploy provisions one API
Gateway per bounded context. Without a custom API domain there is no host
in front of them, so the CLI has nothing to point at.

VewApiRouterStack supplies that host: an HTTP API that path-routes
/{bounded-context}/* to each backend gateway, resolving each target from
the SSM parameter that context's own stack publishes. It is registered as
the `else` of the ApiIntegrationStack branch in backend_app.py, because
with a custom API domain that stack already fronts the gateways under one
host and a second hop would be redundant.

Every route is behind a JWT authorizer. The CLI sends a Cognito access
token, which carries client_id and no aud claim, so the audience is the
CLI's app client id, read from the per-client SSM parameter the frontend
stack publishes for each AdditionalAppClients entry. Registering the
client is therefore a config change, not a code change: add a "vew-cli"
entry naming http://localhost:17823/callback as its callback URL.

deploy.sh gains phase 7b, the single writer of
/<app>-<env>/vew-api-endpoint in both deploy modes — the router's output
when there is no custom domain, the custom domain itself when there is.
Keeping it out of the stacks means an environment that drops its custom
domain does not fail on a parameter that already exists.
One Amazon Bedrock AgentCore Gateway fronts the projects, packaging,
publishing and provisioning APIs as MCP tool targets, so an agent can
drive the workbench through any MCP client.

- Each bounded context opts in with enable_mcp=True on its
  BackendAppOpenApi; backend_app.py collects those that did and passes
  them to the gateway stack.
- infra/helpers/mcp_openapi_transform turns each context's OpenAPI
  document into the shape the gateway accepts.
- A REQUEST interceptor Lambda forwards the caller's Authorization
  header to the target API, so the existing Cedar authorizer still makes
  every decision. The gateway role can invoke the interceptor and read
  the spec bucket, and holds no execute-api:Invoke.
- The gateway authorizes callers itself with CUSTOM_JWT against the
  user pool's discovery document, accepting only its own app client.

The API schemas gain operation descriptions. The gateway publishes those
as its tool descriptions, which is what an agent reasons over to choose a
tool, so a name-only restatement degrades tool selection under ambiguity.
test_mcp_tool_descriptions asserts every published tool and every context
carries a substantive one, against the real schemas rather than the
source, so the check cannot pass on intent alone.

The gateway's Cognito client comes from the frontend deployment's
AdditionalAppClients, read as an SSM parameter, rather than being created
here: the authorizer's accepted-client list stays the one mechanism it
already is. Register the gateway by adding an "mcp-gateway-agentcore"
entry with the callback URLs in MCP_GATEWAY_OAUTH_REDIRECT_URIS.
Running the CLI's own CI checks locally surfaced work the import needed.

- rustls 0.23.45 -> 0.23.46 clears four advisories, the most serious being
  Debug impls on client session values exposing TLS secrets
  (RUSTSEC-2026-0346), plus buffered data after ECH rejection, unbounded
  Brotli certificate decompression, and a ServerHello downgrade.
- rustls-webpki 0.103.15 -> 0.103.16 clears RUSTSEC-2026-0382, where
  certificate verification could accept distrusted intermediates.
- RUSTSEC-2026-0387, timing variability in crypto-bigint, is exempted with
  its reasoning in .cargo/audit.toml. It arrives through jsonwebtoken ->
  p256/p384 -> elliptic-curve, and the fix needs an upstream chain this
  repo cannot pull forward. It does not apply: the validator only verifies
  against public JWKS keys and holds no signing key, and it configures
  RS256 only, so the ECDSA path is linked but never executed.
- cargo fmt reformats the multi-line debug_log! call.
- cli/.gitignore no longer points at a CI config this repo does not have.

cargo fmt --check, cargo clippy --all-targets --release --locked
-- -D warnings, cargo test --release --locked and cargo audit all pass.
@raphaho
raphaho requested a review from a team November 9, 2026 16:13
Raphael Hofer added 9 commits November 9, 2026 17:18
isort orders the from-import list in backend_app.py, and the gateway
stack module was appended rather than inserted. No behaviour change.
Scope the AgentCore trust relationships, drop infrastructure for a
feature this branch does not carry, and restore a setting it removed.

Confused deputy on both AgentCore grants. The gateway role trusted
bedrock-agentcore.amazonaws.com and the interceptor's Lambda policy
granted it invoke, both unconditioned, so the service would act for any
AgentCore gateway in any account. Both now require aws:SourceAccount
and an aws:SourceArn matching this stack's own gateway. The ARN is
pinned by pattern because the gateway cannot exist before the role it
assumes; AgentCore documents the ARN as name plus a generated
ten-character suffix, so the name prefix is sufficient.

The log key granted the global logs.<url suffix> principal. CloudWatch
Logs requires a same-Region principal in a key policy, so the encrypted
log group could not ingest. Now logs.<region>.<url suffix>. The shared
infra.constructs.logs.log_group construct has the same defect and needs
its own change.

Remove the scheduled-jobs Lambda, its hourly marketplace rule and its
legacy export: no scheduled_jobs_handler package exists here, so
bundling it had no handler to bundle. The same applies to the
gsi_image_source index, the marketplace, licence-manager, EC2
describe-image, Organizations and RAM grants, the unread
SPOKE_ACCOUNT_ROLE variable and the ImageImported subscription - all
belong to the image-import feature, which is a separate change.

Restore BUILD_LOGS_S3_BUCKET_NAME on the packaging domain-event
handler. The handler still reads it and passes it to the Image Builder
pipeline service, which omits the s3Logs block when it is empty, so
dropping the variable turned off build-log delivery without any error.

release_component_version declared a required body for an empty model
it never read, so a bodyless call failed validation while the schema
marked the body optional. Drop the parameter, matching
release_recipe_version.

Two operation descriptions promised behaviour that does not exist here:
GetImages advertised image-source and status filters it takes no
parameters for, and GetAmis advertised marketplace metadata absent from
the Ami schema. Under MCP these descriptions are the tool contract an
agent reasons over, so a false one is a defect rather than a typo.

Regenerate the TypeScript clients from the changed schemas. This also
picks up drift that predates the branch: the projects client was
missing ServiceClientAssignment, which its schema already declared.

Add tests covering each fix, plus a static check that every Lambda
entry path declared in infra resolves to a real package. That check
also finds a pre-existing dead entry in ProjectsAppStack, recorded as
a strict xfail so it cannot be forgotten or silently rot.
Make the "no secret is logged" property assertable, then fix every place
a probe with planted markers found one.

debug_log! writes to stderr, which a test cannot read back, so the
property was unassertable and any regression invisible. It now also
records into an in-memory buffer, compiled only under cfg(test) or the
new log-capture feature so a release binary has no buffer at all. The
adapter tests live in cli/tests/, which does not get cfg(test) for this
crate, so CI runs cargo test --features log-capture; without the feature
the new test file compiles to nothing.

New oauth_error module renders a failed OAuth call from its status and
an RFC 6749 / 7009 error code only. A token-endpoint error body can
contain a refresh token, a revocation error body echoes the submitted
token, and error_description is free text chosen by whoever drove the
redirect, so none of it reaches the user or the log. A code outside the
RFC list collapses to a placeholder rather than being echoed.

A serde error quotes the value it rejected, for example
`invalid type: string "<access token>"`. The exchange path now reports
the position only, and the refresh and discovery paths report nothing
from the message.

The callback server no longer puts the request target in the
unexpected-path error, since the query carries code and state, and no
longer forwards error_description or a non-standard error code. Its
request read is capped at 64 KiB: this port takes unauthenticated input,
and read_line on a client that never sends a newline grew without bound.

StateMismatch carried both state values; printing the expected one lets
anyone reading the output replay it, and the mismatch alone is what the
user needs. The JWT validator no longer logs the kid or the sub, and
reports the jsonwebtoken error kind rather than its Display text, which
can quote the token.

The token file's .tmp was created at the umask default and chmod'd to
0600 afterwards, so the secret was briefly readable by others. It is now
created with mode 0600 via create_new, which also refuses to follow a
symlink planted at that path, and a stale .tmp is removed first.

Also: pin cargo-audit to 0.22.2; correct the RUSTSEC-2023-0071 reason,
which claimed upstream has no fix — the advisory records "Patched
>= 0.10.0" and cargo tree shows rsa 0.9.10 is pinned by jsonwebtoken's
rust_crypto backend, which is the real reason we cannot take it;
replace the no-op test_discovery_success, which had neither an act nor
an assert step; and correct cli/README.md, which named a
vew-cli-client-id parameter and a VewCliClientId output that do not
exist and said deploy.sh creates the CLI app client, which it does not.

Each redaction test was confirmed to fail against the unfixed adapter:
5 of 6 fail with the fix stashed. 182 tests pass with the feature,
plain cargo test stays green, clippy --all-targets -D warnings clean.
The router exists only to give the vew CLI one api_endpoint when there
is no custom API domain, but it was built on every domainless deploy.
Its authorizer resolves /<app>-ui-<env>/app-client-id/vew-cli at synth,
and that parameter exists only when the frontend deployment's
ADDITIONAL_APP_CLIENTS contains a vew-cli entry, so a deploy without
that client stood up a stack nothing used and failed on the lookup.

deploy.sh now decides and passes it as context. Two conditions, not
one: the client has to be configured, and the frontend and backend have
to be in the same region. The parameter is written by the frontend
stacks in FE_REGION while the router reads it in AWS_REGION, and a
public deployment puts the frontend in us-east-1 wherever the backend
runs, so that read would miss. A mismatch now warns and skips rather
than failing later.

When the router is no longer configured, Phase 7b deletes a stack left
behind by an earlier deploy that did have the client. Without that it
keeps serving an endpoint nothing maintains, and no later deploy ever
touches it again. A delete that a CloudFormation export blocks warns
instead of aborting, since the leftover is inert once the stack is out
of the CDK app.

Phase 7b also no longer runs under --diff. Its put-parameter is a real
write, and the router-output read fails outright when the router stack
does not exist, so a diff on a fresh account stopped with an error
about a stack a deploy had not yet created. The diff now exits before
it, and the closing summary names the two extra things it skips.

Verified by synthesising the backend app with vew-cli-enabled both true
and false: the router template is present in the first and absent in
the second, with no synth error either way. The jq client test was
checked against an empty list, a list without the entry, and lists with
it. shellcheck and bash -n are clean.
Remove the remaining OAuth callback log leaks and handle API router lifecycle transitions across custom-domain and regional deployments. Correct the documented SSM endpoint path.
Validate names, descriptions, parameters, request properties, and local references on the exact transformed schemas uploaded to AgentCore. Add MCP-only names for cross-target collisions and document exposed inputs.
A rejected ID token was reported as "token rejected: {kind:?}". The
kind is not a fixed enum: ErrorKind::Json wraps the serde error, which
quotes the rejected claim value, and other variants carry text. With
--verbose the value reached the debug log as well as the error.

Map each kind to a fixed name and drop its payload. The new redaction
test signs a token whose sub is a number and fails against the
previous commit.
The gateway stack reads /<app>-ui-<env>/app-client-id/mcp-gateway-agentcore
at deploy time, but it was registered on every deploy. Without an
"mcp-gateway-agentcore" entry in ADDITIONAL_APP_CLIENTS the deploy
failed ("Unable to fetch parameters"), seen on a fresh deployment.

Register the stack only when deploy.sh finds that client and the
frontend and backend share a region (the parameter is written in the
frontend region), as the vew CLI router already does, and delete a
stale gateway stack otherwise. Document the two optional clients.

Also drop the 127.0.0.1 callback URLs: Cognito and the frontend's
AdditionalAppClients validation accept plain http only for localhost,
so registering the documented list failed the frontend deploy. A new
test checks the list against that rule and fails on the old list.
raphaho pushed a commit that referenced this pull request Nov 13, 2026
With the MCP gateway (#188) merged in, its synth-time tool-metadata
check rejected the four operations this branch adds: their
descriptions were one line and their parameters and request
properties had none, so the backend could not synthesize. Describe
them.

The gateway branch also asserted that packaging holds no Marketplace
or License Manager action. Marketplace discovery needs some, so pin
the exact set instead. That turned up four actions packaging was
granted but never calls (DescribeAgreement, GetAgreementTerms,
GetProduct, ListFulfillmentOptions); only SearchAgreements is used,
so drop the rest.
andreameroni
andreameroni previously approved these changes Nov 13, 2026
# Conflicts:
#	README.md
#	backend/infra/config.py
#	backend/infra/constants.py
#	deploy.sh
@raphaho
raphaho merged commit 64420dd into main Nov 13, 2026
10 checks passed
raphaho added a commit that referenced this pull request Nov 13, 2026
#200)

* feat(cli): Add the vew command-line client

A Rust CLI that logs in against the workbench's OIDC provider and calls
the workbench APIs from a terminal, for scripting and CI use where the
web app is not practical.

- `vew login` runs an authorization-code flow with PKCE against the
  configured provider, receiving the callback on a loopback port, and
  stores the tokens per profile. `vew logout` revokes the refresh token
  where the provider exposes a revocation endpoint.
- Commands are derived at runtime from each bounded context's OpenAPI
  document, so the CLI follows the APIs without being regenerated.
  Internal and documentation paths are skipped.
- Configuration is a per-profile file holding the issuer, the OIDC client
  id and the API endpoints. Nothing is discovered from AWS, so the CLI
  needs no AWS credentials.
- Install scripts for Unix shells and PowerShell, and a GitHub Actions
  workflow running fmt, clippy with warnings as errors, the test suite
  and a dependency audit, all pinned to Rust 1.95.

Diagnostics are off unless --verbose is passed. The token-endpoint
response body and the OAuth callback query string are never logged,
since they carry tokens and the authorization code; only their sizes and
the request path are. OAuth error bodies and JWKS documents are logged,
as neither contains a credential.

To use it, register an additional Cognito app client through the
deployment's ADDITIONAL_APP_CLIENTS setting and put that client id in the
CLI's config file.

* feat(infra): Give the vew CLI a single API endpoint

The CLI's config holds one `api_endpoint`, but a deploy provisions one API
Gateway per bounded context. Without a custom API domain there is no host
in front of them, so the CLI has nothing to point at.

VewApiRouterStack supplies that host: an HTTP API that path-routes
/{bounded-context}/* to each backend gateway, resolving each target from
the SSM parameter that context's own stack publishes. It is registered as
the `else` of the ApiIntegrationStack branch in backend_app.py, because
with a custom API domain that stack already fronts the gateways under one
host and a second hop would be redundant.

Every route is behind a JWT authorizer. The CLI sends a Cognito access
token, which carries client_id and no aud claim, so the audience is the
CLI's app client id, read from the per-client SSM parameter the frontend
stack publishes for each AdditionalAppClients entry. Registering the
client is therefore a config change, not a code change: add a "vew-cli"
entry naming http://localhost:17823/callback as its callback URL.

deploy.sh gains phase 7b, the single writer of
/<app>-<env>/vew-api-endpoint in both deploy modes — the router's output
when there is no custom domain, the custom domain itself when there is.
Keeping it out of the stacks means an environment that drops its custom
domain does not fail on a parameter that already exists.

* feat(mcp): Expose the bounded-context APIs through an MCP gateway

One Amazon Bedrock AgentCore Gateway fronts the projects, packaging,
publishing and provisioning APIs as MCP tool targets, so an agent can
drive the workbench through any MCP client.

- Each bounded context opts in with enable_mcp=True on its
  BackendAppOpenApi; backend_app.py collects those that did and passes
  them to the gateway stack.
- infra/helpers/mcp_openapi_transform turns each context's OpenAPI
  document into the shape the gateway accepts.
- A REQUEST interceptor Lambda forwards the caller's Authorization
  header to the target API, so the existing Cedar authorizer still makes
  every decision. The gateway role can invoke the interceptor and read
  the spec bucket, and holds no execute-api:Invoke.
- The gateway authorizes callers itself with CUSTOM_JWT against the
  user pool's discovery document, accepting only its own app client.

The API schemas gain operation descriptions. The gateway publishes those
as its tool descriptions, which is what an agent reasons over to choose a
tool, so a name-only restatement degrades tool selection under ambiguity.
test_mcp_tool_descriptions asserts every published tool and every context
carries a substantive one, against the real schemas rather than the
source, so the check cannot pass on intent alone.

The gateway's Cognito client comes from the frontend deployment's
AdditionalAppClients, read as an SSM parameter, rather than being created
here: the authorizer's accepted-client list stays the one mechanism it
already is. Register the gateway by adding an "mcp-gateway-agentcore"
entry with the callback URLs in MCP_GATEWAY_OAUTH_REDIRECT_URIS.

* fix(cli): Clear six dependency advisories and format the logging change

Running the CLI's own CI checks locally surfaced work the import needed.

- rustls 0.23.45 -> 0.23.46 clears four advisories, the most serious being
  Debug impls on client session values exposing TLS secrets
  (RUSTSEC-2026-0346), plus buffered data after ECH rejection, unbounded
  Brotli certificate decompression, and a ServerHello downgrade.
- rustls-webpki 0.103.15 -> 0.103.16 clears RUSTSEC-2026-0382, where
  certificate verification could accept distrusted intermediates.
- RUSTSEC-2026-0387, timing variability in crypto-bigint, is exempted with
  its reasoning in .cargo/audit.toml. It arrives through jsonwebtoken ->
  p256/p384 -> elliptic-curve, and the fix needs an upstream chain this
  repo cannot pull forward. It does not apply: the validator only verifies
  against public JWKS keys and holds no signing key, and it configures
  RS256 only, so the ECDSA path is linked but never executed.
- cargo fmt reformats the multi-line debug_log! call.
- cli/.gitignore no longer points at a CI config this repo does not have.

cargo fmt --check, cargo clippy --all-targets --release --locked
-- -D warnings, cargo test --release --locked and cargo audit all pass.

* style(mcp): Sort the backend_app stack import

isort orders the from-import list in backend_app.py, and the gateway
stack module was appended rather than inserted. No behaviour change.

* feat(packaging): Add AMI and marketplace image import

Lets a publisher base a product on an existing AMI instead of building one
through a pipeline, and on an AWS Marketplace subscription instead of an
AMI they own.

Three capabilities arrive together because the wizard offers them as one
choice of image source:

- AMI import. A five-step wizard collects the source, AMI, platform,
  software and review; the handler validates the AMI is reachable and
  registers it as an image with imageSource=IMPORTED. New value objects
  cover architecture, platform, OS version, image name and product code.
- Marketplace subscription discovery. The hub lists the account's
  agreements, resolves each to its product and per-region AMI ids, and a
  scheduled job re-checks subscriptions for newer images.
- License Manager grants. A marketplace product VEW is subscribed to is
  licensed to the spoke by creating and accepting a grant; one the
  customer already owns is only verified. Both run as new states in the
  AMI sharing state machine.

Existing images are stamped imageSource=PIPELINE by a new DynamoDB
migration, so records written before this change keep working.

Decisions worth naming, because neither side of the merge was simply
newer:

- make_share_ami_decision now returns a ShareAmiDecisionResult dataclass
  rather than a four-tuple. A marketplace decision has to carry the
  licence ARN, home region and grant name downstream, which a tuple of
  four cannot. The region-aware shared-AMI lookup is kept as it is.
- publish_version_command_handler keeps filtering shared AMIs to the
  distribution's own account, and the marketplace short-circuit sits in
  front of that filter rather than replacing it.
- ShareAmiDecision.NOT_REQUIRED is renamed to NotRequired for consistency
  with the other members, including the two added here. The value is
  unchanged, so nothing on the wire moves.
- get_version_entity and the automated-build-product entrypoint are left
  out: both were defined and never referenced.

Three packaging test fixtures gain the entities GSI and GSI_NAME_ENTITIES,
because their bootstrappers now run the migration, which queries that
index as the deployed Lambdas do. The packaging route total moves from 42
to 45; all three new routes are project-path scoped and address no
component or recipe, so both guard counts are unchanged.

* feat(packaging): Degrade gracefully without Marketplace access

Marketplace discovery assumed the hub can read the account's agreements
and received licences. Two calls fail outright when it cannot:
SearchAgreements needs Organizations access the hub only has as an
organisation admin, and ListReceivedLicenses needs the
AWSServiceRoleForMarketplaceLicenseManagement service-linked role, which
exists only once License Manager integration is enabled in Marketplace
settings.

Both now treat AccessDeniedException and AuthorizationException as "no
marketplace data available": they log a warning naming the likely cause
and return an empty list, so a deployment without marketplace access
keeps working with the rest of the image sources instead of erroring.

Adds docs/marketplace-integration.md covering the prerequisites, setup
and workflow, and points at it from the README.

* feat(packaging): Carry marketplace metadata through image import

Completes the marketplace image source: the import handler stores the
product's subscription metadata on the image, discovery returns the
per-region AMI ids alongside each subscription, and the images and
subscriptions pages show which product an image came from. MarketplaceAmi
gains creationDate, which describe_images already returns.

Deliberately not included: the update-detection half of this work.
Upstream it adds a CheckMarketplaceUpdates command, its handler, a
MarketplaceProductUpdateDetected event, and an hourly EventBridge rule
targeting a packaging "scheduled jobs" Lambda. That Lambda has no handler
module — its entry directory holds only a Pydantic job model, while every
other packaging entrypoint has handler.py and bootstrapper.py, and
BackendAppFunction resolves handler.handler by default with no override.
So the rule would invoke a function that fails at import, hourly, and the
command is never dispatched from anywhere else. Porting it would publish a
feature that cannot run.

For the same reason the packaging "scheduled jobs" Lambda itself is left
out, along with the legacy CfnOutput exporting its role ARN — that export
exists for an old CloudFormation stack this repo never had.

Also left out is the gsi_image_source GSI. It indexes
imageSource for exactly that path, nothing queries it, and an unused
global secondary index costs write capacity and storage on every image
write.

The update check is worth having. It needs a handler first, which is new
code rather than a port, so it belongs in its own change.

* fix(packaging): Pick a region's newest marketplace AMI deterministically

get_regional_ami_ids looped over every AMI a region publishes and assigned
each to the same map key, so it kept whichever describe_images returned
last. That call applies no ordering, so a product publishing more than one
available AMI in a region produced an arbitrary choice that could differ
between runs.

The map becomes MarketplaceMetadata.regionalAmiIds, which decides the AMI a
region launches through the CloudFormation RegionMap, so an arbitrary pick
can launch a superseded image.

Take the newest instead. creationDate was added to MarketplaceAmi to
compare image ages, but this selection was never changed to use it:
CreationDate is ISO 8601 and sorts lexicographically, an AMI without one
loses to any AMI that has one, and amiId breaks a tie so the result is
stable across runs.

A region that publishes no AMI is now skipped explicitly rather than
falling out of the loop body, which reads the same but says so.

The test asserts the same two AMIs ordered newest-last and newest-first
give the same answer; before this change those orders returned different
AMIs.

* fix(mcp): Apply review fixes to the MCP gateway

Scope the AgentCore trust relationships, drop infrastructure for a
feature this branch does not carry, and restore a setting it removed.

Confused deputy on both AgentCore grants. The gateway role trusted
bedrock-agentcore.amazonaws.com and the interceptor's Lambda policy
granted it invoke, both unconditioned, so the service would act for any
AgentCore gateway in any account. Both now require aws:SourceAccount
and an aws:SourceArn matching this stack's own gateway. The ARN is
pinned by pattern because the gateway cannot exist before the role it
assumes; AgentCore documents the ARN as name plus a generated
ten-character suffix, so the name prefix is sufficient.

The log key granted the global logs.<url suffix> principal. CloudWatch
Logs requires a same-Region principal in a key policy, so the encrypted
log group could not ingest. Now logs.<region>.<url suffix>. The shared
infra.constructs.logs.log_group construct has the same defect and needs
its own change.

Remove the scheduled-jobs Lambda, its hourly marketplace rule and its
legacy export: no scheduled_jobs_handler package exists here, so
bundling it had no handler to bundle. The same applies to the
gsi_image_source index, the marketplace, licence-manager, EC2
describe-image, Organizations and RAM grants, the unread
SPOKE_ACCOUNT_ROLE variable and the ImageImported subscription - all
belong to the image-import feature, which is a separate change.

Restore BUILD_LOGS_S3_BUCKET_NAME on the packaging domain-event
handler. The handler still reads it and passes it to the Image Builder
pipeline service, which omits the s3Logs block when it is empty, so
dropping the variable turned off build-log delivery without any error.

release_component_version declared a required body for an empty model
it never read, so a bodyless call failed validation while the schema
marked the body optional. Drop the parameter, matching
release_recipe_version.

Two operation descriptions promised behaviour that does not exist here:
GetImages advertised image-source and status filters it takes no
parameters for, and GetAmis advertised marketplace metadata absent from
the Ami schema. Under MCP these descriptions are the tool contract an
agent reasons over, so a false one is a defect rather than a typo.

Regenerate the TypeScript clients from the changed schemas. This also
picks up drift that predates the branch: the projects client was
missing ServiceClientAssignment, which its schema already declared.

Add tests covering each fix, plus a static check that every Lambda
entry path declared in infra resolves to a real package. That check
also finds a pre-existing dead entry in ProjectsAppStack, recorded as
a strict xfail so it cannot be forgotten or silently rot.

* fix(cli): Keep secrets out of the log and error output

Make the "no secret is logged" property assertable, then fix every place
a probe with planted markers found one.

debug_log! writes to stderr, which a test cannot read back, so the
property was unassertable and any regression invisible. It now also
records into an in-memory buffer, compiled only under cfg(test) or the
new log-capture feature so a release binary has no buffer at all. The
adapter tests live in cli/tests/, which does not get cfg(test) for this
crate, so CI runs cargo test --features log-capture; without the feature
the new test file compiles to nothing.

New oauth_error module renders a failed OAuth call from its status and
an RFC 6749 / 7009 error code only. A token-endpoint error body can
contain a refresh token, a revocation error body echoes the submitted
token, and error_description is free text chosen by whoever drove the
redirect, so none of it reaches the user or the log. A code outside the
RFC list collapses to a placeholder rather than being echoed.

A serde error quotes the value it rejected, for example
`invalid type: string "<access token>"`. The exchange path now reports
the position only, and the refresh and discovery paths report nothing
from the message.

The callback server no longer puts the request target in the
unexpected-path error, since the query carries code and state, and no
longer forwards error_description or a non-standard error code. Its
request read is capped at 64 KiB: this port takes unauthenticated input,
and read_line on a client that never sends a newline grew without bound.

StateMismatch carried both state values; printing the expected one lets
anyone reading the output replay it, and the mismatch alone is what the
user needs. The JWT validator no longer logs the kid or the sub, and
reports the jsonwebtoken error kind rather than its Display text, which
can quote the token.

The token file's .tmp was created at the umask default and chmod'd to
0600 afterwards, so the secret was briefly readable by others. It is now
created with mode 0600 via create_new, which also refuses to follow a
symlink planted at that path, and a stale .tmp is removed first.

Also: pin cargo-audit to 0.22.2; correct the RUSTSEC-2023-0071 reason,
which claimed upstream has no fix — the advisory records "Patched
>= 0.10.0" and cargo tree shows rsa 0.9.10 is pinned by jsonwebtoken's
rust_crypto backend, which is the real reason we cannot take it;
replace the no-op test_discovery_success, which had neither an act nor
an assert step; and correct cli/README.md, which named a
vew-cli-client-id parameter and a VewCliClientId output that do not
exist and said deploy.sh creates the CLI app client, which it does not.

Each redaction test was confirmed to fail against the unfixed adapter:
5 of 6 fail with the fix stashed. 182 tests pass with the feature,
plain cargo test stays green, clippy --all-targets -D warnings clean.

* fix(infra): Register the vew API router only when the CLI is configured

The router exists only to give the vew CLI one api_endpoint when there
is no custom API domain, but it was built on every domainless deploy.
Its authorizer resolves /<app>-ui-<env>/app-client-id/vew-cli at synth,
and that parameter exists only when the frontend deployment's
ADDITIONAL_APP_CLIENTS contains a vew-cli entry, so a deploy without
that client stood up a stack nothing used and failed on the lookup.

deploy.sh now decides and passes it as context. Two conditions, not
one: the client has to be configured, and the frontend and backend have
to be in the same region. The parameter is written by the frontend
stacks in FE_REGION while the router reads it in AWS_REGION, and a
public deployment puts the frontend in us-east-1 wherever the backend
runs, so that read would miss. A mismatch now warns and skips rather
than failing later.

When the router is no longer configured, Phase 7b deletes a stack left
behind by an earlier deploy that did have the client. Without that it
keeps serving an endpoint nothing maintains, and no later deploy ever
touches it again. A delete that a CloudFormation export blocks warns
instead of aborting, since the leftover is inert once the stack is out
of the CDK app.

Phase 7b also no longer runs under --diff. Its put-parameter is a real
write, and the router-output read fails outright when the router stack
does not exist, so a diff on a fresh account stopped with an error
about a stack a deploy had not yet created. The diff now exits before
it, and the closing summary names the two extra things it skips.

Verified by synthesising the backend app with vew-cli-enabled both true
and false: the router template is present in the first and absent in
the second, with no synth error either way. The jq client test was
checked against an empty list, a list without the entry, and lists with
it. shellcheck and bash -n are clean.

* fix(publishing): Page the grant lookups and trim the licence grants

Four of the review findings on the licence-grant path. The authorization
check, the state machine and the deprecated-AMI handling are not in
this commit.

has_active_received_grant called get_paginator("list_received_grants").
License Manager publishes no paginator for that operation -
can_paginate is False - so boto3 raises OperationNotPageableError, which
is not a ClientError and therefore escaped the handler around the call.
That function failed on every invocation. It now follows NextToken by
hand, through one helper shared with the other grants call.

_find_existing_grant read a single page of list_distributed_grants,
which has no paginator either. A grant on a later page looked absent, so
the create that followed failed with "already has a grant". It pages too.

accept_grant called AcceptGrant when ListReceivedGrants returned
nothing: a missing grant left the status as None, which is neither
ACTIVE nor DISABLED, so the code fell through to the accept. It now
stops with a clear adapter error instead.

update_version_command_handler guarded the image source on
`if ami.imageSource:`, which kept the previous AMI's image source and
Marketplace metadata when the new AMI has none - a version updated from
a Marketplace AMI to a pipeline-built one went on claiming a Marketplace
origin and licence. Both attributes are now written on every update,
including as None. Two existing tests asserted the old attribute set and
are updated.

The hub's License Manager grants drop to CreateGrant and
ListDistributedGrants plus the licence reads: it never reads a single
grant, deletes one, or accepts one. The spoke keeps AcceptGrant,
CreateGrantVersion and ListReceivedGrants and loses GetGrant.

Verified: the paging helper exercised across three pages, and
_find_existing_grant shown to find a grant that only appears on page
two. OperationNotPageableError confirmed against the installed boto3.
2751 app tests and 6 infra tests pass.

* fix(publishing): Authorize a licence grant against the project

create_license_grant_command_handler distributed a Marketplace licence
for any AMI id to any AWS account. Neither side of the request was
checked against the project the command names, so a caller with access
to one project could have the hub grant another project's paid licence
to an account of their choosing.

Both halves are now checked before anything is distributed. The AMI has
to belong to the project in the command, which the Ami read model
already records as projectId, and the target account has to be one of
that project's Active accounts, read through the existing
ProjectsQueryService port. Either check failing raises a DomainException
and no grant is created, nothing is persisted, and no event is
published.

That port already existed and had no caller. Wiring it into the two
entry points that dispatch this command needed three supporting
changes: both bootstrappers now build a ProjectsApiQueryService through
the ServiceRegistry, the api and ami-sharing functions get the projects
GET /internal/accounts route via cross_bc_api_access, and their AppConfig
classes extend VEWBaseConfig, which the registry reads. VEWBaseConfig
only wraps environment variables BackendAppEntrypoints already injects
into every Lambda, so this adds no new configuration.

accept_license_grant_command_handler called accept_grant before reading
the grant record, so a command naming a grant the project does not have
still issued a real AcceptGrant against the spoke account and only then
failed. The record is read first and a missing one stops the handler.

Verified: the three new authorization tests fail against the handler
without the check and pass with it; 2754 app tests pass; cdk synth of
PublishingAppStack and ServiceDiscoveryStack is clean, with the
trimmed grants confirmed in the template (no DeleteGrant, no GetGrant)
and /internal/accounts now granted to the api, domain-events and
ami-sharing functions.

* fix(publishing): Stop the AMI sharing machine succeeding on a failure

Three structural defects in the AMI sharing state machine, all on the
Marketplace paths.

VerifyLaunchPermissionLambda reports whether the target account can
actually launch the regional Marketplace AMI, and nothing read the
answer: both the LICENSE_GRANT and VERIFY_EXTERNAL_GRANT chains ran
straight on to SucceedAmiSharing, so a spoke that could not launch the
image was recorded as shared successfully. A Choice now gates that.

SucceedAmiSharing reads $.copiedAmi.copiedAmiId, which the
verify-external-grant path never set, so that path could not complete
even when the grant was valid. Both Marketplace paths now record the
regional AMI - the image the spoke actually launches - at a shared Pass
after the launch-permission check.

FailAmiSharingLambda was invoked without the error. A task failure
populates $.error through add_catch, but a Choice taking its otherwise
branch does not, so the reason a share failed was dropped and the
version showed a bare Failed status. Each failing Choice branch now sets
its own $.error through a Pass - unexpected decision, grant not
verified, launch permission denied - and the Lambda payload carries
$.error on every route. Verified against the synthesised definition:
all twelve routes into that state set $.error, so the new payload
reference always resolves.

The Lambda still ignores the field, because FailAmiSharingCommand has
no reason yet. Carrying it is the prerequisite for that work, which also
has to persist statusReason and return it from GetProductVersion.

Also in the tests: five call sites passed test_event=mocked_test_event
without calling it. That fixture returns a factory, so the tests handed
StartExecution a function instead of an event, which is not
JSON-serialisable - the ParamValidationError I had twice attributed to
these tests needing live credentials. They need Step Functions Local on
localhost:8083, which is a separate matter, so this fix is verified
statically. The 12-digit account-like values in conftest and the module
docstring are now documentation example ids.

Verified: cdk synth of PublishingAppStack clean, with the Choice, the
regional-AMI Pass and every $.error route asserted against the
synthesised definition. infra failures are byte-identical with these
changes stashed - 9 either way, all in the other state-machine suites
that need Step Functions Local.

* feat(publishing): Report why an AMI share failed

A failed version said only "Failed". The state machine already knew the
reason and dropped it, so the only way to find out was to open the Step
Functions execution.

FailAmiSharingLambda now receives $.error, which the previous commit
made available on every route into that state, and turns it into a
short reason stored as statusReason on the version distribution and
returned from GetProductVersion.

step_error.summarize handles both shapes $.error arrives in: a task
catch, where Cause is JSON carrying errorType, errorMessage and a trace
array, and a failing Choice branch, where Cause is already a sentence.
Only the type and message are kept. The trace is never included - it is
long, it is useless to whoever is looking at a failed product version,
and it names internal file paths. The result is collapsed to one line
and capped at 1000 characters, so one failure cannot write an unbounded
string into the version record.

The reason is cleared on success and on retry, so it cannot outlive the
failure it describes and sit on a version that is running again.

FailAmiSharingRequest.error is optional, so an execution already in
flight without the field still parses.

The API schema gains statusReason on VersionDistribution and the
publishing TypeScript client is regenerated, which is how the field
reaches the UI. Only the changed model file lands in the diff; the
generator's whitespace churn is normalised by the existing hooks.

12 tests cover the summariser, including that no stack trace, file path
or trace key survives it, that the cap holds, and that an odd or
unparseable Cause degrades to the error name. A new handler test proves
the reason reaches the version record rather than only that None does.
363 publishing tests and 2767 app tests pass; cdk synth clean.

* fix(packaging): Find a subscription's AMIs when they are deprecated

describe_images hides deprecated images unless asked, so a Marketplace
subscription whose AMIs are all past their deprecation date looked like
a subscription with no AMI at all, and could not be imported. Both
listings now pass IncludeDeprecated=True and capture DeprecationTime,
which MarketplaceAmi exposes as a `deprecated` property.

Including them changes which AMI gets picked, so both pickers now
prefer a supported image. The hub lookup took amis[0] - an arbitrary
image, since describe_images has no defined order - and now takes the
newest supported one, falling back to the newest deprecated one only
when every image is deprecated, so an older subscription still
resolves to something. get_regional_ami_ids already took the newest and
now applies the same preference; without that, adding IncludeDeprecated
would have started handing deprecated AMIs to spoke accounts.

get_resource_shares is paginated and only the first page was read, so
the License Manager share could sit on a later page, the Organizations
integration looked inactive, and an import that should have been
allowed was blocked. It now follows nextToken.

While in these files, the local variable and test names describing the
AWS Organizations management account no longer use "master". The
MasterAccountId and MasterAccountArn response fields keep their names,
because those belong to the AWS API.

Each behaviour was shown to fail against the previous code: the three
hub-pick tests fail with amis[0] restored, and the paging test fails
with the single-page read restored. 2772 app tests pass.

* feat(packaging): Show when a Marketplace subscription's AMI is deprecated

The backend now resolves a deprecated AMI when a product publishes no
supported one, so the person importing has to be able to see that.
`deprecated` and `deprecationTime` are carried on the discovered
subscription read model, the API model and the OpenAPI schema, taken
from whichever AMI the hub lookup settled on.

In the UI: a red "Deprecated" badge beside the product name in both the
subscriptions list and the import wizard's selector, and a warning in
the wizard once a deprecated subscription is the selected one. It is a
warning rather than a blocker because the import still works; the point
is that the vendor no longer supports the image and may have published
a replacement product.

Only DiscoveredMarketplaceSubscription.ts is regenerated, deliberately.
Regenerating the whole packaging client breaks the build: the committed
client exports CreateRecipeRequestRecipePlatformEnum,
...RecipeArchitectureEnum and ...RecipeOsVersionEnum, which
create-recipe.logic.ts imports, but the schema declares those three
properties as plain `type: string` with no enum, so the generator drops
them. The committed client was generated from an older schema and is
stale.

Restoring those enums to the schema is not a safe drive-by: the
committed client lists six OS versions (Ubuntu 20/22/24, Windows Server
2019/2022/2025) while the domain's RecipeOsVersion now has two (Ubuntu
24, Windows Server 2025). Deciding which is authoritative changes what
recipe creation accepts, which has nothing to do with this change. Left
as a separate finding.

1112 packaging tests pass, tsc reports no new errors, 28 frontend tests
pass.

* fix(provisioning): Always report why a launch failed

Two ways a failed workbench showed no usable reason.

get_provisioned_product_failure_reason read the stack's failed
resources and returned None when it found nothing, which happens when a
launch fails before the stack exists or the stack is already gone. It
now falls back to the Service Catalog record's errors, and then to the
provisioned product's status message.

Reading the reason could also be the thing that failed.
__get_stack_events raises an AdapterException when the product or its
events cannot be read, and that escaped to the caller, so a missing
stack turned a reportable failure into an unhandled adapter error. Both
reads are now contained: a reason that cannot be read is logged and
reported as absent, never raised.

"The instance configuration for this AWS Marketplace product is not
supported" classified as UNKNOWN. It names no Availability Zone and
does not start with "Unsupported", so it fell through every pattern. It
is a template problem - the instance type in the product's parameters
is not one the Marketplace offer permits - so it now classifies as
TEMPLATE, which is the class that tells the user to change a parameter.

Both service changes were shown to fail against the previous code: the
fallback test returns None and the containment test raises. Two
classification cases cover the bare message and the form
CloudFormation wraps it in. 2776 app tests pass.

* fix(publishing): Record a licence grant against the registered AMI

The Marketplace decision set both of its AMI ids to the regional image.
They have two different jobs.

original_ami_id must be the registered image - the one the project
imported - because that is what the publishing AMIs table is keyed by,
and what create_license_grant now looks up to check the AMI belongs to
the caller's project. With the regional id that lookup missed, so the
authorization check added earlier in this branch would have rejected
every Marketplace grant as "not part of project". The two changes are
coupled: this is what makes that check work rather than merely compile.

image_id stays the regional image, because that is the one the spoke
launches, the one VerifyLaunchPermission asks about, and the one
recorded as copiedAmiId on success.

CreateLicenseGrantLambda's payload follows, reading
$.decideActionResponse.originalAmiId instead of .imageId. Confirmed
against the synthesised definition: the grant now takes originalAmiId
while VerifyLaunchPermission and PassMarketplaceAmi still take imageId.

When the product publishes no AMI for the spoke's region there is
nothing regional to launch and both ids are the registered image, which
a third test pins.

The two id-separation tests fail against the previous code. 2779 app
tests pass.

* feat(publishing): Distribute a licence for an external subscription

An externally-managed subscription means the customer owns the licence,
so DecideAction only ever verified that the spoke already had a grant.
When the spoke had none the decision stayed verify-only, the state
machine failed the verification, and the launch could never succeed -
even when the hub was perfectly able to distribute a grant itself.

The decision now upgrades to LICENSE_GRANT when both hold: the spoke
has no active received grant, and License Manager's organization
integration is switched on. The second is a new port method,
can_distribute_license, reading
GetServiceSettings.OrganizationConfiguration.EnableIntegration, with
license-manager:GetServiceSettings granted to the AMI-sharing and API
functions.

A spoke that already has a grant stays verify-only, because there is
nothing to distribute. A VEW-managed subscription is untouched: it is
already a grant decision and the upgrade does not consult License
Manager for it, which a test pins.

The licence service is an optional constructor argument, so the
decision still works without it and the existing tests are unaffected.
The home-region fallback that both the decision and the upgrade need is
now one helper rather than two copies.

Note for review: the description of this fix also mentioned
organizations:DescribeOrganization and ram:GetResourceShares. This
implementation uses GetServiceSettings alone, which is License
Manager's own answer to "may I distribute", so only that action is
granted rather than three. If the other two are load-bearing in your
version, say so and I will match it.

Four new tests, the upgrade one shown to fail against the previous
decision. 2783 app tests pass; cdk synth confirms GetServiceSettings is
granted and DeleteGrant and GetGrant are still absent.

* test(publishing): Make the state machine mocks match the definition

Every mock on the Marketplace paths disagreed with what the state
machine actually reads, so these test cases could not have exercised
the paths they are named after.

MockedVerifyLaunchPermissionLambda returned launchPermissionVerified,
but the ResultSelector reads $.Payload.isAccessible. The DecideAction
mocks returned five of the ten fields the selector reads, missing
imageId, projectId, licenseArn, homeRegion and grantName.
MockedCreateLicenseGrantLambda returned grantArn without grantId or
homeRegion. Each field list is taken from the synthesised definition
rather than written by hand.

Adds LaunchPermissionDeniedPath, covering a spoke that cannot launch
the regional AMI. Nothing covered it, which is how the missing Choice
after VerifyLaunchPermission went unnoticed: before that Choice existed
this case would have been reported as a successful share.

Also in this commit:

deploy.sh gains Phase 7c, which reports the License Manager
Organizations integration state and changes nothing. Enabling it is an
account-wide decision for an administrator, and it cannot be done from
a deploy, so the phase distinguishes enabled, disabled, and not
determined - the last covering both no Organizations access and running
outside the management account.

docs/marketplace-integration.md gains the CLI form of enabling the
integration, in order and with the reason the order matters; the ~30
minute delay before the resource share propagates; the fact that the
grant decision is retaken at every publish, so enabling it later needs
no re-import; a table of the Marketplace statusReason values; the
instance-type limits behind "The instance configuration for this AWS
Marketplace product is not supported"; and the deprecated-AMI
behaviour. The Externally Managed section is corrected: it said such a
version always fails without a manual grant, which is no longer true
now that the hub distributes one when it can.

The CLI parameter shapes are checked against botocore's service model.
2833 app and infra tests pass; the two failures are account_onboarding,
which needs Step Functions Local, as do the ami_sharing tests
themselves - so the mock corrections are verified against the
definition, not by running them.

* fix(publishing): Require the resource share before distributing a licence

Resolves the divergence from the review on this check. It asked for
license-manager:GetServiceSettings, organizations:DescribeOrganization
and ram:GetResourceShares; can_distribute_license read only
OrganizationConfiguration.EnableIntegration from the first.

Reading the flag alone is not enough, and the reason is the propagation
delay this branch documents elsewhere: EnableIntegration reads back true
as soon as the setting is saved, but the RAM resource share that
actually permits a cross-account grant takes around half an hour to
appear. In that window the check said yes, an externally-managed
subscription was upgraded to a grant, and CreateGrant then failed.

The share is what has to exist, so require it. GetServiceSettings
returns it as LicenseManagerResourceShareArn, which is the same fact
organizations:DescribeOrganization plus ram:GetResourceShares arrives at
the long way - so this is the stricter check the review was after while
still needing one action rather than three.

Four cases covered: integration on with the share, integration on while
the share has not propagated, integration off, and no organization
configuration at all. 2786 app tests pass.

* fix(cli): Finish security review fixes

Remove the remaining OAuth callback log leaks and handle API router lifecycle transitions across custom-domain and regional deployments. Correct the documented SSM endpoint path.

* fix(mcp): Validate exposed tool metadata

Validate names, descriptions, parameters, request properties, and local references on the exact transformed schemas uploaded to AgentCore. Add MCP-only names for cross-target collisions and document exposed inputs.

* fix(marketplace): Close security review gaps

Derive grant-sensitive Marketplace metadata server-side, require per-license and active organization readiness, and bind grant acceptance to persisted data. Tighten IAM and fix workflow, deprecation, deployment, and documentation regressions.

* fix(cli): Keep ID token claim values out of errors

A rejected ID token was reported as "token rejected: {kind:?}". The
kind is not a fixed enum: ErrorKind::Json wraps the serde error, which
quotes the rejected claim value, and other variants carry text. With
--verbose the value reached the debug log as well as the error.

Map each kind to a fixed name and drop its payload. The new redaction
test signs a token whose sub is a number and fails against the
previous commit.

* fix(packaging): Import an AMI into one project only

Packaging's upstream-id lookup and publishing's AMI read model both
hold one image per AMI id. Publishing keys its row by AMI id alone and
authorizes licence grants against that row's projectId. The import
check only rejected a duplicate in the same project, so a second
project importing the same AMI took the row over: the first project's
grants then failed with "not part of project" and the AMI dropped out
of its AMI list.

Reject an import when any other project holds the AMI. Read every
image for the AMI id, paged, rather than the first match. Only a
Failed or Deleted image releases the AMI; Retired keeps it, because
published versions may still use it. The error does not name the
other project. Document the restriction.

Sharing one AMI across projects needs a project-scoped read model in
publishing and is left for a follow-up.

* fix(publishing): Ship the Organizations stubs in the publishing layer

The License Manager adapter imports mypy_boto3_organizations at module
level for the resource-share check, but the publishing layer did not
pin it. The dev virtualenv has every stub, so unit tests passed; the
deployed publishing API failed to initialise with
Runtime.ImportModuleError (seen on a fresh deploy).

Pin it in the publishing layer and add a test that every runtime
mypy_boto3_* import in a bounded context or app/shared is pinned in
that context's layer lock or the shared lock. The test fails without
the pin.

* fix(mcp): Deploy the gateway only when its client is configured

The gateway stack reads /<app>-ui-<env>/app-client-id/mcp-gateway-agentcore
at deploy time, but it was registered on every deploy. Without an
"mcp-gateway-agentcore" entry in ADDITIONAL_APP_CLIENTS the deploy
failed ("Unable to fetch parameters"), seen on a fresh deployment.

Register the stack only when deploy.sh finds that client and the
frontend and backend share a region (the parameter is written in the
frontend region), as the vew CLI router already does, and delete a
stale gateway stack otherwise. Document the two optional clients.

Also drop the 127.0.0.1 callback URLs: Cognito and the frontend's
AdditionalAppClients validation accept plain http only for localhost,
so registering the documented list failed the frontend deploy. A new
test checks the list against that rule and fails on the old list.

* fix(marketplace): Meet the MCP tool checks and trim packaging grants

With the MCP gateway (#188) merged in, its synth-time tool-metadata
check rejected the four operations this branch adds: their
descriptions were one line and their parameters and request
properties had none, so the backend could not synthesize. Describe
them.

The gateway branch also asserted that packaging holds no Marketplace
or License Manager action. Marketplace discovery needs some, so pin
the exact set instead. That turned up four actions packaging was
granted but never calls (DescribeAgreement, GetAgreementTerms,
GetProduct, ListFulfillmentOptions); only SearchAgreements is used,
so drop the rest.

* test(shared): Simplify the stub-import walk below the complexity limit

flake8's max-complexity check rejected _runtime_stub_imports (C901,
complexity 9). Split the import-name extraction into its own function;
the behaviour is unchanged and the test still fails without the
publishing layer's Organizations pin.

* style(frontend): Apply the repo's lint autofix to the deprecation badges

---------

Co-authored-by: raphaho <raphaho@amazon.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants