Metadata-Version: 2.5
Name: 3lc-compute-plugin-aws
Version: 0.1.2
Summary: AWS EC2 infrastructure plugin for the 3LC compute service: disposable GPU nodes.
License: Apache-2.0
Requires-Python: >=3.11
Requires-Dist: 3lc-compute-plugin-sdk<0.8.0,>=0.7.0.20261105090439
Requires-Dist: 3lc<4.0.0,>=3.5.0.dev149866
Provides-Extra: aws
Requires-Dist: boto3>=1.34; extra == 'aws'
Requires-Dist: httpx>=0.27; extra == 'aws'
Description-Content-Type: text/markdown

# 3lc-compute-plugin-aws

AWS infrastructure plugin for the 3LC compute service (`kind = "infrastructure"`). It creates two
kinds of EC2 instances for the Hub and tears them down:

- **GPU nodes** — disposable instances running the 3LC node agent; the host dispatches training
  jobs to them and terminates them when idle. The AMI is the latest Deep Learning Base GPU AMI
  (Ubuntu 22.04), resolved per region through AWS's public SSM parameter (`ami_id` overrides). A
  managed security group (`3lc-gpu-nodes`, tagged `3lc=node-security-group`; an older untagged one is
  tagged by the first identity allowed to) opens the agent port and the app ports the host asks
  for (one rule per contiguous range) to this controller's current egress IP only; each controller
  prunes only its own rules. The node's workers listen on loopback and are reached through the
  agent, so no worker port is opened.
- **Workspaces** — permanent CPU instances (Ubuntu 24.04) running a person's own Object Service
  and compute service under systemd. TLS is on by default: Caddy terminates TLS under
  `os.<ip>.sslip.io` and `compute.<ip>.sslip.io`, names derived from the instance's public IP, with
  Let's Encrypt certificates, and only ports 80 and 443 are open (`workspace_tls = false` keeps
  plain http on 5015 and 5020 for a local, http Hub). The Object Service is confined
  (`TLC_SERVICE_ALLOWED_URLS`) to object storage, which the instance role bounds, and its local project
  roots: no other local file and no `http(s)` URL (`workspace_confine_object_service = false` lifts it).
  When the launching host names a **deployment
  DNS zone** in the create request (`workspace.dns_zone_id` / `dns_zone_name`, a Route 53 zone of
  3LC's such as `deploy.dev.3lc.ai`), the deployment is named `<deployment>.<zone>` instead, behind an
  Elastic IP reserved in the account it runs in: its services answer on `os.<deployment>.<zone>` and
  `compute.<deployment>.<zone>`, the three A records (TTL 60 s) are written by the host's own AWS
  identity before the instance launches and removed, with the address, when it goes. `<deployment>`
  is the deployment's name as a DNS label (lower-case, runs of other characters become one hyphen,
  at most 63 characters, not a punycode label), first come, first served: a reserved label (`hub`,
  `www`, `api`, `compute`, `os`, environment and cloud names, …) and a name whose records already
  exist in the zone are refused with a sentence asking for another name. There is no owner prefix
  and no random suffix (see `hostnames.py` for the trade-off). Let's Encrypt allows 5 certificates
  per week for one exact set of names, so re-launching one deployment name more than five times in
  a week leaves the sixth without TLS until the week turns; pick a fresh name when iterating. The
  host can ask what a name would get before launching (`GET /infra/deployments/name-check`) and
  runs a periodic **sweep** of the zone (`POST /infra/deployments/sweep`, one pass per account it
  reaches): an Elastic IP tagged `3lc=workspace` whose instance is gone, and that no deployment the
  host tracks claims, loses its records and is released, records first; a dead deployment's leftover
  records go; a name whose address nothing in reach holds is only reported. Nothing is removed on
  first sight (a grace window, 10 minutes by default), and the apex, NS, SOA and names that are not a
  deployment's are never touched (`sweep.py` has the rules). A
  workspace started through a keyless
  Connection runs by that Connection's own deployment role (`<RoleName>-deployment`, made by its
  CloudFormation stack; the stack's control role reserves and releases the deployment's Elastic IP): its S3
  access is the stack's shared storage policy (the `ReadWriteBuckets` and `ReadBuckets` lists), it
  may run, stop and terminate only GPU nodes tagged for its Connection, with the stack's node role, change
  the rules of tagged node security groups only, read AWS's public Deep Learning AMI parameters only, and
  nothing is written to IAM to launch it. A stack whose roles lack the current template's
  `3lc:connection-template` tag was made by an earlier setup: the Connection check, workspaces and shared
  HTTPS access ask for the AWS account to be reconnected. Without a Connection it runs by
  `3lc-workspace-node`, a role the creator prepares,
  limited to its buckets and to launching and terminating 3LC-tagged GPU nodes; that role holds no
  IAM write permissions, and its GPU nodes launch with the same role.

