diff --git a/packages/python/ess-aws-bedrock/LICENSE b/packages/python/ess-aws-bedrock/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/packages/python/ess-aws-bedrock/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/python/ess-aws-bedrock/Pulumi.example.yaml b/packages/python/ess-aws-bedrock/Pulumi.example.yaml new file mode 100644 index 0000000..9fc7d70 --- /dev/null +++ b/packages/python/ess-aws-bedrock/Pulumi.example.yaml @@ -0,0 +1,13 @@ +# Copy to Pulumi..yaml (for example Pulumi.dev.yaml), then replace +# YOUR_TEAM and your-aws-profile. See the README for every config key. +config: + aws:profile: your-aws-profile + aws:region: us-east-1 + ess-aws-bedrock:teamName: YOUR_TEAM + ess-aws-bedrock:environment: development + # Optional (defaults shown): + # ess-aws-bedrock:modelPatterns: + # - anthropic.* + # ess-aws-bedrock:createAccessKey: "true" + # ess-aws-bedrock:createBedrockApiKey: "false" + # ess-aws-bedrock:bedrockApiKeyAgeDays: "180" diff --git a/packages/python/ess-aws-bedrock/Pulumi.yaml b/packages/python/ess-aws-bedrock/Pulumi.yaml new file mode 100644 index 0000000..0d872d9 --- /dev/null +++ b/packages/python/ess-aws-bedrock/Pulumi.yaml @@ -0,0 +1,4 @@ +name: ess-aws-bedrock +description: AWS Bedrock Anthropic model access infrastructure +runtime: python +main: src/ess_aws_bedrock diff --git a/packages/python/ess-aws-bedrock/README.md b/packages/python/ess-aws-bedrock/README.md new file mode 100644 index 0000000..87f54cb --- /dev/null +++ b/packages/python/ess-aws-bedrock/README.md @@ -0,0 +1,200 @@ +# AWS Bedrock Anthropic Access + +A Pulumi project that provisions IAM credentials for invoking Anthropic models on AWS Bedrock. + +```python +from ess_aws_bedrock import deploy_stack + +result = deploy_stack() +# result.iam.access_key_id, result.iam.secret_access_key, result.iam.bedrock_api_key +``` + +## What It Creates + +- An IAM user scoped to Bedrock model invocation +- An inline IAM policy allowing `InvokeModel` on Anthropic foundation models +- A long-lived access key (access key ID + secret access key), unless `createAccessKey` is `false` +- A Bedrock API key (bearer token for `AWS_BEARER_TOKEN_BEDROCK`), when `createBedrockApiKey` is `true` + +## Prerequisites + +1. **AWS CLI** installed and configured with a profile that can create IAM users and policies +2. **Bedrock model access** -- serverless foundation models (including Anthropic Claude) are automatically enabled on first invocation. No manual approval is needed. +3. **Python 3.12+** and **Pulumi CLI** installed + +## Setup + +### 1. Install Dependencies + +```bash +uv sync --all-packages +``` + +### 2. Authenticate to AWS + +```bash +aws sso login --profile +aws sts get-caller-identity --profile +``` + +### 3. Configure Pulumi + +```bash +cd packages/python/ess-aws-bedrock +cp Pulumi.example.yaml Pulumi.dev.yaml # then replace YOUR_TEAM and your-aws-profile +uv run pulumi login file://. +uv run pulumi stack init dev +``` + +### 4. Deploy + +```bash +uv run pulumi up +``` + +## Configuration + +Set via `pulumi config set ess-aws-bedrock: `: + +| Config Key | Description | Default | +| --- | --- | --- | +| `teamName` | Team identifier for resource naming (required). | _None_ (must be set) | +| `environment` | Environment tag. | `development` | +| `modelPatterns` | List of model ID patterns to allow. | `["anthropic.*"]` | +| `userName` | Override IAM user name. | `{team}-{project}-bedrock-{stack}` | +| `policyName` | Override IAM policy name. | `{team}-{project}-bedrock-policy-{stack}` | +| `createAccessKey` | Create a long-lived IAM access key. | `true` | +| `createBedrockApiKey` | Create a Bedrock API key and allow `bedrock:CallWithBearerToken`. | `false` | +| `bedrockApiKeyAgeDays` | Days until the Bedrock API key expires (1-36600). Some AWS organizations cap this with a service control policy; set it to match your limit. | `180` | + +AWS provider config: + +| Config Key | Description | Default | +| --- | --- | --- | +| `aws:region` | AWS region (required), e.g. `us-east-1`. | _None_ (must be set) | +| `aws:profile` | AWS SSO profile name. | _Inherited from AWS CLI config_ | + +## Outputs + +```bash +uv run pulumi stack output # all outputs +uv run pulumi stack output access_key_id # access key ID +uv run pulumi stack output secret_access_key --show-secrets # secret key +uv run pulumi stack output bedrock_api_key --show-secrets # Bedrock API key +uv run pulumi stack output usage_instructions # Usage examples +``` + +- `user_name` -- IAM user name +- `user_arn` -- IAM user ARN +- `access_key_id` -- long-lived access key ID (when `createAccessKey` is on) +- `secret_access_key` -- (secret) long-lived secret access key (when `createAccessKey` is on) +- `bedrock_api_key` -- (secret) Bedrock API key (when `createBedrockApiKey` is on) +- `bedrock_api_key_alias` -- the API key's credential alias (`-at-`) +- `bedrock_api_key_expiration` -- when the API key expires +- `region` -- AWS region +- `allowed_models` -- model ID patterns allowed by the policy +- `usage_instructions` -- connection examples +- `tags` -- applied resource tags (`project`, `managed-by`, `environment`; prefixed when `tag_prefix` is set) + +## Using Bedrock + +### Python (anthropic SDK) + +```python +import anthropic + +client = anthropic.AnthropicBedrock( + aws_access_key="YOUR_ACCESS_KEY_ID", + aws_secret_key="YOUR_SECRET_ACCESS_KEY", + aws_region="us-east-1", +) + +message = client.messages.create( + model="anthropic.claude-sonnet-4-20250514-v1:0", + max_tokens=1024, + messages=[{"role": "user", "content": "Hello, Claude!"}], +) + +print(message.content[0].text) +``` + +### Python (boto3) + +```python +import json +import boto3 + +client = boto3.client( + "bedrock-runtime", + region_name="us-east-1", + aws_access_key_id="YOUR_ACCESS_KEY_ID", + aws_secret_access_key="YOUR_SECRET_ACCESS_KEY", +) + +response = client.invoke_model( + modelId="anthropic.claude-sonnet-4-20250514-v1:0", + contentType="application/json", + accept="application/json", + body=json.dumps({ + "anthropic_version": "bedrock-2023-05-31", + "max_tokens": 1024, + "messages": [{"role": "user", "content": "Hello, Claude!"}], + }), +) + +result = json.loads(response["body"].read()) +print(result["content"][0]["text"]) +``` + +### Environment Variables + +```bash +export AWS_ACCESS_KEY_ID=$(uv run pulumi stack output access_key_id) +export AWS_SECRET_ACCESS_KEY=$(uv run pulumi stack output secret_access_key --show-secrets) +export AWS_DEFAULT_REGION=$(uv run pulumi stack output region) +``` + +### Claude Code (Bedrock API key) + +```bash +export CLAUDE_CODE_USE_BEDROCK=1 +export AWS_REGION=$(uv run pulumi stack output region) +export AWS_BEARER_TOKEN_BEDROCK=$(uv run pulumi stack output bedrock_api_key --show-secrets) +``` + +## Extending (Team-Specific Stacks) + +Import `deploy_stack` from a team wrapper project and pass additional IAM policy statements. Pass `tag_prefix` to namespace the tag keys (`myteam:project` instead of `project`); by default they are unprefixed: + +```python +from ess_aws_bedrock.stack import deploy_stack + +deploy_stack( + extra_statements=[{ + "Effect": "Allow", + "Action": ["bedrock:Retrieve"], + "Resource": "arn:aws:bedrock:us-east-1:123456789012:knowledge-base/*", + }], + tag_prefix="myteam", +) +``` + +## Destroying Resources + +```bash +uv run pulumi destroy +``` + +This deletes the IAM user, policy, access key, and Bedrock API key. Any applications using the credentials will lose access immediately. + +## Running Tests + +```bash +uv run pytest packages/python/ess-aws-bedrock +``` + +Tests cover the policy document builder and config validation. + +## License + +[Apache 2.0](https://choosealicense.com/licenses/apache-2.0/). diff --git a/packages/python/ess-aws-bedrock/pyproject.toml b/packages/python/ess-aws-bedrock/pyproject.toml new file mode 100644 index 0000000..d5bbc62 --- /dev/null +++ b/packages/python/ess-aws-bedrock/pyproject.toml @@ -0,0 +1,22 @@ +[project] +name = "ess-aws-bedrock" +version = "0.1.0" +description = "AWS Bedrock Anthropic model access with Pulumi" +license = "Apache-2.0" +requires-python = ">=3.12,<3.13" +dependencies = [ + "pulumi>=3.202.0,<4.0.0", + "pulumi-aws>=6.0.0", + "pulumi-utils", +] + +[tool.uv.sources] +pulumi-utils = { workspace = true } + +[build-system] +requires = ["hatchling>=1.27"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/ess_aws_bedrock"] +exclude = ["**/test_*.py"] diff --git a/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/__init__.py b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/__init__.py new file mode 100644 index 0000000..9e45641 --- /dev/null +++ b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/__init__.py @@ -0,0 +1,11 @@ +"""AWS Bedrock package for provisioning IAM access to Anthropic models with Pulumi. + +Public API for composing AWS Bedrock stacks:: + + from ess_aws_bedrock import deploy_stack + result = deploy_stack() +""" + +from ess_aws_bedrock.stack import StackOutputs, deploy_stack + +__all__ = ["StackOutputs", "deploy_stack"] diff --git a/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/__main__.py b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/__main__.py new file mode 100644 index 0000000..d8de914 --- /dev/null +++ b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/__main__.py @@ -0,0 +1,15 @@ +"""AWS Bedrock deployment with Pulumi. + +Creates the full AWS Bedrock stack: + 1. IAM user with Bedrock invoke permissions + 2. Scoped IAM policy for Anthropic foundation models + 3. Long-lived access keys for programmatic API access + +This is the standalone entry-point. For deployments that need additional +IAM policy statements or a team-specific tag prefix, call +``ess_aws_bedrock.stack.deploy_stack`` from a team wrapper project. +""" + +from ess_aws_bedrock.stack import deploy_stack + +deploy_stack() diff --git a/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/config.py b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/config.py new file mode 100644 index 0000000..5ed1957 --- /dev/null +++ b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/config.py @@ -0,0 +1,187 @@ +"""Pulumi config loading for AWS Bedrock infrastructure. + +Maps Pulumi stack configuration values (from Pulumi..yaml) to typed +Python objects for use across resource modules. +""" + +from dataclasses import dataclass, field + +import pulumi +from pulumi_utils import get_resource_name + +_DEFAULT_ENVIRONMENT = "development" +_DEFAULT_MODEL_PATTERNS = ("anthropic.*",) +_DEFAULT_BEDROCK_API_KEY_AGE_DAYS = 180 +_MIN_BEDROCK_API_KEY_AGE_DAYS = 1 +_MAX_BEDROCK_API_KEY_AGE_DAYS = 36600 + +MANAGED_BY = "pulumi" +_RESERVED_TAG_NAMESPACE = "aws:" + + +@dataclass(frozen=True) +class AwsBedrockConfig: + """Typed configuration for the AWS Bedrock stack.""" + + project_name: str + region: str + team_name: str + environment: str + user_name: str + policy_name: str + model_patterns: tuple[str, ...] + create_access_key: bool = True + create_bedrock_api_key: bool = False + bedrock_api_key_age_days: int = _DEFAULT_BEDROCK_API_KEY_AGE_DAYS + tags: dict[str, str] = field(default_factory=dict) + + +def _parse_model_patterns(raw: object) -> tuple[str, ...]: + """Parse and validate the ``modelPatterns`` config value. + + Args: + raw: Value from ``cfg.get_object("modelPatterns")``. + ``None`` when the key is omitted. A bare string is + accepted and wrapped into a single-element list. + + Returns: + Validated tuple of non-empty model pattern strings. + + Raises: + TypeError: If *raw* is not a list or contains non-string entries. + ValueError: If the list is empty or contains only blank strings. + """ + if raw is None: + return _DEFAULT_MODEL_PATTERNS + + if isinstance(raw, str): + raw = [raw] + + if not isinstance(raw, list): + raise TypeError( + f"modelPatterns must be a list of strings, got {type(raw).__name__}" + ) + + for entry in raw: + if not isinstance(entry, str): + raise TypeError( + f"each entry in modelPatterns must be a string, " + f"got {type(entry).__name__}: {entry!r}" + ) + + patterns = tuple(pattern.strip() for pattern in raw if pattern.strip()) + if not patterns: + raise ValueError( + "modelPatterns was set but contains no valid patterns; " + "remove the key to use the defaults or provide at least one " + f"non-empty pattern (defaults: {list(_DEFAULT_MODEL_PATTERNS)})" + ) + + return patterns + + +def _parse_bedrock_api_key_age_days(raw: int | None) -> int: + """Validate the ``bedrockApiKeyAgeDays`` config value. + + Args: + raw: Value from ``cfg.get_int("bedrockApiKeyAgeDays")``. + ``None`` when the key is omitted. + + Returns: + Number of days until the Bedrock API key expires. + + Raises: + ValueError: If *raw* is outside the range IAM accepts. + """ + if raw is None: + return _DEFAULT_BEDROCK_API_KEY_AGE_DAYS + + if not _MIN_BEDROCK_API_KEY_AGE_DAYS <= raw <= _MAX_BEDROCK_API_KEY_AGE_DAYS: + raise ValueError( + f"bedrockApiKeyAgeDays must be between {_MIN_BEDROCK_API_KEY_AGE_DAYS} " + f"and {_MAX_BEDROCK_API_KEY_AGE_DAYS}, got {raw}" + ) + + return raw + + +def _compose_tags( + project_name: str, + environment: str, + tag_prefix: str | None, +) -> dict[str, str]: + """Build the resource tags, namespacing each key when a prefix is given. + + Args: + project_name: Value for the ``project`` tag. + environment: Value for the ``environment`` tag. + tag_prefix: Namespace for the tag keys, e.g. ``"myteam"`` produces + ``myteam:project``. ``None`` or ``""`` leaves keys unprefixed. + + Returns: + Tag keys mapped to their values. + + Raises: + ValueError: If *tag_prefix* would produce a key in the ``aws:`` + namespace, which AWS reserves. + """ + if tag_prefix and f"{tag_prefix}:".lower().startswith(_RESERVED_TAG_NAMESPACE): + raise ValueError( + f"tag_prefix {tag_prefix!r} produces keys in the reserved " + f"{_RESERVED_TAG_NAMESPACE!r} namespace" + ) + + def compose_tag_key(name: str) -> str: + return f"{tag_prefix}:{name}" if tag_prefix else name + + return { + compose_tag_key("project"): project_name, + compose_tag_key("managed-by"): MANAGED_BY, + compose_tag_key("environment"): environment, + } + + +def load_config(tag_prefix: str | None = None) -> AwsBedrockConfig: + """Load and validate configuration from the Pulumi stack config. + + Args: + tag_prefix: Namespace for the resource tag keys, e.g. ``"myteam"`` + produces ``myteam:project``. ``None`` leaves keys unprefixed. + + Raises: + TypeError: If ``modelPatterns`` is not a ``str``, ``list[str]``, + or contains non-string entries. + ValueError: If ``modelPatterns`` is set but empty or all-blank, + ``bedrockApiKeyAgeDays`` is outside 1-36600, or *tag_prefix* + produces keys in the reserved ``aws:`` namespace. + + Returns: + AwsBedrockConfig with all infrastructure parameters. + """ + cfg = pulumi.Config() + aws_cfg = pulumi.Config("aws") + project_name = pulumi.get_project() + team_name = cfg.require("teamName") + environment = cfg.get("environment") or _DEFAULT_ENVIRONMENT + region = aws_cfg.require("region") + + raw_patterns = cfg.get_object("modelPatterns") + model_patterns = _parse_model_patterns(raw_patterns) + + return AwsBedrockConfig( + project_name=project_name, + region=region, + team_name=team_name, + environment=environment, + user_name=cfg.get("userName") + or get_resource_name(team_name, project_name, "bedrock"), + policy_name=cfg.get("policyName") + or get_resource_name(team_name, project_name, "bedrock-policy"), + model_patterns=model_patterns, + create_access_key=cfg.get_bool("createAccessKey", True), + create_bedrock_api_key=cfg.get_bool("createBedrockApiKey", False), + bedrock_api_key_age_days=_parse_bedrock_api_key_age_days( + cfg.get_int("bedrockApiKeyAgeDays") + ), + tags=_compose_tags(project_name, environment, tag_prefix), + ) diff --git a/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/iam.py b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/iam.py new file mode 100644 index 0000000..c526f85 --- /dev/null +++ b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/iam.py @@ -0,0 +1,181 @@ +"""AWS IAM resources for Bedrock model access. + +Creates an IAM user with a scoped policy for invoking Bedrock foundation +models, plus optional credentials: a long-lived access key for SigV4 API +access and/or a Bedrock API key (bearer token) for tools such as Claude Code. +""" + +import json +from collections.abc import Sequence +from dataclasses import dataclass + +import pulumi +import pulumi_aws as aws + +_BEDROCK_SERVICE_NAME = "bedrock.amazonaws.com" + + +@dataclass +class IamOutputs: + """Outputs from the IAM module. + + Credential fields are ``None`` when the corresponding credential is + disabled in config. + """ + + user_name: pulumi.Output[str] + user_arn: pulumi.Output[str] + access_key_id: pulumi.Output[str] | None = None + secret_access_key: pulumi.Output[str] | None = None + bedrock_api_key: pulumi.Output[str] | None = None + bedrock_api_key_alias: pulumi.Output[str] | None = None + bedrock_api_key_expiration: pulumi.Output[str] | None = None + + +def _build_model_resources( + model_patterns: Sequence[str], +) -> list[str]: + """Build IAM policy resource ARNs from model ID patterns. + + Args: + model_patterns: Model ID patterns (e.g. ``["anthropic.*"]``). + + Returns: + List of ARN strings with wildcard region for each pattern. + """ + return [ + f"arn:aws:bedrock:*::foundation-model/{pattern}" for pattern in model_patterns + ] + + +def _build_policy_document( + model_patterns: Sequence[str], + extra_statements: Sequence[dict] = (), + allow_bearer_token: bool = False, +) -> str: + """Build the IAM policy JSON document for Bedrock access. + + Args: + model_patterns: Model ID patterns to allow invocation on. + extra_statements: Additional IAM policy statements to include. + Must be plain Python dicts — Pulumi ``Output`` values inside + statements will cause ``json.dumps()`` to fail. + allow_bearer_token: Grant ``bedrock:CallWithBearerToken``, which + Bedrock requires before it accepts a Bedrock API key. + + Returns: + JSON-encoded IAM policy document. + """ + statements: list[dict] = [ + { + "Effect": "Allow", + "Action": [ + "bedrock:InvokeModel", + "bedrock:InvokeModelWithResponseStream", + ], + "Resource": _build_model_resources(model_patterns), + }, + { + "Effect": "Allow", + "Action": [ + "bedrock:InvokeModel", + "bedrock:InvokeModelWithResponseStream", + ], + "Resource": "arn:aws:bedrock:*:*:inference-profile/us.*", + }, + { + "Effect": "Allow", + "Action": [ + "bedrock:ListFoundationModels", + "bedrock:GetFoundationModel", + "bedrock:ListInferenceProfiles", + ], + "Resource": "*", + }, + ] + if allow_bearer_token: + statements.append( + { + "Effect": "Allow", + "Action": "bedrock:CallWithBearerToken", + "Resource": "*", + } + ) + statements.extend(extra_statements) + + return json.dumps({"Version": "2012-10-17", "Statement": statements}) + + +def create_iam( # noqa: PLR0913 + user_name: str, + policy_name: str, + model_patterns: Sequence[str], + tags: dict[str, str], + extra_statements: Sequence[dict] = (), + *, + create_access_key: bool = True, + create_bedrock_api_key: bool = False, + bedrock_api_key_age_days: int | None = None, +) -> IamOutputs: + """Create an IAM user with Bedrock invoke permissions and credentials. + + Args: + user_name: Name for the IAM user. + policy_name: Name for the inline IAM policy. + model_patterns: Model ID patterns to allow (e.g. ``["anthropic.*"]``). + tags: AWS resource tags to apply. + extra_statements: Additional IAM policy statements to merge into the + policy document (e.g. for Bedrock Knowledge Bases or Agents). + Must be plain Python dicts — Pulumi ``Output`` values inside + statements will cause ``json.dumps()`` to fail. + create_access_key: Create a long-lived IAM access key. + create_bedrock_api_key: Create a Bedrock API key (service-specific + credential) and allow ``bedrock:CallWithBearerToken``. + bedrock_api_key_age_days: Days until the Bedrock API key expires. + ``None`` creates a key that never expires. + + Returns: + IamOutputs with user identifiers and the enabled credentials. + """ + user = aws.iam.User( + "bedrock-user", + name=user_name, + tags=tags, + ) + + aws.iam.UserPolicy( + "bedrock-policy", + user=user.name, + name=policy_name, + policy=_build_policy_document( + model_patterns, + extra_statements, + allow_bearer_token=create_bedrock_api_key, + ), + ) + + outputs = IamOutputs(user_name=user.name, user_arn=user.arn) + + if create_access_key: + access_key = aws.iam.AccessKey( + "bedrock-access-key", + user=user.name, + ) + outputs.access_key_id = access_key.id + outputs.secret_access_key = access_key.secret + + if create_bedrock_api_key: + credential = aws.iam.ServiceSpecificCredential( + "bedrock-api-key", + service_name=_BEDROCK_SERVICE_NAME, + user_name=user.name, + credential_age_days=bedrock_api_key_age_days, + ) + # For Bedrock, the secret is already the complete ABSK... API key. + outputs.bedrock_api_key = pulumi.Output.secret( + credential.service_credential_secret + ) + outputs.bedrock_api_key_alias = credential.service_credential_alias + outputs.bedrock_api_key_expiration = credential.expiration_date + + return outputs diff --git a/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/stack.py b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/stack.py new file mode 100644 index 0000000..4418270 --- /dev/null +++ b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/stack.py @@ -0,0 +1,210 @@ +"""Composable AWS Bedrock stack deployment. + +Provides ``deploy_stack()`` -- the single entry-point that orchestrates all +AWS Bedrock IAM resources (user, policy, access key, Bedrock API key). +Callers can extend the base policy by passing ``extra_statements``. + +Usage:: + + from ess_aws_bedrock.stack import deploy_stack + + # Standalone (Anthropic models only) + result = deploy_stack() + + # With additional IAM policy statements + result = deploy_stack(extra_statements=[{ + "Effect": "Allow", + "Action": ["bedrock:Retrieve"], + "Resource": "arn:aws:bedrock:us-east-1:123456789012:knowledge-base/*", + }]) +""" + +from collections.abc import Sequence +from dataclasses import dataclass + +import pulumi + +from ess_aws_bedrock.config import AwsBedrockConfig, load_config +from ess_aws_bedrock.iam import IamOutputs, create_iam + + +@dataclass +class StackOutputs: + """All outputs produced by a full AWS Bedrock stack deployment.""" + + iam: IamOutputs + config: AwsBedrockConfig + + +def deploy_stack( + extra_statements: Sequence[dict] = (), + *, + tag_prefix: str | None = None, +) -> StackOutputs: + """Deploy the full AWS Bedrock stack and export Pulumi outputs. + + Args: + extra_statements: Additional IAM policy statements to merge into + the Bedrock policy (e.g. for Knowledge Bases or Agents). + tag_prefix: Namespace for resource tag keys (``:project``, + ``:managed-by``, ``:environment``). ``None`` + leaves keys unprefixed (``project``, ``managed-by``, + ``environment``). + + Returns: + StackOutputs with IAM credentials and resolved config. + """ + cfg = load_config(tag_prefix=tag_prefix) + + iam = create_iam( + user_name=cfg.user_name, + policy_name=cfg.policy_name, + model_patterns=cfg.model_patterns, + tags=cfg.tags, + extra_statements=extra_statements, + create_access_key=cfg.create_access_key, + create_bedrock_api_key=cfg.create_bedrock_api_key, + bedrock_api_key_age_days=cfg.bedrock_api_key_age_days, + ) + + _export_outputs(iam, cfg) + + return StackOutputs(iam=iam, config=cfg) + + +def _build_usage_instructions( + access_key_id: str, + region: str, +) -> str: + """Build usage instructions text for the provisioned Bedrock access. + + Args: + access_key_id: The IAM access key ID (safe to display). + region: AWS region for Bedrock API calls. + + Returns: + Formatted usage instructions with credentials and Python examples. + """ + return f""" +# AWS Bedrock Connection Information + +## Credentials +Access Key ID: {access_key_id} +Secret Access Key: Use `pulumi stack output secret_access_key --show-secrets` +Region: {region} + +## Python Usage (with anthropic SDK) +```python +import anthropic + +client = anthropic.AnthropicBedrock( + aws_access_key="YOUR_ACCESS_KEY_ID", + aws_secret_key="YOUR_SECRET_ACCESS_KEY", + aws_region="{region}", +) + +message = client.messages.create( + model="anthropic.claude-sonnet-4-20250514-v1:0", + max_tokens=1024, + messages=[ + {{"role": "user", "content": "Hello, Claude!"}} + ], +) + +print(message.content[0].text) +``` + +## Python Usage (with boto3) +```python +import json +import boto3 + +client = boto3.client( + "bedrock-runtime", + region_name="{region}", + aws_access_key_id="YOUR_ACCESS_KEY_ID", + aws_secret_access_key="YOUR_SECRET_ACCESS_KEY", +) + +response = client.invoke_model( + modelId="anthropic.claude-sonnet-4-20250514-v1:0", + contentType="application/json", + accept="application/json", + body=json.dumps({{ + "anthropic_version": "bedrock-2023-05-31", + "max_tokens": 1024, + "messages": [ + {{"role": "user", "content": "Hello, Claude!"}} + ], + }}), +) + +result = json.loads(response["body"].read()) +print(result["content"][0]["text"]) +``` + +## Environment Variables +export AWS_ACCESS_KEY_ID="{access_key_id}" +export AWS_SECRET_ACCESS_KEY="YOUR_SECRET_ACCESS_KEY" +export AWS_REGION="{region}" +export AWS_DEFAULT_REGION="{region}" # Required by boto3 + +## Get Secret Access Key +Use: pulumi stack output secret_access_key --show-secrets +""" + + +def _build_api_key_usage_instructions(region: str) -> str: + """Build usage instructions text for a Bedrock API key. + + Args: + region: AWS region for Bedrock API calls. + + Returns: + Formatted usage instructions for Claude Code and other bearer-token + clients. + """ + return f""" +# AWS Bedrock API Key + +## Get the Key +Use: pulumi stack output bedrock_api_key --show-secrets +Expiry: pulumi stack output bedrock_api_key_expiration + +## Claude Code +export CLAUDE_CODE_USE_BEDROCK=1 +export AWS_REGION="{region}" +export AWS_BEARER_TOKEN_BEDROCK="YOUR_BEDROCK_API_KEY" +""" + + +def _export_outputs(iam: IamOutputs, cfg: AwsBedrockConfig) -> None: + """Register standard Pulumi exports for the stack.""" + pulumi.export("user_name", iam.user_name) + pulumi.export("user_arn", iam.user_arn) + pulumi.export("region", cfg.region) + pulumi.export("allowed_models", list(cfg.model_patterns)) + pulumi.export("tags", cfg.tags) + + instructions: list[pulumi.Input[str]] = [] + + if iam.access_key_id is not None and iam.secret_access_key is not None: + pulumi.export("access_key_id", iam.access_key_id) + pulumi.export("secret_access_key", pulumi.Output.secret(iam.secret_access_key)) + instructions.append( + iam.access_key_id.apply( + lambda key_id: _build_usage_instructions(key_id, cfg.region) + ) + ) + + if iam.bedrock_api_key is not None: + pulumi.export("bedrock_api_key", iam.bedrock_api_key) + pulumi.export("bedrock_api_key_alias", iam.bedrock_api_key_alias) + pulumi.export("bedrock_api_key_expiration", iam.bedrock_api_key_expiration) + instructions.append(_build_api_key_usage_instructions(cfg.region)) + + if instructions: + pulumi.export( + "usage_instructions", + pulumi.Output.all(*instructions).apply("".join), + ) diff --git a/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/test_config.py b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/test_config.py new file mode 100644 index 0000000..a9ca67d --- /dev/null +++ b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/test_config.py @@ -0,0 +1,140 @@ +"""Tests for ess_aws_bedrock.config — config parsing and validation.""" + +import pytest + +from ess_aws_bedrock.config import ( + _DEFAULT_BEDROCK_API_KEY_AGE_DAYS, + _DEFAULT_MODEL_PATTERNS, + AwsBedrockConfig, + _compose_tags, + _parse_bedrock_api_key_age_days, + _parse_model_patterns, +) + + +class TestParseModelPatterns: + """Tests for _parse_model_patterns.""" + + def test_none_returns_defaults(self): + assert _parse_model_patterns(None) == _DEFAULT_MODEL_PATTERNS + + def test_valid_list(self): + assert _parse_model_patterns(["anthropic.*"]) == ("anthropic.*",) + + def test_multiple_patterns(self): + result = _parse_model_patterns(["anthropic.*", "meta.*"]) + assert result == ("anthropic.*", "meta.*") + + def test_filters_blank_strings(self): + result = _parse_model_patterns(["anthropic.*", "", "meta.*"]) + assert result == ("anthropic.*", "meta.*") + + def test_empty_list_raises_value_error(self): + with pytest.raises(ValueError, match="no valid patterns"): + _parse_model_patterns([]) + + def test_all_blank_strings_raises_value_error(self): + with pytest.raises(ValueError, match="no valid patterns"): + _parse_model_patterns(["", ""]) + + def test_string_wraps_to_list(self): + assert _parse_model_patterns("anthropic.*") == ("anthropic.*",) + + def test_blank_string_raises_value_error(self): + with pytest.raises(ValueError, match="no valid patterns"): + _parse_model_patterns("") + + def test_dict_instead_of_list_raises_type_error(self): + with pytest.raises(TypeError, match="must be a list"): + _parse_model_patterns({"pattern": "anthropic.*"}) + + def test_int_instead_of_list_raises_type_error(self): + with pytest.raises(TypeError, match="must be a list"): + _parse_model_patterns(42) + + def test_list_with_non_string_entry_raises_type_error(self): + with pytest.raises(TypeError, match="each entry.*must be a string"): + _parse_model_patterns(["anthropic.*", 123]) + + def test_list_with_none_entry_raises_type_error(self): + with pytest.raises(TypeError, match="each entry.*must be a string"): + _parse_model_patterns(["anthropic.*", None]) + + def test_list_with_dict_entry_raises_type_error(self): + with pytest.raises(TypeError, match="each entry.*must be a string"): + _parse_model_patterns([{"pattern": "anthropic.*"}]) + + def test_whitespace_only_raises_value_error(self): + with pytest.raises(ValueError, match="no valid patterns"): + _parse_model_patterns([" ", "\t"]) + + def test_whitespace_string_raises_value_error(self): + with pytest.raises(ValueError, match="no valid patterns"): + _parse_model_patterns(" ") + + def test_strips_whitespace_from_patterns(self): + result = _parse_model_patterns([" anthropic.* ", " meta.* "]) + assert result == ("anthropic.*", "meta.*") + + +class TestParseBedrockApiKeyAgeDays: + """Tests for _parse_bedrock_api_key_age_days.""" + + def test_none_returns_default(self): + assert ( + _parse_bedrock_api_key_age_days(None) == _DEFAULT_BEDROCK_API_KEY_AGE_DAYS + ) + + @pytest.mark.parametrize("days", [1, 90, 36600]) + def test_in_range_passes_through(self, days): + assert _parse_bedrock_api_key_age_days(days) == days + + @pytest.mark.parametrize("days", [0, -1, 36601]) + def test_out_of_range_raises_value_error(self, days): + with pytest.raises(ValueError, match="between 1 and 36600"): + _parse_bedrock_api_key_age_days(days) + + +class TestCredentialDefaults: + """Credential flags keep the original behavior when unset.""" + + def test_access_key_on_api_key_off(self): + cfg = AwsBedrockConfig( + project_name="ess-aws-bedrock", + region="us-east-1", + team_name="team", + environment="development", + user_name="user", + policy_name="policy", + model_patterns=_DEFAULT_MODEL_PATTERNS, + ) + assert cfg.create_access_key is True + assert cfg.create_bedrock_api_key is False + assert cfg.bedrock_api_key_age_days == _DEFAULT_BEDROCK_API_KEY_AGE_DAYS + + +class TestComposeTags: + """Tests for _compose_tags.""" + + @pytest.mark.parametrize("tag_prefix", [None, ""]) + def test_no_prefix_leaves_keys_unprefixed(self, tag_prefix): + assert _compose_tags("proj", "development", tag_prefix) == { + "project": "proj", + "managed-by": "pulumi", + "environment": "development", + } + + def test_prefix_namespaces_every_key(self): + assert _compose_tags("proj", "production", "myteam") == { + "myteam:project": "proj", + "myteam:managed-by": "pulumi", + "myteam:environment": "production", + } + + @pytest.mark.parametrize("tag_prefix", ["aws", "AWS", "aws:team"]) + def test_reserved_namespace_raises_value_error(self, tag_prefix): + with pytest.raises(ValueError, match="reserved"): + _compose_tags("proj", "development", tag_prefix) + + def test_prefix_merely_starting_with_aws_is_allowed(self): + assert "awsome:project" in _compose_tags("proj", "development", "awsome") diff --git a/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/test_iam.py b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/test_iam.py new file mode 100644 index 0000000..a68468e --- /dev/null +++ b/packages/python/ess-aws-bedrock/src/ess_aws_bedrock/test_iam.py @@ -0,0 +1,40 @@ +"""Tests for ess_aws_bedrock.iam — policy document.""" + +import json + +from ess_aws_bedrock.iam import _build_policy_document + + +def _actions(policy_json: str) -> list: + return [stmt["Action"] for stmt in json.loads(policy_json)["Statement"]] + + +class TestBuildPolicyDocument: + """Tests for _build_policy_document.""" + + def test_default_has_no_bearer_token_statement(self): + policy = _build_policy_document(["anthropic.*"]) + assert "bedrock:CallWithBearerToken" not in _actions(policy) + + def test_bearer_token_statement_when_enabled(self): + policy = _build_policy_document(["anthropic.*"], allow_bearer_token=True) + statements = json.loads(policy)["Statement"] + assert { + "Effect": "Allow", + "Action": "bedrock:CallWithBearerToken", + "Resource": "*", + } in statements + + def test_extra_statements_follow_base_statements(self): + extra = {"Effect": "Allow", "Action": "bedrock:Retrieve", "Resource": "*"} + policy = _build_policy_document( + ["anthropic.*"], [extra], allow_bearer_token=True + ) + assert json.loads(policy)["Statement"][-1] == extra + + def test_model_patterns_become_foundation_model_arns(self): + policy = _build_policy_document(["anthropic.*", "meta.*"]) + assert json.loads(policy)["Statement"][0]["Resource"] == [ + "arn:aws:bedrock:*::foundation-model/anthropic.*", + "arn:aws:bedrock:*::foundation-model/meta.*", + ] diff --git a/pyproject.toml b/pyproject.toml index c246ac6..ab32cce 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,6 +23,7 @@ members = [ "tools/python/langsmith-hosting", "tools/python/pulumi-utils", "packages/python/ess-auth", + "packages/python/ess-aws-bedrock", "packages/python/ess-browser", "packages/python/ess-dirs", "packages/python/ess-langsmith-client", diff --git a/uv.lock b/uv.lock index 59d1167..8f60a91 100644 --- a/uv.lock +++ b/uv.lock @@ -7,6 +7,7 @@ members = [ "azure-ai", "core-github", "ess-auth", + "ess-aws-bedrock", "ess-browser", "ess-dirs", "ess-hello-jwt-auth-code", @@ -540,6 +541,23 @@ requires-dist = [ ] provides-extras = ["jwks"] +[[package]] +name = "ess-aws-bedrock" +version = "0.1.0" +source = { editable = "packages/python/ess-aws-bedrock" } +dependencies = [ + { name = "pulumi" }, + { name = "pulumi-aws" }, + { name = "pulumi-utils" }, +] + +[package.metadata] +requires-dist = [ + { name = "pulumi", specifier = ">=3.202.0,<4.0.0" }, + { name = "pulumi-aws", specifier = ">=6.0.0" }, + { name = "pulumi-utils", editable = "tools/python/pulumi-utils" }, +] + [[package]] name = "ess-browser" version = "0.1.0"