Skip to content

Self-improving AI Employees for everyone

feat(aws): AWS node, a workflow node and AI tool over boto3

trohitgef9f3aa59003
diff --git a/docs-internal/aws_service.md b/docs-internal/aws_service.md
new file mode 100644
index 00000000..3267f4f8
--- /dev/null
+++ b/docs-internal/aws_service.md
@@ -0,0 +1,90 @@
+# AWS Service
+
+Self-contained plugin at [`server/nodes/aws/`](../server/nodes/aws/) over the
+official **AWS SDK for Python** (`boto3`, a server dependency). One
+dual-purpose node, `awsAction` (workflow node + AI tool `aws_action`): typed
+operations for the common flows (identity, EC2 instances, S3 objects), `call`
+for any operation of any AWS service, and `list_operations` to discover them.
+
+**Why the SDK and not the AWS CLI** (unlike the gcloud / cf / gh plugins): AWS
+CLI v2 ships as an MSI on Windows and a `.pkg` on macOS, with no portable
+archive to pin and extract the way `gcloud/_install.py` does, and its browser
+login (`aws login`) cannot run on a remote or hosted server. The SDK installs
+with `uv sync` on every platform, and a stored key pair works headless.
+
+**Auth model: an IAM access key pair in OpenCompany's encrypted store.**
+`AwsCredential` (`ApiKeyCredential`, id `aws`) keeps three rows: the Secret
+Access Key under the provider id (the field the credentials modal validates),
+`aws_access_key_id`, and the optional `aws_region` (`extra_fields`, the
+cloudflare companion-field pattern). The modal probe signs
+`sts:GetCallerIdentity` with the pair; every IAM identity may call it, so a
+least-privilege key validates too. The Access Key ID must be saved before the
+secret is validated, and the probe says so when it is missing.
+
+**No ambient credentials.** Every client is created with the key pair passed
+explicitly, which outranks the SDK's credential chain, so environment
+variables, `~/.aws` and an EC2 instance profile on the server never
+authenticate a node.
+
+## File map
+
+| File | Role |
+|---|---|
+| `__init__.py` | `register_output_schema("awsAction", …)` + `register_option_loader("awsServices" / "awsOperations", …)`; the node auto-registers on import |
+| `aws_action.py` | `AwsActionNode(ActionNode)`, `usable_as_tool=True`, `tool_name="aws_action"`, both canvas handles kept visible, eleven `@Operation`s; `_keys` resolves the credential before any work, so a missing key gives the `PermissionDeniedError` envelope; `_shape` drops only `None` |
+| `_sdk.py` | Every boto3 / botocore touch, imported lazily: introspection (`service_names`, `operations`, `resolve_operation` with `difflib` suggestions), calls (`call`, `collect` over a paginator with a JMESPath projection, `download_object`), `to_plain`, `raise_user_error`, and the two dropdown loaders |
+| `_credentials.py` | `AwsCredential`: `resolve()` also requires the Access Key ID; `_probe()` reads the companion rows and calls STS |
+| `icon.svg` / `aws.svg` / `meta.json` | Node icon and co-located credential icon (lobehub's AWS mark on a dark tile, readable through `<img>` on light and dark themes); colour `#FF9900` |
+
+Paired skill: [`server/skills/aws/aws-skill/SKILL.md`](../server/skills/aws/aws-skill/SKILL.md)
+(bound in `visuals.json`: `"awsAction": {"skill": "aws-skill"}`). Palette
+group: `deployment`. Catalogue entry: `kind: "apiKey"` with the three fields
+in `credential_providers.json`.
+
+## Clients
+
+One botocore session (module-level, cached) holds the service models and
+client classes for every call; it holds no credentials. Each operation creates
+a client with the key pair and region passed explicitly, about 5 ms once the
+service's model is loaded (the first client of a service pays ~0.3 s). Client
+creation is serialised by a lock because botocore sessions are not
+thread-safe; the API calls run in worker threads (`asyncio.to_thread`)
+concurrently. Every client uses 10 s connect / 60 s read timeouts and the
+SDK's `standard` retry mode (3 attempts, throttling and transient errors only).
+
+## Operations
+
+| Op | SDK call | Notes |
+|---|---|---|
+| `whoami` | `sts.get_caller_identity` | |
+| `ec2_instances_list` | `ec2.describe_instances` paginator, projected per instance (`InstanceId`, `Name` tag, `State`, type, IPs, zone, launch time, image, key) | `instance_state` filter; stops at `limit`, reports `truncated` |
+| `ec2_instance_describe` | `ec2.describe_instances(InstanceIds=[id])` | The full instance |
+| `ec2_instance_start` / `_stop` | `ec2.start_instances` / `stop_instances` | |
+| `s3_list` | `s3.list_buckets`, or the `list_objects_v2` paginator (`Key`, `Size`, `LastModified`, `StorageClass`) | `prefix`; stops at `limit` |
+| `s3_upload` | `s3.put_object` | `file` read by `coerce_file_param` (workspace containment, 25 MB); `key` defaults to the file name; content type from the name |
+| `s3_download` | `s3.get_object` | Refused past `MEDIA_MAX_READ_BYTES` before reading; saved with `write_media`, returned as a `FileRef` under `file` |
+| `s3_delete` | `s3.delete_object` | |
+| `call` | `<service>.<api_operation>(**request)` | Resolved before any credential use; botocore validates `request` against the model before sending; one page per call |
+| `list_operations` | botocore's bundled models | No credentials, no network |
+
+Responses are shaped the way the AWS CLI prints them: `ResponseMetadata`
+dropped, timestamps as ISO 8601, blobs as base64, a streaming body (Lambda
+`Payload`) read inline up to 1 MB. Errors become `NodeUserError` with AWS's
+code, message and request id, plus a hint for key (`InvalidClientTokenId`,
+`SignatureDoesNotMatch`, ...), permission (`AccessDenied`,
+`UnauthorizedOperation`) and throttling codes.
+
+## Tests
+
+[`server/tests/nodes/test_aws.py`](../server/tests/nodes/test_aws.py) replaces
+`_sdk._client` with real botocore clients wrapped in `botocore.stub.Stubber`,
+so requests are validated against the real API models without network:
+registration and flat tool schema, region precedence, missing-credential
+envelopes, AWS error mapping, the EC2 projection and truncation, S3 upload
+containment and download to a `FileRef`, `call` resolution before
+credentials, parameter validation, inline streaming bodies, `list_operations`
+without credentials, the credential probe, a clean-interpreter check that
+importing the plugin never loads boto3, and the catalogue / skill / asset
+wiring. `aws` is also in `_MIGRATED_PLUGINS` of
+`tests/test_plugin_self_containment.py`, and the tool name is pinned in
+`tests/fixtures/tool_names_snapshot.json`.
diff --git a/docs-internal/node-logic-flows/README.md b/docs-internal/node-logic-flows/README.md
index 05392331..2b8ab8e7 100644
--- a/docs-internal/node-logic-flows/README.md
+++ b/docs-internal/node-logic-flows/README.md
@@ -125,8 +125,8 @@ that a retired node remains registered.
- [Chat History (`chatHistory`)](./chat_utility/chatHistory.md)
- [Reply in Chat (`chatReply`)](./chat_utility/chatReply.md)
-- [Show UI (`chatUi`)](./chat_utility/chatUi.md)
- [Chat Send (`chatSend`)](./chat_utility/chatSend.md)
+- [Show UI (`chatUi`)](./chat_utility/chatUi.md)
- [Console (`console`)](./chat_utility/console.md)
- [File Handler (`fileHandler`)](./chat_utility/fileHandler.md)
- [Create Map (`gmaps_create`)](./chat_utility/gmaps_create.md)
@@ -137,6 +137,7 @@ that a retired node remains registered.
### cli_integrations
+- [AWS (`awsAction`)](./cli_integrations/awsAction.md)
- [Cloudflare (`cloudflareAction`)](./cli_integrations/cloudflareAction.md)
- [Google Cloud (`gcloudAction`)](./cli_integrations/gcloudAction.md)
- [GitHub (`githubAction`)](./cli_integrations/githubAction.md)
@@ -281,6 +282,10 @@ that a retired node remains registered.
- [WhatsApp Business Send (`whatsappBusinessSend`)](./whatsapp_business/whatsappBusinessSend.md)
- [WhatsApp Business Status (`whatsappBusinessStatus`)](./whatsapp_business/whatsappBusinessStatus.md)
+### workflow
+
+- [Team work (`employeeJob`)](./workflow/employeeJob.md)
+
### workflow_triggers
- [Approval (`approvalGate`)](./workflow_triggers/approvalGate.md)
diff --git a/docs-internal/node-logic-flows/cli_integrations/awsAction.md b/docs-internal/node-logic-flows/cli_integrations/awsAction.md
new file mode 100644
index 00000000..e52ef50c
--- /dev/null
+++ b/docs-internal/node-logic-flows/cli_integrations/awsAction.md
@@ -0,0 +1,173 @@
+# AWS (`awsAction`)
+
+| Field | Value |
+|------|-------|
+| **Category** | deployment / tool (dual-purpose) |
+| **Backend handler** | [`server/nodes/aws/aws_action.py`](../../../server/nodes/aws/aws_action.py) - `AwsActionNode`; dispatched via `BaseNode.execute()` + the `@Operation("<op>")` methods; SDK glue in [`_sdk.py`](../../../server/nodes/aws/_sdk.py) |
+| **Tests** | [`server/tests/nodes/test_aws.py`](../../../server/tests/nodes/test_aws.py) |
+| **Skill (if any)** | [`server/skills/aws/aws-skill/SKILL.md`](../../../server/skills/aws/aws-skill/SKILL.md) |
+| **Dual-purpose tool** | yes - tool name `aws_action` (`usable_as_tool = True`; both canvas handles explicitly kept visible) |
+
+## Purpose
+
+Work with Amazon Web Services through the official boto3 SDK, authenticated
+by an IAM access key pair saved in Credentials -> AWS. Typed operations cover
+the common flows (the identity behind the key, EC2 instance list / describe /
+start / stop, S3 list / upload / download / delete); `call` reaches any
+operation of any AWS service by its boto3 method name, and `list_operations`
+discovers services and operations from the SDK's bundled models without
+credentials or network. Used both as a workflow node and as an AI-agent tool.
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream data; not consumed directly - all inputs come from `parameters` (or the LLM's tool args when used as a tool) |
+
+## Parameters
+
+(Pydantic `AwsActionParams`, `extra="ignore"`; a `@model_validator(mode="before")`
+runs `coerce_blank_params(..., object_fields=("request",))` so the panel's `""`
+and LLM-stringified JSON both become a dict.)
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `operation` | options | `whoami` | yes (dispatch reads the raw key) | - | `whoami` / `ec2_instances_list` / `ec2_instance_describe` / `ec2_instance_start` / `ec2_instance_stop` / `s3_list` / `s3_upload` / `s3_download` / `s3_delete` / `call` / `list_operations` |
+| `region` | string | `""` | no | every operation but `list_operations` | Region for this call; blank = the credential's `aws_region`, else `us-east-1` |
+| `instance_id` | string | `""` | yes for describe / start / stop | `ec2_instance_*` | EC2 instance id |
+| `instance_state` | options | `all` | no | `ec2_instances_list` | `all`, `pending`, `running`, `stopping`, `stopped`, `shutting-down`, `terminated` |
+| `bucket` | string | `""` | yes except `s3_list` | `s3_*` | S3 bucket; `s3_list` without it lists the buckets |
+| `prefix` | string | `""` | no | `s3_list` | Object key prefix |
+| `key` | string | `""` | yes for download / delete | `s3_upload`, `s3_download`, `s3_delete` | Object key; `s3_upload` defaults to the file name |
+| `file` | file (`widget: file`) | `""` | yes for `s3_upload` | `s3_upload` | A file reference, a workspace path, or the legacy upload envelope (read by `coerce_file_param`) |
+| `service` | string (dynamic options: `awsServices`) | `""` | yes for `call` | `call`, `list_operations` | boto3 service name (`ec2`, `s3`, `lambda`, ...) |
+| `api_operation` | string (dynamic options: `awsOperations`, depends on `service`) | `""` | yes for `call` | `call` | boto3 method (`describe_vpcs`) or API name (`DescribeVpcs`) |
+| `request` | object (JSON editor) | `{}` | no | `call` | API parameters with AWS's PascalCase names |
+| `search` | string | `""` | no | `list_operations` | Substring filter over service / operation names and summaries |
+| `limit` | int (`ge=1, le=1000`) | `100` | no | `ec2_instances_list`, `s3_list`, `list_operations` | Maximum items returned |
+
+Field names `model`, `api_key`, `parameters`, `action`, `service_id` and
+`session_id` are deliberately avoided (name-based magic in `ParameterRenderer.tsx`).
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| `output-main` | object | `_shape(operation, **fields)` payload (see below); the same payload is returned to the LLM when wired to `input-tools` |
+| `output-tool` | - | Auto-appended for `usable_as_tool` |
+
+### Output payload (TypeScript shape)
+
+```ts
+// AwsActionOutput (extra="allow"); _shape drops only None, so [] / {} results stay
+{
+ operation: string;
+ region?: string; // every operation that called AWS
+ service?: string; // call / list_operations with a service
+ api_operation?: string; // call: the resolved boto3 method
+ result: unknown; // AWS's own response fields (timestamps ISO 8601, blobs base64),
+ // without ResponseMetadata. ec2_instances_list: one row per
+ // instance {InstanceId, Name, State, InstanceType, PublicIpAddress,
+ // PrivateIpAddress, AvailabilityZone, LaunchTime, ImageId, KeyName}
+ count?: number; // listings: items returned
+ total?: number; // list_operations: matches before limit
+ truncated?: boolean; // ec2_instances_list / s3_list: more items than limit
+ file?: FileRef; // s3_download: the saved workspace file (kind "file")
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[BaseNode.execute -> AwsActionNode.&lt;operation&gt;] --> B{operation}
+
+ B -- list_operations --> L1[service_names / operations - botocore bundled models, no credentials, no network]
+ L1 --> L2[substring search, slice to limit] --> L3[_shape: result, count, total]
+
+ B -- call --> C1{service + api_operation given?}
+ C1 -- no --> Ereq[NodeUserError: field required]
+ C1 -- yes --> C2[resolve_operation: xform_name, unknown -> difflib suggestions]
+ C2 -- unknown --> Eunk[NodeUserError with closest names, before any credential use]
+ C2 -- ok --> S
+
+ B -- typed ops --> V{required fields present?}
+ V -- no --> Ereq
+ V -- yes --> S[_keys: AwsCredential.resolve -> KeyPair, passed explicitly to every client]
+ S -- key or ID missing --> Eperm[PermissionError provider=aws -> PermissionDeniedError envelope]
+ S -- ok --> R[region = param, else credential aws_region, else us-east-1]
+ R --> X[_sdk.call / collect / download_object in a worker thread<br/>client: timeouts 10s / 60s, standard retries, 3 attempts]
+ X -- ClientError --> Emap[NodeUserError: code + message + hint for auth / denied / throttle codes + request id]
+ X -- ParamValidationError --> Eval[NodeUserError: AWS validation message]
+ X -- connection / timeout --> Econ[NodeUserError: could not reach AWS in region]
+ X -- ok --> P[to_plain: drop ResponseMetadata, ISO timestamps, base64 blobs, streaming body inline up to 1 MB]
+ P --> O[_shape operation, region, result, ...]
+
+ B -- s3_upload --> U1[coerce_file_param: contained workspace read, 25 MB] --> S
+ B -- s3_download --> D1[get_object, refused past MEDIA_MAX_READ_BYTES] --> D2[write_media -> FileRef under media/]
+```
+
+## Decision Logic
+
+- **Validation**: dispatch requires the `operation` key; `instance_id` for
+ describe / start / stop; `bucket` for upload / download / delete; `file`
+ for upload; `key` for download / delete; `service` and `api_operation`
+ for `call`. Each missing field raises before any credential or network use.
+- **Operation resolution** (`call`): accepts the boto3 method or the API
+ name; unknown services and operations fail with up to five close matches.
+- **Parameter validation**: botocore validates `request` against the API
+ model before building a request; errors name the offending parameter.
+- **Region**: the `region` field, else the credential's `aws_region`, else
+ `us-east-1`. S3 follows bucket-region redirects itself.
+- **Pagination**: `ec2_instances_list` and `s3_list` page through results
+ until `limit` items and report `truncated`; `call` returns one page
+ (pass the service's `NextToken` back in `request`).
+- **Error paths**: missing credential -> `PermissionDeniedError` envelope;
+ AWS `ClientError` -> `NodeUserError` with the AWS code, message and
+ request id; client-side botocore errors -> `NodeUserError`. Anything else
+ keeps its traceback.
+
+## Side Effects
+
+- **Database writes**: none.
+- **Broadcasts**: per-node status via `BaseNode.execute`; the credential
+ path emits `credential.api_key.runtime_failed` when the key is missing.
+- **External API calls**: AWS service endpoints of the chosen region, signed
+ with SigV4 by botocore using the saved key pair; `list_operations` makes none.
+- **File I/O**: `s3_upload` reads one workspace file (containment-checked);
+ `s3_download` writes one file under the workspace's `media/` folder.
+- **Subprocess**: none.
+
+## External Dependencies
+
+- **Credentials**: `AwsCredential` (`ApiKeyCredential`, id `aws`): the Secret
+ Access Key under the provider id, plus the `aws_access_key_id` and
+ `aws_region` rows (`extra_fields`), resolved via
+ `AwsCredential.resolve(user_id=ctx.credential_customer_id)`. Modal
+ probe: `sts:GetCallerIdentity` signed with the pair.
+- **Services**: option-loader registry (`awsServices`, `awsOperations`),
+ `services.media` (`coerce_file_param`, `write_media`).
+- **Python packages**: `boto3` (with `botocore`, `s3transfer`, `jmespath`),
+ imported lazily inside `_sdk.py` only.
+- **Environment variables**: none. Ambient AWS credentials (environment,
+ `~/.aws`, an instance profile) are never used: the key pair is passed explicitly.
+
+## Edge cases & known limits
+
+- **Transfers are capped at 25 MB** (`MEDIA_MAX_READ_BYTES`) and run in
+ memory; larger objects need a different path.
+- **Streaming responses** (Lambda `Payload`) are read inline up to 1 MB as
+ UTF-8 text (base64 if binary); event streams are refused.
+- **Long listings**: `call` returns whatever one AWS page holds; filters in
+ `request` keep results small.
+- **A new client per call**: each operation builds a client, with the key
+ pair, from one shared botocore session that caches service models (about
+ 5 ms when warm; the first client of a service loads its model, ~0.3 s).
+ Client creation is serialised by a lock because botocore sessions are not
+ thread-safe; the API calls run concurrently.
+
+## Related
+
+- **Skills using this as a tool**: [`aws-skill/SKILL.md`](../../../server/skills/aws/aws-skill/SKILL.md)
+- **Companion nodes**: [`gcloudAction`](./gcloudAction.md), [`cloudflareAction`](./cloudflareAction.md)
+- **Architecture docs**: [AWS Service](../../aws_service.md), [Plugin System](../../plugin_system.md), [Media Transport](../../media_transport.md), [Credentials Encryption](../../credentials_encryption.md)
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.json
index 55d556dd..2c19df5f 100644
--- a/server/config/credential_providers.json
+++ b/server/config/credential_providers.json
@@ -1115,6 +1115,45 @@
},
"instructions": "Click 'Login with Google Cloud' — the gcloud CLI (auto-installed, ~100 MB on first use) opens your default browser itself for Google sign-in and completes via a localhost callback (browser must run on this machine; the badge flips when the CLI finishes). Credentials are stored by gcloud under OpenCompany's data directory — isolated from any gcloud you may have installed yourself — and OpenCompany never keeps them."
},
+ "aws": {
+ "name": "AWS",
+ "publisher": "Amazon Web Services",
+ "verified": true,
+ "consumer_category": "developer",
+ "description": "Run and manage your servers, storage and services on AWS.",
+ "category": "deployment",
+ "category_label": "Deployment",
+ "color": "dracula.orange",
+ "kind": "apiKey",
+ "icon_ref": "/api/schemas/credentials/aws/icon",
+ "fields": [
+ {
+ "key": "apiKey",
+ "label": "Secret Access Key",
+ "type": "password",
+ "secret": true,
+ "placeholder": "The secret shown once when the access key was created",
+ "required": true
+ },
+ {
+ "key": "aws_access_key_id",
+ "label": "Access Key ID",
+ "type": "text",
+ "required": true,
+ "placeholder": "AKIA...",
+ "help": "The ID of the same access key. Save it before validating the secret: validation signs a call with both."
+ },
+ {
+ "key": "aws_region",
+ "label": "Default Region",
+ "type": "text",
+ "required": false,
+ "placeholder": "us-east-1",
+ "help": "Used when a node or tool call names no region. Blank means us-east-1."
+ }
+ ],
+ "instructions": "Create an access key for an IAM user (IAM -> Users -> your user -> Security credentials -> Create access key). Fill the Access Key ID (and optionally a Default Region), Save Credentials, then paste the Secret Access Key and validate. Give the IAM user only the permissions your workflows need; avoid root-user keys. The keys are stored encrypted by OpenCompany and passed to AWS on each call; AWS credentials configured elsewhere on this machine are never used."
+ },
"deepl": {
"extends": "_ai_base",
"name": "DeepL",
diff --git a/server/nodes/README.md b/server/nodes/README.md
index 3703aae7..900e2181 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -242,6 +242,8 @@ vercel/ — Vercel (CLI deploy / inspect / list / custom passthrough)
github/ — GitHub (gh CLI: clone / PRs / issues / custom; palette group "vcs")
cloudflare/ — Cloudflare (cf CLI: command search / zones / DNS / GraphQL analytics / custom; palette group "deployment")
gcloud/ — Google Cloud (gcloud CLI: projects / Compute Engine / Cloud Run / Cloud Storage / custom; palette group "deployment")
+aws/ — AWS (boto3 SDK: identity / EC2 / S3 / any API operation via call + list_operations; IAM key pair
+ in the encrypted store; palette group "deployment")
speech/ — Provider-abstracted text_to_speech / speech_to_text (palette group "language").
One node per direction with a `provider` dropdown, not one node per vendor. Owns
its own protocol / registries / dispatch / per-vendor modules — see below.
diff --git a/server/nodes/aws/__init__.py b/server/nodes/aws/__init__.py
new file mode 100644
index 00000000..ddcd1e06
--- /dev/null
+++ b/server/nodes/aws/__init__.py
@@ -0,0 +1,27 @@
+"""Plugin for the 'deployment' palette group — Amazon Web Services via the
+official boto3 SDK.
+
+One dual-purpose node, ``awsAction`` (AI tool ``aws_action``): typed EC2 / S3
+operations, ``call`` for any AWS API operation, and ``list_operations`` to
+discover them. Auth is an IAM access key pair saved in Credentials -> AWS and
+passed to boto3 explicitly; the SDK is imported lazily (``_sdk.py``), so the
+plugin registers and the credentials modal answers even without it.
+"""
+
+from __future__ import annotations
+
+from services.node_output_schemas import register_output_schema
+from services.ws_handler_registry import register_option_loader
+
+from ._credentials import AwsCredential
+from ._sdk import load_aws_operations, load_aws_services
+from .aws_action import AwsActionNode, AwsActionOutput
+
+register_output_schema("awsAction", AwsActionOutput)
+register_option_loader("awsServices", load_aws_services)
+register_option_loader("awsOperations", load_aws_operations)
+
+__all__ = [
+ "AwsActionNode",
+ "AwsCredential",
+]
diff --git a/server/nodes/aws/_credentials.py b/server/nodes/aws/_credentials.py
new file mode 100644
index 00000000..96897d36
--- /dev/null
+++ b/server/nodes/aws/_credentials.py
@@ -0,0 +1,78 @@
+"""AWS credential — an IAM access key pair kept in OpenCompany's encrypted
+credential store (``ApiKeyCredential`` shape, cloudflare-style companion rows).
+
+Three rows under one provider:
+
+* ``apiKey`` (stored under the provider id ``aws``) — the Secret Access Key,
+ the field the credentials modal validates;
+* ``aws_access_key_id`` — the Access Key ID the secret belongs to;
+* ``aws_region`` — the default region for calls that name none.
+
+Validation signs ``sts:GetCallerIdentity`` with the pair: every IAM identity
+may call it, so a least-privilege key validates too. The pair is always handed
+to boto3 explicitly, so ambient AWS credentials on the server (environment
+variables, ``~/.aws``, an instance profile) never authenticate a node.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from services.plugin.credential import ApiKeyCredential, ProbeResult
+
+ACCESS_KEY_ID_FIELD = "aws_access_key_id"
+REGION_FIELD = "aws_region"
+DEFAULT_REGION = "us-east-1"
+
+
+class AwsCredential(ApiKeyCredential):
+ id = "aws"
+ display_name = "AWS"
+ category = "Deployment"
+ docs_url = "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html"
+ extra_fields = (ACCESS_KEY_ID_FIELD, REGION_FIELD)
+
+ @classmethod
+ async def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:
+ """The secret, plus the Access Key ID it belongs to (required) and the
+ default region (optional). A missing ID raises the same annotated
+ ``PermissionError`` as a missing secret, so the node answers with the
+ ``PermissionDeniedError`` envelope that points at the modal."""
+ secrets = await super().resolve(user_id=user_id)
+ if not secrets.get(ACCESS_KEY_ID_FIELD):
+ err = PermissionError("No AWS Access Key ID saved. Add it in Credentials -> AWS.")
+ err.provider = cls.id
+ err.reason = "missing"
+ err.auth = cls.auth
+ raise err
+ return secrets
+
+ @classmethod
+ async def _probe(cls, api_key: str) -> ProbeResult:
+ """Sign ``sts:GetCallerIdentity`` with the stored Access Key ID and the
+ secret being validated. Reads the companion rows (not a side effect);
+ the base ``Credential.validate`` stores and broadcasts the result."""
+ from services.plugin import NodeUserError
+ from services.plugin.deps import get_auth_service
+
+ from ._sdk import call, key_pair
+
+ auth = get_auth_service()
+ access_key_id = (await auth.get_api_key(ACCESS_KEY_ID_FIELD) or "").strip()
+ if not access_key_id:
+ return ProbeResult(
+ valid=False,
+ message="Fill the Access Key ID field below, Save Credentials, then validate again.",
+ )
+ region = (await auth.get_api_key(REGION_FIELD) or "").strip() or DEFAULT_REGION
+ keys = key_pair({"api_key": api_key, ACCESS_KEY_ID_FIELD: access_key_id})
+ try:
+ identity = await call(keys, "sts", "get_caller_identity", {}, region)
+ except NodeUserError as exc:
+ return ProbeResult(valid=False, message=str(exc))
+ arn = identity.get("Arn", "")
+ return ProbeResult(
+ valid=True,
+ message=f"AWS access key is valid for {arn}",
+ extra={"arn": arn, "account": identity.get("Account", "")},
+ )
diff --git a/server/nodes/aws/_sdk.py b/server/nodes/aws/_sdk.py
new file mode 100644
index 00000000..1bc0469f
--- /dev/null
+++ b/server/nodes/aws/_sdk.py
@@ -0,0 +1,426 @@
+"""Everything that touches boto3 / botocore, imported lazily.
+
+The node never imports the SDK at module level: the plugin must register (and
+the credentials modal must answer) even when boto3 is missing, and the import
+costs startup time the rest of the server should not pay. Every function here
+that needs the SDK imports it inside its body.
+
+Three jobs:
+
+* **Introspection** (no credentials, no network): :func:`service_names` and
+ :func:`operations` read botocore's bundled service models, so
+ ``list_operations`` and the panel dropdowns always match the installed SDK.
+* **Calls**: :func:`call`, :func:`collect` and :func:`download_object` run a
+ client method in a worker thread (the SDK is synchronous) with the stored
+ key pair passed explicitly, bounded timeouts and the SDK's standard retry
+ mode. Clients come from one shared botocore session, which caches models.
+* **Shaping**: :func:`to_plain` turns a response into JSON-ready data the way
+ the AWS CLI prints it (timestamps as ISO 8601, blobs as base64), and
+ :func:`raise_user_error` maps botocore's errors onto ``NodeUserError``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import datetime as dt
+import difflib
+import functools
+import itertools
+import re
+import threading
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, NoReturn, Tuple
+
+from core.logging import get_logger
+from services.plugin import NodeUserError
+
+from ._credentials import ACCESS_KEY_ID_FIELD
+
+logger = get_logger(__name__)
+
+_CONNECT_TIMEOUT = 10
+_READ_TIMEOUT = 60
+# The SDK's "standard" retry mode: at most this many attempts in total, and
+# only for throttling, transient 5xx and connection errors.
+_MAX_ATTEMPTS = 3
+# A streaming response body (a Lambda invoke Payload, ...) is read inline up
+# to this size; S3 objects go through s3_download instead.
+_MAX_INLINE_BODY_BYTES = 1024 * 1024
+_MAX_SUGGESTIONS = 5
+_SUMMARY_CHARS = 200
+_TAG_RE = re.compile(r"<[^>]+>")
+_MB = 1024 * 1024
+
+# Error codes that get a pointed hint: the key pair itself is wrong, the IAM
+# identity lacks the permission, or AWS throttled the call past the retries.
+_AUTH_CODES = frozenset(
+ {
+ "AuthFailure",
+ "ExpiredToken",
+ "IncompleteSignature",
+ "InvalidAccessKeyId",
+ "InvalidClientTokenId",
+ "SignatureDoesNotMatch",
+ "UnrecognizedClientException",
+ }
+)
+_DENIED_CODES = frozenset({"AccessDenied", "AccessDeniedException", "UnauthorizedOperation"})
+_THROTTLE_CODES = frozenset(
+ {"RequestLimitExceeded", "SlowDown", "Throttling", "ThrottlingException", "TooManyRequestsException"}
+)
+
+
+def _require_sdk() -> None:
+ try:
+ import boto3 # noqa: F401
+ except ImportError as exc:
+ raise NodeUserError("The 'boto3' package is not installed. Run `uv sync` in server/.") from exc
+
+
+# ---------------------------------------------------------------------------
+# Introspection
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class OperationInfo:
+ service: str # "ec2"
+ operation: str # boto3 method name, "describe_instances"
+ api_name: str # AWS API name, "DescribeInstances"
+ required: Tuple[str, ...]
+ params: Tuple[str, ...]
+ streaming_output: bool
+ summary: str
+
+ def as_dict(self) -> Dict[str, Any]:
+ return {
+ "operation": self.operation,
+ "api_name": self.api_name,
+ "required": list(self.required),
+ "params": list(self.params),
+ "streaming_output": self.streaming_output,
+ "summary": self.summary,
+ }
+
+
[email protected]_cache(maxsize=1)
+def _botocore_session() -> Any:
+ _require_sdk()
+ import botocore.session
+
+ return botocore.session.get_session()
+
+
+def service_names() -> List[str]:
+ """Every service the installed SDK knows (``ec2``, ``s3``, ``lambda``, ...)."""
+ return sorted(_botocore_session().get_available_services())
+
+
+def _summary(documentation: str) -> str:
+ """The first sentence of an operation's HTML documentation, as plain text."""
+ text = " ".join(_TAG_RE.sub(" ", documentation or "").split())
+ first = text.split(". ")[0]
+ return first if len(first) <= _SUMMARY_CHARS else first[: _SUMMARY_CHARS - 3] + "..."
+
+
+def _known_service(service: str) -> str:
+ names = service_names()
+ key = service.strip().lower()
+ if key in names:
+ return key
+ suggestions = difflib.get_close_matches(key, names, n=_MAX_SUGGESTIONS, cutoff=0.6)
+ hint = f" Did you mean: {', '.join(suggestions)}?" if suggestions else ""
+ raise NodeUserError(
+ f"Unknown AWS service '{service.strip()}'.{hint} "
+ "Use operation=list_operations without a service to list them."
+ )
+
+
[email protected]_cache(maxsize=None)
+def _operations(service: str) -> Tuple[OperationInfo, ...]:
+ from botocore import xform_name
+
+ model = _botocore_session().get_service_model(service)
+ infos = []
+ for api_name in model.operation_names:
+ op = model.operation_model(api_name)
+ shape = op.input_shape
+ infos.append(
+ OperationInfo(
+ service=service,
+ operation=xform_name(api_name),
+ api_name=api_name,
+ required=tuple(shape.required_members) if shape is not None else (),
+ params=tuple(shape.members) if shape is not None else (),
+ streaming_output=op.has_streaming_output,
+ summary=_summary(op.documentation),
+ )
+ )
+ return tuple(sorted(infos, key=lambda info: info.operation))
+
+
+def operations(service: str) -> List[OperationInfo]:
+ """The operations of one service, with their parameter names."""
+ return list(_operations(_known_service(service)))
+
+
+def resolve_operation(service: str, operation: str) -> OperationInfo:
+ """Map ``describe_vpcs`` or ``DescribeVpcs`` to the service's operation,
+ failing before any network call with the closest names."""
+ from botocore import xform_name
+
+ infos = operations(service)
+ key = xform_name(operation.strip())
+ for info in infos:
+ if info.operation == key:
+ return info
+ names = [info.operation for info in infos]
+ suggestions = difflib.get_close_matches(key, names, n=_MAX_SUGGESTIONS, cutoff=0.5)
+ hint = f" Did you mean: {', '.join(suggestions)}?" if suggestions else ""
+ service_name = infos[0].service if infos else service.strip()
+ raise NodeUserError(
+ f"Unknown {service_name} operation '{operation.strip()}'.{hint} "
+ f"Use operation=list_operations with service={service_name} to list them."
+ )
+
+
+# ---------------------------------------------------------------------------
+# Response + error shaping
+# ---------------------------------------------------------------------------
+
+
[email protected]_cache(maxsize=1)
+def _stream_types() -> Tuple[type, type]:
+ from botocore.eventstream import EventStream
+ from botocore.response import StreamingBody
+
+ return StreamingBody, EventStream
+
+
+def _read_body(body: Any) -> str:
+ try:
+ payload = body.read(_MAX_INLINE_BODY_BYTES + 1)
+ finally:
+ body.close()
+ if len(payload) > _MAX_INLINE_BODY_BYTES:
+ raise NodeUserError(
+ "The response body is larger than 1 MB. For S3 objects use operation=s3_download, "
+ "which saves the object to the workspace."
+ )
+ try:
+ return payload.decode("utf-8")
+ except UnicodeDecodeError:
+ return base64.b64encode(payload).decode("ascii")
+
+
+def to_plain(value: Any) -> Any:
+ """JSON-ready data, printed the way the AWS CLI prints it: timestamps as
+ ISO 8601, blobs as base64, a streaming body read inline (up to 1 MB)."""
+ streaming_body, event_stream = _stream_types()
+ if isinstance(value, dict):
+ return {key: to_plain(item) for key, item in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [to_plain(item) for item in value]
+ if isinstance(value, (dt.datetime, dt.date)):
+ return value.isoformat()
+ if isinstance(value, (bytes, bytearray)):
+ return base64.b64encode(bytes(value)).decode("ascii")
+ if isinstance(value, streaming_body):
+ return _read_body(value)
+ if isinstance(value, event_stream):
+ raise NodeUserError("This operation answers with an event stream, which the node cannot return.")
+ return value
+
+
+def raise_user_error(exc: Exception, label: str, region: str) -> NoReturn:
+ """Translate a botocore ``ClientError`` / ``BotoCoreError`` into a
+ ``NodeUserError`` carrying AWS's own code and message."""
+ from botocore.exceptions import (
+ ClientError,
+ ConnectTimeoutError,
+ EndpointConnectionError,
+ ParamValidationError,
+ ReadTimeoutError,
+ )
+
+ if isinstance(exc, ClientError):
+ error = exc.response.get("Error") or {}
+ code = error.get("Code") or "Unknown"
+ message = f"AWS {label} failed ({code}): {error.get('Message') or exc}"
+ if code in _AUTH_CODES:
+ message += ". Check the key pair in Credentials -> AWS."
+ elif code in _DENIED_CODES:
+ message += ". The IAM identity behind the key lacks this permission."
+ elif code in _THROTTLE_CODES:
+ message += ". AWS throttled the request after retries; try again shortly."
+ request_id = (exc.response.get("ResponseMetadata") or {}).get("RequestId")
+ if request_id:
+ message += f" [request_id={request_id}]"
+ elif isinstance(exc, ParamValidationError):
+ message = f"AWS {label} rejected the request: {exc}"
+ elif isinstance(exc, (EndpointConnectionError, ConnectTimeoutError, ReadTimeoutError)):
+ message = f"Could not reach AWS for {label} in region {region}: {exc}"
+ else:
+ message = f"AWS {label} failed: {exc}"
+ raise NodeUserError(message) from exc
+
+
+# ---------------------------------------------------------------------------
+# Sessions + calls
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class KeyPair:
+ """The stored IAM access key pair, handed to every client explicitly."""
+
+ access_key_id: str
+ secret_access_key: str = field(repr=False)
+
+
+def key_pair(secrets: Dict[str, Any]) -> KeyPair:
+ """The key pair from ``AwsCredential.resolve()``. Explicit keys outrank
+ every ambient source (environment, ``~/.aws``, an instance profile), so
+ the server's own AWS identity never answers for a node."""
+ return KeyPair(access_key_id=secrets[ACCESS_KEY_ID_FIELD], secret_access_key=secrets["api_key"])
+
+
+# One botocore session caches the service models and client classes for every
+# call (a client from a warm session costs ~10 ms against ~110 ms from a fresh
+# one). It holds no credentials: each client gets its key pair explicitly.
+# botocore sessions are not thread-safe, so client creation is serialised;
+# the API calls themselves run concurrently (clients are thread-safe).
+_CLIENT_LOCK = threading.Lock()
+
+
+def _client(keys: KeyPair, service: str, region: str) -> Any:
+ from botocore.config import Config
+
+ with _CLIENT_LOCK:
+ return _botocore_session().create_client(
+ service,
+ region_name=region,
+ aws_access_key_id=keys.access_key_id,
+ aws_secret_access_key=keys.secret_access_key,
+ config=Config(
+ connect_timeout=_CONNECT_TIMEOUT,
+ read_timeout=_READ_TIMEOUT,
+ retries={"mode": "standard", "max_attempts": _MAX_ATTEMPTS},
+ user_agent_extra="OpenCompany",
+ ),
+ )
+
+
+async def call(keys: KeyPair, service: str, method: str, request: Dict[str, Any], region: str) -> Dict[str, Any]:
+ """``client.<method>(**request)`` in a worker thread, returned as plain data
+ without the SDK's ``ResponseMetadata``."""
+ from botocore.exceptions import BotoCoreError, ClientError
+
+ def run() -> Dict[str, Any]:
+ response = getattr(_client(keys, service, region), method)(**request)
+ response.pop("ResponseMetadata", None)
+ return to_plain(response)
+
+ try:
+ return await asyncio.to_thread(run)
+ except (ClientError, BotoCoreError) as exc:
+ raise_user_error(exc, f"{service}.{method}", region)
+
+
+async def collect(
+ keys: KeyPair,
+ service: str,
+ method: str,
+ request: Dict[str, Any],
+ region: str,
+ expression: str,
+ limit: int,
+) -> Tuple[List[Any], bool]:
+ """Items of a paginated call, projected by a JMESPath ``expression`` (the
+ AWS CLI's ``--query`` language), stopping after ``limit`` items. Returns
+ ``(items, truncated)``."""
+ from botocore.exceptions import BotoCoreError, ClientError
+
+ def run() -> Tuple[List[Any], bool]:
+ pages = _client(keys, service, region).get_paginator(method).paginate(**request)
+ found = (item for item in pages.search(expression) if item is not None)
+ items = list(itertools.islice(found, limit + 1))
+ return to_plain(items[:limit]), len(items) > limit
+
+ try:
+ return await asyncio.to_thread(run)
+ except (ClientError, BotoCoreError) as exc:
+ raise_user_error(exc, f"{service}.{method}", region)
+
+
+async def download_object(keys: KeyPair, bucket: str, key: str, region: str, max_bytes: int) -> Tuple[bytes, Any]:
+ """One S3 object's bytes and content type, refused past ``max_bytes``."""
+ from botocore.exceptions import BotoCoreError, ClientError
+
+ def run() -> Tuple[bytes, Any]:
+ response = _client(keys, "s3", region).get_object(Bucket=bucket, Key=key)
+ body = response["Body"]
+ try:
+ size = response.get("ContentLength") or 0
+ payload = b"" if size > max_bytes else body.read(max_bytes + 1)
+ finally:
+ body.close()
+ if size > max_bytes or len(payload) > max_bytes:
+ raise NodeUserError(
+ f"s3://{bucket}/{key} is {max(size, len(payload)) // _MB} MB; "
+ f"the download limit is {max_bytes // _MB} MB."
+ )
+ return payload, response.get("ContentType")
+
+ try:
+ return await asyncio.to_thread(run)
+ except (ClientError, BotoCoreError) as exc:
+ raise_user_error(exc, "s3.get_object", region)
+
+
+# ---------------------------------------------------------------------------
+# Dropdown loaders
+# ---------------------------------------------------------------------------
+
+
+async def load_aws_services(params: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """``loadOptionsMethod`` for the ``service`` dropdown. A missing SDK must
+ never break the parameter panel, so it degrades to no options."""
+ try:
+ names = await asyncio.to_thread(service_names)
+ except NodeUserError as exc:
+ logger.warning("aws service loader failed", error=str(exc))
+ return []
+ return [{"value": name, "label": name} for name in names]
+
+
+async def load_aws_operations(params: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """``loadOptionsMethod`` for the ``api_operation`` dropdown (depends on
+ ``service``)."""
+ service = str((params or {}).get("service") or "").strip()
+ if not service:
+ return []
+ try:
+ infos = await asyncio.to_thread(operations, service)
+ except NodeUserError as exc:
+ logger.warning("aws operation loader failed", service=service, error=str(exc))
+ return []
+ return [{"value": info.operation, "label": info.operation, "description": info.summary} for info in infos]
+
+
+__all__ = [
+ "KeyPair",
+ "OperationInfo",
+ "call",
+ "collect",
+ "download_object",
+ "load_aws_operations",
+ "load_aws_services",
+ "operations",
+ "raise_user_error",
+ "resolve_operation",
+ "service_names",
+ "key_pair",
+ "to_plain",
+]
diff --git a/server/nodes/aws/aws.svg b/server/nodes/aws/aws.svg
new file mode 100644
index 00000000..c0c152af
--- /dev/null
+++ b/server/nodes/aws/aws.svg
@@ -0,0 +1,7 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
+ <rect width="24" height="24" rx="5" fill="#232F3E"/>
+ <g transform="translate(3 3) scale(0.75)" fill-rule="evenodd">
+ <path fill="#FFFFFF" d="M6.763 11.212c0 .296.032.535.088.71.064.176.144.368.256.576.04.063.056.127.056.183 0 .08-.048.16-.152.24l-.503.335a.383.383 0 01-.208.072c-.08 0-.16-.04-.239-.112a2.47 2.47 0 01-.287-.375 6.18 6.18 0 01-.248-.471c-.622.734-1.405 1.101-2.347 1.101-.67 0-1.205-.191-1.596-.574-.39-.384-.59-.894-.59-1.533 0-.678.24-1.23.726-1.644.487-.415 1.133-.623 1.955-.623.272 0 .551.024.846.064.296.04.6.104.918.176v-.583c0-.607-.127-1.03-.375-1.277-.255-.248-.686-.367-1.3-.367-.28 0-.568.031-.863.103-.295.072-.583.16-.862.272a2.4 2.4 0 01-.28.104.488.488 0 01-.127.023c-.112 0-.168-.08-.168-.247v-.391c0-.128.016-.224.056-.28a.597.597 0 01.224-.167 4.577 4.577 0 011.005-.36 4.84 4.84 0 011.246-.151c.95 0 1.644.216 2.091.647.44.43.662 1.085.662 1.963v2.586h.016zm-3.24 1.214c.263 0 .534-.048.822-.144a1.78 1.78 0 00.758-.51 1.27 1.27 0 00.272-.512c.047-.191.08-.423.08-.694v-.335a6.66 6.66 0 00-.735-.136 6.02 6.02 0 00-.75-.048c-.535 0-.926.104-1.19.32-.263.215-.39.518-.39.917 0 .375.095.655.295.846.191.2.47.296.838.296zm6.41.862c-.144 0-.24-.024-.304-.08-.064-.048-.12-.16-.168-.311L7.586 6.726a1.398 1.398 0 01-.072-.32c0-.128.064-.2.191-.2h.783c.151 0 .255.025.31.08.065.048.113.16.16.312l1.342 5.284 1.245-5.284c.04-.16.088-.264.151-.312a.549.549 0 01.32-.08h.638c.152 0 .256.025.32.08.063.048.12.16.151.312l1.261 5.348 1.381-5.348c.048-.16.104-.264.16-.312a.52.52 0 01.311-.08h.743c.127 0 .2.065.2.2 0 .04-.009.08-.017.128a1.137 1.137 0 01-.056.2l-1.923 6.17c-.048.16-.104.263-.168.311a.51.51 0 01-.303.08h-.687c-.15 0-.255-.024-.32-.08-.063-.056-.119-.16-.15-.32L12.32 7.747l-1.23 5.14c-.04.16-.087.264-.15.32-.065.056-.177.08-.32.08l-.686.001zm10.256.215c-.415 0-.83-.048-1.229-.143-.399-.096-.71-.2-.918-.32-.128-.071-.215-.151-.247-.223a.563.563 0 01-.048-.224v-.407c0-.167.064-.247.183-.247.048 0 .096.008.144.024.048.016.12.048.2.08.271.12.566.215.878.279.32.064.63.096.95.096.502 0 .894-.088 1.165-.264a.86.86 0 00.415-.758.777.777 0 00-.215-.559c-.144-.151-.416-.287-.807-.415l-1.157-.36c-.583-.183-1.014-.454-1.277-.813a1.902 1.902 0 01-.4-1.158c0-.335.073-.63.216-.886.144-.255.335-.479.575-.654.24-.184.51-.32.83-.415.32-.096.655-.136 1.006-.136.175 0 .36.008.535.032.183.024.35.056.518.088.16.04.312.08.455.127.144.048.256.096.336.144a.69.69 0 01.24.2.43.43 0 01.071.263v.375c0 .168-.064.256-.184.256a.83.83 0 01-.303-.096 3.652 3.652 0 00-1.532-.311c-.455 0-.815.071-1.062.223-.248.152-.375.383-.375.71 0 .224.08.416.24.567.16.152.454.304.877.44l1.134.358c.574.184.99.44 1.237.767.247.327.367.702.367 1.117 0 .343-.072.655-.207.926a2.157 2.157 0 01-.583.703c-.248.2-.543.343-.886.447-.36.111-.734.167-1.142.167z"/>
+ <path fill="#FF9900" d="M.378 15.475c3.384 1.963 7.56 3.153 11.877 3.153 2.914 0 6.114-.607 9.06-1.852.44-.2.814.287.383.607-2.626 1.94-6.442 2.969-9.722 2.969-4.598 0-8.74-1.7-11.87-4.526-.247-.223-.024-.527.272-.351zm23.531-.2c.287.36-.08 2.826-1.485 4.007-.215.184-.423.088-.327-.151l.175-.439c.343-.88.802-2.198.52-2.555-.336-.43-2.22-.207-3.074-.103-.255.032-.295-.192-.063-.36 1.5-1.053 3.967-.75 4.254-.399z"/>
+ </g>
+</svg>
diff --git a/server/nodes/aws/aws_action.py b/server/nodes/aws/aws_action.py
new file mode 100644
index 00000000..0f9948ff
--- /dev/null
+++ b/server/nodes/aws/aws_action.py
@@ -0,0 +1,394 @@
+"""AWS Action — typed core operations over the official boto3 SDK, plus a
+passthrough to any AWS API operation.
+
+Dual-purpose: a workflow node and the AI tool ``aws_action``. Auth is the IAM
+access key pair saved in Credentials -> AWS (``_credentials.py``), passed
+explicitly to every SDK client. Every SDK touch lives in ``_sdk.py``, imported
+lazily. Results are AWS's own response fields, shaped the way the AWS CLI
+prints them.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import mimetypes
+from pathlib import PurePosixPath
+from typing import Any, Dict, Literal, Optional, Tuple
+
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+from services.media import MEDIA_MAX_READ_BYTES, coerce_file_param, write_media
+from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue, coerce_blank_params
+
+from . import _sdk
+from ._credentials import DEFAULT_REGION, REGION_FIELD, AwsCredential
+
+_OPERATIONS = (
+ "whoami",
+ "ec2_instances_list",
+ "ec2_instance_describe",
+ "ec2_instance_start",
+ "ec2_instance_stop",
+ "s3_list",
+ "s3_upload",
+ "s3_download",
+ "s3_delete",
+ "call",
+ "list_operations",
+)
+
+
+def _show(*ops: str) -> Dict[str, Any]:
+ return {"displayOptions": {"show": {"operation": list(ops)}}}
+
+
+_REGIONAL = _show(*(op for op in _OPERATIONS if op != "list_operations"))
+_INSTANCE = _show("ec2_instance_describe", "ec2_instance_start", "ec2_instance_stop")
+_INSTANCES_LIST = _show("ec2_instances_list")
+_BUCKET = _show("s3_list", "s3_upload", "s3_download", "s3_delete")
+_PREFIX = _show("s3_list")
+_KEY = _show("s3_upload", "s3_download", "s3_delete")
+_UPLOAD = _show("s3_upload")
+_SERVICE = _show("call", "list_operations")
+_CALL = _show("call")
+_SEARCH = _show("list_operations")
+_LIMIT = _show("ec2_instances_list", "s3_list", "list_operations")
+
+# The AWS CLI's own --query idiom for an instance overview: one row per
+# instance with the fields that identify and locate it.
+_INSTANCE_SUMMARY = (
+ "Reservations[].Instances[].{InstanceId: InstanceId, Name: Tags[?Key=='Name'] | [0].Value, "
+ "State: State.Name, InstanceType: InstanceType, PublicIpAddress: PublicIpAddress, "
+ "PrivateIpAddress: PrivateIpAddress, AvailabilityZone: Placement.AvailabilityZone, "
+ "LaunchTime: LaunchTime, ImageId: ImageId, KeyName: KeyName}"
+)
+_OBJECT_SUMMARY = "Contents[].{Key: Key, Size: Size, LastModified: LastModified, StorageClass: StorageClass}"
+
+
+class AwsActionParams(BaseModel):
+ operation: Literal[_OPERATIONS] = "whoami"
+
+ # Shared: blank means the default region saved with the credential.
+ region: str = Field(
+ default="",
+ description="AWS region for this call (blank = the default region saved in Credentials -> AWS)",
+ json_schema_extra={"placeholder": "us-east-1", **_REGIONAL},
+ )
+
+ # ec2
+ instance_id: str = Field(
+ default="",
+ description="EC2 instance id",
+ json_schema_extra={"placeholder": "i-0123456789abcdef0", **_INSTANCE},
+ )
+ instance_state: Literal["all", "pending", "running", "stopping", "stopped", "shutting-down", "terminated"] = Field(
+ default="all",
+ description="Only list instances in this state",
+ json_schema_extra=_INSTANCES_LIST,
+ )
+
+ # s3
+ bucket: str = Field(
+ default="",
+ description="S3 bucket name (s3_list without a bucket lists the buckets)",
+ json_schema_extra={"placeholder": "my-bucket", **_BUCKET},
+ )
+ prefix: str = Field(
+ default="",
+ description="Only list object keys starting with this prefix",
+ json_schema_extra={"placeholder": "reports/2026/", **_PREFIX},
+ )
+ key: str = Field(
+ default="",
+ description="S3 object key (s3_upload defaults to the file's name)",
+ json_schema_extra={"placeholder": "reports/q3.pdf", **_KEY},
+ )
+ # Three shapes reach this field: a file reference from an upstream node or
+ # the upload route, a bare workspace path, or the legacy base64 envelope.
+ # coerce_file_param reads all three with workspace containment.
+ file: Any = Field(
+ default="",
+ description="File to upload: upload one, or point at a workspace path",
+ json_schema_extra={"widget": "file", **_UPLOAD},
+ )
+
+ # call / list_operations
+ service: str = Field(
+ default="",
+ description="boto3 service name (ec2, s3, lambda, iam, rds, cloudwatch, ...)",
+ json_schema_extra={
+ "placeholder": "ec2",
+ "dynamicOptions": True,
+ "loadOptionsMethod": "awsServices",
+ **_SERVICE,
+ },
+ )
+ api_operation: str = Field(
+ default="",
+ description="boto3 method of the service, e.g. describe_vpcs (DescribeVpcs also works)",
+ json_schema_extra={
+ "placeholder": "describe_vpcs",
+ "dynamicOptions": True,
+ "loadOptionsMethod": "awsOperations",
+ "loadOptionsDependsOn": ["service"],
+ **_CALL,
+ },
+ )
+ request: Dict[str, Any] = Field(
+ default_factory=dict,
+ description="API parameters as a JSON object, with AWS's own PascalCase names",
+ json_schema_extra={"editor": "json", "rows": 6, **_CALL},
+ )
+ search: str = Field(
+ default="",
+ description="Case-insensitive substring over service or operation names",
+ json_schema_extra={"placeholder": "vpc", **_SEARCH},
+ )
+
+ limit: int = Field(default=100, ge=1, le=1000, json_schema_extra=_LIMIT)
+
+ model_config = ConfigDict(extra="ignore")
+
+ @model_validator(mode="before")
+ @classmethod
+ def _coerce(cls, values: Any) -> Any:
+ # The panel stores "" for cleared fields and renders `request` as
+ # text; an LLM may also stringify the JSON object.
+ return coerce_blank_params(cls, values, object_fields=("request",))
+
+
+class AwsActionOutput(BaseModel):
+ operation: Optional[str] = None
+ region: Optional[str] = None
+ service: Optional[str] = None
+ api_operation: Optional[str] = None
+ result: Optional[Any] = None
+ count: Optional[int] = None
+ total: Optional[int] = None
+ truncated: Optional[bool] = None
+ file: Optional[Dict[str, Any]] = None
+
+ model_config = ConfigDict(extra="allow")
+
+
+class AwsActionNode(ActionNode):
+ type = "awsAction"
+ display_name = "AWS"
+ subtitle = "Amazon Web Services"
+ group = ("deployment", "tool")
+ description = (
+ "Amazon Web Services through the official boto3 SDK: EC2 instances, S3 storage, "
+ "or any AWS API operation"
+ )
+ component_kind = "square"
+ tool_name = "aws_action"
+ tool_description = (
+ "Work with Amazon Web Services through the official boto3 SDK, authenticated by the access key "
+ "saved in Credentials -> AWS. Operations: whoami (the account and IAM identity behind the key; run "
+ "it first when unsure); ec2_instances_list (one row per instance: id, name, state, type, IPs; "
+ "optional instance_state filter), ec2_instance_describe / ec2_instance_start / ec2_instance_stop "
+ "(instance_id required); s3_list (the buckets, or a bucket's objects under prefix), s3_upload "
+ "(bucket, file = a workspace path or file reference, key defaults to the file name), s3_download "
+ "(bucket + key; saves the object to the workspace and returns a file reference), s3_delete "
+ "(bucket + key); call (any other AWS API operation: service is the boto3 service name such as "
+ "ec2, s3, lambda, iam, rds; api_operation the boto3 method such as describe_vpcs; request the API "
+ "parameters as a JSON object with AWS's own PascalCase names, e.g. {\"Filters\": [{\"Name\": "
+ "\"tag:Name\", \"Values\": [\"web\"]}]}); list_operations (no service: every service name; with a "
+ "service: its operations and parameter names; needs no credentials). region overrides the "
+ "credential's default region for one call. Results are AWS's own response fields, timestamps in "
+ "ISO 8601. Reference: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html"
+ )
+ handles = (
+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
+ )
+ # start / stop / s3_delete / call mutate cloud state.
+ annotations = {"destructive": True, "readonly": False, "open_world": True}
+ credentials = (AwsCredential,)
+ task_queue = TaskQueue.REST_API
+ usable_as_tool = True
+ # usable_as_tool auto-sets both hide flags unless declared. This node
+ # stays wirable on the canvas through its declared `handles`; the
+ # frontend reads the flags only for a spec with no handles.
+ hide_input_handle = False
+ hide_output_handle = False
+
+ Params = AwsActionParams
+ Output = AwsActionOutput
+
+ # ---- shared plumbing -------------------------------------------------
+
+ @staticmethod
+ def _shape(operation: str, **fields: Any) -> Dict[str, Any]:
+ """``{"operation": ...}`` plus every field that is not ``None``. An empty
+ ``[]`` / ``{}`` result is a real answer from AWS and is kept."""
+ shaped: Dict[str, Any] = {"operation": operation}
+ shaped.update({k: v for k, v in fields.items() if v is not None})
+ return shaped
+
+ @staticmethod
+ def _required(value: str, field: str, operation: str, example: str) -> str:
+ value = value.strip()
+ if not value:
+ raise NodeUserError(f"{field} is required for {operation} (e.g. {example})")
+ return value
+
+ async def _keys(self, ctx: NodeContext, params: AwsActionParams) -> Tuple[_sdk.KeyPair, str]:
+ """The credential is resolved first, so a missing key surfaces as the
+ ``PermissionDeniedError`` envelope that points at the modal."""
+ secrets = await AwsCredential.resolve(user_id=ctx.credential_customer_id)
+ region = params.region.strip() or (secrets.get(REGION_FIELD) or "").strip() or DEFAULT_REGION
+ return _sdk.key_pair(secrets), region
+
+ # ---- identity ----------------------------------------------------------
+
+ @Operation("whoami")
+ async def whoami(self, ctx: NodeContext, params: AwsActionParams) -> Any:
+ keys, region = await self._keys(ctx, params)
+ identity = await _sdk.call(keys, "sts", "get_caller_identity", {}, region)
+ return self._shape("whoami", region=region, result=identity)
+
+ # ---- ec2 ---------------------------------------------------------------
+
+ @Operation("ec2_instances_list")
+ async def ec2_instances_list(self, ctx: NodeContext, params: AwsActionParams) -> Any:
+ keys, region = await self._keys(ctx, params)
+ request: Dict[str, Any] = {}
+ if params.instance_state != "all":
+ request["Filters"] = [{"Name": "instance-state-name", "Values": [params.instance_state]}]
+ items, truncated = await _sdk.collect(
+ keys, "ec2", "describe_instances", request, region, _INSTANCE_SUMMARY, params.limit
+ )
+ return self._shape("ec2_instances_list", region=region, result=items, count=len(items), truncated=truncated)
+
+ @Operation("ec2_instance_describe")
+ async def ec2_instance_describe(self, ctx: NodeContext, params: AwsActionParams) -> Any:
+ instance_id = self._required(params.instance_id, "instance_id", "ec2_instance_describe", "i-0123456789abcdef0")
+ keys, region = await self._keys(ctx, params)
+ items, _ = await _sdk.collect(
+ keys, "ec2", "describe_instances", {"InstanceIds": [instance_id]}, region, "Reservations[].Instances[]", 1
+ )
+ if not items:
+ raise NodeUserError(f"No EC2 instance {instance_id} in {region}")
+ return self._shape("ec2_instance_describe", region=region, result=items[0])
+
+ @Operation("ec2_instance_start")
+ async def ec2_instance_start(self, ctx: NodeContext, params: AwsActionParams) -> Any:
+ instance_id = self._required(params.instance_id, "instance_id", "ec2_instance_start", "i-0123456789abcdef0")
+ keys, region = await self._keys(ctx, params)
+ response = await _sdk.call(keys, "ec2", "start_instances", {"InstanceIds": [instance_id]}, region)
+ return self._shape("ec2_instance_start", region=region, result=response)
+
+ @Operation("ec2_instance_stop")
+ async def ec2_instance_stop(self, ctx: NodeContext, params: AwsActionParams) -> Any:
+ instance_id = self._required(params.instance_id, "instance_id", "ec2_instance_stop", "i-0123456789abcdef0")
+ keys, region = await self._keys(ctx, params)
+ response = await _sdk.call(keys, "ec2", "stop_instances", {"InstanceIds": [instance_id]}, region)
+ return self._shape("ec2_instance_stop", region=region, result=response)
+
+ # ---- s3 ----------------------------------------------------------------
+
+ @Operation("s3_list")
+ async def s3_list(self, ctx: NodeContext, params: AwsActionParams) -> Any:
+ keys, region = await self._keys(ctx, params)
+ bucket = params.bucket.strip()
+ if not bucket:
+ buckets = (await _sdk.call(keys, "s3", "list_buckets", {}, region)).get("Buckets", [])
+ shown = buckets[: params.limit]
+ return self._shape(
+ "s3_list", region=region, result=shown, count=len(shown), truncated=len(buckets) > params.limit
+ )
+ items, truncated = await _sdk.collect(
+ keys, "s3", "list_objects_v2", {"Bucket": bucket, "Prefix": params.prefix}, region,
+ _OBJECT_SUMMARY, params.limit,
+ )
+ return self._shape("s3_list", region=region, result=items, count=len(items), truncated=truncated)
+
+ @Operation("s3_upload")
+ async def s3_upload(self, ctx: NodeContext, params: AwsActionParams) -> Any:
+ bucket = self._required(params.bucket, "bucket", "s3_upload", "my-bucket")
+ if not params.file:
+ raise NodeUserError(
+ "file is required for s3_upload: a workspace path such as 'reports/q3.pdf', "
+ "or a file from an upstream node"
+ )
+ filename, payload = coerce_file_param(params.file, ctx=ctx)
+ key = params.key.strip() or filename
+ content_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"
+ keys, region = await self._keys(ctx, params)
+ response = await _sdk.call(
+ keys, "s3", "put_object",
+ {"Bucket": bucket, "Key": key, "Body": payload, "ContentType": content_type}, region,
+ )
+ return self._shape(
+ "s3_upload", region=region, result={"Bucket": bucket, "Key": key, "Size": len(payload), **response}
+ )
+
+ @Operation("s3_download")
+ async def s3_download(self, ctx: NodeContext, params: AwsActionParams) -> Any:
+ bucket = self._required(params.bucket, "bucket", "s3_download", "my-bucket")
+ key = self._required(params.key, "key", "s3_download", "reports/q3.pdf")
+ keys, region = await self._keys(ctx, params)
+ payload, content_type = await _sdk.download_object(keys, bucket, key, region, MEDIA_MAX_READ_BYTES)
+ name = PurePosixPath(key).name
+ ref = write_media(
+ payload,
+ ctx=ctx,
+ stem=PurePosixPath(name).stem or "object",
+ ext=PurePosixPath(name).suffix or ".bin",
+ mime_type=content_type,
+ )
+ return self._shape(
+ "s3_download",
+ region=region,
+ result={"Bucket": bucket, "Key": key, "Size": len(payload), "ContentType": content_type},
+ file=ref.model_dump(mode="json"),
+ )
+
+ @Operation("s3_delete")
+ async def s3_delete(self, ctx: NodeContext, params: AwsActionParams) -> Any:
+ bucket = self._required(params.bucket, "bucket", "s3_delete", "my-bucket")
+ key = self._required(params.key, "key", "s3_delete", "reports/q3.pdf")
+ keys, region = await self._keys(ctx, params)
+ response = await _sdk.call(keys, "s3", "delete_object", {"Bucket": bucket, "Key": key}, region)
+ return self._shape("s3_delete", region=region, result={"Bucket": bucket, "Key": key, **response})
+
+ # ---- any operation -----------------------------------------------------
+
+ @Operation("call")
+ async def call(self, ctx: NodeContext, params: AwsActionParams) -> Any:
+ service = self._required(params.service, "service", "call", "ec2")
+ api_operation = self._required(params.api_operation, "api_operation", "call", "describe_vpcs")
+ # Resolved before any credential or network use, with the closest
+ # names on a miss.
+ info = await asyncio.to_thread(_sdk.resolve_operation, service, api_operation)
+ keys, region = await self._keys(ctx, params)
+ response = await _sdk.call(keys, info.service, info.operation, params.request, region)
+ return self._shape(
+ "call", region=region, service=info.service, api_operation=info.operation, result=response
+ )
+
+ @Operation("list_operations")
+ async def list_operations(self, ctx: NodeContext, params: AwsActionParams) -> Any:
+ # Pure introspection of the installed SDK: no credentials, no network.
+ needle = params.search.strip().lower()
+ service = params.service.strip()
+ if not service:
+ names = [name for name in await asyncio.to_thread(_sdk.service_names) if needle in name]
+ shown = names[: params.limit]
+ return self._shape("list_operations", result=shown, count=len(shown), total=len(names))
+ infos = await asyncio.to_thread(_sdk.operations, service)
+ matches = [
+ info for info in infos if not needle or needle in info.operation or needle in info.summary.lower()
+ ]
+ shown = matches[: params.limit]
+ return self._shape(
+ "list_operations",
+ service=infos[0].service if infos else service,
+ result=[info.as_dict() for info in shown],
+ count=len(shown),
+ total=len(matches),
+ )
+
+
+__all__ = ["AwsActionNode", "AwsActionOutput", "AwsActionParams"]
diff --git a/server/nodes/aws/icon.svg b/server/nodes/aws/icon.svg
new file mode 100644
index 00000000..c0c152af
--- /dev/null
+++ b/server/nodes/aws/icon.svg
@@ -0,0 +1,7 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
+ <rect width="24" height="24" rx="5" fill="#232F3E"/>
+ <g transform="translate(3 3) scale(0.75)" fill-rule="evenodd">
+ <path fill="#FFFFFF" d="M6.763 11.212c0 .296.032.535.088.71.064.176.144.368.256.576.04.063.056.127.056.183 0 .08-.048.16-.152.24l-.503.335a.383.383 0 01-.208.072c-.08 0-.16-.04-.239-.112a2.47 2.47 0 01-.287-.375 6.18 6.18 0 01-.248-.471c-.622.734-1.405 1.101-2.347 1.101-.67 0-1.205-.191-1.596-.574-.39-.384-.59-.894-.59-1.533 0-.678.24-1.23.726-1.644.487-.415 1.133-.623 1.955-.623.272 0 .551.024.846.064.296.04.6.104.918.176v-.583c0-.607-.127-1.03-.375-1.277-.255-.248-.686-.367-1.3-.367-.28 0-.568.031-.863.103-.295.072-.583.16-.862.272a2.4 2.4 0 01-.28.104.488.488 0 01-.127.023c-.112 0-.168-.08-.168-.247v-.391c0-.128.016-.224.056-.28a.597.597 0 01.224-.167 4.577 4.577 0 011.005-.36 4.84 4.84 0 011.246-.151c.95 0 1.644.216 2.091.647.44.43.662 1.085.662 1.963v2.586h.016zm-3.24 1.214c.263 0 .534-.048.822-.144a1.78 1.78 0 00.758-.51 1.27 1.27 0 00.272-.512c.047-.191.08-.423.08-.694v-.335a6.66 6.66 0 00-.735-.136 6.02 6.02 0 00-.75-.048c-.535 0-.926.104-1.19.32-.263.215-.39.518-.39.917 0 .375.095.655.295.846.191.2.47.296.838.296zm6.41.862c-.144 0-.24-.024-.304-.08-.064-.048-.12-.16-.168-.311L7.586 6.726a1.398 1.398 0 01-.072-.32c0-.128.064-.2.191-.2h.783c.151 0 .255.025.31.08.065.048.113.16.16.312l1.342 5.284 1.245-5.284c.04-.16.088-.264.151-.312a.549.549 0 01.32-.08h.638c.152 0 .256.025.32.08.063.048.12.16.151.312l1.261 5.348 1.381-5.348c.048-.16.104-.264.16-.312a.52.52 0 01.311-.08h.743c.127 0 .2.065.2.2 0 .04-.009.08-.017.128a1.137 1.137 0 01-.056.2l-1.923 6.17c-.048.16-.104.263-.168.311a.51.51 0 01-.303.08h-.687c-.15 0-.255-.024-.32-.08-.063-.056-.119-.16-.15-.32L12.32 7.747l-1.23 5.14c-.04.16-.087.264-.15.32-.065.056-.177.08-.32.08l-.686.001zm10.256.215c-.415 0-.83-.048-1.229-.143-.399-.096-.71-.2-.918-.32-.128-.071-.215-.151-.247-.223a.563.563 0 01-.048-.224v-.407c0-.167.064-.247.183-.247.048 0 .096.008.144.024.048.016.12.048.2.08.271.12.566.215.878.279.32.064.63.096.95.096.502 0 .894-.088 1.165-.264a.86.86 0 00.415-.758.777.777 0 00-.215-.559c-.144-.151-.416-.287-.807-.415l-1.157-.36c-.583-.183-1.014-.454-1.277-.813a1.902 1.902 0 01-.4-1.158c0-.335.073-.63.216-.886.144-.255.335-.479.575-.654.24-.184.51-.32.83-.415.32-.096.655-.136 1.006-.136.175 0 .36.008.535.032.183.024.35.056.518.088.16.04.312.08.455.127.144.048.256.096.336.144a.69.69 0 01.24.2.43.43 0 01.071.263v.375c0 .168-.064.256-.184.256a.83.83 0 01-.303-.096 3.652 3.652 0 00-1.532-.311c-.455 0-.815.071-1.062.223-.248.152-.375.383-.375.71 0 .224.08.416.24.567.16.152.454.304.877.44l1.134.358c.574.184.99.44 1.237.767.247.327.367.702.367 1.117 0 .343-.072.655-.207.926a2.157 2.157 0 01-.583.703c-.248.2-.543.343-.886.447-.36.111-.734.167-1.142.167z"/>
+ <path fill="#FF9900" d="M.378 15.475c3.384 1.963 7.56 3.153 11.877 3.153 2.914 0 6.114-.607 9.06-1.852.44-.2.814.287.383.607-2.626 1.94-6.442 2.969-9.722 2.969-4.598 0-8.74-1.7-11.87-4.526-.247-.223-.024-.527.272-.351zm23.531-.2c.287.36-.08 2.826-1.485 4.007-.215.184-.423.088-.327-.151l.175-.439c.343-.88.802-2.198.52-2.555-.336-.43-2.22-.207-3.074-.103-.255.032-.295-.192-.063-.36 1.5-1.053 3.967-.75 4.254-.399z"/>
+ </g>
+</svg>
diff --git a/server/nodes/aws/meta.json b/server/nodes/aws/meta.json
new file mode 100644
index 00000000..6b22dcd7
--- /dev/null
+++ b/server/nodes/aws/meta.json
@@ -0,0 +1 @@
+{"color": "#FF9900"}
diff --git a/server/nodes/visuals.json b/server/nodes/visuals.json
index a836e0b3..b0975b56 100644
--- a/server/nodes/visuals.json
+++ b/server/nodes/visuals.json
@@ -31,6 +31,9 @@
"tikhubAction": {
"skill": "tikhub-skill"
},
+ "awsAction": {
+ "skill": "aws-skill"
+ },
"appLauncher": {
"icon": "🚀",
"skill": "app-launcher-skill"
diff --git a/server/pyproject.toml b/server/pyproject.toml
index c45fda59..1f5b3815 100644
--- a/server/pyproject.toml
+++ b/server/pyproject.toml
@@ -113,6 +113,9 @@ dependencies = [
# release. Pulls typer for its own `tikhub` CLI (not imported by us).
"tikhub>=2.1.2,<3",
+ # AWS SDK for the awsAction node (nodes/aws/), imported lazily there.
+ "boto3>=1.34.0",
+
# Crawlee Web Scraping
"crawlee[beautifulsoup]>=1.4.0",
# Security floor for beautifulsoup4's selector engine (pulled in by
diff --git a/server/skills/aws/aws-skill/SKILL.md b/server/skills/aws/aws-skill/SKILL.md
new file mode 100644
index 00000000..104d777b
--- /dev/null
+++ b/server/skills/aws/aws-skill/SKILL.md
@@ -0,0 +1,136 @@
+---
+name: aws-skill
+description: Work with Amazon Web Services through the official boto3 SDK — check the identity behind the key, list, start and stop EC2 instances, list, upload, download and delete S3 objects, and call any other AWS API operation. Output is AWS's own JSON response.
+allowed-tools: "aws_action"
+metadata:
+ author: opencompany
+ version: "1.0"
+ category: deployment
+
+---
+
+# AWS Skill
+
+Wrapper over the official [AWS SDK for Python (boto3)](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html).
+Typed operations for the common EC2 and S3 flows, plus `call`, which
+reaches every operation of every AWS service, and `list_operations` to
+discover them. Results are AWS's own response fields, with timestamps in
+ISO 8601 and binary values in base64, as the AWS CLI prints them.
+
+## Tool: aws_action
+
+### Operations
+
+| Operation | Purpose | Key fields |
+|---|---|---|
+| `whoami` | The account and IAM identity behind the saved key | `region` (optional) |
+| `ec2_instances_list` | One row per instance: id, name, state, type, IPs, zone, launch time | `instance_state` (default `all`), `limit`, `region` |
+| `ec2_instance_describe` | Every field of one instance | `instance_id` (required), `region` |
+| `ec2_instance_start` | Start an instance | `instance_id` (required), `region` |
+| `ec2_instance_stop` | Stop an instance | `instance_id` (required), `region` |
+| `s3_list` | The buckets, or a bucket's objects under a prefix | `bucket` (omit to list buckets), `prefix`, `limit` |
+| `s3_upload` | Upload a workspace file | `bucket`, `file` (required), `key` (defaults to the file name) |
+| `s3_download` | Save an object into the workspace and get a file reference | `bucket`, `key` (required) |
+| `s3_delete` | Delete one object | `bucket`, `key` (required) |
+| `call` | Any other AWS API operation | `service`, `api_operation` (required), `request`, `region` |
+| `list_operations` | Discover services, or one service's operations and parameters | `service` (optional), `search`, `limit` |
+
+`region` overrides the default region saved with the credential for one
+call. EC2 instances are regional: list them in the region you mean.
+
+### Response
+
+```json
+{
+ "operation": "ec2_instances_list",
+ "region": "us-east-1",
+ "result": [
+ { "InstanceId": "i-0abc123", "Name": "web-1", "State": "running", "InstanceType": "t3.micro", "PublicIpAddress": "203.0.113.10" }
+ ],
+ "count": 1,
+ "truncated": false
+}
+```
+
+`truncated: true` means there were more items than `limit`. On failure the
+tool raises an error carrying AWS's own error code and message: surface it
+verbatim, because it names the exact permission, parameter or resource.
+
+## Typical flows
+
+Orient first when the account or region is unknown:
+
+```json
+{ "operation": "whoami" }
+{ "operation": "ec2_instances_list", "instance_state": "running" }
+{ "operation": "ec2_instance_stop", "instance_id": "i-0abc123" }
+```
+
+S3. Local files are workspace paths; a download returns a file reference
+under `file` that other nodes and tools can use:
+
+```json
+{ "operation": "s3_list" }
+{ "operation": "s3_list", "bucket": "my-bucket", "prefix": "reports/" }
+{ "operation": "s3_upload", "bucket": "my-bucket", "file": "reports/q3.pdf", "key": "reports/2026/q3.pdf" }
+{ "operation": "s3_download", "bucket": "my-bucket", "key": "reports/2026/q3.pdf" }
+```
+
+Uploads and downloads are limited to 25 MB per file.
+
+## The full AWS surface via call
+
+Discover, then call. `list_operations` needs no credentials and makes no
+request:
+
+```json
+{ "operation": "list_operations", "search": "lambda" }
+{ "operation": "list_operations", "service": "lambda", "search": "function" }
+```
+
+Each operation lists its `required` and accepted `params`. Then call it
+with the boto3 method name and the API parameters in AWS's own PascalCase:
+
+```json
+{ "operation": "call", "service": "ec2", "api_operation": "describe_vpcs" }
+{ "operation": "call", "service": "ec2", "api_operation": "describe_instances", "request": { "Filters": [{ "Name": "tag:Name", "Values": ["web-*"] }] } }
+{ "operation": "call", "service": "lambda", "api_operation": "list_functions" }
+{ "operation": "call", "service": "lambda", "api_operation": "invoke", "request": { "FunctionName": "my-fn", "Payload": "{\"ping\": true}" } }
+{ "operation": "call", "service": "iam", "api_operation": "list_roles", "request": { "MaxItems": 20 } }
+{ "operation": "call", "service": "cloudwatch", "api_operation": "describe_alarms", "request": { "StateValue": "ALARM" } }
+```
+
+Notes for `call`:
+
+- `api_operation` accepts `describe_vpcs` or `DescribeVpcs`; an unknown
+ name fails before any request, with the closest names.
+- `request` is checked against the API model before sending; a wrong
+ parameter name fails with AWS's own validation message.
+- One page per call. A truncated answer carries `NextToken` (or the
+ service's own marker); pass it back in `request` for the next page.
+- A streaming response (Lambda `Payload`) comes back inline as text up
+ to 1 MB; use `s3_download` for S3 objects.
+
+## Authentication
+
+The tool uses the IAM access key saved in **Credentials -> AWS** (Access
+Key ID, Secret Access Key, optional default region). AWS credentials
+configured elsewhere on the server are never used.
+
+If a call fails with `InvalidClientTokenId` or `SignatureDoesNotMatch`,
+the saved key is wrong or deleted: point the user at Credentials -> AWS.
+If it fails with `AccessDenied` / `UnauthorizedOperation`, the IAM
+identity lacks that permission: name the action from the message. Never
+ask the user to paste keys in chat.
+
+## Best practices
+
+1. **Run `whoami` first** when unsure which account or region you are in.
+2. **Confirm destructive operations** (instance stop, `s3_delete`,
+ terminate / delete calls via `call`) with the user unless they asked
+ explicitly.
+3. **Prefer filters over long listings**: `instance_state`, `prefix`, or
+ `Filters` in `request`.
+4. **Surface AWS error messages verbatim**; they name the exact fix.
+5. **Costs are real**: starting instances and creating resources bill the
+ user's AWS account; mention it when the intent is exploratory.
diff --git a/server/tests/fixtures/tool_names_snapshot.json b/server/tests/fixtures/tool_names_snapshot.json
index 8ecc924b..ee0b80eb 100644
--- a/server/tests/fixtures/tool_names_snapshot.json
+++ b/server/tests/fixtures/tool_names_snapshot.json
@@ -73,6 +73,7 @@
"githubAction": "github",
"vercelAction": "vercel",
"gcloudAction": "gcloud",
+ "awsAction": "aws_action",
"typescriptExecutor": "typescript_code",
"apifyActor": "apify_actor",
"tikhubAction": "tikhub_action",
diff --git a/server/tests/nodes/test_aws.py b/server/tests/nodes/test_aws.py
new file mode 100644
index 00000000..27048146
--- /dev/null
+++ b/server/tests/nodes/test_aws.py
@@ -0,0 +1,684 @@
+"""Contract tests for the AWS node (``awsAction``).
+
+The node calls AWS through the official boto3 SDK; every SDK touch lives in
+``nodes/aws/_sdk.py``. These tests replace its client factory with real
+botocore clients wrapped in ``botocore.stub.Stubber`` (the SDK's own test
+double): requests are still validated against the real API models, and
+nothing touches the network.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+import io
+import json
+import re
+import subprocess
+import sys
+from pathlib import Path
+from typing import get_args
+
+import botocore.session
+import pytest
+from botocore.response import StreamingBody
+from botocore.stub import Stubber
+
+from tests.nodes._mocks import patched_container
+
+pytestmark = pytest.mark.node_contract
+
+import nodes.aws as aws_pkg # noqa: E402
+from nodes.aws import _sdk, aws_action # noqa: E402
+from nodes.aws._credentials import AwsCredential # noqa: E402
+from services.node_registry import get_node_class # noqa: E402
+from services.plugin.base import NodeUserError # noqa: E402
+from services.plugin.credential import CREDENTIAL_REGISTRY # noqa: E402
+from services.ws_handler_registry import get_option_loader # noqa: E402
+
+PLUGIN_DIR = Path(aws_pkg.__file__).parent
+SERVER_DIR = PLUGIN_DIR.parents[1]
+SKILL_MD = SERVER_DIR / "skills" / "aws" / "aws-skill" / "SKILL.md"
+
+KEYS = {"aws": "secret", "aws_access_key_id": "AKIDEXAMPLE", "aws_region": "eu-west-1"}
+IDENTITY = {"UserId": "AIDAEXAMPLE", "Account": "123456789012", "Arn": "arn:aws:iam::123456789012:user/ops"}
+LAUNCHED = dt.datetime(2026, 10, 9, 12, 0, tzinfo=dt.timezone.utc)
+
+
+class StubbedClients:
+ """Stands in for ``_sdk._client``: one stubbed client per service + region."""
+
+ def __init__(self) -> None:
+ self.stubbers: dict = {}
+ self.calls: list = []
+
+ def stub(self, service: str, region: str = "eu-west-1") -> Stubber:
+ if (service, region) not in self.stubbers:
+ client = botocore.session.get_session().create_client(
+ service, region_name=region, aws_access_key_id="x", aws_secret_access_key="y"
+ )
+ stubber = Stubber(client)
+ stubber.activate()
+ self.stubbers[(service, region)] = stubber
+ return self.stubbers[(service, region)]
+
+ def client(self, session, service: str, region: str):
+ self.calls.append((service, region))
+ return self.stub(service, region).client
+
+
+def clients(monkeypatch):
+ stubs = StubbedClients()
+ monkeypatch.setattr(_sdk, "_client", stubs.client)
+ yield stubs
+ for stubber in stubs.stubbers.values():
+ stubber.assert_no_pending_responses()
+
+
+async def _execute(harness, params, *, keys=KEYS, **kwargs):
+ with patched_container(auth_api_keys=keys):
+ return await harness.execute("awsAction", params, **kwargs)
+
+
+def _instance(instance_id: str, name: str, state: str = "running") -> dict:
+ return {
+ "InstanceId": instance_id,
+ "InstanceType": "t3.micro",
+ "State": {"Code": 16, "Name": state},
+ "Tags": [{"Key": "Name", "Value": name}],
+ "PublicIpAddress": "203.0.113.10",
+ "PrivateIpAddress": "172.31.0.10",
+ "Placement": {"AvailabilityZone": "eu-west-1a"},
+ "LaunchTime": LAUNCHED,
+ "ImageId": "ami-0abc",
+ "KeyName": "ops",
+ }
+
+
+# ============================================================================
+# Registration
+# ============================================================================
+
+
+class TestRegistration:
+ def test_class_attributes(self):
+ cls = get_node_class("awsAction")
+ assert cls is not None, "awsAction is not registered"
+ assert cls.tool_name == "aws_action"
+ assert tuple(cls.group) == ("deployment", "tool")
+ assert cls.usable_as_tool is True
+ assert AwsCredential in tuple(cls.credentials)
+ assert cls.annotations["destructive"] is True
+
+ def test_both_canvas_handles_stay_visible(self):
+ cls = get_node_class("awsAction")
+ assert cls.hide_input_handle is False
+ assert cls.hide_output_handle is False
+ assert {h["name"] for h in cls.handles} == {"input-main", "output-main"}
+
+ def test_option_loaders_and_credential_registered(self):
+ assert get_option_loader("awsServices") is not None
+ assert get_option_loader("awsOperations") is not None
+ assert CREDENTIAL_REGISTRY["aws"] is AwsCredential
+
+ def test_tool_schema_is_flat(self):
+ from services.plugin.tool import inline_schema_refs
+
+ cls = get_node_class("awsAction")
+ schema = inline_schema_refs(cls.Params.model_json_schema())
+ dumped = json.dumps(schema)
+ assert "$defs" not in dumped
+ assert '"$ref"' not in dumped
+
+ def test_operations_match_the_literal(self):
+ cls = get_node_class("awsAction")
+ declared = set(get_args(cls.Params.model_fields["operation"].annotation))
+ assert declared == set(aws_action._OPERATIONS)
+ assert cls.Params().operation == "whoami"
+
+ def test_reserved_field_names_absent(self):
+ # ParameterRenderer keys magic on these literal names.
+ cls = get_node_class("awsAction")
+ assert not {"model", "api_key", "parameters", "action", "service_id", "session_id"} & set(cls.Params.model_fields)
+
+
+# ============================================================================
+# Identity + credentials at run time
+# ============================================================================
+
+
+class TestWhoami:
+ async def test_uses_the_default_region_from_the_credential(self, harness, clients):
+ clients.stub("sts").add_response("get_caller_identity", dict(IDENTITY), {})
+
+ result = await _execute(harness, {"operation": "whoami"})
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["operation"] == "whoami"
+ assert payload["region"] == "eu-west-1"
+ assert payload["result"] == IDENTITY
+ assert clients.calls == [("sts", "eu-west-1")]
+
+ async def test_region_parameter_overrides_the_default(self, harness, clients):
+ clients.stub("sts", "us-west-2").add_response("get_caller_identity", dict(IDENTITY), {})
+
+ result = await _execute(harness, {"operation": "whoami", "region": "us-west-2"})
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["region"] == "us-west-2"
+ assert clients.calls == [("sts", "us-west-2")]
+
+ async def test_without_a_saved_region_uses_us_east_1(self, harness, clients):
+ clients.stub("sts", "us-east-1").add_response("get_caller_identity", dict(IDENTITY), {})
+ keys = {k: v for k, v in KEYS.items() if k != "aws_region"}
+
+ result = await _execute(harness, {"operation": "whoami"}, keys=keys)
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["region"] == "us-east-1"
+
+ @pytest.mark.parametrize("keys", [{}, {"aws": "secret"}])
+ async def test_missing_key_parts_point_at_the_modal(self, harness, clients, keys):
+ result = await _execute(harness, {"operation": "whoami"}, keys=keys)
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "PermissionDeniedError"
+ assert clients.calls == []
+
+ async def test_aws_errors_carry_code_and_hint(self, harness, clients):
+ clients.stub("sts").add_client_error(
+ "get_caller_identity",
+ service_error_code="InvalidClientTokenId",
+ service_message="The security token included in the request is invalid.",
+ http_status_code=403,
+ )
+
+ result = await _execute(harness, {"operation": "whoami"})
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "NodeUserError"
+ assert "InvalidClientTokenId" in result["error"]
+ assert "Credentials -> AWS" in result["error"]
+
+
+# ============================================================================
+# EC2
+# ============================================================================
+
+
+class TestEc2:
+ async def test_list_returns_one_row_per_instance(self, harness, clients):
+ clients.stub("ec2").add_response(
+ "describe_instances",
+ {"Reservations": [{"Instances": [_instance("i-1", "web-1"), _instance("i-2", "web-2", "stopped")]}]},
+ {},
+ )
+
+ result = await _execute(harness, {"operation": "ec2_instances_list"})
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["count"] == 2
+ assert payload["truncated"] is False
+ assert payload["result"][0] == {
+ "InstanceId": "i-1",
+ "Name": "web-1",
+ "State": "running",
+ "InstanceType": "t3.micro",
+ "PublicIpAddress": "203.0.113.10",
+ "PrivateIpAddress": "172.31.0.10",
+ "AvailabilityZone": "eu-west-1a",
+ "LaunchTime": LAUNCHED.isoformat(),
+ "ImageId": "ami-0abc",
+ "KeyName": "ops",
+ }
+
+ async def test_state_filter_is_sent(self, harness, clients):
+ clients.stub("ec2").add_response(
+ "describe_instances",
+ {"Reservations": []},
+ {"Filters": [{"Name": "instance-state-name", "Values": ["running"]}]},
+ )
+
+ result = await _execute(harness, {"operation": "ec2_instances_list", "instance_state": "running"})
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["result"] == []
+ assert result["result"]["count"] == 0
+
+ async def test_limit_marks_truncation(self, harness, clients):
+ clients.stub("ec2").add_response(
+ "describe_instances",
+ {"Reservations": [{"Instances": [_instance("i-1", "a"), _instance("i-2", "b")]}]},
+ {},
+ )
+
+ result = await _execute(harness, {"operation": "ec2_instances_list", "limit": 1})
+
+ assert result["result"]["count"] == 1
+ assert result["result"]["truncated"] is True
+
+ async def test_describe_returns_the_full_instance(self, harness, clients):
+ clients.stub("ec2").add_response(
+ "describe_instances",
+ {"Reservations": [{"Instances": [_instance("i-1", "web-1")]}]},
+ {"InstanceIds": ["i-1"]},
+ )
+
+ result = await _execute(harness, {"operation": "ec2_instance_describe", "instance_id": "i-1"})
+
+ harness.assert_envelope(result, success=True)
+ instance = result["result"]["result"]
+ assert instance["InstanceId"] == "i-1"
+ assert instance["Tags"] == [{"Key": "Name", "Value": "web-1"}]
+ assert instance["LaunchTime"] == LAUNCHED.isoformat()
+
+ @pytest.mark.parametrize(
+ ("operation", "method", "key"),
+ [
+ ("ec2_instance_start", "start_instances", "StartingInstances"),
+ ("ec2_instance_stop", "stop_instances", "StoppingInstances"),
+ ],
+ )
+ async def test_start_and_stop(self, harness, clients, operation, method, key):
+ response = {
+ key: [{"InstanceId": "i-1", "CurrentState": {"Code": 0, "Name": "pending"}, "PreviousState": {"Code": 80, "Name": "stopped"}}]
+ }
+ clients.stub("ec2").add_response(method, response, {"InstanceIds": ["i-1"]})
+
+ result = await _execute(harness, {"operation": operation, "instance_id": "i-1"})
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["result"] == response
+
+ @pytest.mark.parametrize("operation", ["ec2_instance_describe", "ec2_instance_start", "ec2_instance_stop"])
+ async def test_instance_id_is_required_before_any_call(self, harness, clients, operation):
+ result = await _execute(harness, {"operation": operation})
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "NodeUserError"
+ assert "instance_id" in result["error"]
+ assert clients.calls == []
+
+ async def test_permission_errors_name_the_cause(self, harness, clients):
+ clients.stub("ec2").add_client_error(
+ "start_instances",
+ service_error_code="UnauthorizedOperation",
+ service_message="You are not authorized to perform this operation.",
+ http_status_code=403,
+ )
+
+ result = await _execute(harness, {"operation": "ec2_instance_start", "instance_id": "i-1"})
+
+ assert result["error_type"] == "NodeUserError"
+ assert "UnauthorizedOperation" in result["error"]
+ assert "lacks this permission" in result["error"]
+
+
+# ============================================================================
+# S3
+# ============================================================================
+
+
+class TestS3:
+ async def test_list_buckets_without_a_bucket(self, harness, clients):
+ clients.stub("s3").add_response(
+ "list_buckets", {"Buckets": [{"Name": "alpha", "CreationDate": LAUNCHED}], "Owner": {"ID": "abc"}}, {}
+ )
+
+ result = await _execute(harness, {"operation": "s3_list"})
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["result"] == [{"Name": "alpha", "CreationDate": LAUNCHED.isoformat()}]
+
+ async def test_list_objects_under_a_prefix(self, harness, clients):
+ clients.stub("s3").add_response(
+ "list_objects_v2",
+ {
+ "IsTruncated": False,
+ "Contents": [{"Key": "reports/q3.pdf", "Size": 12, "LastModified": LAUNCHED, "StorageClass": "STANDARD"}],
+ },
+ {"Bucket": "alpha", "Prefix": "reports/"},
+ )
+
+ result = await _execute(harness, {"operation": "s3_list", "bucket": "alpha", "prefix": "reports/"})
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["result"] == [
+ {"Key": "reports/q3.pdf", "Size": 12, "LastModified": LAUNCHED.isoformat(), "StorageClass": "STANDARD"}
+ ]
+
+ async def test_upload_reads_a_workspace_file(self, harness, clients, tmp_path):
+ (tmp_path / "reports").mkdir()
+ (tmp_path / "reports" / "q3.txt").write_bytes(b"hello")
+ clients.stub("s3").add_response(
+ "put_object",
+ {"ETag": '"etag"'},
+ {"Bucket": "alpha", "Key": "q3.txt", "Body": b"hello", "ContentType": "text/plain"},
+ )
+
+ result = await _execute(
+ harness,
+ {"operation": "s3_upload", "bucket": "alpha", "file": "reports/q3.txt"},
+ context=harness.build_context(workspace_dir=str(tmp_path)),
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["result"] == {"Bucket": "alpha", "Key": "q3.txt", "Size": 5, "ETag": '"etag"'}
+
+ async def test_upload_refuses_paths_outside_the_workspace(self, harness, clients, tmp_path):
+ workspace = tmp_path / "ws"
+ workspace.mkdir()
+ (tmp_path / "secret.txt").write_text("do not upload", encoding="utf-8")
+
+ result = await _execute(
+ harness,
+ {"operation": "s3_upload", "bucket": "alpha", "file": "../secret.txt"},
+ context=harness.build_context(workspace_dir=str(workspace)),
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "NodeUserError"
+ assert "outside" in result["error"]
+ assert clients.calls == []
+
+ async def test_download_returns_a_file_reference(self, harness, clients, tmp_path):
+ clients.stub("s3").add_response(
+ "get_object",
+ {"Body": StreamingBody(io.BytesIO(b"hello"), 5), "ContentLength": 5, "ContentType": "text/plain"},
+ {"Bucket": "alpha", "Key": "reports/q3.txt"},
+ )
+
+ result = await _execute(
+ harness,
+ {"operation": "s3_download", "bucket": "alpha", "key": "reports/q3.txt"},
+ context=harness.build_context(workspace_dir=str(tmp_path)),
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["result"] == {"Bucket": "alpha", "Key": "reports/q3.txt", "Size": 5, "ContentType": "text/plain"}
+ ref = payload["file"]
+ assert ref["kind"] == "file"
+ assert ref["path"].startswith("media/")
+ assert (tmp_path / ref["path"]).read_bytes() == b"hello"
+
+ async def test_download_refuses_oversize_objects(self, harness, clients, tmp_path, monkeypatch):
+ monkeypatch.setattr(aws_action, "MEDIA_MAX_READ_BYTES", 4)
+ clients.stub("s3").add_response(
+ "get_object",
+ {"Body": StreamingBody(io.BytesIO(b"hello"), 5), "ContentLength": 5},
+ {"Bucket": "alpha", "Key": "big.bin"},
+ )
+
+ result = await _execute(
+ harness,
+ {"operation": "s3_download", "bucket": "alpha", "key": "big.bin"},
+ context=harness.build_context(workspace_dir=str(tmp_path)),
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert "limit" in result["error"]
+ assert not (tmp_path / "media").exists()
+
+ async def test_delete(self, harness, clients):
+ clients.stub("s3").add_response("delete_object", {}, {"Bucket": "alpha", "Key": "old.txt"})
+
+ result = await _execute(harness, {"operation": "s3_delete", "bucket": "alpha", "key": "old.txt"})
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["result"] == {"Bucket": "alpha", "Key": "old.txt"}
+
+ @pytest.mark.parametrize(
+ ("params", "missing"),
+ [
+ ({"operation": "s3_upload", "file": "a.txt"}, "bucket"),
+ ({"operation": "s3_upload", "bucket": "alpha"}, "file"),
+ ({"operation": "s3_download", "bucket": "alpha"}, "key"),
+ ({"operation": "s3_delete", "key": "a.txt"}, "bucket"),
+ ],
+ )
+ async def test_required_fields(self, harness, clients, params, missing):
+ result = await _execute(harness, params)
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "NodeUserError"
+ assert missing in result["error"]
+ assert clients.calls == []
+
+
+# ============================================================================
+# call + list_operations
+# ============================================================================
+
+
+class TestCall:
+ async def test_api_name_spelling_resolves_to_the_boto3_method(self, harness, clients):
+ clients.stub("ec2").add_response(
+ "describe_vpcs",
+ {"Vpcs": [{"VpcId": "vpc-1", "IsDefault": True}]},
+ {"Filters": [{"Name": "is-default", "Values": ["true"]}]},
+ )
+
+ result = await _execute(
+ harness,
+ {
+ "operation": "call",
+ "service": "ec2",
+ "api_operation": "DescribeVpcs",
+ "request": {"Filters": [{"Name": "is-default", "Values": ["true"]}]},
+ },
+ )
+
+ harness.assert_envelope(result, success=True)
+ payload = result["result"]
+ assert payload["service"] == "ec2"
+ assert payload["api_operation"] == "describe_vpcs"
+ assert payload["result"] == {"Vpcs": [{"VpcId": "vpc-1", "IsDefault": True}]}
+
+ async def test_request_as_json_string(self, harness, clients):
+ clients.stub("ec2").add_response("describe_vpcs", {"Vpcs": []}, {"VpcIds": ["vpc-1"]})
+
+ result = await _execute(
+ harness,
+ {"operation": "call", "service": "ec2", "api_operation": "describe_vpcs", "request": '{"VpcIds": ["vpc-1"]}'},
+ )
+
+ harness.assert_envelope(result, success=True)
+
+ async def test_blank_request_from_the_panel(self, harness, clients):
+ clients.stub("sts").add_response("get_caller_identity", dict(IDENTITY), {})
+
+ result = await _execute(
+ harness, {"operation": "call", "service": "sts", "api_operation": "get_caller_identity", "request": ""}
+ )
+
+ harness.assert_envelope(result, success=True)
+
+ async def test_unknown_operation_fails_before_credentials(self, harness, clients):
+ result = await _execute(
+ harness, {"operation": "call", "service": "ec2", "api_operation": "describe_vpc"}, keys={}
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "NodeUserError"
+ assert "describe_vpcs" in result["error"]
+ assert clients.calls == []
+
+ async def test_unknown_service_suggests_close_names(self, harness, clients):
+ result = await _execute(harness, {"operation": "call", "service": "ecs2", "api_operation": "x"})
+
+ assert result["error_type"] == "NodeUserError"
+ assert "ec2" in result["error"]
+
+ async def test_wrong_parameter_is_rejected_before_sending(self, harness, monkeypatch):
+ # A real, unstubbed client: botocore validates the parameters before
+ # building any request (Stubber would check its queue first).
+ client = botocore.session.get_session().create_client(
+ "ec2", region_name="eu-west-1", aws_access_key_id="x", aws_secret_access_key="y"
+ )
+ monkeypatch.setattr(_sdk, "_client", lambda session, service, region: client)
+
+ result = await _execute(
+ harness,
+ {"operation": "call", "service": "ec2", "api_operation": "describe_vpcs", "request": {"Bogus": 1}},
+ )
+
+ harness.assert_envelope(result, success=False)
+ assert result["error_type"] == "NodeUserError"
+ assert "Bogus" in result["error"]
+
+ async def test_streaming_payload_is_read_inline(self, harness, clients):
+ clients.stub("lambda").add_response(
+ "invoke",
+ {"StatusCode": 200, "Payload": StreamingBody(io.BytesIO(b'{"ok": true}'), 12)},
+ {"FunctionName": "fn"},
+ )
+
+ result = await _execute(
+ harness, {"operation": "call", "service": "lambda", "api_operation": "invoke", "request": {"FunctionName": "fn"}}
+ )
+
+ harness.assert_envelope(result, success=True)
+ assert result["result"]["result"] == {"StatusCode": 200, "Payload": '{"ok": true}'}
+
+
+class TestListOperations:
+ async def test_lists_services_without_credentials(self, harness):
+ result = await _execute(harness, {"operation": "list_operations", "search": "ec2"}, keys={})
+
+ harness.assert_envelope(result, success=True)
+ assert "ec2" in result["result"]["result"]
+
+ async def test_lists_one_services_operations(self, harness):
+ result = await _execute(harness, {"operation": "list_operations", "service": "sts"}, keys={})
+
+ harness.assert_envelope(result, success=True)
+ rows = {row["operation"]: row for row in result["result"]["result"]}
+ assert rows["get_caller_identity"]["api_name"] == "GetCallerIdentity"
+ assert rows["assume_role"]["required"] == ["RoleArn", "RoleSessionName"]
+ assert result["result"]["total"] == len(rows)
+
+ async def test_operation_dropdown_loader(self):
+ options = await get_option_loader("awsOperations")({"service": "sts"})
+ assert {"value": "get_caller_identity", "label": "get_caller_identity"}.items() <= next(
+ o for o in options if o["value"] == "get_caller_identity"
+ ).items()
+ assert await get_option_loader("awsOperations")({}) == []
+
+
+# ============================================================================
+# Shaping
+# ============================================================================
+
+
+class TestToPlain:
+ def test_timestamps_and_blobs_print_like_the_aws_cli(self):
+ assert _sdk.to_plain({"T": LAUNCHED, "B": b"\x00\x01", "L": [1]}) == {
+ "T": LAUNCHED.isoformat(),
+ "B": "AAE=",
+ "L": [1],
+ }
+
+ def test_large_streaming_bodies_are_refused(self, monkeypatch):
+ monkeypatch.setattr(_sdk, "_MAX_INLINE_BODY_BYTES", 4)
+ with pytest.raises(NodeUserError, match="s3_download"):
+ _sdk.to_plain({"Payload": StreamingBody(io.BytesIO(b"hello"), 5)})
+
+
+# ============================================================================
+# Credential
+# ============================================================================
+
+
+class TestCredentialProbe:
+ async def test_valid_key_pair(self, clients):
+ clients.stub("sts").add_response("get_caller_identity", dict(IDENTITY), {})
+
+ with patched_container(auth_api_keys={"aws_access_key_id": "AKIDEXAMPLE", "aws_region": "eu-west-1"}):
+ result = await AwsCredential._probe("secret")
+
+ assert result.valid is True
+ assert IDENTITY["Arn"] in result.message
+ assert result.extra == {"arn": IDENTITY["Arn"], "account": IDENTITY["Account"]}
+
+ async def test_missing_access_key_id_explains_the_order(self, clients):
+ with patched_container(auth_api_keys={}):
+ result = await AwsCredential._probe("secret")
+
+ assert result.valid is False
+ assert "Access Key ID" in result.message
+ assert clients.calls == []
+
+ async def test_rejected_key_pair(self, clients):
+ clients.stub("sts", "us-east-1").add_client_error(
+ "get_caller_identity", service_error_code="SignatureDoesNotMatch", http_status_code=403
+ )
+
+ with patched_container(auth_api_keys={"aws_access_key_id": "AKIDEXAMPLE"}):
+ result = await AwsCredential._probe("wrong")
+
+ assert result.valid is False
+ assert "SignatureDoesNotMatch" in result.message
+
+
+class TestNoEagerSdkImport:
+ """Importing the plugin must never import boto3 (clean interpreter: the
+ pytest process already loaded the SDK above)."""
+
+ def _probe(self, code: str) -> str:
+ result = subprocess.run([sys.executable, "-c", code], cwd=SERVER_DIR, capture_output=True, text=True, timeout=180)
+ assert result.returncode == 0, f"probe subprocess failed (rc={result.returncode}):\n{result.stderr}"
+ return result.stdout
+
+ def test_plugin_registers_without_the_sdk(self):
+ out = self._probe(
+ "import sys\n"
+ "sys.modules['boto3'] = None\n"
+ "import nodes.aws\n"
+ "from services.node_registry import get_node_class\n"
+ "print('REGISTERED=' + str(get_node_class('awsAction') is not None))\n"
+ )
+ assert "REGISTERED=True" in out
+
+ def test_plugin_import_does_not_load_the_sdk(self):
+ out = self._probe("import sys\nimport nodes.aws\nprint('LEAKED=' + str('boto3' in sys.modules))\n")
+ assert "LEAKED=False" in out
+
+
+# ============================================================================
+# Catalogue + assets
+# ============================================================================
+
+
+class TestCatalogueAndAssets:
+ def test_credential_providers_entry(self):
+ config = json.loads((SERVER_DIR / "config" / "credential_providers.json").read_text(encoding="utf-8"))
+ entry = config["providers"]["aws"]
+ assert entry["kind"] == "apiKey"
+ assert entry["category"] == "deployment"
+ assert entry["icon_ref"] == "/api/schemas/credentials/aws/icon"
+ assert [f["key"] for f in entry["fields"]] == ["apiKey", "aws_access_key_id", "aws_region"]
+ assert entry["fields"][0]["secret"] is True
+ assert tuple(AwsCredential.extra_fields) == ("aws_access_key_id", "aws_region")
+
+ def test_visuals_skill_binding(self):
+ visuals = json.loads((SERVER_DIR / "nodes" / "visuals.json").read_text(encoding="utf-8"))
+ assert visuals["awsAction"]["skill"] == "aws-skill"
+
+ def test_tool_name_snapshot(self):
+ snapshot = json.loads((SERVER_DIR / "tests" / "fixtures" / "tool_names_snapshot.json").read_text(encoding="utf-8"))
+ assert snapshot["awsAction"] == "aws_action"
+
+ def test_plugin_folder_assets(self):
+ meta = json.loads((PLUGIN_DIR / "meta.json").read_text(encoding="utf-8"))
+ assert re.fullmatch(r"#[0-9a-fA-F]{6}", meta["color"])
+ assert "<svg" in (PLUGIN_DIR / "icon.svg").read_text(encoding="utf-8")
+ assert AwsCredential.get_icon_path() == PLUGIN_DIR / "aws.svg"
+
+ def test_skill_binds_the_tool(self):
+ text = SKILL_MD.read_text(encoding="utf-8")
+ frontmatter = text.split("---", 2)[1]
+ assert "name: aws-skill" in frontmatter
+ assert '"aws_action"' in frontmatter
diff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.py
index 30c422c2..1452293f 100644
--- a/server/tests/test_plugin_self_containment.py
+++ b/server/tests/test_plugin_self_containment.py
@@ -58,6 +58,7 @@ from services import ws_handler_registry
# telegram and stripe are the pre-Wave-11.H references.
_MIGRATED_PLUGINS = (
"android",
+ "aws",
"browser",
"cloudflare",
"code",
diff --git a/server/uv.lock b/server/uv.lock
index b9e3c2fc..21d9af82 100644
--- a/server/uv.lock
+++ b/server/uv.lock
@@ -1920,6 +1920,7 @@ dependencies = [
{ name = "apify-client" },
{ name = "asyncpg" },
{ name = "bcrypt" },
+ { name = "boto3" },
{ name = "crawlee", extra = ["beautifulsoup"] },
{ name = "cryptography" },
{ name = "ddgs" },
@@ -2008,6 +2009,7 @@ requires-dist = [
{ name = "asyncpg", specifier = ">=0.30.0,<1" },
{ name = "bcrypt", specifier = ">=4.2.0" },
{ name = "beautifulsoup4", marker = "extra == 'docs'", specifier = ">=4.12.0" },
+ { name = "boto3", specifier = ">=1.34.0" },
{ name = "boto3", marker = "extra == 'aws'", specifier = ">=1.34.0" },
{ name = "crawlee", extras = ["beautifulsoup"], specifier = ">=1.4.0" },
{ name = "cryptography", specifier = ">=50.0.0" },