**Contract.** `AwsPlugin` is an `InfrastructurePlugin` of the plugin SDK with four facets:
`StorageFacet` (S3 buckets), `CatalogFacet` (GPU instance types and workspace sizes),
`WorkspaceFacet` (the workspaces the account runs) and the legacy `LegacyOwnerCredentialsFacet`
(a visitor's own account, sign-in, role grant). The SDK mounts every `/infra/*` route from the
plugin's methods and lists the facets in `GET /infra/capabilities` (`facets`); the plugin writes
no route handler. `POST /infra/nodes` creates a GPU node, or a workspace for `flavor: "workspace"`
(answered with `services` and `managed_by`); `GET /infra/nodes/{id}?diagnostics=true` adds the
startup milestones read from the instance console, with `bootstrap_failed` left out when the
console could not be read, and its `detail` is then one sentence: the last boot stage reached (or
the stage that failed) and, when the kernel killed a process for running out of memory, which one
(the Object Service or the compute service by name) with the advice to choose a larger size; `DELETE /infra/nodes/{id}` and `POST /infra/nodes/{id}/terminate`
answer `{state: "terminated"}`.

**Settings.** One record, served by the SDK's settings layer as `GET/POST /settings`. It holds no
credential: regions, instance types, `iam_instance_profile`, pricing, workspace options and
`extra_env` (shown as `extra_env_keys`). `extra_env` is plain environment for the node and is not
for secrets: it is written into the node's user data. A `region` or `pricing` that is not one is
refused with a sentence (400). A settings file that does not parse answers 409 until it is fixed or
deleted. A `region` never saved is `AWS_DEFAULT_REGION` (when it names a region), else `us-east-1`;
an `iam_instance_profile` never saved is `TLC_AWS_NODE_INSTANCE_PROFILE`, else empty. A saved value
wins. A file saved by an older version that still holds `tlc_api_key`, `aws_access_key_id`,
`aws_secret_access_key` or `seed_provider_configs_for` loads as before; those keys are ignored and
the file is not rewritten on load.

**Credentials.** Every AWS call uses, in order: the credentials the request carries (a person's
access keys, a sign-in with AWS IAM Identity Center, or a role this host assumed — the SDK hands
them over through its legacy request context, never as a request field), the request's
Connection (a `KEYLESS` role assumed with this deployment's own identity, or `AMBIENT`: boto3's
default chain), then boto3's default chain (this deployment's instance role, AWS profile or
environment). When none of these has a credential, `GET /infra/capabilities` answers `ready: false`
with the reason in `not_ready_reason`, and every route that needs AWS answers with the same sentence:
a 409, or the `error` of the GPU and CPU catalogs and the failed check of the preflight (the role
setup words it as it cannot prepare the role). A default chain that raises (an expired IAM Identity
Center sign-in, a broken profile) gets its own sentence naming the error. The IAM Identity Center
sign-in still works. Request credentials are used for that call
only: nothing is written to a node or a workspace. A request that carries
a `credentials` object without a key pair or a role is refused (400), never run on this compute's
own account, and a GPU node create refuses request credentials altogether: GPU nodes run in this
compute's account.

