diff --git a/README.md b/README.md index 39fc7f1..9d039ca 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,7 @@ run the benchmarks with Freehand. | Anthropic | `freehand login anthropic`, then `freehand --provider anthropic` | | GitHub Copilot (experimental) | [Install the optional SDK](docs/copilot.md), then `freehand login copilot` | | Amazon Bedrock | `freehand login bedrock` (Claude) or `freehand login bedrock-openai`, with a Bedrock API key and a region | +| Amazon Bedrock with your AWS login | `pip install 'freehand-ai[bedrock]'`, then `freehand login bedrock-aws --region us-east-1 --aws-profile ` (Claude); leave the profile empty to use your current AWS login (`AWS_PROFILE`, `aws sso login`) | | Azure OpenAI, Claude in Microsoft Foundry | `freehand login azure` or `freehand login azure-claude`, with an API key, the resource and the deployment | | Google Vertex AI | `pip install 'freehand-ai[vertex]'` and `gcloud auth application-default login`, then `freehand login vertex` (Gemini) or `freehand login vertex-claude`, with the project | | Any OpenAI-compatible Chat Completions API | `freehand --provider openai-chat --api-base --api-key-env ` | diff --git a/pyproject.toml b/pyproject.toml index a32b933..7aa3697 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,9 +36,11 @@ Issues = "https://github.com/microsoft/FreeHand/issues" freehand = "freehand.cli:main" [project.optional-dependencies] -dev = ["pytest>=8", "pyflakes>=3"] +dev = ["pytest>=8", "pyflakes>=3", "boto3>=1.28.57,<2"] copilot = ["microsoft-copilot-sdk==2.0.6; python_version >= '3.11'"] vertex = ["google-auth[requests]>=2,<3"] +# Claude on Bedrock signed with an AWS profile or the current AWS login (the Anthropic SDK's own Bedrock extra) +bedrock = ["boto3>=1.28.57,<2", "botocore>=1.31.57,<2"] [tool.setuptools.dynamic] version = { attr = "freehand.__version__" } diff --git a/src/freehand/cli.py b/src/freehand/cli.py index 5cb7527..a8a1a80 100644 --- a/src/freehand/cli.py +++ b/src/freehand/cli.py @@ -47,6 +47,8 @@ # services that take the person's Google Cloud sign-in instead of a key: `login` only names the project GOOGLE_SERVICES = {"vertex": ("Google Vertex AI", providers.CHAT), "vertex-claude": ("Vertex AI Claude", providers.ANTHROPIC)} +# services that take the person's AWS sign-in instead of a key: `login` names the region and, optionally, a profile +AWS_SERVICES = {"bedrock-aws": ("Amazon Bedrock (AWS sign-in)", providers.ANTHROPIC)} UNTRUSTED_HEADLESS = ("This folder is not trusted, so its AGENTS.md and project skills are left out. To load them, " "run `freehand` here once and trust the folder.") CHECK_TASK = ("This is a connectivity check of the Freehand harness. Call the bash tool with command " @@ -173,6 +175,41 @@ def login_google(args: argparse.Namespace) -> int: return 0 +def aws_settings(service: str, places: dict[str, str], profile: str) -> dict[str, Any]: + """What an AWS sign-in service sets: its address in the region, and the profile when one is named (none: the + AWS CLI's default, which follows AWS_PROFILE and whatever `aws sso login` last signed in).""" + from freehand import session + return {**session.service_settings(service, places), "aws_profile": profile or None} + + +def login_aws(args: argparse.Namespace) -> int: + """Point new sessions at Claude on Bedrock signed with an AWS profile. Nothing secret is saved: the AWS tools + keep the credentials, and boto3 reads them for each request.""" + from freehand import session + label, provider = AWS_SERVICES[args.service] + if auth.aws_problem() == auth.AWS_INSTALL: + print(auth.AWS_INSTALL, file=sys.stderr) + return 1 + try: + places = ask_places(args, label) + if places is None: + return 1 + profile = (args.aws_profile if args.aws_profile is not None + else read_line("AWS profile (empty: your current AWS login)")).strip() + except KeyboardInterrupt: + print() + return 1 + problem = auth.aws_problem(profile or None) + if problem: + print(problem + " Nothing was saved.", file=sys.stderr) + return 1 + dropped = session.set_default_provider(provider, aws_settings(args.service, places, profile)) + who = f"the AWS profile {profile}" if profile else "your current AWS login" + print(f"New sessions use {label} in {places['region']} with {who}" + ( + f" (removed the previous provider's {', '.join(dropped)} from {session.settings_path()})." if dropped else ".")) + return 0 + + def login_key(args: argparse.Namespace, label: str, provider: str | None, name: str) -> int: from freehand import session preset = {} if args.key_env else session.SERVICES.get(args.service) or {} @@ -252,6 +289,8 @@ def cmd_login(args: argparse.Namespace) -> int: return login_copilot(args) if args.service in GOOGLE_SERVICES and not args.key_env: return login_google(args) + if args.service in AWS_SERVICES and not args.key_env: + return login_aws(args) target = key_target(args) if target: return login_key(args, *target) @@ -1186,15 +1225,17 @@ def main(argv: list[str] | None = None) -> int: p = sub.add_parser("login", help="Continue with ChatGPT (your ChatGPT plan), or save an API key: " "`login openai`, `login anthropic`, or sign in with `login copilot`") p.add_argument("service", nargs="?", default="chatgpt", choices=["chatgpt", "copilot", *KEY_SERVICES, - *GOOGLE_SERVICES], + *GOOGLE_SERVICES, *AWS_SERVICES], help="chatgpt (the default) signs in through the browser; openai and anthropic ask for an API key; " - "vertex and vertex-claude use the Google Cloud sign-in") + "vertex and vertex-claude use the Google Cloud sign-in; bedrock-aws uses an AWS profile") p.add_argument("--key-env", metavar="NAME", help="save a key under this variable's name instead, for a gateway " 'or another service that config.json names with "api_key_env"') p.add_argument("--default", action="store_true", help="make this the provider of new sessions") p.add_argument("--region", help="the region of a regional service (bedrock: default AWS_REGION or us-east-1)") p.add_argument("--resource", help="the resource name in an Azure service's address (azure, azure-claude)") p.add_argument("--deployment", help="the deployment name an Azure service calls the model by") + p.add_argument("--aws-profile", metavar="NAME", help="the AWS profile that signs bedrock-aws requests " + '(default: your current AWS login; "" for it without being asked)') p.add_argument("--project", help="the Google Cloud project of a Vertex AI service (default GOOGLE_CLOUD_PROJECT)") p.add_argument("--new-account", action="store_true", help="register another ChatGPT account") p.add_argument("--port", type=int, default=auth.DEFAULT_PORT, help="local callback port (default 1455)") diff --git a/src/freehand/connections.py b/src/freehand/connections.py index 2301cf4..7ae8b38 100644 --- a/src/freehand/connections.py +++ b/src/freehand/connections.py @@ -9,6 +9,7 @@ from typing import Any import uuid import urllib.error +import urllib.parse from freehand import session from freehand.runtime import auth, providers @@ -39,7 +40,7 @@ def identity(config: dict) -> tuple: if mode == "auto" and (name != providers.RESPONSES or base != prov.api_base.rstrip("/")): mode = "api_key" return (name, base, config.get("api_key_env") or prov.api_key_env, mode, - config.get("gateway")) + config.get("gateway"), config.get("aws_profile") or None) def materialize(settings: dict) -> dict: @@ -96,8 +97,8 @@ def credential(config: dict) -> dict: return {"source": "sign-in" if copilot.ready() else "", "variable": "COPILOT_GITHUB_TOKEN", "ready": copilot.ready(), "saved": False} mode = config.get("auth") or "auto" - if mode == "google": # Vertex AI: the Google Cloud sign-in, never a saved key - ready = auth.google_problem() is None + if mode in ("google", "aws"): # Vertex AI or Bedrock: the cloud's own sign-in, never a saved key + ready = (auth.google_problem() if mode == "google" else auth.aws_problem(config.get("aws_profile"))) is None return {"source": "sign-in" if ready else "", "variable": "", "ready": ready, "saved": False} env = (config.get("gateway") or {}).get("api_key_env") or config.get("api_key_env") or prov.api_key_env source = "" @@ -129,7 +130,8 @@ def service_preset(name: str, spec: dict) -> dict: return {"id": name, "name": spec["label"], "config": {**config, "auth": spec.get("auth", "api_key")}, **({"places": places, "address": spec["api_base"]} if places else {}), **({"deployment": True} if spec.get("deployment") else {}), - **({"signin": auth.google_problem() or ""} if spec.get("auth") == "google" else {})} + **({"signin": auth.google_problem() or ""} if spec.get("auth") == "google" else {}), + **({"signin": auth.aws_problem() or ""} if spec.get("auth") == "aws" else {})} def overview() -> dict: @@ -173,6 +175,13 @@ def validate(config: Any) -> dict: require(config["provider"] != providers.ANTHROPIC or providers.VERTEX.fullmatch(str(config.get("api_base"))), "Claude on Vertex AI is reached at https://aiplatform.googleapis.com/v1/projects//locations/" ".") + require(config.get("aws_profile") is None or config.get("auth") == "aws", + "An AWS profile is used only by the AWS sign-in.") + if config.get("auth") == "aws": + require(config["provider"] == providers.ANTHROPIC and not config.get("gateway") + and providers.BEDROCK_REGION.search(urllib.parse.urlsplit(str(config.get("api_base") or "")).hostname + or ""), + "The AWS sign-in is for Claude on Bedrock, at https://bedrock-runtime..amazonaws.com.") if config.get("auth") == "chatgpt": require(config["provider"] == providers.RESPONSES and not config.get("gateway") and (config.get("api_base") or "https://api.openai.com/v1").rstrip("/") @@ -260,7 +269,7 @@ def mutate(request: dict) -> dict: # Custom connections get isolated credentials unless the person explicitly shares a variable (and those # signed by a sign-in, Copilot's or Google's, take none). if (not config.get("api_key_env") and not config.get("gateway") and cid != "current" - and config["provider"] != providers.COPILOT and config.get("auth") != "google"): + and config["provider"] != providers.COPILOT and config.get("auth") not in ("google", "aws")): config["api_key_env"] = f"FREEHAND_CONNECTION_{cid.upper()}_API_KEY" previous = profiles.get(cid) check_required = (previous is None or identity(previous["config"]) != identity(config) diff --git a/src/freehand/runtime/agent.py b/src/freehand/runtime/agent.py index ec5587c..a770a75 100755 --- a/src/freehand/runtime/agent.py +++ b/src/freehand/runtime/agent.py @@ -230,9 +230,12 @@ def base_model(model: Any) -> str: "api_base": "OpenAI-compatible Responses API base URL including the version; POST {api_base}/responses", "provider": "openai-responses | anthropic | openai-chat: the API, and the native format of transcript.json", "api_key_env": "environment variable holding the API key; unset = no key (e.g. behind a proxy)", - "auth": "auto | chatgpt | api_key | google | none: auto uses the ChatGPT sign-in (`freehand login`) when there " - "is one, otherwise the API key from api_key_env, otherwise no Authorization header; google sends an " - "access token from the Google Cloud sign-in (Vertex AI)", + "auth": "auto | chatgpt | api_key | google | aws | none: auto uses the ChatGPT sign-in (`freehand login`) " + "when there is one, otherwise the API key from api_key_env, otherwise no Authorization header; google " + "sends an access token from the Google Cloud sign-in (Vertex AI); aws signs Claude on Bedrock with " + "the AWS sign-in", + "aws_profile": "with auth aws: the AWS profile to sign with; unset = the AWS CLI's default (AWS_PROFILE, " + "AWS_* variables, SSO)", "stream": "stream responses as server-sent events; always on with a ChatGPT sign-in, which requires it", "prompt_cache_key": "send the session ID as prompt_cache_key and as the session_id header, so the provider routes " "every turn of the session to the same prompt cache", @@ -1088,13 +1091,16 @@ def load_state(self) -> bool: return True # ---- model ------------------------------------------------------------------------------------------------------ # - def credentials(self, force_refresh: bool = False) -> tuple[str | None, str]: - """The secret for the next call and which credential it is: "chatgpt", "google", "api_key" or "none".""" + def credentials(self, force_refresh: bool = False) -> tuple[Any, str]: + """The secret for the next call and which credential it is: "chatgpt", "google", "aws", "api_key" or + "none".""" if self.provider.name == _providers.COPILOT: return None, "copilot" mode = str(self.cfg.get("auth") or "auto") if mode == "google": return _auth.google_token(force_refresh), "google" + if mode == "aws": + return _auth.aws_credentials(self.cfg.get("aws_profile") or None, force_refresh), "aws" if plan_signs(self.cfg): return _auth.Store().access_token(force_refresh), "chatgpt" if mode in ("auto", "api_key"): @@ -1274,7 +1280,9 @@ def call_model(self) -> dict[str, Any]: except _providers.HTTPStatusError as exc: self._check_cancel() last = ModelError(exc.status, exc.body) - if exc.status == 401 and kind in ("chatgpt", "google") and not refreshed: + # Bedrock refuses an expired or unsigned AWS request with 403, not 401. + if (exc.status == 401 and kind in ("chatgpt", "google") or exc.status == 403 and kind == "aws") \ + and not refreshed: refreshed = force_refresh = True continue if last.code in NON_RETRYABLE_CODES: diff --git a/src/freehand/runtime/auth.py b/src/freehand/runtime/auth.py index 8b29ce0..f03cc90 100644 --- a/src/freehand/runtime/auth.py +++ b/src/freehand/runtime/auth.py @@ -496,3 +496,102 @@ def google_token(force_refresh: bool = False) -> str: except google.auth.exceptions.TransportError as exc: raise AuthError(f"Google's sign-in service could not be reached: {exc}") from None return str(creds.token) + + +# ---- Amazon Web Services (Bedrock) --------------------------------------------------------------------------------- # +# Claude on Bedrock can also be signed with the person's AWS sign-in instead of a Bedrock API key: a named profile, or +# whatever the AWS CLI would use (AWS_PROFILE, the AWS_* variables, an SSO session, assume-role, credential_process). +# boto3 finds those credentials; it is optional and imported only here, so this module still imports without it. +AWS_INSTALL = "Signing in with an AWS profile needs boto3: pip install 'freehand-ai[bedrock]'" +_aws: dict[str, Any] = {} +_aws_lock = threading.Lock() + + +class AwsCredentials(tuple): + """(access key, secret key, session token or None), the order AnthropicBedrock takes them in.""" + + def __repr__(self) -> str: # a log or a traceback never shows the keys + return "AwsCredentials(...)" + + +def aws_installed() -> bool: + """Whether boto3 is there to import (`freehand-ai[bedrock]`), without importing it.""" + try: + return importlib.util.find_spec("boto3") is not None + except (ImportError, ValueError): + return False + + +def aws_login_hint(profile: str | None) -> str: + flag = f" --profile {profile}" if profile else "" + return f"Run `aws sso login{flag}` (or `aws configure{flag}`), then try again." + + +def aws_profiles() -> set[str]: + """The profiles named in the AWS config and credentials files, read the way the AWS CLI reads them.""" + import configparser + names: set[str] = set() + aws = Path.home() / ".aws" + for env, default, prefix in (("AWS_CONFIG_FILE", aws / "config", "profile "), + ("AWS_SHARED_CREDENTIALS_FILE", aws / "credentials", "")): + parser = configparser.RawConfigParser() + try: + parser.read(Path(os.environ.get(env) or default).expanduser(), encoding="utf-8") + except (configparser.Error, OSError, UnicodeDecodeError): + continue + for section in parser.sections(): + # in the config file only [default] and [profile x] are profiles; [sso-session x] and [services x] are not + if prefix and section.strip() != "default" and not section.startswith(prefix): + continue + names.add(section[len(prefix):].strip() if prefix and section.startswith(prefix) else section.strip()) + return names + + +# what makes boto3's default chain find credentials without a profile in the AWS files +AWS_SIGN_IN_VARIABLES = ("AWS_ACCESS_KEY_ID", "AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_WEB_IDENTITY_TOKEN_FILE", + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI") + + +def aws_problem(profile: str | None = None) -> str | None: + """Why there is no AWS sign-in to use, in words for the person; None when there seems to be one. Reads files and + variables only, so whether the sign-in still works (an SSO session lasts hours) is learned when credentials are + asked for. Like Google's, a machine whose only credentials are its instance role is not recognised here.""" + if not aws_installed(): + return AWS_INSTALL + if profile: + if profile not in aws_profiles(): + return f"There is no AWS profile named {profile!r} in ~/.aws/config or ~/.aws/credentials." + return None + if any(os.environ.get(name) for name in AWS_SIGN_IN_VARIABLES) or aws_profiles(): + return None + return "No AWS sign-in was found on this computer. Run `aws configure sso` (or `aws configure`)." + + +def aws_credentials(profile: str | None = None, force_refresh: bool = False) -> AwsCredentials: + """Credentials from the AWS sign-in, *profile*'s or the default one, renewed by boto3 when they are about to + expire. *force_refresh* (the service refused the last ones) reads the files again, so that a sign-in renewed + since (`aws sso login`) is used. NeedLogin when there are none; AuthError when AWS could not be reached.""" + try: + import boto3 + import botocore.exceptions as errors + except ImportError: + raise NeedLogin(AWS_INSTALL) from None + with _aws_lock: + key = profile or "" + try: + sess = _aws.get(key) + if sess is None or force_refresh: + sess = _aws[key] = boto3.Session(profile_name=profile or None) + creds = sess.get_credentials() + if creds is None: + raise NeedLogin(f"No AWS credentials were found. {aws_login_hint(profile)}") + frozen = creds.get_frozen_credentials() + except NeedLogin: + _aws.pop(key, None) + raise + except errors.ConnectionError as exc: + raise AuthError(f"AWS could not be reached for credentials: {exc}") from None + except (errors.BotoCoreError, errors.ClientError) as exc: + _aws.pop(key, None) # an expired SSO session: read it again once it is renewed + raise NeedLogin(f"The AWS credentials could not be used ({exc}). {aws_login_hint(profile)}") from None + return AwsCredentials((frozen.access_key, frozen.secret_key, frozen.token)) diff --git a/src/freehand/runtime/providers.py b/src/freehand/runtime/providers.py index d96bc73..161a0fc 100644 --- a/src/freehand/runtime/providers.py +++ b/src/freehand/runtime/providers.py @@ -1121,17 +1121,23 @@ def takes_system(model: str) -> bool: VERTEX = re.compile(r"(?Phttps?://[^/]+/v1)/projects/(?P[^/]+)/locations/(?P[^/]+)/?") +# The region in a Bedrock address, which the signature names: bedrock-runtime..amazonaws.com, also behind a +# FIPS or VPC endpoint (bedrock-runtime-fips...., vpce-....bedrock-runtime..vpce.amazonaws.com). +BEDROCK_REGION = re.compile(r"(?:^|\.)bedrock-runtime(?:-fips)?\.([a-z]{2}(?:-[a-z]+)+-\d{1,2})\.") def anthropic_client(api_key: str, base_url: str, max_retries: int = 0, timeout: float = 300, - google: bool = False) -> Any: + google: bool = False, aws: Any = None) -> Any: """An SDK client. Loopback addresses (a local gateway, a test double) never go through a proxy: the SDK mounts the system proxy for every host, and unlike urllib it ignores the macOS proxy exception list, so 127.0.0.1 would be sent to the proxy. A mount of None is httpx's own "no proxy" rule (the same one NO_PROXY produces). *google*: *api_key* is a Google access token and *base_url* a Vertex AI location (https://aiplatform.googleapis.com/v1/projects//locations/); the SDK's Vertex client puts - the model in the path and the API version in the body.""" + the model in the path and the API version in the body. + + *aws*: AWS credentials (auth.AwsCredentials) to sign with, and *base_url* a Bedrock address + (https://bedrock-runtime..amazonaws.com); the SDK's Bedrock client puts the model in the path.""" import anthropic kwargs: dict[str, Any] = {"base_url": base_url, "max_retries": max_retries, "timeout": timeout} if urllib.parse.urlsplit(base_url).hostname in ("127.0.0.1", "localhost", "::1"): @@ -1144,6 +1150,15 @@ def anthropic_client(api_key: str, base_url: str, max_retries: int = 0, timeout: if vertex: return anthropic.AnthropicVertex(access_token=api_key, project_id=vertex["project"], region=vertex["location"], **{**kwargs, "base_url": vertex["root"]}) + if aws is not None: + region = BEDROCK_REGION.search(urllib.parse.urlsplit(base_url).hostname or "") + client = anthropic.AnthropicBedrock( + aws_region=region[1] if region else os.environ.get("AWS_REGION") or "us-east-1", **kwargs) + # Given no key, the SDK takes AWS_BEARER_TOKEN_BEDROCK from the environment, and it refuses a key together + # with credentials; set after, the credentials sign the request even when that variable is set. + client.api_key = None + client.aws_access_key, client.aws_secret_key, client.aws_session_token = aws + return client return anthropic.Anthropic(api_key=api_key, **kwargs) @@ -1419,7 +1434,8 @@ def send(self, agent: Any, token: str | None, kind: str) -> dict[str, Any]: raise HTTPStatusError(401, json.dumps({"error": {"type": "authentication_error", "message": f"set {agent.cfg.get('api_key_env') or self.api_key_env}"}})) client = anthropic_client(token, str(agent.cfg.get("api_base") or self.api_base), - timeout=response_timeout(agent), google=agent.cfg.get("auth") == "google") + timeout=response_timeout(agent), google=agent.cfg.get("auth") == "google", + aws=token if kind == "aws" else None) params = self.params(agent) points = self.cache_points(agent.request_ends, params["messages"]) agent.sending(params, "messages", points) # the SDK's own serialization may differ from json.dumps(params) diff --git a/src/freehand/server.py b/src/freehand/server.py index 6b29af5..f2d715f 100644 --- a/src/freehand/server.py +++ b/src/freehand/server.py @@ -475,6 +475,11 @@ def credentials(self) -> list[dict[str, Any]]: rows.append({"id": name, "label": spec["label"], "name": spec["label"], "present": google, "source": "sign-in" if google else "", "detail": "Google Cloud sign-in", "provider": spec["provider"], "primary": False}) + elif spec.get("auth") == "aws": # Bedrock: the AWS sign-in, no key + aws = auth.aws_problem() is None + rows.append({"id": name, "label": spec["label"], "name": spec["label"], "present": aws, + "source": "sign-in" if aws else "", "detail": "AWS sign-in", + "provider": spec["provider"], "primary": False}) return rows @staticmethod diff --git a/src/freehand/session.py b/src/freehand/session.py index fc0cb96..88aee71 100644 --- a/src/freehand/session.py +++ b/src/freehand/session.py @@ -43,13 +43,12 @@ # Appended to the system prompt in interactive sessions only; headless runs use prompt.md unchanged. INTERACTIVE_NOTE = ("\nThis is an interactive session with a person. A reply without a tool call ends your turn and is " "shown to them; their next message continues the session.\n") -USER_SETTINGS = ("model", "reasoning_effort", "api_base", "auth", "api_key_env", "bash_timeout_s", "request_extra", - "shell_environment_policy", "retry_budget_s", "request_max_retries", "stream_max_retries", - "unbounded_connection_retries", "stream_idle_timeout_ms", "compaction", "progress_updates", - "next_question", - "context_window", "max_output_tokens", "model_options", "service_tier") +USER_SETTINGS = ("model", "reasoning_effort", "api_base", "auth", "aws_profile", "api_key_env", "bash_timeout_s", + "request_extra", "shell_environment_policy", "retry_budget_s", "request_max_retries", + "stream_max_retries", "unbounded_connection_retries", "stream_idle_timeout_ms", "compaction", + "progress_updates", "next_question", "context_window", "max_output_tokens", "model_options", "service_tier") RETRY_BUDGET_S = None -PROVIDER_SETTINGS = ("model", "api_base", "auth", "api_key_env", "request_extra", "context_window", +PROVIDER_SETTINGS = ("model", "api_base", "auth", "aws_profile", "api_key_env", "request_extra", "context_window", "max_output_tokens", "model_options", "service_tier") PROJECT_FILES = ("AGENTS.md", "CLAUDE.md") # per directory, the first that exists # Context windows reported by GET /v1/models on the ChatGPT plan, 2026-10-11; the cache in models.json is preferred. @@ -95,6 +94,11 @@ "api_key_env": "AWS_BEARER_TOKEN_BEDROCK", "api_base": "https://bedrock-runtime.{region}.amazonaws.com/openai/v1", "region": "us-east-1", "model": "openai.gpt-oss-120b-1:0"}, + # Claude on Bedrock signed with the person's AWS sign-in (auth "aws": a profile, or the AWS CLI's default) instead + # of an API key, through the SDK's Bedrock client, which puts the model in the path after this address. + "bedrock-aws": {"label": "Amazon Bedrock (AWS sign-in)", "provider": providers.ANTHROPIC, "auth": "aws", + "api_base": "https://bedrock-runtime.{region}.amazonaws.com", "region": "us-east-1", + "model": "global.anthropic.claude-opus-5-5"}, # Azure names a model by the deployment the person made of it, so the model is asked for ("deployment") and the # preset's is only the name offered first. Each key variable is the one its vendor's own SDK reads. "azure": {"label": "Azure OpenAI", "provider": providers.RESPONSES, "api_key_env": "AZURE_OPENAI_API_KEY", @@ -397,6 +401,8 @@ def credentials_problem(cfg: dict[str, Any]) -> str | None: env = str(cfg.get("api_key_env") or prov.api_key_env) if mode == "google": return auth.google_problem() + if mode == "aws": + return auth.aws_problem(cfg.get("aws_profile") or None) if mode == "none" or name == providers.CHAT: return None if str(cfg.get("api_base") or prov.api_base).rstrip("/") != prov.api_base.rstrip("/"): diff --git a/src/freehand/ui.py b/src/freehand/ui.py index 92ecb82..a126539 100644 --- a/src/freehand/ui.py +++ b/src/freehand/ui.py @@ -2496,8 +2496,9 @@ def login(self) -> bool: subtitle=("Nothing to sign requests with yet. " if missing else "") + "Pick how the model is reached; /login brings this list back.") if pick == 3: - other = [k for k in (*cli.KEY_SERVICES, *cli.GOOGLE_SERVICES) if k not in ("openai", "anthropic")] - rows = [((cli.KEY_SERVICES.get(k) or cli.GOOGLE_SERVICES[k])[0], + other = [k for k in (*cli.KEY_SERVICES, *cli.GOOGLE_SERVICES, *cli.AWS_SERVICES) + if k not in ("openai", "anthropic")] + rows = [((cli.KEY_SERVICES.get(k) or cli.GOOGLE_SERVICES.get(k) or cli.AWS_SERVICES[k])[0], str(session.SERVICES.get(k, {}).get("model") or "")) for k in other] rows.append(("A gateway or a local server", "LiteLLM, Ollama, vLLM: how to set one up")) got = self.select("Which service?", rows, subtitle="Its API key (for Vertex AI, the project) is asked for " @@ -2507,6 +2508,8 @@ def login(self) -> bool: if got < len(other): if other[got] in cli.GOOGLE_SERVICES: self.login_google(other[got]) + elif other[got] in cli.AWS_SERVICES: + self.login_aws(other[got]) else: self.login_key(other[got], default=True) return self.adopt_credentials() @@ -2597,6 +2600,29 @@ def login_google(self, service: str) -> None: if problem: self.say(problem, "dim") + def login_aws(self, service: str) -> None: + """Point new sessions at Claude on Bedrock signed with an AWS profile: the region and the profile are asked + for, and nothing secret is saved.""" + label, provider = cli.AWS_SERVICES[service] + if auth.aws_problem() == auth.AWS_INSTALL: + self.say(auth.AWS_INSTALL, "dim") + return + places = self.ask_places(service, label) + if places is None: + return + profile = self.ask("AWS profile", "A profile in ~/.aws/config; leave it empty for your current AWS login " + "(AWS_PROFILE, `aws sso login`).") + if profile is None: + return + problem = auth.aws_problem(profile.strip() or None) + if problem: + self.say(f"{problem} Nothing was saved.", "dim") + return + dropped = session.set_default_provider(provider, cli.aws_settings(service, places, profile.strip())) + gone = f" (removed the previous provider's {', '.join(dropped)})" if dropped else "" + who = f"the AWS profile {profile.strip()}" if profile.strip() else "your current AWS login" + self.say(f"New sessions use {label} in {places['region']} with {who}{gone}.", "ok") + def login_key(self, service: str, default: bool = False) -> None: """Ask for an API key without showing it and save it in auth.json: it goes from the masked field to the store and is never printed, logged or put in the input's history. *default*: the service was picked by @@ -3040,6 +3066,9 @@ def _fetch_models(cfg: dict[str, Any]) -> list[str]: if cfg.get("auth") == "google": # Vertex AI lists no models for its Chat or Claude routes raise connections.DiscoveryGuidance(auth.google_problem() or "Vertex AI does not list its models here; enter " "a model ID, like google/gemini-4-neon or claude-opus-5-5.") + if cfg.get("auth") == "aws": # Bedrock's runtime address lists no models + raise connections.DiscoveryGuidance(auth.aws_problem(cfg.get("aws_profile")) or "Bedrock does not list its " + "models here; enter a model ID, like global.anthropic.claude-opus-5-5.") official = str(cfg.get("api_base") or "").rstrip("/") == providers.get(providers.RESPONSES).api_base if provider == "openai-responses" and official and plan_signs(cfg): # Not shortened: the server rotates the refresh token before it answers, so a refresh cut off at 5 s leaves a diff --git a/src/freehand/web/app.js b/src/freehand/web/app.js index 51e7732..e52f77f 100644 --- a/src/freehand/web/app.js +++ b/src/freehand/web/app.js @@ -5261,7 +5261,7 @@ function brandTile(names, initial) { // people know it by), a mainland endpoint its maker's // Kimi's coloured mark has a black K lost on a dark page: Moonshot's one-colour mark takes the text's colour const serviceBrand = (id) => ({ chatgpt: "openai", anthropic: "claude", kimi: "moonshot", "kimi-cn": "moonshot", - vertex: "vertexai" })[id] + vertex: "vertexai", "bedrock-aws": "bedrock" })[id] || String(id || "").replace(/-cn$/, ""); // a service's tile: its brand, with the service named on it for styles that want it function serviceTile(id, initial) { diff --git a/src/freehand/web/workbench.js b/src/freehand/web/workbench.js index e807de1..832160c 100644 --- a/src/freehand/web/workbench.js +++ b/src/freehand/web/workbench.js @@ -1321,7 +1321,7 @@ const signs = (p) => p.config.provider === "copilot" || p.config.auth === "chatgpt" || (serviceOf(p)?.id === "chatgpt"); const state = (p) => p.credential?.ready ? ["ok", tr("Ready", "可以使用")] - : signs(p) || p.config.auth === "google" ? ["warn", tr("Needs you to sign in", "需要登录")] + : signs(p) || ["google", "aws"].includes(p.config.auth) ? ["warn", tr("Needs you to sign in", "需要登录")] : ["warn", tr("Needs an API key", "需要 API 密钥")]; const save = async (p, change, key = null) => { await post("connection", { id: p.id, name: p.name, config: { ...p.config, ...change }, key }); @@ -1439,6 +1439,14 @@ p.credential?.ready ? tr("Found on this computer.", "已在本机找到。") : tr("Run `gcloud auth application-default login`, and install freehand-ai[vertex].", "请运行 `gcloud auth application-default login`,并安装 freehand-ai[vertex]。")); + // Bedrock: the AWS tools keep the sign-in (a profile, or the current one); there is no key to paste here + if (p.config.auth === "aws") { + const who = p.config.aws_profile ? tr(`The AWS profile ${p.config.aws_profile}.`, + `AWS 配置文件 ${p.config.aws_profile}。`) : tr("Your current AWS login.", "你当前的 AWS 登录。"); + return sub(tr("AWS sign-in", "AWS 登录"), p.credential?.ready ? who + : tr("Install freehand-ai[bedrock], and check the profile is in ~/.aws/config.", + "请安装 freehand-ai[bedrock],并确认该配置文件在 ~/.aws/config 中。")); + } const box = textBox("", "password", tr("Paste your API key", "粘贴 API 密钥")); box.autocomplete = "new-password"; box.setAttribute("aria-label", "API key"); @@ -1711,6 +1719,7 @@ : ["ollama", "lmstudio"].includes(preset.id) ? tr("Runs on this computer", "在本机运行") : preset.id === "custom" ? tr("Any compatible endpoint", "任意兼容接口") : preset.config.auth === "google" ? tr("Google Cloud sign-in, no key", "Google Cloud 登录,无需密钥") + : preset.config.auth === "aws" ? tr("AWS profile or current login, no key", "AWS 配置文件或当前登录,无需密钥") : tr("API key", "API 密钥"); const words = el("span", "words"); words.append(el("b", "", preset.id === "chatgpt" ? "ChatGPT" : preset.name.replace(/ \(local\)$/, "")), @@ -1788,6 +1797,14 @@ // Vertex AI: no key; requests are signed with the Google Cloud sign-in Google's own tools keep if (config.auth === "google") rows.push(card(tr("Google Cloud sign-in", "Google Cloud 登录"), preset.signin || tr("Found on this computer; requests are signed with it.", "已在本机找到,请求将用它签名。"))); + // Bedrock with the AWS sign-in: the profile that signs, or none for whatever the AWS CLI uses now + const awsProfile = config.auth === "aws" ? textBox("", "text", tr("Current AWS login", "当前 AWS 登录")) : null; + if (awsProfile) { + awsProfile.setAttribute("aria-label", tr("AWS profile", "AWS 配置文件")); + rows.push(card(tr("AWS profile", "AWS 配置文件"), preset.signin || tr("A profile in ~/.aws/config. Leave it " + + "empty to use your current AWS login (AWS_PROFILE, `aws sso login`).", "~/.aws/config 中的配置文件。留空则使用" + + "当前 AWS 登录(AWS_PROFILE、`aws sso login`)。"), awsProfile)); + } let asDefault = true; rows.push(card(tr("Use for new conversations", "用于新会话"), "", toggle(true, (on) => { asDefault = on; }, tr("Use for new conversations", "用于新会话")))); @@ -1809,6 +1826,7 @@ } config.api_base = address; } + if (awsProfile) config.aws_profile = awsProfile.value.trim() || null; if (deployment) { if (!deployment.value.trim()) throw new Error(tr("Enter the deployment's name.", "请填写部署名。")); config.model = deployment.value.trim(); @@ -2070,7 +2088,7 @@ provider.setAttribute("aria-label", "Protocol"); const authentication = select([["auto", tr("Automatic", "自动")], ["api_key", tr("API key", "API 密钥")], ["chatgpt", tr("ChatGPT sign-in", "ChatGPT 登录")], ["google", tr("Google Cloud sign-in", "Google Cloud 登录")], - ["none", tr("No authentication", "无需认证")]], + ["aws", tr("AWS sign-in", "AWS 登录")], ["none", tr("No authentication", "无需认证")]], values.auth || "auto"); authentication.setAttribute("aria-label", "Authentication"); const fields = {}; @@ -2151,6 +2169,8 @@ + "Use a separate variable for a custom service to avoid reusing another service's key.", "优先读取环境变量,其次读取已保存的凭据。自定义服务请使用独立变量名,避免误用其他服务的密钥。"), "CUSTOM_API_KEY"), + entry("aws_profile", tr("AWS profile", "AWS 配置文件"), tr("With the AWS sign-in: the profile that signs. " + + "Empty: your current AWS login.", "使用 AWS 登录时用于签名的配置文件。留空:当前 AWS 登录。"), "default"), ]; const keyState = { environment: tr("From the environment variable", "来自环境变量"), saved: tr("Saved on this computer. Paste a new one to replace it.", "已保存在本机。粘贴新密钥即可替换。") }; diff --git a/src/freehand/workbench.py b/src/freehand/workbench.py index 3cdcaa6..63eb7d7 100644 --- a/src/freehand/workbench.py +++ b/src/freehand/workbench.py @@ -178,7 +178,7 @@ def save_scripts(project: str, items: Any) -> list[dict]: return clean -ADVANCED = {"provider", "model", "api_base", "api_key_env", "auth", "reasoning_effort", "gateway", +ADVANCED = {"provider", "model", "api_base", "api_key_env", "auth", "aws_profile", "reasoning_effort", "gateway", "request_extra", "bash_timeout_s", "retry_budget_s", "shell_environment_policy", "request_max_retries", "stream_max_retries", "unbounded_connection_retries", "stream_idle_timeout_ms", "compaction", "context_window", "max_output_tokens", "model_options", "service_tier"} @@ -211,7 +211,11 @@ def validate_advanced(values: dict) -> None: from freehand.runtime import providers require(value in providers.PROVIDERS, "Unknown provider.") elif key == "auth": - require(value in ("auto", "chatgpt", "api_key", "google", "none"), "Unknown authentication method.") + require(value in ("auto", "chatgpt", "api_key", "google", "aws", "none"), "Unknown authentication method.") + elif key == "aws_profile": + # the name is given to boto3 and shown in hints to run `aws sso login --profile ` + require(isinstance(value, str) and re.fullmatch(r"[\w.@+-]{1,128}", value), + "An AWS profile name is letters, digits and . _ - @ +, up to 128 characters.") elif key == "api_key_env": require(isinstance(value, str) and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", value), "Choose the environment variable containing the API key.") diff --git a/tests/conftest.py b/tests/conftest.py index 4f000cd..ba4192d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -87,6 +87,14 @@ def isolated_home(tmp_path, monkeypatch): for key in ("COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN", "FREEHAND_COPILOT_PYTHON"): monkeypatch.delenv(key, raising=False) monkeypatch.delenv("OPENAI_API_KEY", raising=False) # tests talk to fake servers only + # nor the machine's AWS sign-in: its files and variables would make Bedrock's AWS sign-in look present + for key in ("AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", + "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", + "AWS_CONTAINER_CREDENTIALS_FULL_URI"): + monkeypatch.delenv(key, raising=False) + monkeypatch.setenv("AWS_CONFIG_FILE", str(tmp_path / "no-aws" / "config")) + monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", str(tmp_path / "no-aws" / "credentials")) + monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true") # naming a session takes a model call of its own, which scripted fake servers do not expect; tests of it turn it on monkeypatch.setattr("freehand.session.auto_titles", lambda: False) # nor a model list fetched ahead of a picker (the tests of it turn it on); each test starts with none kept diff --git a/tests/fake_providers.py b/tests/fake_providers.py index 7f823d6..8c34c15 100644 --- a/tests/fake_providers.py +++ b/tests/fake_providers.py @@ -1,8 +1,11 @@ """Scripted stand-ins for the Anthropic Messages API and an OpenAI-compatible Chat Completions service.""" from __future__ import annotations +import base64 import json +import struct import threading +import zlib from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from fakes import SERVER_POLL_INTERVAL, send_json @@ -18,6 +21,23 @@ def _sse(handler, events, content_type="text/event-stream"): handler.wfile.flush() +def _eventstream(handler, events): + """The events as Bedrock's InvokeModelWithResponseStream sends them: AWS event-stream frames, each a "chunk" + whose payload carries the Messages API event, base64-encoded, the way the SDK's Bedrock client decodes them.""" + handler.send_response(200) + handler.send_header("Content-Type", "application/vnd.amazon.eventstream") + handler.end_headers() + for _, payload in events: + body = json.dumps({"bytes": base64.b64encode(json.dumps(payload).encode()).decode()}).encode() + headers = b"".join(bytes([len(k)]) + k.encode() + b"\x07" + struct.pack(">H", len(v)) + v.encode() + for k, v in ((":event-type", "chunk"), (":content-type", "application/json"), + (":message-type", "event"))) + prelude = struct.pack(">II", 12 + len(headers) + len(body) + 4, len(headers)) + frame = prelude + struct.pack(">I", zlib.crc32(prelude)) + headers + body + handler.wfile.write(frame + struct.pack(">I", zlib.crc32(frame))) + handler.wfile.flush() + + class _Server: def __init__(self, respond): self.requests: list[dict] = [] @@ -63,11 +83,15 @@ class FakeAnthropic(_Server): ("cut", blocks) for a stream that ends cleanly but early (no signatures, no message_delta or message_stop, as a dropped upstream behind a proxy looks), or a callable taking the request body and returning one of those. Streams the Messages API events the SDK accumulates.""" - def __init__(self, script, usage=None): + def __init__(self, script, usage=None, bedrock=False): + """*bedrock*: answer as Bedrock's runtime does, the model in the path and the events in AWS frames.""" self.script = list(script) self.usage = usage or {"input_tokens": 100, "cache_creation_input_tokens": 50, "cache_read_input_tokens": 850} + stream = _eventstream if bedrock else _sse def respond(handler, k, body): + if bedrock: + body = {**body, "model": handler.path.split("/")[2]} entry = self.script[k] if k < len(self.script) else [text("script exhausted")] if callable(entry): entry = entry(body) @@ -75,13 +99,13 @@ def respond(handler, k, body): send_json(handler, entry[1], entry[2]) return if isinstance(entry, tuple) and entry and entry[0] == "cut": - _sse(handler, [e for e in self.events(entry[1], "end_turn", body.get("model")) + stream(handler, [e for e in self.events(entry[1], "end_turn", body.get("model")) if e[0] not in ("message_delta", "message_stop") and (e[1].get("delta") or {}).get("type") != "signature_delta"]) return blocks, stop, details = (tuple(entry) + (None,))[:3] if isinstance(entry, tuple) else (entry, None, None) stop = stop or ("tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn") - _sse(handler, self.events(blocks, stop, body.get("model"), details)) + stream(handler, self.events(blocks, stop, body.get("model"), details)) super().__init__(respond) diff --git a/tests/test_bedrock_aws.py b/tests/test_bedrock_aws.py new file mode 100644 index 0000000..40bff95 --- /dev/null +++ b/tests/test_bedrock_aws.py @@ -0,0 +1,186 @@ +"""Claude on Amazon Bedrock signed with an AWS profile or the current AWS login, instead of a Bedrock API key.""" +from __future__ import annotations + +import io +import json +import sys + +import pytest + +from fake_providers import FakeAnthropic, text +from fakes import load_runtime, make_session, meta +from freehand import cli, connections, server, session +from freehand.runtime import auth, providers +from freehand.workbench import WorkbenchError + +MODEL = "global.anthropic.claude-opus-5-5" + + +@pytest.fixture(autouse=True) +def aws_home(tmp_path, monkeypatch): + """AWS files of the test's own (conftest keeps the machine's sign-in out), with a default and a work profile.""" + for name in ("AWS_REGION", "AWS_DEFAULT_REGION", "AWS_BEARER_TOKEN_BEDROCK"): + monkeypatch.delenv(name, raising=False) + home = tmp_path / "aws" + home.mkdir() + monkeypatch.setenv("AWS_CONFIG_FILE", str(home / "config")) + monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", str(home / "credentials")) + (home / "config").write_text("[default]\nregion = us-east-1\n\n[profile work]\nregion = eu-west-1\n\n" + "[sso-session corp]\nsso_region = us-east-1\n") + monkeypatch.setattr(auth, "_aws", {}) + return home + + +def credentials_file(home, **profiles): + (home / "credentials").write_text("".join( + f"[{name}]\naws_access_key_id = {key}\naws_secret_access_key = secret-{key}\n\n" + for name, key in profiles.items())) + + +def login(monkeypatch, *args, typed=""): + monkeypatch.setattr(sys, "stdin", io.StringIO(typed)) + return cli.main(["login", "bedrock-aws", *args]) + + +def test_login_with_a_profile_points_new_sessions_at_bedrock_in_the_region_and_saves_no_secret(tmp_path, monkeypatch, + capsys): + assert login(monkeypatch, "--region", "eu-west-1", "--aws-profile", "work") == 0 + assert "Amazon Bedrock (AWS sign-in) in eu-west-1 with the AWS profile work" in capsys.readouterr().out + cfg = json.loads((session.create(tmp_path, interactive=True) / "config.json").read_text()) + assert cfg["provider"] == "anthropic" and cfg["auth"] == "aws" and cfg["aws_profile"] == "work" + assert cfg["api_base"] == "https://bedrock-runtime.eu-west-1.amazonaws.com" and cfg["model"] == MODEL + assert auth.Store().api_keys() == {} + + +def test_login_without_a_profile_uses_the_current_aws_login_and_an_unknown_profile_saves_nothing(monkeypatch, + capsys): + assert login(monkeypatch, "--aws-profile", "") == 0 + assert "with your current AWS login" in capsys.readouterr().out + settings = session.read_settings() + assert settings["auth"] == "aws" and "aws_profile" not in settings + assert settings["api_base"] == "https://bedrock-runtime.us-east-1.amazonaws.com" + + assert login(monkeypatch, "--aws-profile", "nope") == 1 + assert "no AWS profile named 'nope'" in capsys.readouterr().err + assert "aws_profile" not in session.read_settings() + + +def test_a_profile_in_the_credentials_file_alone_counts_and_boto3_missing_is_said_plainly(aws_home, monkeypatch): + (aws_home / "config").unlink() + assert "No AWS sign-in was found" in auth.aws_problem() + monkeypatch.setenv("AWS_PROFILE", "from-sso") + assert auth.aws_problem() is None + monkeypatch.delenv("AWS_PROFILE") + (aws_home / "config").write_text("[default]\nregion = us-east-1\n\n[profile work]\nregion = eu-west-1\n") + credentials_file(aws_home, ci="AKIDCI") + assert auth.aws_profiles() == {"default", "work", "ci"} + assert auth.aws_problem("ci") is None and auth.aws_problem() is None + monkeypatch.setattr(auth, "aws_installed", lambda: False) + assert auth.aws_problem("ci") == auth.AWS_INSTALL + assert session.credentials_problem({"provider": "anthropic", "auth": "aws"}) == auth.AWS_INSTALL + + +def test_no_credentials_or_an_unknown_profile_asks_for_an_aws_sign_in(aws_home): + with pytest.raises(auth.NeedLogin, match=r"aws sso login --profile gone"): + auth.aws_credentials("gone") + with pytest.raises(auth.NeedLogin, match=r"No AWS credentials were found\. Run `aws sso login`"): + auth.aws_credentials() + assert auth._aws == {} # read again once the person signs in + credentials_file(aws_home, default="AKIDDEFAULT", work="AKIDWORK") + assert auth.aws_credentials()[0] == "AKIDDEFAULT" and auth.aws_credentials("work")[0] == "AKIDWORK" + assert "AKID" not in repr(auth.aws_credentials("work")) + + +def run_on_fake_bedrock(tmp_path, script, **cfg): + srv = FakeAnthropic(script, bedrock=True) + try: + h = make_session(tmp_path, srv.url, provider="anthropic", auth="aws", model=MODEL, pricing_per_token=None, + **cfg) + code = load_runtime(h).Agent(h).run() + finally: + srv.close() + return srv, h, code + + +def test_claude_on_bedrock_is_signed_with_the_profile_even_with_a_bedrock_key_in_the_environment(aws_home, tmp_path, + monkeypatch): + credentials_file(aws_home, default="AKIDDEFAULT", work="AKIDWORK") + monkeypatch.setenv("AWS_BEARER_TOKEN_BEDROCK", "a-key-that-must-not-be-sent") + monkeypatch.setenv("AWS_REGION", "eu-west-1") # a test double's address names no region + srv, h, code = run_on_fake_bedrock(tmp_path, [[text("signed ok")]], aws_profile="work") + assert code == 0 and meta(h)["finish_summary"] == "signed ok" and meta(h)["auth"] == "aws" + assert srv.paths[0] == f"/model/{MODEL}/invoke-with-response-stream" + signature = srv.headers[0]["authorization"] + assert signature.startswith("AWS4-HMAC-SHA256 Credential=AKIDWORK/") + assert "/eu-west-1/bedrock/aws4_request" in signature and "x-amz-date" in srv.headers[0] + assert "x-api-key" not in srv.headers[0] and "a-key-that-must-not-be-sent" not in json.dumps(srv.headers[0]) + assert "model" not in srv.requests[0] and srv.requests[0]["anthropic_version"] == "bedrock-2023-05-31" + + +def test_a_refused_signature_reads_the_aws_sign_in_again_once(aws_home, tmp_path): + credentials_file(aws_home, default="AKIDOLD") + + def expired(body): # meanwhile the person ran `aws sso login`, which renewed the keys + credentials_file(aws_home, default="AKIDNEW") + return ("error", 403, {"message": "The security token included in the request is expired"}) + srv, h, code = run_on_fake_bedrock(tmp_path, [expired, [text("renewed")]]) + assert code == 0 and meta(h)["finish_summary"] == "renewed" + assert [h["authorization"].split("/")[0] for h in srv.headers] == [ + "AWS4-HMAC-SHA256 Credential=AKIDOLD", "AWS4-HMAC-SHA256 Credential=AKIDNEW"] + + +@pytest.mark.parametrize("host, region", [ + ("bedrock-runtime.eu-central-1.amazonaws.com", "eu-central-1"), + ("bedrock-runtime-fips.us-gov-west-1.amazonaws.com", "us-gov-west-1"), + ("vpce-0abc.bedrock-runtime.ap-southeast-2.vpce.amazonaws.com", "ap-southeast-2"), + ("evil-bedrock-runtime.us-east-1.amazonaws.com", None), ("127.0.0.1", None)]) +def test_the_signing_region_comes_from_the_bedrock_address(host, region): + found = providers.BEDROCK_REGION.search(host) + assert (found[1] if found else None) == region + + +def test_the_page_offers_the_aws_sign_in_and_keeps_each_profile_a_connection_of_its_own(aws_home): + preset = {p["id"]: p for p in connections.overview()["presets"]}["bedrock-aws"] + assert preset["config"]["auth"] == "aws" and preset["signin"] == "" + assert preset["config"]["api_base"] == "https://bedrock-runtime.us-east-1.amazonaws.com" + config = {**preset["config"], "api_base": "https://bedrock-runtime.eu-west-1.amazonaws.com"} + assert connections.label(config) == "Amazon Bedrock (AWS sign-in)" + assert server.Hub.current_service(config) == "bedrock-aws" + assert connections.identity(config) != connections.identity({**config, "aws_profile": "work"}) + for cid, profile in (("one", None), ("two", "work")): + assert connections.mutate({"id": None, "name": f"Bedrock {cid}", "default": True, + "config": {**config, "aws_profile": profile}})["ok"] + items = connections.overview()["items"] + mine = [p for p in items if p["config"].get("auth") == "aws"] + assert sorted(p["config"].get("aws_profile") or "" for p in mine) == ["", "work"] + assert all(p["credential"] == {"source": "sign-in", "variable": "", "ready": True, "saved": False} for p in mine) + assert all("api_key_env" not in p["config"] for p in mine) and auth.Store().api_keys() == {} + assert session.read_settings()["aws_profile"] == "work" + + +@pytest.mark.parametrize("config, problem", [ + ({"provider": "anthropic", "auth": "aws", "api_base": "https://api.anthropic.com"}, "Claude on Bedrock"), + ({"provider": "openai-chat", "auth": "aws", + "api_base": "https://bedrock-runtime.us-east-1.amazonaws.com/openai/v1"}, "Claude on Bedrock"), + ({"provider": "anthropic", "auth": "aws", "aws_profile": "bad profile", + "api_base": "https://bedrock-runtime.us-east-1.amazonaws.com"}, "AWS profile name"), + ({"provider": "anthropic", "auth": "api_key", "aws_profile": "work", + "api_base": "https://bedrock-runtime.us-east-1.amazonaws.com"}, "only by the AWS sign-in")]) +def test_the_aws_sign_in_is_refused_anywhere_but_claude_on_bedrock(config, problem): + with pytest.raises(WorkbenchError, match=problem): + connections.validate(config) + + +def test_the_terminal_login_asks_for_the_region_and_profile_and_refuses_one_not_in_the_files(monkeypatch): + from types import SimpleNamespace + from freehand import ui + said: list[str] = [] + typed = iter(["work", "nope"]) + me = SimpleNamespace(ask_places=lambda service, label: {"region": "eu-west-1"}, + ask=lambda title, subtitle="", default="": next(typed), say=lambda t, s="": said.append(t)) + ui.Interactive.login_aws(me, "bedrock-aws") + assert said[-1].startswith("New sessions use Amazon Bedrock (AWS sign-in) in eu-west-1 with the AWS profile work") + settings = session.read_settings() + assert settings["auth"] == "aws" and settings["aws_profile"] == "work" + ui.Interactive.login_aws(me, "bedrock-aws") + assert "no AWS profile named 'nope'" in said[-1] and session.read_settings()["aws_profile"] == "work" diff --git a/tests/test_web_e2e.py b/tests/test_web_e2e.py index 7d1c55e..58c9fde 100644 --- a/tests/test_web_e2e.py +++ b/tests/test_web_e2e.py @@ -402,6 +402,45 @@ def test_web_e2e_vertex_ai_is_added_with_its_project_and_no_key(tmp_path, isolat httpd.server_close() +def test_web_e2e_bedrock_is_added_with_an_aws_profile_and_no_key(tmp_path, isolated_home, chrome_page, monkeypatch): + for name in ("AWS_REGION", "AWS_DEFAULT_REGION"): + monkeypatch.delenv(name, raising=False) + config = tmp_path / "aws-config" + config.write_text("[profile work]\nregion = eu-west-1\n") + monkeypatch.setenv("AWS_CONFIG_FILE", str(config)) + monkeypatch.setattr("freehand.runtime.auth.aws_installed", lambda: True) + monkeypatch.setattr("freehand.ui._fetch_models", lambda cfg: []) + httpd, hub = server.make_server(tmp_path, 0) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + try: + chrome_page.navigate(server.address(httpd, hub)) + chrome_page.wait_for("Boolean(view.overview && view.overview.version)") + chrome_page.eval("document.getElementById('settings').click()") + tile = "#dialog .service-tile[data-service=bedrock-aws]" + chrome_page.wait_for(f"Boolean(document.querySelector('{tile}'))") + assert chrome_page.eval(f"document.querySelector('{tile}').textContent" + ".includes('AWS profile or current login, no key')") + chrome_page.eval(f"document.querySelector('{tile}').click()") + profile = '#dialog input[aria-label="AWS profile"]' + chrome_page.wait_for(f"Boolean(document.querySelector('{profile}'))") + assert chrome_page.eval("!document.querySelector('#dialog input[type=password]')") + chrome_page.eval(f"""(() => {{ + document.querySelector('#dialog input[aria-label=Region]').value = 'eu-west-1'; + document.querySelector('{profile}').value = 'work'; + [...document.querySelectorAll('#dialog button.ink')] + .find(b => b.textContent === 'Add connection').click(); + }})()""") + chrome_page.wait_for("[...document.querySelectorAll('#dialog .model-conn')].some(c => " + "c.textContent.includes('Amazon Bedrock (AWS sign-in)') && c.textContent.includes('Ready'))") + settings = session.load_settings() + assert settings["provider"] == providers.ANTHROPIC and settings["auth"] == "aws" + assert settings["api_base"] == "https://bedrock-runtime.eu-west-1.amazonaws.com" + assert settings["aws_profile"] == "work" and "api_key_env" not in settings + finally: + httpd.shutdown() + httpd.server_close() + + def test_web_e2e_state_machine_fuzz_invariants(tmp_path, isolated_home, chrome_page): """Randomized UI stress across multiple sessions: switch, send, open/close drawers & settings, reload, stop.""" replies = [[say(f"reply-{i}")] for i in range(60)] diff --git a/uv.lock b/uv.lock index ae44a1e..d3fa8f0 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.15' and platform_python_implementation != 'PyPy' and sys_platform == 'emscripten'", @@ -54,6 +54,34 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" }, ] +[[package]] +name = "boto3" +version = "1.44.19" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, + { name = "jmespath" }, + { name = "s3transfer" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/44/c7/818162a4f641b24c30e04075256817fd8f781da0b7da3fbb47c635bff433/boto3-1.44.19.tar.gz", hash = "sha256:34e1d0fd923c25435c95131e9c2da4bef1c937d2fe2655d59f200601ab53f3fd", size = 113572, upload-time = "2026-12-04T20:21:46.104Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/96/6c/3e29cde4d4145bc5a9b550098694d8461b7c08f9925b37c92adc4d4e8b96/boto3-1.44.19-py3-none-any.whl", hash = "sha256:44a0df026f03730a3b075c0aa21262d2d8361d1457d6d9c86a038548f7e4b537", size = 140588, upload-time = "2026-12-04T20:21:44.886Z" }, +] + +[[package]] +name = "botocore" +version = "1.44.19" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "jmespath" }, + { name = "python-dateutil" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/05/05/5f8a00fb3304d9861944b087c360ea67539ea2515188e9bc5390653237ac/botocore-1.44.19.tar.gz", hash = "sha256:52d58a57c30c460fd167c6548327636cb1c9f03e99a0a9194827589d5e843a57", size = 17807334, upload-time = "2026-12-04T20:21:40.887Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/00/d8/2fd3579cd466dc24fddb092a767ee2addfd36914765d3499b0a2dc531eae/botocore-1.44.19-py3-none-any.whl", hash = "sha256:9988f00452e58376f2836b27af8572747f14ac00a873b3f4132efeac9c0a12a0", size = 17519907, upload-time = "2026-12-04T20:21:38.456Z" }, +] + [[package]] name = "certifi" version = "2026.11.20" @@ -69,7 +97,7 @@ version = "2.1.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pycparser", version = "3.11", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and implementation_name != 'PyPy'" }, - { name = "pycparser", version = "3.12", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and implementation_name != 'PyPy'" }, + { name = "pycparser", version = "3.12", source = { registry = "https://pypi.org/simple" }, marker = "(python_full_version >= '3.11' and python_full_version < '3.14' and implementation_name != 'PyPy') or (python_full_version >= '3.11' and implementation_name != 'PyPy' and platform_python_implementation != 'PyPy')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } wheels = [ @@ -433,7 +461,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -450,10 +478,15 @@ dependencies = [ ] [package.optional-dependencies] +bedrock = [ + { name = "boto3" }, + { name = "botocore" }, +] copilot = [ { name = "microsoft-copilot-sdk", marker = "python_full_version >= '3.11'" }, ] dev = [ + { name = "boto3" }, { name = "pyflakes" }, { name = "pytest" }, ] @@ -464,6 +497,9 @@ vertex = [ [package.metadata] requires-dist = [ { name = "anthropic", specifier = ">=1.13,<2" }, + { name = "boto3", marker = "extra == 'bedrock'", specifier = ">=1.28.57,<2" }, + { name = "boto3", marker = "extra == 'dev'", specifier = ">=1.28.57,<2" }, + { name = "botocore", marker = "extra == 'bedrock'", specifier = ">=1.31.57,<2" }, { name = "google-auth", extras = ["requests"], marker = "extra == 'vertex'", specifier = ">=2,<3" }, { name = "microsoft-copilot-sdk", marker = "python_full_version >= '3.11' and extra == 'copilot'", specifier = "==2.0.6" }, { name = "prompt-toolkit", specifier = ">=3.0.43" }, @@ -471,7 +507,7 @@ requires-dist = [ { name = "pytest", marker = "extra == 'dev'", specifier = ">=8" }, { name = "rich", specifier = ">=13.7" }, ] -provides-extras = ["dev", "copilot", "vertex"] +provides-extras = ["dev", "copilot", "vertex", "bedrock"] [[package]] name = "google-auth" @@ -505,8 +541,8 @@ name = "httpcore" version = "1.0.9" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "certifi" }, - { name = "h11" }, + { name = "certifi", marker = "python_full_version >= '3.11'" }, + { name = "h11", marker = "python_full_version >= '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } wheels = [ @@ -518,8 +554,8 @@ name = "httpcore2" version = "2.13.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "h11" }, - { name = "truststore" }, + { name = "h11", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" }, + { name = "truststore", marker = "python_full_version < '3.12' or sys_platform != 'emscripten'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/cb/f3/1db7aa2bc2524062192bb0e0323969492d1883152a232fe36eea65f4e35c/httpcore2-2.13.1.tar.gz", hash = "sha256:e0aa977abe17e69a3b820a24542a6fa88702676d83880b8d194dcd18408e5103", size = 68071, upload-time = "2026-09-23T07:47:22.372Z" } wheels = [ @@ -531,10 +567,10 @@ name = "httpx" version = "0.29.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "anyio" }, - { name = "certifi" }, - { name = "httpcore" }, - { name = "idna" }, + { name = "anyio", marker = "python_full_version >= '3.11'" }, + { name = "certifi", marker = "python_full_version >= '3.11'" }, + { name = "httpcore", marker = "python_full_version >= '3.11'" }, + { name = "idna", marker = "python_full_version >= '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/9a/d5/b4d2c4d397b7c0222635cd069098f232fb5cba31f6749e77b339e263b52c/httpx-0.29.0.tar.gz", hash = "sha256:700928ee6c1f4213795e67c47eba8f8553639069fea89199f71d654e38edc593", size = 141642, upload-time = "2026-11-26T15:58:37.028Z" } wheels = [ @@ -711,6 +747,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e1/8b/d76219ebdbcf3d4209d9d21a0810db4c8d0a6f88e3ee87d30bdea4e90d30/jiter-0.17.0-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d2c0bf24c72fd0491405dce5d40194f2070e9021ce648c1a1d46234b93d848ff", size = 307147, upload-time = "2026-09-12T15:14:12.897Z" }, ] +[[package]] +name = "jmespath" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d3/59/322338183ecda247fb5d1763a6cbe46eff7222eaeebafd9fa65d4bf5cb11/jmespath-1.1.0.tar.gz", hash = "sha256:472c87d80f36026ae83c6ddd0f1d05d4e510134ed462851fd5f754c8c3cbb88d", size = 27377, upload-time = "2026-01-22T16:35:26.279Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" }, +] + [[package]] name = "markdown-it-py" version = "4.2.0" @@ -737,9 +782,9 @@ name = "microsoft-copilot-sdk" version = "2.0.6" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "httpx" }, - { name = "pydantic" }, - { name = "python-dateutil" }, + { name = "httpx", marker = "python_full_version >= '3.11'" }, + { name = "pydantic", marker = "python_full_version >= '3.11'" }, + { name = "python-dateutil", marker = "python_full_version >= '3.11'" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/30/68/bfebdc16e6866ab4dcfb3ef896e0586fdc170ca66e5a2b4e503c14ff4686/microsoft_copilot_sdk-2.0.6-py3-none-any.whl", hash = "sha256:ca9b6fcdd34a65c03f5ba4d50b8375607243e4822f89fa781c726ca40992483f", size = 1332139, upload-time = "2026-12-02T13:03:18.772Z" }, @@ -1025,14 +1070,14 @@ wheels = [ [[package]] name = "python-dateutil" -version = "4.0.0" +version = "2.9.0.post0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "tzdata" }, + { name = "six" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" } +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, ] [[package]] @@ -1063,6 +1108,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, ] +[[package]] +name = "s3transfer" +version = "0.19.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "botocore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/49/c5/0a5ce655109cb96b8dfad36908a4e108d15f5dc2eff8fbc3146c4312e704/s3transfer-0.19.3.tar.gz", hash = "sha256:8326acc3d056d7f7b8a37110c7d2aea41f67e83f6ae79cd3b5fbcca34c726406", size = 166087, upload-time = "2026-10-19T19:19:49.751Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e2/a4/88f9e10498759121060b8050a1554753dfc04df39bbbcc7aad9ecc8d9440/s3transfer-0.19.3-py3-none-any.whl", hash = "sha256:24eb7535804306355e31c952a90022bf5b2f9d760f9a11062c7493a217c08553", size = 90252, upload-time = "2026-10-19T19:19:48.309Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + [[package]] name = "sniffio" version = "1.3.1" @@ -1174,15 +1240,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" }, ] -[[package]] -name = "tzdata" -version = "2026.6" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, -] - [[package]] name = "urllib3" version = "2.8.0"