**Connections and the launcher.** A `KEYLESS` Connection is a CloudFormation stack in the
customer's account whose control role trusts **one principal** with the Connection's external id:
`TrustedPrincipal`, the identity of the host the Connection was set up from, never a whole
account. An assumed-role session (an instance profile, IRSA, an IAM Identity Center role) is named
by its role, an IAM user or role by its own ARN. For a hosted Hub that launches deployments into
customers' accounts this is the hosted launcher's principal; for a self-hosted compute it is that
host's own identity. `POST /infra/connection/onboarding` answers it as `principal`, and the Config
Service may store it on the Connection as `trusted_principal`. When it is stored, the `KEYLESS`
resolver compares it with this process's own identity before STS is asked: a foreign principal is
refused with a sentence naming both identities, saying to create the Connection from this
deployment or add this identity to the role's trust policy. A deployment launched through a
Connection never assumes the control role: it acts as the stack's deployment role (below), on its
own Connection only, and a request naming another stack's Connection is refused the same way. The
deployment DNS zone is the launcher's, so its records are written by the launcher's own AWS
identity, not through the Connection.

**What a node receives.** No AWS keys, no `TLC_API_KEY` and no plugin settings file.
`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN`, `AWS_SECURITY_TOKEN` and
`TLC_API_KEY` are dropped from the environment of every GPU node and workspace, including the one the
host passes on a create (the names dropped are logged, never the values); every other variable is
forwarded. A GPU node's own 3LC identity is the node credential the host sends in the create
request's `env` as `TLC_NODE_CREDENTIAL` (issued by the Config Service with the person's
`node.create` grant): it rides the user data under the node agent's own name, which the agent alone
reads, and the agent hands it to its workers so they reach 3LC as the person who created the node. A
workspace launched through a Connection gets its two service keys by redeeming the request's
single-use `bootstrap_token` at first boot. A GPU node reaches S3 and terminates itself by `iam_instance_profile`, and is tagged
`3lc-connection=<RoleName>` when launched through a Connection or by one of its deployments. A workspace
runs its services by an instance role: on a keyless Connection, the Connection's deployment role (its
`deployment_instance_profile`, confirmed with IAM when the Connection does not record it); otherwise its own
(`3lc-workspace-node`, or `workspace_iam_instance_profile`), refused when that role cannot be prepared. A
keyless Connection that names no node instance profile, or whose stack an earlier setup made, is refused (400)
before anything launches, asking for the AWS account to be reconnected. The workspace's
project root and data buckets must lie within the Connection's declared write locations; the check
(`provider.check_connection_scopes`) uses Config Service's installed configuration. Project roots
need write access; dataset locations need read access. Account and bucket-pattern scopes require
bucket ownership evidence before provisioning. Pending edits and metadata location lists do not
grant access. The stack carries the declaration as three comma-separated parameters: `ReadBuckets`
(read only), `WriteBuckets` (read/write without delete), and `ReadWriteBuckets` (read/write/delete).
Each entry is one rule (`bucket`, `bucket/folder`, `prefix*` or `*`), compiled into one
managed storage policy shared by the control, deployment and (with `NodeStorage`) node roles. A folder
entry limits objects to the folder; listing covers the bucket's object names. Patterns and `*` reach only
buckets the connected account owns; an exact bucket name may be another account's. A Connection accepts
at most 50 rules; the generated policy must also fit IAM's 6,144-character managed-policy limit, so long
names or prefixes can reach the policy limit sooner.

**Reviewing access changes.** Save the desired Connection access in the Hub, then prepare a change set
for the Connection's own stack. The control role can prepare and describe it, but cannot execute it.
An AWS administrator reviews the template diff as well as the resource list and executes the change
set in CloudFormation. The Connection template is version 2. Version 1 was never released and has no
compatibility guarantee: update or recreate any test stacks made with it before using this build.
For an in-place console update, use the current template, retain the existing parameter values, and
leave the new `WriteBuckets` list empty unless adding read/write access without delete.

**Sign-in and role trust.** `POST /infra/login` starts the IAM Identity Center device flow: a code
and a link, the person approves in AWS and picks an account and role; the pending sign-in is bound
to the person who started it and is spent once credentials are issued. `GET /infra/role-setup`
returns a CloudFormation quick-create link for administrators: it creates a `3lc-workspace-creator`
role trusting this host's account with an external id bound to the person, and the
`3lc-workspace-boundary` permissions boundary that caps every role 3LC creates in that account.
The template is generated from the same policy definitions as the node role.

**CloudFormation templates are release artifacts.** Both templates (the workspace creator's and a
Connection's) are static, so every quick-create link reads them from the public bucket that serves
the Hub catalog, under a content-addressed key such as
`hub/templates/aws/connection-<sha256[:16]>.json`; the plugin computes the URL from its own template
text and uploads nothing at run time. `python scripts/publish_templates.py --out <dir>` renders the
objects a release must publish (keep every earlier object: old links point at them), and
`--check` verifies the public URLs serve the same bytes. Set `TLC_AWS_TEMPLATE_BASE_URL` to read
them from another bucket or mirror. `POST /infra/connection/onboarding` also answers a
ready-to-paste `aws cloudformation create-stack` command (`cli_command`) for the same stack.

**Storage.** S3 buckets: list the account's buckets with their region, create a private bucket
with browser-upload CORS, presign uploads and downloads, browse a prefix, bundle a folder into one
zip for download, copy and move between folders and buckets (server-side, as a background job),
delete files and folders, and discover the requester's own buckets with the credentials in the
request. The transfer and bundle routes are served by the SDK over the plugin's registries.
The host forwards these routes as `/api/infra/storage/aws/...`:

| Route | What it does |
| --- | --- |
| `GET /infra/storage` | The buckets the credentials can list, with region, by name |
| `POST /infra/storage` | Create a private bucket with browser-upload CORS (`{name, region?}`), tagged with the request's `owner` |
| `DELETE /infra/storage/{bucket}` | Delete an empty bucket; a bucket with objects is a 409 |
| `POST /infra/storage/discover` | The buckets in the requester's own account, with the credentials in the request |
| `GET /infra/storage/list?url=s3://bucket/prefix&next_token=` | One page of one level of a prefix: sub-folders and objects, at most 1000 entries. A longer folder answers `truncated: true` and a `next_token`; send it back as `next_token` for the next page |
| `POST /infra/storage/presign` | Presigned URLs for the browser. `mode: "upload"` (default): PUT URLs for `files: [{path, size, content_type}]`. `mode: "download"`: GET URLs, saved as attachments, for `files: [{path}]` under `url` → `{downloads: [{path, key, url, method, s3_url}], expires_s, refused}` |
| `POST /infra/storage/bundle` | Zip a folder in the background: `{url, name?}` → the bundle's status with `bundle_id`. The zip lands under `.3lc/downloads/` in the bucket with a 24-hour link; zips there older than a day are removed when a bundle starts |
| `GET /infra/storage/bundle/{bundle_id}` | Bundle progress: `state` (listing, running, uploading, done, failed, cancelled), `files_done`/`files_total`, `bytes_done`/`bytes_total`, `percent`, `download_url`, `error`; 404 six hours after it finished |
| `DELETE /infra/storage/bundle/{bundle_id}` | Stop a running bundle → `{cancelled}` |
| `POST /infra/storage/delete` | Delete files and folders under a prefix (`{url, paths, dry_run?}`; `dry_run` only counts) |
| `POST /infra/storage/transfer` | Copy or move items between folders and buckets (`{src_url, dst_url, items, mode?, rename_to?, dry_run?}`) |
| `GET`/`DELETE /infra/storage/transfer/{transfer_id}` | Transfer progress; stop a running transfer → `{cancelled}` |

**Pricing.** A GPU node is launched on-demand or as a spot instance: `pricing: "on_demand" | "spot"`
on `POST /infra/nodes`, the plugin setting `pricing` as the default when the request names none, and
`GET /infra/capabilities` lists `pricing: ["on_demand", "spot"]` so the host knows it may offer spot.
On-demand runs until it is stopped and is billed at the on-demand price. A spot instance is spare EC2
capacity billed at the current spot price, which moves with demand and never exceeds the on-demand
price; no maximum price is set. AWS can reclaim a spot instance with two minutes' notice: the request
is one-time with `InstanceInterruptionBehavior: terminate`, so a reclaimed node is terminated, the job
running on it fails, and it has to be started again; nothing is re-requested behind the host's back.
A spot launch that finds no capacity (`InsufficientInstanceCapacity`, `SpotMaxPriceTooLow`,
`MaxSpotInstanceCountExceeded`) fails with a sentence naming the type, the region and the code; the
options are on-demand, another type, or a later attempt. The instance table shows the current spot
price per type (the lowest availability zone, one `DescribeSpotPriceHistory` call per region, cached
five minutes); that needs `ec2:DescribeSpotPriceHistory`, which the node-management policy and the
CloudFormation template grant. Workspaces are always on-demand.

**Applied at launch.** IMDSv2 only (token required, hop limit 1), encrypted root volumes, `3lc`
tags on every instance. Request values (bucket names, regions, instance ids, role ARNs, environment
keys and values) are checked before they reach AWS; AWS error text shown to people has account
identifiers, request ids and endpoints removed (the plugin's `describe_error`, which the SDK applies
on every route and to the copy and bundle jobs' recorded errors).

Idle nodes terminate themselves through IMDSv2 + awscli after the `idle_ttl_s` the host sends on
each create (`0`: never), by their instance profile (a node without one cannot, and is left to the
host); the plugin has no idle setting of its own. The controller's idle teardown
and heartbeat handling are the other two layers.

## Interactive Hub guide

The UI registers eight AWS-specific tips through the plugin SDK's optional
`PLUGIN_API.guide` browser contract, version 1. These cover storage, node access,
hardware, pricing, advanced defaults, launching, and node lifecycle. A guide-enabled
Hub replaces its generic infrastructure tips with these instructions. Older hosts
without the hook continue to work unchanged; no compute-service API or dependency
upgrade is required just to register guide content.

Registration uses static text and targets only this fragment. It does not read
credentials, launch nodes, save settings, or mark a cloud operation as completed.
The Hub owns pause state and releases the guide handle when the fragment unmounts.

Run the no-cloud tests (the SDK's conformance kit included) against a local SDK checkout when
testing unreleased SDK work:

```sh
PYTHONPATH=../3lc-compute-plugin-sdk/src:src .venv/bin/python -m pytest tests -q
```

## Staging development and publishing

The plugin requires plugin SDK 0.5.3 or newer: 0.5.3 is the first SDK whose `WorkspaceRequest`
keeps the deployment DNS zone (`dns_zone_id` / `dns_zone_name`), and a host with a zone refuses
to launch a deployment through a plugin whose SDK would drop it. The plugin SDK 0.5 and the 3.5
core it is locked against are not on PyPI yet; `pyproject.toml` routes both to the private
`staging` index
(CloudRepo `prereleases`). Set that index's credentials in your shell (keep them out of source files):

```bash
export UV_INDEX_STAGING_USERNAME="<account email>"
export UV_INDEX_STAGING_PASSWORD="<read token>"
uv sync --locked --group dev --extra aws
uv run --no-sync pytest
```

The Release workflow builds verified artifacts on manual runs. `publish=true` uploads them
to the private staging index; publishing is disabled by default. The timestamp, run and
attempt suffix stamps the distribution and manifest together.

The separate `v*` tag path provides PyPI Trusted Publishing plumbing. Configure the PyPI
project's trusted publisher before using that path; no public release is needed while the SDK is staged.

### Ambient Connection node storage

An ambient Connection uses the compute host's existing AWS identity. In the Hub, open the
Connection's **Set up** panel and choose **Set up node access**. The plugin creates an EC2-trusted
role, an inline policy and an instance profile directly through IAM. The policy permits read/write
under the displayed S3 project location, plus idle self-termination of 3LC-tagged nodes. It does
not copy host credentials or assume that every bucket the host can browse is available to nodes.

An admin can give the nodes more buckets on the Connection's edit page: a bucket, a folder in one, a
name pattern or every bucket in the account, each read only, read/write without delete, or
read/write/delete. Saving reviews and applies them as one step through the host's node-access setup,
which takes Connection administration (the Config Service's `connection.verify` grant, or an admin of
the service for a Connection the host resolves itself). The rules are kept in their own record beside
the plugin's settings, which cannot change them. A stale review is refused, invalid rules and a policy
over IAM's 10,240-character inline limit are refused before any IAM write, and the rules take effect
only once IAM accepted the role for them; a refused setup leaves the previous role in use.

The host identity needs `iam:GetRole`, `iam:GetRolePolicy`, `iam:ListRolePolicies`, `iam:GetInstanceProfile`, `iam:CreateRole`,
`iam:PutRolePolicy`, `iam:CreateInstanceProfile`, `iam:AddRoleToInstanceProfile`, `iam:TagRole` and
`iam:TagInstanceProfile`, scoped to the managed resources, plus `iam:PassRole` to EC2 for the node
role. `iam:SimulatePrincipalPolicy` is optional: its result is advisory, and unavailable simulation
does not prevent setup. API refusals identify the operation; retry resumes completed steps.
Accounts that require a permissions boundary can supply an operator-managed instance profile.

Managed resources use `3lc-ambient-node-<digest>` names derived from the Connection id, normalized
project root and bucket rules, with `3lc:managed-by` and `3lc:scope` ownership tags. A new root or new
rules get a separate profile, so running nodes retain their existing scope; removing access does not
take it from a running node. Setup refuses unowned resources or changed EC2 trust.
Configured `iam_instance_profile` / `TLC_AWS_NODE_INSTANCE_PROFILE` values take precedence and are
never modified by this setup. The keyless Connection's own profile remains authoritative as before.

Verification and preflight inspect setup; launching a node requires a configured profile. EC2 dry-run
checks include that exact profile. IAM propagation can temporarily prevent launch immediately after
setup; retry preflight after propagation. The node's existing storage probe checks listing after
startup, not every possible read/write operation. After terminating all users of a managed profile,
an account administrator may delete its IAM profile, inline policy and role. Disabling the Connection
alone does not revoke storage from running nodes. Existing machines and RunPod require their own
storage identities until credential leases are available.

#### The AWS trust boundary

Granting the host identity these IAM rights trusts 3LC admins to decide what nodes may reach. The
node role IAM creates is not bounded by the host's own S3 access, so nodes can be given buckets the
host itself cannot read. Restricting only the host's own S3 policy does not change that. An AWS
administrator who needs a firmer ceiling has two options:

- Require a permissions boundary: allow `iam:CreateRole` and `iam:PutRolePolicy` only with an approved
  `iam:PermissionsBoundary`, and deny the host removing or changing it. This setup does not attach a
  boundary yet, so with such a policy it is refused until it does.
- Supply a fixed node instance profile (`iam_instance_profile`), whose permissions the host cannot
  change. The edit page then offers no bucket choice.
