fix(aws): final review round for the environment stacks
Critical
- Owner key is sha256("<region>:<aws:userid>") (12 hex): IAM role names are
account-global and environments regional, so the same user and env name
in two regions no longer collide. Every caller, the onboarding module's
owner_key validation, docs and a two-region test.
Important
- A failed onboarding is Incomplete, not Joined: Joined needs the task role
and, where the bucket is readable, the state's new onboarding_complete
output (depends_on every resource); a failed or errored local run or a
stale lock is Incomplete. Join stays as the retry; Follow, Unlock (own
key only, stale, conditional delete) and Push saved state work on the
caller's own onboarding.
- errored.tfstate: the runner logs an Error line naming it, follow's
summary says so, materialize refuses while it exists, and the new
push_aws_saved_state command runs `tofu state push errored.tfstate`
through the same runner (file set aside once pushed); UI on the row.
- Bundle README: the bucket is created with the component tag in
--create-bucket-configuration (the policy's RequestTag condition), plus
the TLS-only bucket policy; the boundary bundle names an account admin
WITHOUT the environment-admin files.
- Destroy-incomplete refuses while any users/<env>/ state remains.
- existing network: data.aws_subnet lookups and a precondition (same VPC,
different AZs) on the task security group.
Minor
- The TLS statement is added to an existing bucket policy, never put over it.
- Deploy progress is emitted to the main window only.
- materialize checks and writes under start.lock.
- UI: managed-elsewhere label and explanation, Incomplete explained,
Repair/Destroy disabled under a held lock ("Unlock first").
- Cargo.toml libc comment; README: Cancel unavailable on Windows, session.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0b3b100a91
commit
6911b9de27
29 files changed
+1436
-161
No files matched your search
@@ -332,7 +332,8 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
|
||||
binary), in a throwaway state bucket.
|
||||
**Environments are OpenTofu modules** (`aws/terraform/{environment,user-onboard,permissions-boundary}`;
|
||||
spec D2–D10). `tofu_modules.rs` embeds them and is the **only** place the shared names are built
|
||||
(environment, `/triple-c/environments/<env>` record, owner key, per-user roles, state bucket
|
||||
(environment, `/triple-c/environments/<env>` record, owner key — `sha256("<region>:<aws:userid>")`,
|
||||
12 hex, regional because role names are account-global — per-user roles, state bucket
|
||||
`triple-c-tfstate-<account>-<region>`, state keys); its tests pin the HCL to those names, the
|
||||
versions and tags, and `MODULE_CALLS` (every provider call) to the admin policy.
|
||||
`tofu.rs` downloads the pinned OpenTofu (SHA-256 checked **before** extraction), writes a work
|
||||
|
||||
@@ -78,15 +78,16 @@ aws-runtime = { version = "1.10.4", default-features = false }
|
||||
aws-smithy-async = { version = "1.3.1", default-features = false, features = ["rt-tokio"] }
|
||||
aws-sdk-s3 = { version = "1.159.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] }
|
||||
|
||||
# Linux only: WebKitGTK refuses getUserMedia until the embedder enables media
|
||||
# streams and answers the permission request (see src/linux_media.rs). Same
|
||||
# version tauri/wry already resolve, so this adds no second copy.
|
||||
# aws/tofu.rs: `setsid` for the detached OpenTofu runner, SIGINT to its
|
||||
# process group on Cancel, and a liveness probe for its PID. Already in the
|
||||
# tree through tokio and friends.
|
||||
# aws/tofu.rs: `setsid` puts the detached OpenTofu runner in its own session,
|
||||
# and Cancel sends SIGINT to the runner process alone (never a group), which
|
||||
# forwards it to `tofu`. Liveness is the runner's `apply.lock`, not a PID.
|
||||
# Already in the tree through tokio and friends.
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
# Linux only: WebKitGTK refuses getUserMedia until the embedder enables media
|
||||
# streams and answers the permission request (see src/linux_media.rs). Same
|
||||
# version tauri/wry already resolve, so this adds no second copy.
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
webkit2gtk = "2.0.2"
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@
|
||||
"allow-unlock-aws-state",
|
||||
"allow-follow-aws-deployment",
|
||||
"allow-cancel-aws-deployment",
|
||||
"allow-push-aws-saved-state",
|
||||
"allow-onboard-aws-user",
|
||||
"allow-deploy-aws-permissions-boundary",
|
||||
"allow-save-aws-admin-bundle",
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"__app-acl__":{"default_permission":null,"permissions":{"allow-acquire-claude-token":{"identifier":"allow-acquire-claude-token","description":"Enables the acquire_claude_token command without any pre-configured scope.","commands":{"allow":["acquire_claude_token"],"deny":[]}},"allow-add-aws-keys-connection":{"identifier":"allow-add-aws-keys-connection","description":"Enables the add_aws_keys_connection command without any pre-configured scope.","commands":{"allow":["add_aws_keys_connection"],"deny":[]}},"allow-add-aws-profile-connection":{"identifier":"allow-add-aws-profile-connection","description":"Enables the add_aws_profile_connection command without any pre-configured scope.","commands":{"allow":["add_aws_profile_connection"],"deny":[]}},"allow-add-marketplace":{"identifier":"allow-add-marketplace","description":"Enables the add_marketplace command without any pre-configured scope.","commands":{"allow":["add_marketplace"],"deny":[]}},"allow-add-marketplace-gh-host-account":{"identifier":"allow-add-marketplace-gh-host-account","description":"Enables the add_marketplace_gh_host_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_gh_host_account"],"deny":[]}},"allow-add-marketplace-token-account":{"identifier":"allow-add-marketplace-token-account","description":"Enables the add_marketplace_token_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_token_account"],"deny":[]}},"allow-add-project":{"identifier":"allow-add-project","description":"Enables the add_project command without any pre-configured scope.","commands":{"allow":["add_project"],"deny":[]}},"allow-add-scheduled-task":{"identifier":"allow-add-scheduled-task","description":"Enables the add_scheduled_task command without any pre-configured scope.","commands":{"allow":["add_scheduled_task"],"deny":[]}},"allow-apply-marketplace-now":{"identifier":"allow-apply-marketplace-now","description":"Enables the apply_marketplace_now command without any pre-configured scope.","commands":{"allow":["apply_marketplace_now"],"deny":[]}},"allow-apply-settings-import":{"identifier":"allow-apply-settings-import","description":"Enables the apply_settings_import command without any pre-configured scope.","commands":{"allow":["apply_settings_import"],"deny":[]}},"allow-aws-connection-identity":{"identifier":"allow-aws-connection-identity","description":"Enables the aws_connection_identity command without any pre-configured scope.","commands":{"allow":["aws_connection_identity"],"deny":[]}},"allow-aws-connection-sso-login":{"identifier":"allow-aws-connection-sso-login","description":"Enables the aws_connection_sso_login command without any pre-configured scope.","commands":{"allow":["aws_connection_sso_login"],"deny":[]}},"allow-aws-policy-document":{"identifier":"allow-aws-policy-document","description":"Enables the aws_policy_document command without any pre-configured scope.","commands":{"allow":["aws_policy_document"],"deny":[]}},"allow-aws-sso-refresh":{"identifier":"allow-aws-sso-refresh","description":"Enables the aws_sso_refresh command without any pre-configured scope.","commands":{"allow":["aws_sso_refresh"],"deny":[]}},"allow-build-gateway-image":{"identifier":"allow-build-gateway-image","description":"Enables the build_gateway_image command without any pre-configured scope.","commands":{"allow":["build_gateway_image"],"deny":[]}},"allow-build-image":{"identifier":"allow-build-image","description":"Enables the build_image command without any pre-configured scope.","commands":{"allow":["build_image"],"deny":[]}},"allow-build-stt-image":{"identifier":"allow-build-stt-image","description":"Enables the build_stt_image command without any pre-configured scope.","commands":{"allow":["build_stt_image"],"deny":[]}},"allow-cancel-aws-deployment":{"identifier":"allow-cancel-aws-deployment","description":"Enables the cancel_aws_deployment command without any pre-configured scope.","commands":{"allow":["cancel_aws_deployment"],"deny":[]}},"allow-cancel-claude-token":{"identifier":"allow-cancel-claude-token","description":"Enables the cancel_claude_token command without any pre-configured scope.","commands":{"allow":["cancel_claude_token"],"deny":[]}},"allow-cancel-marketplace-gh-login":{"identifier":"allow-cancel-marketplace-gh-login","description":"Enables the cancel_marketplace_gh_login command without any pre-configured scope.","commands":{"allow":["cancel_marketplace_gh_login"],"deny":[]}},"allow-check-aws-permissions":{"identifier":"allow-check-aws-permissions","description":"Enables the check_aws_permissions command without any pre-configured scope.","commands":{"allow":["check_aws_permissions"],"deny":[]}},"allow-check-browser-view-support":{"identifier":"allow-check-browser-view-support","description":"Enables the check_browser_view_support command without any pre-configured scope.","commands":{"allow":["check_browser_view_support"],"deny":[]}},"allow-check-docker":{"identifier":"allow-Line truncated
|
||||
{"__app-acl__":{"default_permission":null,"permissions":{"allow-acquire-claude-token":{"identifier":"allow-acquire-claude-token","description":"Enables the acquire_claude_token command without any pre-configured scope.","commands":{"allow":["acquire_claude_token"],"deny":[]}},"allow-add-aws-keys-connection":{"identifier":"allow-add-aws-keys-connection","description":"Enables the add_aws_keys_connection command without any pre-configured scope.","commands":{"allow":["add_aws_keys_connection"],"deny":[]}},"allow-add-aws-profile-connection":{"identifier":"allow-add-aws-profile-connection","description":"Enables the add_aws_profile_connection command without any pre-configured scope.","commands":{"allow":["add_aws_profile_connection"],"deny":[]}},"allow-add-marketplace":{"identifier":"allow-add-marketplace","description":"Enables the add_marketplace command without any pre-configured scope.","commands":{"allow":["add_marketplace"],"deny":[]}},"allow-add-marketplace-gh-host-account":{"identifier":"allow-add-marketplace-gh-host-account","description":"Enables the add_marketplace_gh_host_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_gh_host_account"],"deny":[]}},"allow-add-marketplace-token-account":{"identifier":"allow-add-marketplace-token-account","description":"Enables the add_marketplace_token_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_token_account"],"deny":[]}},"allow-add-project":{"identifier":"allow-add-project","description":"Enables the add_project command without any pre-configured scope.","commands":{"allow":["add_project"],"deny":[]}},"allow-add-scheduled-task":{"identifier":"allow-add-scheduled-task","description":"Enables the add_scheduled_task command without any pre-configured scope.","commands":{"allow":["add_scheduled_task"],"deny":[]}},"allow-apply-marketplace-now":{"identifier":"allow-apply-marketplace-now","description":"Enables the apply_marketplace_now command without any pre-configured scope.","commands":{"allow":["apply_marketplace_now"],"deny":[]}},"allow-apply-settings-import":{"identifier":"allow-apply-settings-import","description":"Enables the apply_settings_import command without any pre-configured scope.","commands":{"allow":["apply_settings_import"],"deny":[]}},"allow-aws-connection-identity":{"identifier":"allow-aws-connection-identity","description":"Enables the aws_connection_identity command without any pre-configured scope.","commands":{"allow":["aws_connection_identity"],"deny":[]}},"allow-aws-connection-sso-login":{"identifier":"allow-aws-connection-sso-login","description":"Enables the aws_connection_sso_login command without any pre-configured scope.","commands":{"allow":["aws_connection_sso_login"],"deny":[]}},"allow-aws-policy-document":{"identifier":"allow-aws-policy-document","description":"Enables the aws_policy_document command without any pre-configured scope.","commands":{"allow":["aws_policy_document"],"deny":[]}},"allow-aws-sso-refresh":{"identifier":"allow-aws-sso-refresh","description":"Enables the aws_sso_refresh command without any pre-configured scope.","commands":{"allow":["aws_sso_refresh"],"deny":[]}},"allow-build-gateway-image":{"identifier":"allow-build-gateway-image","description":"Enables the build_gateway_image command without any pre-configured scope.","commands":{"allow":["build_gateway_image"],"deny":[]}},"allow-build-image":{"identifier":"allow-build-image","description":"Enables the build_image command without any pre-configured scope.","commands":{"allow":["build_image"],"deny":[]}},"allow-build-stt-image":{"identifier":"allow-build-stt-image","description":"Enables the build_stt_image command without any pre-configured scope.","commands":{"allow":["build_stt_image"],"deny":[]}},"allow-cancel-aws-deployment":{"identifier":"allow-cancel-aws-deployment","description":"Enables the cancel_aws_deployment command without any pre-configured scope.","commands":{"allow":["cancel_aws_deployment"],"deny":[]}},"allow-cancel-claude-token":{"identifier":"allow-cancel-claude-token","description":"Enables the cancel_claude_token command without any pre-configured scope.","commands":{"allow":["cancel_claude_token"],"deny":[]}},"allow-cancel-marketplace-gh-login":{"identifier":"allow-cancel-marketplace-gh-login","description":"Enables the cancel_marketplace_gh_login command without any pre-configured scope.","commands":{"allow":["cancel_marketplace_gh_login"],"deny":[]}},"allow-check-aws-permissions":{"identifier":"allow-check-aws-permissions","description":"Enables the check_aws_permissions command without any pre-configured scope.","commands":{"allow":["check_aws_permissions"],"deny":[]}},"allow-check-browser-view-support":{"identifier":"allow-check-browser-view-support","description":"Enables the check_browser_view_support command without any pre-configured scope.","commands":{"allow":["check_browser_view_support"],"deny":[]}},"allow-check-docker":{"identifier":"allow-Line truncated
|
||||
@@ -1 +1 @@
|
||||
{"default":{"identifier":"default","description":"Default capabilities for Triple-C. Every entry here is an IPC command a compromised webview can call directly, so the set is an enumeration of what `app/src` actually invokes — plugin and core grants verified against tauri 2.11.0's `PLUGINS` table in tauri's own `build.rs` rather than assumed from a plugin's `default` set, app-command grants (the bare `allow-*` entries) cross-checked by this crate's `build.rs` against `generate_handler!`. `core:default` in particular is NOT used: it is an alias for `core:{path,event,window,webview,app,image,resources,menu,tray}:default`, and `core:image:default` carries `allow-from-path`, whose handler (`tauri-2.11.0/src/image/plugin.rs:41` → `src/image/mod.rs:96`) is a bare `std::fs::read(path)` with no scope mechanism of any kind. Nothing imports `@tauri-apps/api/image`, so the whole plugin is dropped rather than scoped — there is nothing to scope it with. `core:menu` and `core:tray` are dropped for the same reason (no menu, no tray icon); `core:window` and `core:path` because nothing imports them; `core:resources:allow-close` because no frontend value is a `Resource`; and `core:event`'s `allow-emit`/`allow-emit-to` because the frontend only ever *listens* — every emit in this app originates in Rust. Three notes on what is deliberately kept or accepted: (1) `core:webview:allow-internal-toggle-devtools` is not called by `app/src` at all — it is called by Tauri's own injected `toggle-devtools.js`, which binds Ctrl/Cmd+Shift+I. Both that script and the command behind it are `#[cfg(any(debug_assertions, feature = \"devtools\"))]`, so this grant is a `tauri dev` convenience that does not exist in a release bundle. (2) `opener:allow-open-url` is **gone**. It could not be narrowed by host — `TerminalView`'s `WebLinksAddon` opens links Claude printed inside the container, which are arbitrary by construction, so a host allowlist would have deleted the feature rather than bounded it — and it was carried here as an accepted residual risk: a compromised webview could make the OS open an attacker-chosen http(s) URL, an outbound channel. That risk is now closed rather than recorded. Every host-browser open in the app goes through the `open_url_external` command in `url_open.rs`, which exists because the AppImage environment leaks into a cold-launched browser on Linux (triple-c#34) and which re-validates the URL in Rust — scheme allowlist, no embedded credentials, no control characters, length cap, ASCII asserted before `execvp`. On macOS and Windows that command reaches the same plugin as before, via `OpenerExt::open_url`, whose desktop implementation calls `crate::open::open` directly and is therefore not gated by this file at all (`tauri-plugin-opener-2.5.3/src/lib.rs:60`). The plugin stays a dependency for exactly that reason; what is removed is the webview's ability to reach it without passing the Rust validation. (3) `drag:allow-start-drag` is **gone**, together with the OS drag-out it existed for. It could not be scoped — `tauri-plugin-drag` takes the item paths from the caller and has no scope mechanism, so a compromised webview could call `startDrag({ item: ['~/.ssh/id_rsa'] })` against any host path the user can read — and it was carried as an accepted residual risk for one gesture. Drag-out was held back for separate hardening (see branch `hold/disk-and-dragout`) and the plugin is no longer a dependency. Getting a file *out* of a container is either \"Back up container\" on the project's Overview tab, which archives a tree through the Docker API, or the Files tab's per-row \"Save to host…\", which copies one file; getting one *in* is a drop on the Terminal or the Files tab's \"Upload…\". None of the four touches this permission. The Files tab's two are worth separating out here, because they are the only host-path commands in the app whose dialog is opened by **Rust** rather than by the webview — `pick_save_path` and `pick_files_to_upload` in `commands/file_commands.rs` drive `tauri-plugin-dialog` from the backend, so a compromised webview can ask for a picker and nothing more: it cannot name a host path as an *input* to either command. Be precise about the limit of that claim — host paths do still travel outward in error text (`Failed to create /home/j/Documents/x.txt.triple-c-part-1a2b3c4d: Permission denied`), including canonicalized ones, which disclose symlink targets. That is accepted; the app already hands the webview the project paths. What is closed is the direction that mattered — the webview naming where bytes go. That is the shape an earlier revision of this file named as the honest one if the Files tab ever regained host I/O, and it is the shape it regained it in. The `dialog:allow-open` / `dialog:allow-save` grants below are therefore *not* what those two use; they remain for the frontend pickers in Add Project, the Config tab's workspace and access sections, the CA-certificate fielLine truncated
|
||||
{"default":{"identifier":"default","description":"Default capabilities for Triple-C. Every entry here is an IPC command a compromised webview can call directly, so the set is an enumeration of what `app/src` actually invokes — plugin and core grants verified against tauri 2.11.0's `PLUGINS` table in tauri's own `build.rs` rather than assumed from a plugin's `default` set, app-command grants (the bare `allow-*` entries) cross-checked by this crate's `build.rs` against `generate_handler!`. `core:default` in particular is NOT used: it is an alias for `core:{path,event,window,webview,app,image,resources,menu,tray}:default`, and `core:image:default` carries `allow-from-path`, whose handler (`tauri-2.11.0/src/image/plugin.rs:41` → `src/image/mod.rs:96`) is a bare `std::fs::read(path)` with no scope mechanism of any kind. Nothing imports `@tauri-apps/api/image`, so the whole plugin is dropped rather than scoped — there is nothing to scope it with. `core:menu` and `core:tray` are dropped for the same reason (no menu, no tray icon); `core:window` and `core:path` because nothing imports them; `core:resources:allow-close` because no frontend value is a `Resource`; and `core:event`'s `allow-emit`/`allow-emit-to` because the frontend only ever *listens* — every emit in this app originates in Rust. Three notes on what is deliberately kept or accepted: (1) `core:webview:allow-internal-toggle-devtools` is not called by `app/src` at all — it is called by Tauri's own injected `toggle-devtools.js`, which binds Ctrl/Cmd+Shift+I. Both that script and the command behind it are `#[cfg(any(debug_assertions, feature = \"devtools\"))]`, so this grant is a `tauri dev` convenience that does not exist in a release bundle. (2) `opener:allow-open-url` is **gone**. It could not be narrowed by host — `TerminalView`'s `WebLinksAddon` opens links Claude printed inside the container, which are arbitrary by construction, so a host allowlist would have deleted the feature rather than bounded it — and it was carried here as an accepted residual risk: a compromised webview could make the OS open an attacker-chosen http(s) URL, an outbound channel. That risk is now closed rather than recorded. Every host-browser open in the app goes through the `open_url_external` command in `url_open.rs`, which exists because the AppImage environment leaks into a cold-launched browser on Linux (triple-c#34) and which re-validates the URL in Rust — scheme allowlist, no embedded credentials, no control characters, length cap, ASCII asserted before `execvp`. On macOS and Windows that command reaches the same plugin as before, via `OpenerExt::open_url`, whose desktop implementation calls `crate::open::open` directly and is therefore not gated by this file at all (`tauri-plugin-opener-2.5.3/src/lib.rs:60`). The plugin stays a dependency for exactly that reason; what is removed is the webview's ability to reach it without passing the Rust validation. (3) `drag:allow-start-drag` is **gone**, together with the OS drag-out it existed for. It could not be scoped — `tauri-plugin-drag` takes the item paths from the caller and has no scope mechanism, so a compromised webview could call `startDrag({ item: ['~/.ssh/id_rsa'] })` against any host path the user can read — and it was carried as an accepted residual risk for one gesture. Drag-out was held back for separate hardening (see branch `hold/disk-and-dragout`) and the plugin is no longer a dependency. Getting a file *out* of a container is either \"Back up container\" on the project's Overview tab, which archives a tree through the Docker API, or the Files tab's per-row \"Save to host…\", which copies one file; getting one *in* is a drop on the Terminal or the Files tab's \"Upload…\". None of the four touches this permission. The Files tab's two are worth separating out here, because they are the only host-path commands in the app whose dialog is opened by **Rust** rather than by the webview — `pick_save_path` and `pick_files_to_upload` in `commands/file_commands.rs` drive `tauri-plugin-dialog` from the backend, so a compromised webview can ask for a picker and nothing more: it cannot name a host path as an *input* to either command. Be precise about the limit of that claim — host paths do still travel outward in error text (`Failed to create /home/j/Documents/x.txt.triple-c-part-1a2b3c4d: Permission denied`), including canonicalized ones, which disclose symlink targets. That is accepted; the app already hands the webview the project paths. What is closed is the direction that mattered — the webview naming where bytes go. That is the shape an earlier revision of this file named as the honest one if the Files tab ever regained host I/O, and it is the shape it regained it in. The `dialog:allow-open` / `dialog:allow-save` grants below are therefore *not* what those two use; they remain for the frontend pickers in Add Project, the Config tab's workspace and access sections, the CA-certificate fielLine truncated
|
||||
@@ -908,6 +908,12 @@
|
||||
"const": "allow-pull-stt-image",
|
||||
"markdownDescription": "Enables the pull_stt_image command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the push_aws_saved_state command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-push-aws-saved-state",
|
||||
"markdownDescription": "Enables the push_aws_saved_state command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the read_container_file command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
@@ -1832,6 +1838,12 @@
|
||||
"const": "deny-pull-stt-image",
|
||||
"markdownDescription": "Denies the pull_stt_image command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the push_aws_saved_state command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-push-aws-saved-state",
|
||||
"markdownDescription": "Denies the push_aws_saved_state command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the read_container_file command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
|
||||
@@ -908,6 +908,12 @@
|
||||
"const": "allow-pull-stt-image",
|
||||
"markdownDescription": "Enables the pull_stt_image command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the push_aws_saved_state command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "allow-push-aws-saved-state",
|
||||
"markdownDescription": "Enables the push_aws_saved_state command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Enables the read_container_file command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
@@ -1832,6 +1838,12 @@
|
||||
"const": "deny-pull-stt-image",
|
||||
"markdownDescription": "Denies the pull_stt_image command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the push_aws_saved_state command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
"const": "deny-push-aws-saved-state",
|
||||
"markdownDescription": "Denies the push_aws_saved_state command without any pre-configured scope."
|
||||
},
|
||||
{
|
||||
"description": "Denies the read_container_file command without any pre-configured scope.",
|
||||
"type": "string",
|
||||
|
||||
@@ -54,6 +54,9 @@ const MAX_LOCKS: usize = 200;
|
||||
/// or data source with a pre/postcondition): 453 bytes for two, measured.
|
||||
/// The modules have at most a handful, so 2 KiB leaves a wide margin.
|
||||
const EMPTY_STATE_MAX_BYTES: i64 = 2048;
|
||||
/// The caller's onboarding state is read whole (for its outputs) only up to
|
||||
/// this size; one user's module state is a few tens of KiB.
|
||||
const MAX_STATE_DOCUMENT_BYTES: usize = 1024 * 1024;
|
||||
/// At most this many small state objects are read per scan; the rest count
|
||||
/// as deployments.
|
||||
const MAX_STATE_PEEKS: usize = 200;
|
||||
@@ -277,15 +280,25 @@ pub enum EnvironmentAction {
|
||||
Destroy,
|
||||
Follow,
|
||||
Unlock,
|
||||
/// Push the state a failed run on this machine couldn't save
|
||||
/// (`errored.tfstate`) back to the bucket.
|
||||
PushState,
|
||||
}
|
||||
|
||||
/// The caller's onboarding to one environment.
|
||||
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||
#[serde(tag = "state", rename_all = "snake_case")]
|
||||
pub enum OnboardingState {
|
||||
/// Their task role exists and, where the bucket is readable, their state
|
||||
/// records a finished apply (its `onboarding_complete` output).
|
||||
Joined,
|
||||
NotJoined,
|
||||
InProgress,
|
||||
Incomplete,
|
||||
/// A local runner, or a recent lock.
|
||||
InProgress { lock: Option<LockInfo> },
|
||||
/// The last onboarding run didn't finish: a stale lock, a failed run on
|
||||
/// this machine, or a state without the completion output. Join is a
|
||||
/// re-apply and finishes it.
|
||||
Incomplete { lock: Option<LockInfo> },
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||
@@ -297,6 +310,12 @@ pub struct DetectedEnvironment {
|
||||
pub info: Option<EnvironmentInfo>,
|
||||
/// The caller's onboarding; resolved only for joinable environments.
|
||||
pub onboarding: Option<OnboardingState>,
|
||||
/// What the caller can do with their own onboarding's run (`Follow`,
|
||||
/// `Unlock`, `PushState`); Join stays in `actions`.
|
||||
pub onboarding_actions: Vec<EnvironmentAction>,
|
||||
/// How many users' onboarding states (`users/<env>/…`, non-empty) the
|
||||
/// bucket holds; `None` when the caller can't list it.
|
||||
pub onboarded_users: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||
@@ -355,9 +374,27 @@ fn environment_of_key(key: &str) -> Option<&str> {
|
||||
(validate_environment_name(env).is_ok()).then_some(env)
|
||||
}
|
||||
|
||||
/// Whether this machine's runner is applying a deployment
|
||||
/// (`tofu::is_running(&tofu::workdir_for(..))`).
|
||||
pub type RunningLocally<'a> = &'a (dyn Fn(Deployment) -> bool + Sync);
|
||||
/// The environment name of a `users/<env>/<key>/terraform.tfstate` key.
|
||||
fn user_environment_of_key(key: &str) -> Option<&str> {
|
||||
let mut parts = key.strip_prefix("users/")?.split('/');
|
||||
let (env, _, file, rest) = (parts.next()?, parts.next()?, parts.next()?, parts.next());
|
||||
(file == "terraform.tfstate" && rest.is_none() && validate_environment_name(env).is_ok())
|
||||
.then_some(env)
|
||||
}
|
||||
|
||||
/// What this machine's work folder says of a deployment's runs.
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct LocalRun {
|
||||
/// A runner here is applying it (`tofu::is_running`).
|
||||
pub running: bool,
|
||||
/// The last run here finished with an error (`tofu::last_run_failed`).
|
||||
pub failed: bool,
|
||||
/// OpenTofu left `errored.tfstate` here (`tofu::has_errored_state`).
|
||||
pub errored_state: bool,
|
||||
}
|
||||
|
||||
/// This machine's runs, per deployment.
|
||||
pub type LocalRuns<'a> = &'a (dyn Fn(Deployment) -> LocalRun + Sync);
|
||||
|
||||
/// One environment from its record (if any), the bucket listing (if this
|
||||
/// caller can read it) and whether a local runner is applying it.
|
||||
@@ -365,12 +402,13 @@ fn detect_one(
|
||||
name: &str,
|
||||
record: Option<Result<EnvironmentInfo, String>>,
|
||||
objects: Option<&StateObjects>,
|
||||
running_locally: RunningLocally,
|
||||
local_runs: LocalRuns,
|
||||
current_version: u32,
|
||||
) -> DetectedEnvironment {
|
||||
use EnvironmentAction::*;
|
||||
let key = state_key(Deployment::Environment(name));
|
||||
let local = running_locally(Deployment::Environment(name));
|
||||
let run = local_runs(Deployment::Environment(name));
|
||||
let local = run.running;
|
||||
let lock = objects
|
||||
.and_then(|o| o.lock(&key))
|
||||
.map(|(json, age)| lock_info(json, age, local));
|
||||
@@ -418,6 +456,25 @@ fn detect_one(
|
||||
)
|
||||
};
|
||||
|
||||
// A saved state must go back before anything else runs here: nothing
|
||||
// that would re-apply or destroy is offered until it has.
|
||||
let actions = if run.errored_state && !local {
|
||||
let mut kept: Vec<_> = actions
|
||||
.into_iter()
|
||||
.filter(|a| !matches!(a, Update | Repair | Destroy))
|
||||
.collect();
|
||||
kept.insert(0, PushState);
|
||||
kept
|
||||
} else {
|
||||
actions
|
||||
};
|
||||
let onboarded_users = objects.map(|o| {
|
||||
o.states
|
||||
.iter()
|
||||
.filter(|k| user_environment_of_key(k) == Some(name))
|
||||
.count() as u32
|
||||
});
|
||||
|
||||
DetectedEnvironment {
|
||||
name: name.to_string(),
|
||||
template_version,
|
||||
@@ -425,6 +482,8 @@ fn detect_one(
|
||||
actions,
|
||||
info,
|
||||
onboarding: None,
|
||||
onboarding_actions: Vec::new(),
|
||||
onboarded_users,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,7 +494,7 @@ fn detect_one(
|
||||
pub fn merge(
|
||||
records: Vec<(String, Result<EnvironmentInfo, String>)>,
|
||||
objects: Option<&StateObjects>,
|
||||
running_locally: RunningLocally,
|
||||
local_runs: LocalRuns,
|
||||
current_version: u32,
|
||||
) -> Vec<DetectedEnvironment> {
|
||||
let mut by_name: BTreeMap<String, Option<Result<EnvironmentInfo, String>>> = BTreeMap::new();
|
||||
@@ -450,28 +509,50 @@ pub fn merge(
|
||||
}
|
||||
by_name
|
||||
.into_iter()
|
||||
.map(|(name, record)| detect_one(&name, record, objects, running_locally, current_version))
|
||||
.map(|(name, record)| detect_one(&name, record, objects, local_runs, current_version))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The caller's onboarding from the bucket alone, or `None` when only
|
||||
/// `iam:GetRole` on the task role can tell.
|
||||
fn onboarding_from_objects(
|
||||
/// Whether an onboarding state records a finished apply: the module's
|
||||
/// `onboarding_complete` output, which depends on every resource it makes,
|
||||
/// so a run that failed part-way never writes it.
|
||||
pub(crate) fn onboarding_complete(state: &str) -> bool {
|
||||
serde_json::from_str::<Value>(state)
|
||||
.ok()
|
||||
.and_then(|v| v.pointer("/outputs/onboarding_complete/value").cloned())
|
||||
== Some(Value::Bool(true))
|
||||
}
|
||||
|
||||
/// The caller's onboarding as far as the lock, this machine's runs and the
|
||||
/// bucket listing tell, and what they may do with its run. `None` (with
|
||||
/// the actions) when the state must be read or the role looked up.
|
||||
fn onboarding_from_runs(
|
||||
objects: Option<&StateObjects>,
|
||||
deployment: Deployment,
|
||||
local: bool,
|
||||
) -> Option<OnboardingState> {
|
||||
if local {
|
||||
return Some(OnboardingState::InProgress);
|
||||
}
|
||||
let objects = objects?;
|
||||
run: LocalRun,
|
||||
) -> (Option<OnboardingState>, Vec<EnvironmentAction>) {
|
||||
use EnvironmentAction::*;
|
||||
let key = state_key(deployment);
|
||||
match objects.lock(&key) {
|
||||
Some((_, age)) if age < LIVE_LOCK_SECS => Some(OnboardingState::InProgress),
|
||||
Some(_) => Some(OnboardingState::Incomplete),
|
||||
None if objects.has_state(&key) => Some(OnboardingState::Joined),
|
||||
None => None,
|
||||
let lock = objects
|
||||
.and_then(|o| o.lock(&key))
|
||||
.map(|(json, age)| lock_info(json, age, run.running));
|
||||
let mut actions = Vec::new();
|
||||
if run.running {
|
||||
actions.push(Follow);
|
||||
} else if run.errored_state {
|
||||
actions.push(PushState);
|
||||
}
|
||||
let state = if run.running || lock.as_ref().is_some_and(|l| l.age_secs < LIVE_LOCK_SECS) {
|
||||
Some(OnboardingState::InProgress { lock })
|
||||
} else if lock.is_some() {
|
||||
actions.push(Unlock);
|
||||
Some(OnboardingState::Incomplete { lock })
|
||||
} else if run.failed || run.errored_state {
|
||||
Some(OnboardingState::Incomplete { lock: None })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(state, actions)
|
||||
}
|
||||
|
||||
/// What detection asks AWS. Each method returns a `Send` future so [`scan`]
|
||||
@@ -497,6 +578,13 @@ pub trait DetectApi: Send + Sync {
|
||||
account: &str,
|
||||
) -> impl Future<Output = Result<Knowable, AwsError>> + Send;
|
||||
fn role_exists(&self, name: &str) -> impl Future<Output = Result<Knowable, AwsError>> + Send;
|
||||
/// A state object's contents, capped; `None` when it is missing, can't
|
||||
/// be read or is too large.
|
||||
fn state_document(
|
||||
&self,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
) -> impl Future<Output = Result<Option<String>, AwsError>> + Send;
|
||||
}
|
||||
|
||||
/// Everything the account holds for this caller in `region`.
|
||||
@@ -504,10 +592,10 @@ pub async fn scan<D: DetectApi>(
|
||||
d: &D,
|
||||
who: &CallerIdentity,
|
||||
region: &str,
|
||||
running_locally: RunningLocally<'_>,
|
||||
local_runs: LocalRuns<'_>,
|
||||
) -> Result<EnvironmentScan, AwsError> {
|
||||
let bucket = state_bucket_name(&who.account, region);
|
||||
scan_in_bucket(d, who, region, &bucket, running_locally).await
|
||||
scan_in_bucket(d, who, region, &bucket, local_runs).await
|
||||
}
|
||||
|
||||
/// [`scan`] against a given state bucket instead of the account's: the live
|
||||
@@ -517,7 +605,7 @@ pub(crate) async fn scan_in_bucket<D: DetectApi>(
|
||||
who: &CallerIdentity,
|
||||
region: &str,
|
||||
bucket: &str,
|
||||
running_locally: RunningLocally<'_>,
|
||||
local_runs: LocalRuns<'_>,
|
||||
) -> Result<EnvironmentScan, AwsError> {
|
||||
let prefix = environment_parameter_name("");
|
||||
let records = d
|
||||
@@ -545,10 +633,10 @@ pub(crate) async fn scan_in_bucket<D: DetectApi>(
|
||||
let mut environments = merge(
|
||||
records,
|
||||
objects.as_ref(),
|
||||
running_locally,
|
||||
local_runs,
|
||||
super::tofu_modules::ENVIRONMENT_MODULE_VERSION,
|
||||
);
|
||||
let key = owner_key(&who.user_id);
|
||||
let key = owner_key(region, &who.user_id);
|
||||
for env in &mut environments {
|
||||
if !env.actions.contains(&EnvironmentAction::Join) {
|
||||
continue;
|
||||
@@ -557,10 +645,24 @@ pub(crate) async fn scan_in_bucket<D: DetectApi>(
|
||||
env: &env.name,
|
||||
owner_key: &key,
|
||||
};
|
||||
let from_objects =
|
||||
onboarding_from_objects(objects.as_ref(), deployment, running_locally(deployment));
|
||||
env.onboarding = Some(match from_objects {
|
||||
let (from_runs, actions) =
|
||||
onboarding_from_runs(objects.as_ref(), deployment, local_runs(deployment));
|
||||
let user_state = state_key(deployment);
|
||||
env.onboarding_actions = actions;
|
||||
env.onboarding = Some(match from_runs {
|
||||
Some(state) => state,
|
||||
// A state the app can read must record a finished apply: a
|
||||
// failed onboarding leaves a partial state (and maybe its task
|
||||
// role), which is not Joined.
|
||||
None if objects.as_ref().is_some_and(|o| o.has_state(&user_state)) => {
|
||||
match d.state_document(bucket, &user_state).await? {
|
||||
Some(text) if onboarding_complete(&text) => OnboardingState::Joined,
|
||||
_ => OnboardingState::Incomplete { lock: None },
|
||||
}
|
||||
}
|
||||
// Without a state here (a workspace user, who can't list the
|
||||
// bucket, or an onboarding managed elsewhere) the task role is
|
||||
// the only signal.
|
||||
None => {
|
||||
let (task_role, _) = user_role_names(&env.name, &key);
|
||||
match d.role_exists(&task_role).await? {
|
||||
@@ -893,6 +995,46 @@ impl DetectApi for SdkDetectApi {
|
||||
let res = self.iam.get_role().role_name(name).send().await;
|
||||
knowable("iam:GetRole", res)
|
||||
}
|
||||
|
||||
async fn state_document(&self, bucket: &str, key: &str) -> Result<Option<String>, AwsError> {
|
||||
const ACTION: &str = "s3:GetObject";
|
||||
let res = self
|
||||
.s3
|
||||
.get_object()
|
||||
.bucket(bucket)
|
||||
.key(key)
|
||||
.expected_bucket_owner(&self.account)
|
||||
.send()
|
||||
.await;
|
||||
let obj = match res {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
let (code, status) = error_parts(&e);
|
||||
return match lookup_outcome(code.as_deref(), status) {
|
||||
Lookup::Missing | Lookup::Denied => Ok(None),
|
||||
Lookup::Error => Err(classify_sdk_error(ACTION, &e)),
|
||||
};
|
||||
}
|
||||
};
|
||||
if obj
|
||||
.content_length()
|
||||
.is_some_and(|n| n < 0 || n as usize > MAX_STATE_DOCUMENT_BYTES)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
// Capped while reading too: the length header may be absent.
|
||||
let mut body = obj.body;
|
||||
let mut bytes = Vec::new();
|
||||
while let Some(chunk) = body.try_next().await.map_err(|e| AwsError::Other {
|
||||
message: format!("Could not read a state object: {e}"),
|
||||
})? {
|
||||
if bytes.len() + chunk.len() > MAX_STATE_DOCUMENT_BYTES {
|
||||
return Ok(None);
|
||||
}
|
||||
bytes.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(Some(String::from_utf8_lossy(&bytes).into_owned()))
|
||||
}
|
||||
}
|
||||
|
||||
/// `s3:CreateBucket`'s answer, by error code: `Some(Ok)` for a bucket this
|
||||
@@ -961,7 +1103,7 @@ fn create_bucket_configuration(region: &str) -> CreateBucketConfiguration {
|
||||
}
|
||||
|
||||
/// Deny every request to the bucket that doesn't use TLS.
|
||||
fn state_bucket_policy(bucket: &str) -> String {
|
||||
pub(crate) fn state_bucket_policy(bucket: &str) -> String {
|
||||
json!({
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
@@ -979,6 +1121,45 @@ fn state_bucket_policy(bucket: &str) -> String {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// The bucket policy to put, given the bucket's current one: ours when it
|
||||
/// has none, `None` when our TLS statement is already in it, and otherwise
|
||||
/// the existing policy with our statement added (or a stale statement under
|
||||
/// our Sid replaced). An organisation's own statements are never dropped.
|
||||
/// Refuses a policy it can't parse rather than overwrite it.
|
||||
pub(crate) fn state_bucket_policy_update(
|
||||
existing: Option<&str>,
|
||||
bucket: &str,
|
||||
) -> Result<Option<String>, String> {
|
||||
let ours: Value = serde_json::from_str(&state_bucket_policy(bucket)).expect("our policy is JSON");
|
||||
let Some(existing) = existing else {
|
||||
return Ok(Some(ours.to_string()));
|
||||
};
|
||||
let ours = ours["Statement"][0].clone();
|
||||
let sid = ours["Sid"].clone();
|
||||
let mut policy: Value = serde_json::from_str(existing)
|
||||
.ok()
|
||||
.filter(Value::is_object)
|
||||
.ok_or("The state bucket's existing policy can't be read, so it was left as it is")?;
|
||||
let statements = match policy.get("Statement") {
|
||||
Some(Value::Array(a)) => a.clone(),
|
||||
Some(single @ Value::Object(_)) => vec![single.clone()],
|
||||
None => Vec::new(),
|
||||
Some(_) => {
|
||||
return Err("The state bucket's existing policy can't be read, so it was left as it is".into())
|
||||
}
|
||||
};
|
||||
if statements.contains(&ours) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut kept: Vec<Value> = statements.into_iter().filter(|s| s.get("Sid") != Some(&sid)).collect();
|
||||
kept.push(ours);
|
||||
policy["Statement"] = Value::Array(kept);
|
||||
if policy.get("Version").is_none() {
|
||||
policy["Version"] = json!("2012-10-17");
|
||||
}
|
||||
Ok(Some(policy.to_string()))
|
||||
}
|
||||
|
||||
/// Create (or adopt) `triple-c-tfstate-<account>-<region>` and configure it:
|
||||
/// the component tag, versioning, SSE-S3, all four public-access blocks and
|
||||
/// a TLS-only policy. Idempotent. Every call after the create carries
|
||||
@@ -1116,13 +1297,30 @@ pub(crate) async fn ensure_named_state_bucket(
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| classify_sdk_error("s3:PutBucketPublicAccessBlock", &e))?;
|
||||
s3.put_bucket_policy()
|
||||
// Only when the TLS statement is missing, and then added to whatever
|
||||
// policy the bucket has (an organisation may have its own statements).
|
||||
let existing = match s3
|
||||
.get_bucket_policy()
|
||||
.bucket(&bucket)
|
||||
.expected_bucket_owner(account)
|
||||
.policy(state_bucket_policy(&bucket))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| classify_sdk_error("s3:PutBucketPolicy", &e))?;
|
||||
{
|
||||
Ok(out) => out.policy().map(str::to_string),
|
||||
Err(e) if e.code() == Some("NoSuchBucketPolicy") => None,
|
||||
Err(e) => return Err(classify_sdk_error("s3:GetBucketPolicy", &e)),
|
||||
};
|
||||
if let Some(policy) = state_bucket_policy_update(existing.as_deref(), &bucket)
|
||||
.map_err(|message| AwsError::Other { message })?
|
||||
{
|
||||
s3.put_bucket_policy()
|
||||
.bucket(&bucket)
|
||||
.expected_bucket_owner(account)
|
||||
.policy(policy)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| classify_sdk_error("s3:PutBucketPolicy", &e))?;
|
||||
}
|
||||
Ok(bucket)
|
||||
}
|
||||
|
||||
|
||||
@@ -201,8 +201,15 @@ fn untrusted_environment_records_are_rejected() {
|
||||
);
|
||||
}
|
||||
|
||||
fn nobody_local(_: Deployment) -> bool {
|
||||
false
|
||||
fn nobody_local(_: Deployment) -> LocalRun {
|
||||
LocalRun::default()
|
||||
}
|
||||
|
||||
fn running() -> LocalRun {
|
||||
LocalRun {
|
||||
running: true,
|
||||
..LocalRun::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn env_key(env: &str) -> String {
|
||||
@@ -383,7 +390,13 @@ fn interrupted_deployments_get_the_right_actions() {
|
||||
|
||||
// A local process, even under an old lock: Deploying, Follow.
|
||||
let objs = objects(&[env_key("c")], &[(env_key("c"), stale)]);
|
||||
let local_c = |d: Deployment| d == Deployment::Environment("c");
|
||||
let local_c = |d: Deployment| {
|
||||
if d == Deployment::Environment("c") {
|
||||
running()
|
||||
} else {
|
||||
LocalRun::default()
|
||||
}
|
||||
};
|
||||
let envs = merge(Vec::new(), Some(&objs), &local_c, 1);
|
||||
let c = find(&envs, "c");
|
||||
let EnvironmentState::Deploying { lock: Some(lock) } = &c.state else {
|
||||
@@ -447,6 +460,8 @@ struct FakeDetect {
|
||||
bucket: Knowable,
|
||||
boundary: Knowable,
|
||||
roles: HashMap<String, Knowable>,
|
||||
/// State objects' contents, by key.
|
||||
documents: HashMap<String, String>,
|
||||
calls: Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
@@ -458,6 +473,7 @@ impl FakeDetect {
|
||||
bucket: Knowable::Yes,
|
||||
boundary: Knowable::Yes,
|
||||
roles: HashMap::new(),
|
||||
documents: HashMap::new(),
|
||||
calls: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
@@ -500,6 +516,10 @@ impl DetectApi for FakeDetect {
|
||||
self.log(format!("role {name}"));
|
||||
Ok(self.roles.get(name).cloned().unwrap_or(Knowable::No))
|
||||
}
|
||||
async fn state_document(&self, bucket: &str, key: &str) -> Result<Option<String>, AwsError> {
|
||||
self.log(format!("document {bucket} {key}"));
|
||||
Ok(self.documents.get(key).cloned())
|
||||
}
|
||||
}
|
||||
|
||||
fn who() -> CallerIdentity {
|
||||
@@ -510,7 +530,7 @@ fn who() -> CallerIdentity {
|
||||
}
|
||||
}
|
||||
|
||||
fn run_scan(d: &FakeDetect, local: &(dyn Fn(Deployment) -> bool + Sync)) -> EnvironmentScan {
|
||||
fn run_scan(d: &FakeDetect, local: LocalRuns) -> EnvironmentScan {
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.build()
|
||||
.unwrap()
|
||||
@@ -521,12 +541,12 @@ fn run_scan(d: &FakeDetect, local: &(dyn Fn(Deployment) -> bool + Sync)) -> Envi
|
||||
fn user_key(env: &str) -> String {
|
||||
state_key(Deployment::User {
|
||||
env,
|
||||
owner_key: &owner_key(USER_ID),
|
||||
owner_key: &owner_key(REGION, USER_ID),
|
||||
})
|
||||
}
|
||||
|
||||
fn task_role(env: &str) -> String {
|
||||
user_role_names(env, &owner_key(USER_ID)).0
|
||||
user_role_names(env, &owner_key(REGION, USER_ID)).0
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -554,16 +574,20 @@ fn onboarding_is_found_by_state_then_by_role() {
|
||||
});
|
||||
d.roles.insert(task_role("byrole"), Knowable::Yes);
|
||||
d.roles.insert(task_role("denied"), Knowable::Unknown);
|
||||
d.documents.insert(user_key("bystate"), completed_state());
|
||||
|
||||
let scan = run_scan(&d, &nobody_local);
|
||||
assert_eq!(scan.owner_id, USER_ID);
|
||||
assert_eq!(scan.owner_key, owner_key(USER_ID));
|
||||
assert_eq!(scan.owner_key, owner_key(REGION, USER_ID));
|
||||
let onboarding = |n: &str| find(&scan.environments, n).onboarding.clone();
|
||||
assert_eq!(onboarding("bystate"), Some(OnboardingState::Joined));
|
||||
assert_eq!(onboarding("byrole"), Some(OnboardingState::Joined));
|
||||
assert_eq!(onboarding("denied"), Some(OnboardingState::NotJoined));
|
||||
assert_eq!(onboarding("absent"), Some(OnboardingState::NotJoined));
|
||||
assert_eq!(onboarding("joining"), Some(OnboardingState::InProgress));
|
||||
assert!(matches!(
|
||||
onboarding("joining"),
|
||||
Some(OnboardingState::InProgress { lock: Some(_) })
|
||||
));
|
||||
|
||||
// The state key answered for `bystate` and the lock for `joining`, so
|
||||
// only the others cost a GetRole.
|
||||
@@ -588,22 +612,31 @@ fn onboarding_is_found_by_state_then_by_role() {
|
||||
3 * 3600,
|
||||
)],
|
||||
});
|
||||
let ok = owner_key(USER_ID);
|
||||
let ok = owner_key(REGION, USER_ID);
|
||||
let local_x = move |dep: Deployment| {
|
||||
dep == Deployment::User {
|
||||
env: "x",
|
||||
owner_key: &ok,
|
||||
if dep
|
||||
== (Deployment::User {
|
||||
env: "x",
|
||||
owner_key: &ok,
|
||||
})
|
||||
{
|
||||
running()
|
||||
} else {
|
||||
LocalRun::default()
|
||||
}
|
||||
};
|
||||
let scan = run_scan(&d, &local_x);
|
||||
assert_eq!(
|
||||
find(&scan.environments, "x").onboarding,
|
||||
Some(OnboardingState::InProgress)
|
||||
);
|
||||
assert_eq!(
|
||||
find(&scan.environments, "y").onboarding,
|
||||
Some(OnboardingState::Incomplete)
|
||||
);
|
||||
let x = find(&scan.environments, "x");
|
||||
assert_eq!(x.onboarding, Some(OnboardingState::InProgress { lock: None }));
|
||||
assert_eq!(x.onboarding_actions, vec![EnvironmentAction::Follow]);
|
||||
let y = find(&scan.environments, "y");
|
||||
let Some(OnboardingState::Incomplete { lock: Some(lock) }) = &y.onboarding else {
|
||||
panic!("{y:#?}");
|
||||
};
|
||||
assert!(!lock.local_process);
|
||||
assert_eq!(y.onboarding_actions, vec![EnvironmentAction::Unlock]);
|
||||
// Join stays: it is the retry.
|
||||
assert!(y.actions.contains(&EnvironmentAction::Join));
|
||||
|
||||
// Not joinable, not resolved.
|
||||
let mut d = FakeDetect::new();
|
||||
@@ -862,3 +895,183 @@ fn a_state_that_cannot_be_read_still_counts() {
|
||||
// An S3 error on one object degrades that entry, not the scan.
|
||||
assert!(keep_state("k", Err(AwsError::Other { message: "boom".into() })));
|
||||
}
|
||||
|
||||
fn completed_state() -> String {
|
||||
json!({
|
||||
"version": 4,
|
||||
"resources": [{"type": "aws_iam_role", "name": "task"}],
|
||||
"outputs": {"onboarding_complete": {"value": true, "type": "bool"}},
|
||||
})
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_onboarding_is_incomplete_not_joined() {
|
||||
// A partial state (the task role made, the file system not): the role
|
||||
// exists, but the state has no completion output.
|
||||
let mut d = FakeDetect::new()
|
||||
.with_record("partial", 1)
|
||||
.with_record("done", 1)
|
||||
.with_record("failedhere", 1)
|
||||
.with_record("errored", 1);
|
||||
let partial = json!({
|
||||
"version": 4,
|
||||
"resources": [{"type": "aws_iam_role", "name": "task"}],
|
||||
"outputs": {"task_role_arn": {"value": "arn:aws:iam::1:role/x", "type": "string"}},
|
||||
})
|
||||
.to_string();
|
||||
d.objects = Some(StateObjects {
|
||||
states: ["partial", "done", "failedhere", "errored"]
|
||||
.iter()
|
||||
.flat_map(|e| [env_key(e), user_key(e)])
|
||||
.collect(),
|
||||
locks: Vec::new(),
|
||||
});
|
||||
d.documents.insert(user_key("partial"), partial);
|
||||
d.documents.insert(user_key("done"), completed_state());
|
||||
d.documents.insert(user_key("failedhere"), completed_state());
|
||||
d.documents.insert(user_key("errored"), completed_state());
|
||||
for e in ["partial", "done", "failedhere", "errored"] {
|
||||
d.roles.insert(task_role(e), Knowable::Yes);
|
||||
}
|
||||
let ok = owner_key(REGION, USER_ID);
|
||||
let local = move |dep: Deployment| match dep {
|
||||
Deployment::User { env: "failedhere", owner_key } if owner_key == ok => LocalRun {
|
||||
failed: true,
|
||||
..LocalRun::default()
|
||||
},
|
||||
Deployment::User { env: "errored", owner_key } if owner_key == ok => LocalRun {
|
||||
failed: true,
|
||||
errored_state: true,
|
||||
..LocalRun::default()
|
||||
},
|
||||
_ => LocalRun::default(),
|
||||
};
|
||||
let scan = run_scan(&d, &local);
|
||||
let row = |n: &str| find(&scan.environments, n).clone();
|
||||
|
||||
assert_eq!(row("done").onboarding, Some(OnboardingState::Joined));
|
||||
for name in ["partial", "failedhere", "errored"] {
|
||||
let r = row(name);
|
||||
assert_eq!(
|
||||
r.onboarding,
|
||||
Some(OnboardingState::Incomplete { lock: None }),
|
||||
"{name}"
|
||||
);
|
||||
// Join is kept: an idempotent re-apply finishes it.
|
||||
assert!(r.actions.contains(&EnvironmentAction::Join), "{name}");
|
||||
}
|
||||
assert!(row("partial").onboarding_actions.is_empty());
|
||||
// The saved state has to go back first.
|
||||
assert_eq!(
|
||||
row("errored").onboarding_actions,
|
||||
vec![EnvironmentAction::PushState]
|
||||
);
|
||||
// Neither the local failures nor the lock-free ones cost a GetRole.
|
||||
assert!(!d.calls().iter().any(|c| c.starts_with("role ")), "{:?}", d.calls());
|
||||
assert!(onboarding_complete(&completed_state()));
|
||||
assert!(!onboarding_complete("{}"));
|
||||
assert!(!onboarding_complete(
|
||||
&json!({"outputs": {"onboarding_complete": {"value": "true"}}}).to_string()
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_errored_environment_state_offers_only_the_push() {
|
||||
let objs = objects(&[env_key("e")], &[]);
|
||||
let errored = |d: Deployment| LocalRun {
|
||||
failed: true,
|
||||
errored_state: d == Deployment::Environment("e"),
|
||||
..LocalRun::default()
|
||||
};
|
||||
let envs = merge(Vec::new(), Some(&objs), &errored, 1);
|
||||
// State without a record: normally Repair and Destroy.
|
||||
assert_eq!(find(&envs, "e").actions, vec![EnvironmentAction::PushState]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn onboarded_users_are_counted_per_environment() {
|
||||
let ok = owner_key(REGION, USER_ID);
|
||||
let objs = objects(
|
||||
&[
|
||||
env_key("a"),
|
||||
env_key("b"),
|
||||
state_key(Deployment::User { env: "a", owner_key: &ok }),
|
||||
state_key(Deployment::User { env: "a", owner_key: "0123456789ab" }),
|
||||
"users/a/x/y/terraform.tfstate".to_string(),
|
||||
],
|
||||
&[],
|
||||
);
|
||||
let envs = merge(Vec::new(), Some(&objs), &nobody_local, 1);
|
||||
assert_eq!(find(&envs, "a").onboarded_users, Some(2));
|
||||
assert_eq!(find(&envs, "b").onboarded_users, Some(0));
|
||||
let envs = merge(vec![("c".into(), Ok(parsed("c", 1)))], None, &nobody_local, 1);
|
||||
assert_eq!(find(&envs, "c").onboarded_users, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tls_statement_is_added_to_a_bucket_policy_never_replacing_it() {
|
||||
let bucket = state_bucket_name(ACCOUNT, REGION);
|
||||
let ours: Value = serde_json::from_str(&state_bucket_policy(&bucket)).unwrap();
|
||||
let tls = ours["Statement"][0].clone();
|
||||
|
||||
// No policy: ours.
|
||||
let new: Value =
|
||||
serde_json::from_str(&state_bucket_policy_update(None, &bucket).unwrap().unwrap()).unwrap();
|
||||
assert_eq!(new, ours);
|
||||
|
||||
// Ours already there (statement order or key order aside): nothing to put.
|
||||
let same = json!({"Statement": [tls.clone()], "Version": "2012-10-17"}).to_string();
|
||||
assert_eq!(state_bucket_policy_update(Some(&same), &bucket).unwrap(), None);
|
||||
|
||||
// An organisation's statements are kept; ours is added once.
|
||||
let org = json!({
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Sid": "OrgDenyOutsideVpce",
|
||||
"Effect": "Deny",
|
||||
"Principal": "*",
|
||||
"Action": "s3:*",
|
||||
"Resource": format!("arn:aws:s3:::{bucket}/*"),
|
||||
"Condition": {"StringNotEquals": {"aws:SourceVpce": "vpce-1234"}},
|
||||
}],
|
||||
});
|
||||
let merged: Value = serde_json::from_str(
|
||||
&state_bucket_policy_update(Some(&org.to_string()), &bucket)
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let st = merged["Statement"].as_array().unwrap();
|
||||
assert_eq!(st.len(), 2);
|
||||
assert_eq!(st[0], org["Statement"][0]);
|
||||
assert_eq!(st[1], tls);
|
||||
assert_eq!(merged["Version"], "2012-10-17");
|
||||
|
||||
// A single statement object (not a list) is kept too.
|
||||
let single = json!({"Version": "2012-10-17", "Statement": org["Statement"][0].clone()});
|
||||
let merged: Value = serde_json::from_str(
|
||||
&state_bucket_policy_update(Some(&single.to_string()), &bucket)
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(merged["Statement"].as_array().unwrap().len(), 2);
|
||||
|
||||
// A stale statement under our Sid is replaced, not duplicated.
|
||||
let mut old = tls.clone();
|
||||
old["Resource"] = json!("arn:aws:s3:::elsewhere");
|
||||
let stale = json!({"Version": "2012-10-17", "Statement": [org["Statement"][0].clone(), old]});
|
||||
let merged: Value = serde_json::from_str(
|
||||
&state_bucket_policy_update(Some(&stale.to_string()), &bucket)
|
||||
.unwrap()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let st = merged["Statement"].as_array().unwrap();
|
||||
assert_eq!(st.len(), 2);
|
||||
assert_eq!(st[1], tls);
|
||||
|
||||
// Something that isn't a policy is never overwritten.
|
||||
assert!(state_bucket_policy_update(Some("not json"), &bucket).is_err());
|
||||
}
|
||||
@@ -1156,8 +1156,12 @@ mod environment {
|
||||
let (root, bucket) = (self.root.clone(), self.bucket.clone());
|
||||
let running = move |d: Deployment| {
|
||||
tofu::workdir_for(&root, d, &bucket)
|
||||
.map(|wd| tofu::is_running(&wd))
|
||||
.unwrap_or(false)
|
||||
.map(|wd| crate::aws::environments::LocalRun {
|
||||
running: tofu::is_running(&wd),
|
||||
failed: tofu::last_run_failed(&wd),
|
||||
errored_state: tofu::has_errored_state(&wd),
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
scan_in_bucket(&api, who, &self.e.region, &self.bucket, &running)
|
||||
.await
|
||||
@@ -1533,7 +1537,7 @@ mod environment {
|
||||
let found = t.scan(&cfg, &who).await;
|
||||
onboard_refusal(&found, &name).expect("join is offered");
|
||||
let owner = validate_owner_id(&who.user_id).expect("owner id");
|
||||
let okey = owner_key(&owner);
|
||||
let okey = owner_key(&t.e.region, &owner);
|
||||
let (_, outcome, denied) = t
|
||||
.run(
|
||||
ModuleKind::UserOnboard,
|
||||
|
||||
@@ -100,6 +100,16 @@ const EXIT_FILE: &str = "apply.exit";
|
||||
const LOCK_FILE: &str = "apply.lock";
|
||||
/// Held by [`start_detached`] for its check → clear → spawn → wait.
|
||||
const START_LOCK_FILE: &str = "start.lock";
|
||||
/// What OpenTofu writes into its working directory when it can't save the
|
||||
/// state to the backend after a run: the only copy of what it changed.
|
||||
const ERRORED_STATE_FILE: &str = "errored.tfstate";
|
||||
/// Where a pushed `errored.tfstate` is set aside (kept, not deleted).
|
||||
const PUSHED_STATE_FILE: &str = "errored.tfstate.pushed";
|
||||
/// The error a run leaving [`ERRORED_STATE_FILE`] ends with; the outcome's
|
||||
/// summary and the UI's recovery both name it.
|
||||
pub const ERRORED_STATE_MESSAGE: &str = "OpenTofu could not save this deployment's state to the \
|
||||
state bucket and kept it in errored.tfstate in the work folder. Nothing else can run here \
|
||||
until it is pushed back: use Push saved state";
|
||||
/// The names (not values) of the variables the app gave the runner, so the
|
||||
/// runner can hand `tofu` exactly those (see [`tofu_env`]).
|
||||
const ENV_KEYS_VAR: &str = "TRIPLEC_TOFU_ENV_KEYS";
|
||||
@@ -357,12 +367,36 @@ pub fn materialize(
|
||||
}
|
||||
let region = validate_supported_region(region).map_err(other)?;
|
||||
let key = state_key(deployment);
|
||||
if is_running(&wd) {
|
||||
return Err(other("A deploy is already running for this deployment"));
|
||||
}
|
||||
|
||||
let io = |e: io::Error| other(format!("Could not write the work folder: {e}"));
|
||||
fs::create_dir_all(&wd.dir).map_err(io)?;
|
||||
// The same lock `start_detached` holds from its check to its spawn: a
|
||||
// second app instance can't rewrite the folder between another's check
|
||||
// and its start.
|
||||
let start_lock = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.open(wd.dir.join(START_LOCK_FILE))
|
||||
.map_err(io)?;
|
||||
match start_lock.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(fs::TryLockError::WouldBlock) => {
|
||||
return Err(other("A deploy is already starting for this deployment"))
|
||||
}
|
||||
Err(fs::TryLockError::Error(e)) => return Err(io(e)),
|
||||
}
|
||||
if is_running(&wd) {
|
||||
return Err(other("A deploy is already running for this deployment"));
|
||||
}
|
||||
if has_errored_state(&wd) {
|
||||
return Err(other(format!(
|
||||
"The last run could not save its state: OpenTofu kept it in {}. Push it back first \
|
||||
with Push saved state (or by hand, from that folder: tofu init \
|
||||
-backend-config=backend.hcl, then tofu state push errored.tfstate)",
|
||||
wd.dir.join(ERRORED_STATE_FILE).display()
|
||||
)));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
@@ -384,6 +418,7 @@ pub fn materialize(
|
||||
let json = serde_json::to_vec_pretty(vars)
|
||||
.map_err(|e| other(format!("Could not encode the module variables: {e}")))?;
|
||||
write_private(&wd.dir.join("terraform.tfvars.json"), &json).map_err(io)?;
|
||||
drop(start_lock);
|
||||
Ok(wd)
|
||||
}
|
||||
|
||||
@@ -595,6 +630,9 @@ pub fn child_env(
|
||||
pub enum TofuOp {
|
||||
Apply,
|
||||
Destroy,
|
||||
/// `tofu state push errored.tfstate`: the recovery after a run that
|
||||
/// couldn't save its state ([`ERRORED_STATE_MESSAGE`]).
|
||||
PushState,
|
||||
}
|
||||
|
||||
impl TofuOp {
|
||||
@@ -602,6 +640,7 @@ impl TofuOp {
|
||||
match self {
|
||||
TofuOp::Apply => "apply",
|
||||
TofuOp::Destroy => "destroy",
|
||||
TofuOp::PushState => "push-state",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,6 +648,7 @@ impl TofuOp {
|
||||
match s {
|
||||
"apply" => Some(TofuOp::Apply),
|
||||
"destroy" => Some(TofuOp::Destroy),
|
||||
"push-state" => Some(TofuOp::PushState),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -830,6 +870,20 @@ pub fn has_run(wd: &Workdir) -> bool {
|
||||
wd.dir.join(LOG_FILE).exists() || wd.dir.join(EXIT_FILE).exists() || is_running(wd)
|
||||
}
|
||||
|
||||
/// OpenTofu left `errored.tfstate` here: the state it couldn't save.
|
||||
pub fn has_errored_state(wd: &Workdir) -> bool {
|
||||
wd.dir.join(ERRORED_STATE_FILE).is_file()
|
||||
}
|
||||
|
||||
/// The last run here finished with a non-zero exit code (and none is
|
||||
/// running now).
|
||||
pub fn last_run_failed(wd: &Workdir) -> bool {
|
||||
!is_running(wd)
|
||||
&& fs::read_to_string(wd.dir.join(EXIT_FILE))
|
||||
.ok()
|
||||
.is_some_and(|t| t.trim().parse::<i32>() != Ok(0))
|
||||
}
|
||||
|
||||
fn read_pid(wd: &Workdir) -> Option<u32> {
|
||||
fs::read_to_string(wd.dir.join(PID_FILE))
|
||||
.ok()?
|
||||
@@ -1006,6 +1060,8 @@ pub async fn follow(
|
||||
let mut pending: Vec<u8> = Vec::new();
|
||||
let mut last_summary: Option<String> = None;
|
||||
let mut last_error: Option<String> = None;
|
||||
// The run's own last error, apart from the runner's errored-state line.
|
||||
let mut cause: Option<String> = None;
|
||||
loop {
|
||||
// Checked before reading: the runner writes the exit code only after
|
||||
// tofu has written its last line, so this read sees everything.
|
||||
@@ -1031,6 +1087,9 @@ pub async fn follow(
|
||||
}
|
||||
if e.level == "error" {
|
||||
last_error = Some(e.message.clone());
|
||||
if !e.message.contains(ERRORED_STATE_FILE) {
|
||||
cause = Some(e.message.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if !events.is_empty() {
|
||||
@@ -1044,6 +1103,11 @@ pub async fn follow(
|
||||
let ok = exit_code == 0;
|
||||
let summary = if ok {
|
||||
last_summary
|
||||
} else if has_errored_state(wd) {
|
||||
Some(match cause.take() {
|
||||
Some(c) => format!("{ERRORED_STATE_MESSAGE}. The run's error: {c}"),
|
||||
None => ERRORED_STATE_MESSAGE.to_string(),
|
||||
})
|
||||
} else {
|
||||
last_error.or(last_summary)
|
||||
};
|
||||
@@ -1231,9 +1295,34 @@ fn run_steps(dir: &Path, op: TofuOp, tofu: &Path, env: &[(String, String)], log:
|
||||
let _ = writeln!(log, "triple-c: cancelled before tofu {}", op.as_arg());
|
||||
return 130;
|
||||
}
|
||||
let run = [op.as_arg(), "-auto-approve", "-json", "-input=false"];
|
||||
let code = step(tofu, dir, &run, env, log);
|
||||
let run: &[&str] = match op {
|
||||
TofuOp::Apply => &["apply", "-auto-approve", "-json", "-input=false"],
|
||||
TofuOp::Destroy => &["destroy", "-auto-approve", "-json", "-input=false"],
|
||||
// No -force: tofu refuses a state of another lineage or an older
|
||||
// serial, which is exactly what must not be pushed.
|
||||
TofuOp::PushState => &["state", "push", ERRORED_STATE_FILE],
|
||||
};
|
||||
let code = step(tofu, dir, run, env, log);
|
||||
let _ = writeln!(log, "triple-c: tofu {} finished (exit {code})", op.as_arg());
|
||||
if op == TofuOp::PushState && code == 0 {
|
||||
// Kept, not deleted: it was the only copy until the push.
|
||||
match fs::rename(dir.join(ERRORED_STATE_FILE), dir.join(PUSHED_STATE_FILE)) {
|
||||
Ok(()) => {
|
||||
let _ = writeln!(log, "triple-c: the saved state was pushed to the state bucket");
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = writeln!(
|
||||
log,
|
||||
"Error: the saved state was pushed but errored.tfstate could not be set aside ({e}); remove it by hand"
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
} else if code != 0 && dir.join(ERRORED_STATE_FILE).is_file() {
|
||||
// A plain `Error:` line is an error event, and the last one is the
|
||||
// outcome's summary.
|
||||
let _ = writeln!(log, "Error: {ERRORED_STATE_MESSAGE}");
|
||||
}
|
||||
code
|
||||
}
|
||||
|
||||
|
||||
@@ -997,3 +997,127 @@ fn a_started_runner_reports_its_pid() {
|
||||
|
||||
assert_eq!(started, Started { pid: Some(31337) });
|
||||
}
|
||||
|
||||
/// A failed apply whose state OpenTofu could not save leaves
|
||||
/// `errored.tfstate`: the runner says so in an error line, the outcome's
|
||||
/// summary names it, and nothing new is materialized over it.
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn an_errored_state_is_reported_and_blocks_the_next_launch() {
|
||||
let _turn = runner_turn();
|
||||
let bin = tempfile::tempdir().unwrap();
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let bucket = "triple-c-tfstate-123456789012-us-east-1";
|
||||
let wd = materialize(
|
||||
root.path(),
|
||||
ModuleKind::PermissionsBoundary,
|
||||
Deployment::Boundary,
|
||||
bucket,
|
||||
"us-east-1",
|
||||
&boundary_vars("us-east-1"),
|
||||
)
|
||||
.unwrap();
|
||||
// init succeeds; the apply "fails to persist" and leaves errored.tfstate.
|
||||
let tofu = fake_tofu(
|
||||
bin.path(),
|
||||
"[ \"$1\" = init ] && exit 0\necho '{\"version\":4}' > errored.tfstate\nexit 1",
|
||||
);
|
||||
let env = vec![("PATH".to_string(), "/usr/bin:/bin".to_string())];
|
||||
|
||||
assert_eq!(run_runner(&wd.dir, TofuOp::Apply, &tofu, &env), Some(1));
|
||||
assert!(has_errored_state(&wd));
|
||||
assert!(last_run_failed(&wd));
|
||||
let log = std::fs::read_to_string(wd.dir.join("apply.log")).unwrap();
|
||||
assert!(
|
||||
log.lines()
|
||||
.any(|l| l.starts_with("Error:") && l.contains("errored.tfstate")),
|
||||
"{log}"
|
||||
);
|
||||
let outcome = follow(&wd, Duration::from_millis(10), |_| {})
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!outcome.ok);
|
||||
let summary = outcome.summary.unwrap();
|
||||
assert!(summary.contains("errored.tfstate"), "{summary}");
|
||||
assert!(summary.contains("Push saved state"), "{summary}");
|
||||
|
||||
// Launching anything there now is refused, naming the recovery.
|
||||
let err = materialize(
|
||||
root.path(),
|
||||
ModuleKind::PermissionsBoundary,
|
||||
Deployment::Boundary,
|
||||
bucket,
|
||||
"us-east-1",
|
||||
&boundary_vars("us-east-1"),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("errored.tfstate"), "{err}");
|
||||
assert!(err.contains("tofu state push errored.tfstate"), "{err}");
|
||||
|
||||
// The recovery: push it back through the runner; it is set aside once
|
||||
// pushed, and the folder can be used again.
|
||||
let pushed = fake_tofu(
|
||||
bin.path(),
|
||||
"[ \"$1\" = init ] && exit 0\n[ \"$1 $2 $3\" = 'state push errored.tfstate' ] || exit 9\necho pushed",
|
||||
);
|
||||
assert_eq!(run_runner(&wd.dir, TofuOp::PushState, &pushed, &env), Some(0));
|
||||
assert!(!has_errored_state(&wd));
|
||||
assert!(wd.dir.join("errored.tfstate.pushed").exists());
|
||||
assert!(!last_run_failed(&wd));
|
||||
assert!(materialize(
|
||||
root.path(),
|
||||
ModuleKind::PermissionsBoundary,
|
||||
Deployment::Boundary,
|
||||
bucket,
|
||||
"us-east-1",
|
||||
&boundary_vars("us-east-1"),
|
||||
)
|
||||
.is_ok());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_failed_push_keeps_the_saved_state() {
|
||||
let _turn = runner_turn();
|
||||
let bin = tempfile::tempdir().unwrap();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let wd = Workdir {
|
||||
dir: tmp.path().to_path_buf(),
|
||||
};
|
||||
std::fs::write(wd.dir.join("errored.tfstate"), "{}").unwrap();
|
||||
let tofu = fake_tofu(bin.path(), "[ \"$1\" = init ] && exit 0\nexit 1");
|
||||
let env = vec![("PATH".to_string(), "/usr/bin:/bin".to_string())];
|
||||
assert_eq!(run_runner(&wd.dir, TofuOp::PushState, &tofu, &env), Some(1));
|
||||
assert!(has_errored_state(&wd));
|
||||
}
|
||||
|
||||
/// materialize checks for a running deploy under `start.lock`, so a second
|
||||
/// app instance between its check and its start can't interleave.
|
||||
#[test]
|
||||
fn materialize_waits_its_turn_on_the_start_lock() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let bucket = "triple-c-tfstate-123456789012-us-east-1";
|
||||
let wd = workdir_for(root.path(), Deployment::Boundary, bucket).unwrap();
|
||||
std::fs::create_dir_all(&wd.dir).unwrap();
|
||||
let starting = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.open(wd.dir.join("start.lock"))
|
||||
.unwrap();
|
||||
starting.try_lock().unwrap();
|
||||
let err = materialize(
|
||||
root.path(),
|
||||
ModuleKind::PermissionsBoundary,
|
||||
Deployment::Boundary,
|
||||
bucket,
|
||||
"us-east-1",
|
||||
&boundary_vars("us-east-1"),
|
||||
)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("already"), "{err}");
|
||||
assert!(!wd.dir.join("backend.hcl").exists(), "materialize wrote under another's lock");
|
||||
drop(starting);
|
||||
}
|
||||
@@ -101,10 +101,13 @@ pub fn environment_parameter_name(env: &str) -> String {
|
||||
format!("/triple-c/environments/{env}")
|
||||
}
|
||||
|
||||
/// The first 12 hex characters of `sha256(aws:userid)`. A `UserId` holds a
|
||||
/// `:`, which IAM role names reject, so per-user names use this instead.
|
||||
pub fn owner_key(user_id: &str) -> String {
|
||||
Sha256::digest(user_id.as_bytes())
|
||||
/// The first 12 hex characters of `sha256("<region>:<aws:userid>")`. A
|
||||
/// `UserId` holds a `:`, which IAM role names reject, so per-user names use
|
||||
/// this instead. The region is part of it because role names are
|
||||
/// account-global while environments are regional: the same user in the same
|
||||
/// environment name in two regions gets two sets of roles.
|
||||
pub fn owner_key(region: &str, user_id: &str) -> String {
|
||||
Sha256::digest(format!("{region}:{user_id}").as_bytes())
|
||||
.iter()
|
||||
.take(6)
|
||||
.map(|b| format!("{b:02x}"))
|
||||
@@ -230,7 +233,7 @@ pub fn onboarding_vars(env: &str, region: &str, owner_id: &str) -> serde_json::V
|
||||
"environment_name": env,
|
||||
"region": region,
|
||||
"owner_id": owner_id,
|
||||
"owner_key": owner_key(owner_id),
|
||||
"owner_key": owner_key(region, owner_id),
|
||||
"bedrock_on_task_role": false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -163,18 +163,41 @@ fn environment_names_are_validated() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_user_and_environment_in_two_regions_do_not_collide() {
|
||||
// IAM role names are account-global but environments are regional: the
|
||||
// same user joining "dev" in two regions needs distinct roles (and
|
||||
// distinct onboarding state keys, though the buckets differ anyway).
|
||||
let user = "AROAEXAMPLEID:alice@example.com";
|
||||
let west = owner_key("us-west-2", user);
|
||||
let east = owner_key("us-east-1", user);
|
||||
assert_ne!(west, east);
|
||||
let (wt, we) = user_role_names("dev", &west);
|
||||
let (et, ee) = user_role_names("dev", &east);
|
||||
assert_ne!(wt, et);
|
||||
assert_ne!(we, ee);
|
||||
assert_ne!(
|
||||
state_key(Deployment::User { env: "dev", owner_key: &west }),
|
||||
state_key(Deployment::User { env: "dev", owner_key: &east })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owner_keys_are_stable_and_role_safe() {
|
||||
let a = owner_key("AROAEXAMPLEID:alice@example.com");
|
||||
let a = owner_key("us-west-2", "AROAEXAMPLEID:alice@example.com");
|
||||
assert_eq!(a.len(), 12);
|
||||
assert!(
|
||||
a.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')),
|
||||
"{a}"
|
||||
);
|
||||
assert_eq!(a, owner_key("AROAEXAMPLEID:alice@example.com"));
|
||||
assert_ne!(a, owner_key("AROAEXAMPLEID:bob@example.com"));
|
||||
// The key is the first 12 hex characters of the SHA-256 of the user ID.
|
||||
assert_eq!(owner_key("AIDAEXAMPLE"), sha256_prefix("AIDAEXAMPLE"));
|
||||
assert_eq!(a, owner_key("us-west-2", "AROAEXAMPLEID:alice@example.com"));
|
||||
assert_ne!(a, owner_key("us-west-2", "AROAEXAMPLEID:bob@example.com"));
|
||||
// The key is the first 12 hex characters of the SHA-256 of
|
||||
// "<region>:<user ID>".
|
||||
assert_eq!(
|
||||
owner_key("eu-west-1", "AIDAEXAMPLE"),
|
||||
sha256_prefix("eu-west-1:AIDAEXAMPLE")
|
||||
);
|
||||
|
||||
let env = "abcdefghij0123456789";
|
||||
assert_eq!(env.len(), 20);
|
||||
@@ -259,6 +282,61 @@ fn subnet_availability_zones_are_stable_once_chosen() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_existing_network_is_checked_before_anything_is_built() {
|
||||
// `existing` takes the user's VPC and subnets on trust otherwise: the
|
||||
// module looks the subnets up and refuses ones outside var.vpc_id or in
|
||||
// one availability zone (the onboarding module's own check), before the
|
||||
// security group, the first thing built in that VPC.
|
||||
let body = parsed(ModuleKind::Environment);
|
||||
let lookups: Vec<_> = top_blocks(&body, "data")
|
||||
.filter(|b| label(b, 0) == Some("aws_subnet"))
|
||||
.collect();
|
||||
assert_eq!(lookups.len(), 1, "one aws_subnet lookup");
|
||||
let lookup = lookups[0];
|
||||
assert_eq!(label(lookup, 1), Some("existing"));
|
||||
let count = render(attr(&lookup.body, "count").expect("count"));
|
||||
assert!(count.contains("var.network_mode") && count.contains("\"existing\""), "{count}");
|
||||
assert!(count.contains('2'), "{count}");
|
||||
let id = render(attr(&lookup.body, "id").expect("id"));
|
||||
assert!(id.contains("var.subnet_ids[count.index]"), "{id}");
|
||||
|
||||
let sg = resource(&body, "aws_security_group", "tasks");
|
||||
let lifecycle = top_blocks(&sg.body, "lifecycle").next().expect("lifecycle");
|
||||
let pre = top_blocks(&lifecycle.body, "precondition")
|
||||
.next()
|
||||
.expect("a precondition on the task security group");
|
||||
let cond = render(attr(&pre.body, "condition").expect("condition"));
|
||||
for needle in [
|
||||
"data.aws_subnet.existing",
|
||||
".vpc_id == var.vpc_id",
|
||||
"availability_zone",
|
||||
"distinct",
|
||||
] {
|
||||
assert!(cond.contains(needle), "{needle} missing from {cond}");
|
||||
}
|
||||
assert!(attr(&pre.body, "error_message").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_onboarding_completion_output_waits_for_every_resource() {
|
||||
// Detection reads Joined only from a state holding this output, so it
|
||||
// must depend on every resource the module makes.
|
||||
let body = parsed(ModuleKind::UserOnboard);
|
||||
let out = top_blocks(&body, "output")
|
||||
.find(|b| label(b, 0) == Some("onboarding_complete"))
|
||||
.expect("an onboarding_complete output");
|
||||
assert_eq!(attr(&out.body, "value"), Some(&Expression::Bool(true)));
|
||||
let deps = render(attr(&out.body, "depends_on").expect("depends_on"));
|
||||
let mut n = 0;
|
||||
for r in top_blocks(&body, "resource") {
|
||||
let addr = format!("{}.{}", label(r, 0).unwrap(), label(r, 1).unwrap());
|
||||
assert!(deps.contains(&addr), "onboarding_complete doesn't wait for {addr}: {deps}");
|
||||
n += 1;
|
||||
}
|
||||
assert!(n >= 9, "only {n} resources");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_module_versions_agree() {
|
||||
assert_eq!(ENVIRONMENT_MODULE_VERSION, 1);
|
||||
@@ -767,7 +845,7 @@ fn every_onboarding_role_carries_the_boundary_and_owner_tag() {
|
||||
// module doesn't spell out).
|
||||
let roles = resources(&body, "aws_iam_role");
|
||||
assert_eq!(roles.len(), 2, "task and exec roles");
|
||||
let key = owner_key("AROAEXAMPLE:alice");
|
||||
let key = owner_key("us-west-2", "AROAEXAMPLE:alice");
|
||||
let (task, exec) = user_role_names("dev", &key);
|
||||
for (name, want) in [("task", task), ("exec", exec)] {
|
||||
let role = resource(&body, "aws_iam_role", name);
|
||||
@@ -966,7 +1044,7 @@ fn the_environment_security_group_gains_no_ingress() {
|
||||
assert_eq!(groups.len(), 1);
|
||||
let sg = groups[0];
|
||||
assert_eq!(label(sg, 1), Some("efs"));
|
||||
let key = owner_key("AROAEXAMPLE:alice");
|
||||
let key = owner_key("us-west-2", "AROAEXAMPLE:alice");
|
||||
let name = expand_locals(&body, &template_text(attr(&sg.body, "name").unwrap()))
|
||||
.replace("${var.environment_name}", "dev")
|
||||
.replace("${var.owner_key}", &key);
|
||||
@@ -1151,7 +1229,7 @@ fn onboarding_vars_name_the_owner() {
|
||||
"environment_name": "dev",
|
||||
"region": "us-west-2",
|
||||
"owner_id": owner,
|
||||
"owner_key": owner_key(owner),
|
||||
"owner_key": owner_key("us-west-2", owner),
|
||||
"bedrock_on_task_role": false,
|
||||
})
|
||||
);
|
||||
|
||||
@@ -38,8 +38,9 @@ use aws_sdk_s3::error::ProvideErrorMetadata;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use crate::aws::environments::{
|
||||
ensure_state_bucket, scan, LIVE_LOCK_SECS, DetectedEnvironment, EnvironmentAction, EnvironmentInfo,
|
||||
EnvironmentScan, EnvironmentState, Knowable, OnboardingState, SdkDetectApi,
|
||||
ensure_state_bucket, scan, state_bucket_policy, LIVE_LOCK_SECS, DetectedEnvironment,
|
||||
EnvironmentAction, EnvironmentInfo, EnvironmentScan, EnvironmentState, Knowable, LocalRun,
|
||||
OnboardingState, SdkDetectApi,
|
||||
};
|
||||
use crate::aws::tofu::{
|
||||
self, backend_hcl, StartError, TofuEvent, TofuOp, TofuOutcome, Workdir,
|
||||
@@ -239,6 +240,7 @@ pub(crate) fn require_action<'a>(
|
||||
EnvironmentAction::Destroy => "Destroy",
|
||||
EnvironmentAction::Follow => "Follow",
|
||||
EnvironmentAction::Unlock => "Unlock",
|
||||
EnvironmentAction::PushState => "Push saved state",
|
||||
}
|
||||
))
|
||||
}
|
||||
@@ -256,6 +258,30 @@ pub(crate) fn unlock_refusal(scan: &EnvironmentScan, name: &str) -> Result<(), S
|
||||
}
|
||||
}
|
||||
|
||||
/// Unlock the caller's own onboarding state: only their own owner key, and
|
||||
/// only a stale lock no local runner holds (detection offers Unlock on the
|
||||
/// onboarding).
|
||||
pub(crate) fn onboarding_unlock_refusal(
|
||||
scan: &EnvironmentScan,
|
||||
name: &str,
|
||||
owner_key: &str,
|
||||
) -> Result<(), String> {
|
||||
if owner_key != scan.owner_key {
|
||||
return Err("Only your own onboarding's state lock can be removed from the app".into());
|
||||
}
|
||||
let env = find(scan, name).ok_or_else(|| format!("No environment named \"{name}\" was found"))?;
|
||||
match &env.onboarding {
|
||||
Some(OnboardingState::Incomplete { lock: Some(l) })
|
||||
if !l.local_process && env.onboarding_actions.contains(&EnvironmentAction::Unlock) =>
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(format!(
|
||||
"Your onboarding to \"{name}\" has no stale state lock to remove"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Self-onboarding needs the boundary (not known missing), an environment
|
||||
/// that can be joined, and no onboarding already running.
|
||||
pub(crate) fn onboard_refusal(scan: &EnvironmentScan, name: &str) -> Result<(), String> {
|
||||
@@ -263,7 +289,7 @@ pub(crate) fn onboard_refusal(scan: &EnvironmentScan, name: &str) -> Result<(),
|
||||
return Err("The account has no Triple-C permissions boundary yet".into());
|
||||
}
|
||||
let env = require_action(scan, name, EnvironmentAction::Join)?;
|
||||
if env.onboarding == Some(OnboardingState::InProgress) {
|
||||
if matches!(env.onboarding, Some(OnboardingState::InProgress { .. })) {
|
||||
return Err(format!(
|
||||
"Your onboarding to \"{name}\" is already in progress"
|
||||
));
|
||||
@@ -313,6 +339,26 @@ pub(crate) fn destroy_refusal<'a>(
|
||||
name: &str,
|
||||
) -> Result<&'a DetectedEnvironment, String> {
|
||||
let env = require_action(scan, name, EnvironmentAction::Destroy)?;
|
||||
// Each onboarded user's stack holds the environment's security group (a
|
||||
// mount-target group references it) and reads its record: destroying
|
||||
// the environment under them fails part-way and strands their stacks.
|
||||
match env.onboarded_users {
|
||||
Some(0) => {}
|
||||
Some(n) => {
|
||||
return Err(format!(
|
||||
"Environment \"{name}\" still has {n} onboarded user{} (state under \
|
||||
users/{name}/); remove the onboarded users' stacks first (tofu destroy from each \
|
||||
user's onboarding bundle)",
|
||||
if n == 1 { "" } else { "s" }
|
||||
))
|
||||
}
|
||||
None => {
|
||||
return Err(format!(
|
||||
"The state bucket can't list users onboarded to \"{name}\", so it can't be \
|
||||
destroyed from the app"
|
||||
))
|
||||
}
|
||||
}
|
||||
if env.info.is_some() {
|
||||
return Err(format!(
|
||||
"Environment \"{name}\" has a valid record, so it may be working; it can't be \
|
||||
@@ -384,10 +430,29 @@ fn bundle_readme(d: Deployment, account: &str, region: &str, bucket: &str, key:
|
||||
.to_string()
|
||||
}
|
||||
};
|
||||
let location = if region == "us-east-1" {
|
||||
String::new()
|
||||
// The admin policy allows s3:CreateBucket only with the component tag in
|
||||
// the request (aws:RequestTag), so it goes on the create; a later
|
||||
// put-bucket-tagging can't satisfy that. us-east-1 refuses a
|
||||
// LocationConstraint.
|
||||
let tags = r#""Tags":[{"Key":"triple-c:component","Value":"state"}]"#;
|
||||
let create_config = if region == "us-east-1" {
|
||||
format!("{{{tags}}}")
|
||||
} else {
|
||||
format!(" --create-bucket-configuration LocationConstraint={region}")
|
||||
format!(r#"{{"LocationConstraint":"{region}",{tags}}}"#)
|
||||
};
|
||||
let policy = state_bucket_policy(bucket);
|
||||
let credentials = match d {
|
||||
Deployment::Boundary => format!(
|
||||
"- Credentials of an account administrator for account {account} WITHOUT
|
||||
the Triple-C environment-admin policies attached: those policies deny
|
||||
changing or deleting the boundary policy to anyone holding them, account
|
||||
administrators included. (This bundle needs iam:CreatePolicy and, to
|
||||
remove it, iam:DeletePolicy on triple-c-permissions-boundary.)"
|
||||
),
|
||||
_ => format!(
|
||||
"- Credentials for account {account} that carry the Triple-C environment-admin
|
||||
policies."
|
||||
),
|
||||
};
|
||||
format!(
|
||||
"Triple-C admin bundle
|
||||
@@ -403,8 +468,7 @@ Requirements
|
||||
------------
|
||||
- OpenTofu 1.10 or later, or Terraform 1.10 or later. Both are needed for
|
||||
S3-native state locking (use_lockfile in backend.hcl).
|
||||
- Credentials for account {account} that carry the Triple-C environment-admin
|
||||
policies.
|
||||
{credentials}
|
||||
- .terraform.lock.hcl pins the AWS provider's hashes for OpenTofu
|
||||
(registry.opentofu.org). With Terraform, first run
|
||||
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
|
||||
@@ -415,13 +479,14 @@ Requirements
|
||||
-------------------
|
||||
The bucket {bucket} must exist first. Either deploy anything from
|
||||
Triple-C once with this account and region (the app creates and configures
|
||||
it), or create it by hand (POSIX shell syntax):
|
||||
it), or create it by hand exactly as the app does (POSIX shell syntax; an
|
||||
AWS CLI v2 recent enough that create-bucket accepts Tags, e.g. 2.39):
|
||||
|
||||
aws s3api create-bucket --bucket {bucket} --region {region}{location}
|
||||
aws s3api create-bucket --bucket {bucket} --region {region} --create-bucket-configuration '{create_config}'
|
||||
aws s3api put-bucket-versioning --bucket {bucket} --region {region} --expected-bucket-owner {account} --versioning-configuration Status=Enabled
|
||||
aws s3api put-bucket-encryption --bucket {bucket} --region {region} --expected-bucket-owner {account} --server-side-encryption-configuration '{{\"Rules\":[{{\"ApplyServerSideEncryptionByDefault\":{{\"SSEAlgorithm\":\"AES256\"}}}}]}}'
|
||||
aws s3api put-public-access-block --bucket {bucket} --region {region} --expected-bucket-owner {account} --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
|
||||
aws s3api put-bucket-tagging --bucket {bucket} --region {region} --expected-bucket-owner {account} --tagging 'TagSet=[{{Key=triple-c:component,Value=state}}]'
|
||||
aws s3api put-bucket-policy --bucket {bucket} --region {region} --expected-bucket-owner {account} --policy '{policy}'
|
||||
|
||||
2. Deploy
|
||||
---------
|
||||
@@ -758,8 +823,12 @@ async fn detect(ctx: &Ctx) -> Result<EnvironmentScan, AwsError> {
|
||||
let (root, bucket) = (ctx.root.clone(), ctx.bucket());
|
||||
let running = move |d: Deployment| {
|
||||
tofu::workdir_for(&root, d, &bucket)
|
||||
.map(|wd| tofu::is_running(&wd))
|
||||
.unwrap_or(false)
|
||||
.map(|wd| LocalRun {
|
||||
running: tofu::is_running(&wd),
|
||||
failed: tofu::last_run_failed(&wd),
|
||||
errored_state: tofu::has_errored_state(&wd),
|
||||
})
|
||||
.unwrap_or_default()
|
||||
};
|
||||
scan(&api, &ctx.who, &ctx.region, &running).await
|
||||
}
|
||||
@@ -833,8 +902,9 @@ fn cancellable(wd: &Workdir) -> bool {
|
||||
cfg!(unix) && tofu::runner_pid(wd).is_some()
|
||||
}
|
||||
|
||||
/// Only the main window shows deploys; no other window gets the events.
|
||||
fn emit_progress(app: &AppHandle, p: &DeployProgress) {
|
||||
if let Err(e) = app.emit(PROGRESS_EVENT, p) {
|
||||
if let Err(e) = app.emit_to("main", PROGRESS_EVENT, p) {
|
||||
log::warn!("Could not emit deploy progress: {e}");
|
||||
}
|
||||
}
|
||||
@@ -882,6 +952,21 @@ fn install_follower(
|
||||
Ok((op_id, gate))
|
||||
}
|
||||
|
||||
/// The runner's whole environment ([`tofu::child_env`]): a keys
|
||||
/// connection's keys come from the keychain and go nowhere else.
|
||||
fn runner_env(ctx: &Ctx) -> Result<Vec<(String, String)>, AwsError> {
|
||||
let HostKind::Aws { auth, .. } = &ctx.conn.kind;
|
||||
let keys = match auth {
|
||||
AwsAuth::Keys { keyring_ref } => Some(
|
||||
secure::get_aws_keys(keyring_ref)
|
||||
.map_err(other)?
|
||||
.ok_or(AwsError::KeysMissing)?,
|
||||
),
|
||||
AwsAuth::Profile { .. } => None,
|
||||
};
|
||||
tofu::child_env(&ctx.conn, keys.as_ref(), &ctx.root, std::env::vars())
|
||||
}
|
||||
|
||||
/// Ensure OpenTofu and the state bucket, write the work folder and start a
|
||||
/// detached `init` + `op`. Returns the op id its progress is emitted under
|
||||
/// and the gate the command opens just before returning it.
|
||||
@@ -905,16 +990,7 @@ async fn launch(
|
||||
let bucket = ensure_state_bucket(&ctx.cfg, &ctx.who.account, &ctx.region).await?;
|
||||
let wd = tofu::materialize(&ctx.root, module_kind(d), d, &bucket, &ctx.region, vars)?;
|
||||
|
||||
let HostKind::Aws { auth, .. } = &ctx.conn.kind;
|
||||
let keys = match auth {
|
||||
AwsAuth::Keys { keyring_ref } => Some(
|
||||
secure::get_aws_keys(keyring_ref)
|
||||
.map_err(other)?
|
||||
.ok_or(AwsError::KeysMissing)?,
|
||||
),
|
||||
AwsAuth::Profile { .. } => None,
|
||||
};
|
||||
let env = tofu::child_env(&ctx.conn, keys.as_ref(), &ctx.root, std::env::vars())?;
|
||||
let env = runner_env(ctx)?;
|
||||
|
||||
let start_wd = wd.clone();
|
||||
let started = tokio::task::spawn_blocking(move || {
|
||||
@@ -1042,9 +1118,9 @@ pub async fn destroy_incomplete_aws_environment(
|
||||
opened(launch(app, &ctx, &key, &vars, TofuOp::Destroy).await)
|
||||
}
|
||||
|
||||
/// Delete an environment's stale `.tflock`. Only an environment's lock,
|
||||
/// only when detection offers Unlock and no runner on this machine holds
|
||||
/// the deployment. The delete is conditional on the ETag of the lock object
|
||||
/// Delete a stale `.tflock`: an environment's, or the caller's own
|
||||
/// onboarding's (`users/<env>/<their key>/…`), only when detection offers
|
||||
/// Unlock on it and no runner on this machine holds the deployment. The delete is conditional on the ETag of the lock object
|
||||
/// as just re-read (and re-checked stale), so a lock taken since is never
|
||||
/// removed; there is no unconditional fallback.
|
||||
#[tauri::command]
|
||||
@@ -1055,12 +1131,19 @@ pub async fn unlock_aws_state(
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<(), AwsError> {
|
||||
let key = parse_state_key(&state_key)?;
|
||||
let DeploymentKey::Environment(name) = &key else {
|
||||
return Err(other("Only an environment's state lock can be removed from the app"));
|
||||
};
|
||||
if key == DeploymentKey::Boundary {
|
||||
return Err(other(
|
||||
"The permissions boundary's state lock can't be removed from the app",
|
||||
));
|
||||
}
|
||||
let ctx = context(&state, &connection_id, ®ion).await?;
|
||||
let found = detect(&ctx).await?;
|
||||
unlock_refusal(&found, name).map_err(other)?;
|
||||
match &key {
|
||||
DeploymentKey::Environment(name) => unlock_refusal(&found, name),
|
||||
DeploymentKey::User { env, owner_key } => onboarding_unlock_refusal(&found, env, owner_key),
|
||||
DeploymentKey::Boundary => unreachable!("refused above"),
|
||||
}
|
||||
.map_err(other)?;
|
||||
if tofu::is_running(&ctx.workdir(key.deployment())?) {
|
||||
return Err(other("A deploy on this machine holds the lock"));
|
||||
}
|
||||
@@ -1159,6 +1242,50 @@ pub async fn follow_aws_deployment(
|
||||
Ok(op_id)
|
||||
}
|
||||
|
||||
/// Push the state a failed run on this machine couldn't save
|
||||
/// (`errored.tfstate`) back to the bucket: `tofu state push errored.tfstate`
|
||||
/// through the same detached runner and environment as a deploy, followed
|
||||
/// like one. Once pushed the file is set aside and the deployment can be
|
||||
/// re-applied (until then [`tofu::materialize`] refuses).
|
||||
#[tauri::command]
|
||||
pub async fn push_aws_saved_state(
|
||||
connection_id: String,
|
||||
region: String,
|
||||
state_key: String,
|
||||
app: AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<String, AwsError> {
|
||||
let key = parse_state_key(&state_key)?;
|
||||
let ctx = context(&state, &connection_id, ®ion).await?;
|
||||
opened(launch_push(app, &ctx, &key).await)
|
||||
}
|
||||
|
||||
async fn launch_push(app: AppHandle, ctx: &Ctx, key: &DeploymentKey) -> Result<(String, Gate), AwsError> {
|
||||
let d = key.deployment();
|
||||
let label = key.label();
|
||||
let wd = ctx.workdir(d)?;
|
||||
if tofu::is_running(&wd) {
|
||||
return Err(start_error(StartError::AlreadyRunning, &label));
|
||||
}
|
||||
if !tofu::has_errored_state(&wd) {
|
||||
return Err(other(format!(
|
||||
"There is no saved state of {label} on this machine to push"
|
||||
)));
|
||||
}
|
||||
let _launching = LaunchGuard::take(&wd.dir, &label)?;
|
||||
let tofu_bin = tofu::ensure_tofu(&ctx.root).await?;
|
||||
let env = runner_env(ctx)?;
|
||||
let start_wd = wd.clone();
|
||||
let started = tokio::task::spawn_blocking(move || {
|
||||
tofu::start_detached(&tofu_bin, &start_wd, TofuOp::PushState, &env)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| other(format!("The push could not be started: {e}")))?
|
||||
.map_err(|e| start_error(e, &label))?;
|
||||
let can_cancel = cfg!(unix) && started.pid.is_some();
|
||||
install_follower(app, wd, state_key(d), &label, can_cancel, true)
|
||||
}
|
||||
|
||||
/// Cancel: interrupt the runner, which stops OpenTofu gracefully.
|
||||
#[tauri::command]
|
||||
pub async fn cancel_aws_deployment(
|
||||
@@ -1189,7 +1316,7 @@ pub async fn onboard_aws_user(
|
||||
onboard_refusal(&found, &env).map_err(other)?;
|
||||
let vars = onboarding_vars(&env, &ctx.region, &owner);
|
||||
let key = DeploymentKey::User {
|
||||
owner_key: owner_key(&owner),
|
||||
owner_key: owner_key(&ctx.region, &owner),
|
||||
env,
|
||||
};
|
||||
opened(launch(app, &ctx, &key, &vars, TofuOp::Apply).await)
|
||||
@@ -1273,7 +1400,7 @@ pub async fn save_aws_admin_bundle(
|
||||
let vars = onboarding_vars(&env, ®ion_ok, &owner);
|
||||
(
|
||||
DeploymentKey::User {
|
||||
owner_key: owner_key(&owner),
|
||||
owner_key: owner_key(®ion_ok, &owner),
|
||||
env,
|
||||
},
|
||||
vars,
|
||||
|
||||
@@ -43,6 +43,8 @@ fn env(name: &str, state: EnvironmentState, actions: Vec<EnvironmentAction>) ->
|
||||
actions,
|
||||
info: None,
|
||||
onboarding: None,
|
||||
onboarding_actions: Vec::new(),
|
||||
onboarded_users: Some(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +53,7 @@ fn scan(boundary: Knowable, environments: Vec<DetectedEnvironment>) -> Environme
|
||||
region: REGION.into(),
|
||||
account: ACCOUNT.into(),
|
||||
owner_id: USER_ID.into(),
|
||||
owner_key: owner_key(USER_ID),
|
||||
owner_key: owner_key(REGION, USER_ID),
|
||||
state_bucket: Knowable::Yes,
|
||||
boundary,
|
||||
environments,
|
||||
@@ -70,7 +72,7 @@ fn lock(age_secs: u64, local_process: bool) -> LockInfo {
|
||||
|
||||
#[test]
|
||||
fn only_our_state_keys_are_accepted() {
|
||||
let ok = owner_key(USER_ID);
|
||||
let ok = owner_key(REGION, USER_ID);
|
||||
let good = [
|
||||
(
|
||||
"environments/dev/terraform.tfstate".to_string(),
|
||||
@@ -189,7 +191,7 @@ fn the_vpc_is_read_from_the_state_outputs() {
|
||||
#[test]
|
||||
fn bundles_contain_the_module_backend_vars_and_readme() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ok = owner_key(USER_ID);
|
||||
let ok = owner_key(REGION, USER_ID);
|
||||
let d = Deployment::User { env: "dev", owner_key: &ok };
|
||||
let vars = onboarding_vars("dev", REGION, USER_ID);
|
||||
let written = write_bundle(dir.path(), d, ACCOUNT, REGION, &vars).unwrap();
|
||||
@@ -225,7 +227,29 @@ fn bundles_contain_the_module_backend_vars_and_readme() {
|
||||
assert!(readme.contains(needle), "README lacks {needle:?}:\n{readme}");
|
||||
}
|
||||
// Outside us-east-1 the bucket needs a location constraint.
|
||||
assert!(readme.contains(&format!("LocationConstraint={REGION}")), "{readme}");
|
||||
assert!(readme.contains(&format!("\"LocationConstraint\":\"{REGION}\"")), "{readme}");
|
||||
// The admin policy allows s3:CreateBucket only with the component tag
|
||||
// in the request, so the tag goes on the create itself; and the bucket
|
||||
// is configured as the app configures it, TLS-only policy included.
|
||||
let create = readme
|
||||
.lines()
|
||||
.find(|l| l.contains("aws s3api create-bucket"))
|
||||
.unwrap();
|
||||
assert!(
|
||||
create.contains(r#""Tags":[{"Key":"triple-c:component","Value":"state"}]"#),
|
||||
"{create}"
|
||||
);
|
||||
for needle in [
|
||||
"put-bucket-versioning",
|
||||
"put-bucket-encryption",
|
||||
"put-public-access-block",
|
||||
"put-bucket-policy",
|
||||
"aws:SecureTransport",
|
||||
"DenyInsecureTransport",
|
||||
] {
|
||||
assert!(readme.contains(needle), "README lacks {needle:?}:\n{readme}");
|
||||
}
|
||||
assert!(!readme.contains("put-bucket-tagging"), "a later tag can't satisfy the create");
|
||||
|
||||
// Writing again over our own files is fine...
|
||||
write_bundle(dir.path(), d, ACCOUNT, REGION, &vars).unwrap();
|
||||
@@ -247,6 +271,7 @@ fn a_us_east_1_bundle_creates_its_bucket_without_a_location_constraint() {
|
||||
let readme = fs::read_to_string(dir.path().join("README.txt")).unwrap();
|
||||
assert!(readme.contains("aws s3api create-bucket"), "{readme}");
|
||||
assert!(!readme.contains("LocationConstraint"), "{readme}");
|
||||
assert!(readme.contains(r#""Tags":[{"Key":"triple-c:component","Value":"state"}]"#), "{readme}");
|
||||
assert!(readme.contains("tofu destroy"), "{readme}");
|
||||
for (name, _) in module_files(ModuleKind::Environment) {
|
||||
assert!(dir.path().join(name).is_file(), "{name}");
|
||||
@@ -316,7 +341,7 @@ fn onboarding_needs_a_joinable_environment_and_the_boundary() {
|
||||
let mut ready = env("dev", EnvironmentState::Ready, vec![Join]);
|
||||
ready.onboarding = Some(OnboardingState::NotJoined);
|
||||
let mut busy = env("busy", EnvironmentState::Ready, vec![Join]);
|
||||
busy.onboarding = Some(OnboardingState::InProgress);
|
||||
busy.onboarding = Some(OnboardingState::InProgress { lock: None });
|
||||
let half = env("half", EnvironmentState::Incomplete { lock: None }, vec![Repair, Destroy]);
|
||||
let s = scan(Knowable::Yes, vec![ready.clone(), busy, half]);
|
||||
assert!(onboard_refusal(&s, "dev").is_ok());
|
||||
@@ -461,6 +486,51 @@ fn destroy_needs_the_action_no_record_and_no_lock() {
|
||||
assert_eq!(destroy_refusal(&s, "half").unwrap().name, "half");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destroy_is_refused_while_users_are_onboarded() {
|
||||
use EnvironmentAction::*;
|
||||
let mut onboarded = env("half", EnvironmentState::Incomplete { lock: None }, vec![Repair, Destroy]);
|
||||
onboarded.onboarded_users = Some(2);
|
||||
let mut unknown = env("blind", EnvironmentState::Incomplete { lock: None }, vec![Repair, Destroy]);
|
||||
unknown.onboarded_users = None;
|
||||
let s = scan(Knowable::Yes, vec![onboarded, unknown]);
|
||||
let e = destroy_refusal(&s, "half").unwrap_err();
|
||||
assert!(e.contains("remove the onboarded users' stacks first"), "{e}");
|
||||
assert!(e.contains("users/half/"), "{e}");
|
||||
// Without a listing there's no telling, and nothing to destroy from.
|
||||
assert!(destroy_refusal(&s, "blind").unwrap_err().contains("can't list"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_your_own_stale_onboarding_lock_can_be_removed() {
|
||||
use EnvironmentAction::*;
|
||||
let mut stale = env("dev", EnvironmentState::Ready, vec![Join]);
|
||||
stale.onboarding = Some(OnboardingState::Incomplete { lock: Some(lock(9000, false)) });
|
||||
stale.onboarding_actions = vec![Unlock];
|
||||
let mut live = env("live", EnvironmentState::Ready, vec![Join]);
|
||||
live.onboarding = Some(OnboardingState::InProgress { lock: Some(lock(10, false)) });
|
||||
let mut none = env("none", EnvironmentState::Ready, vec![Join]);
|
||||
none.onboarding = Some(OnboardingState::Incomplete { lock: None });
|
||||
let s = scan(Knowable::Yes, vec![stale, live, none]);
|
||||
let mine = owner_key(REGION, USER_ID);
|
||||
assert!(onboarding_unlock_refusal(&s, "dev", &mine).is_ok());
|
||||
let e = onboarding_unlock_refusal(&s, "dev", "0123456789ab").unwrap_err();
|
||||
assert!(e.contains("your own"), "{e}");
|
||||
assert!(onboarding_unlock_refusal(&s, "live", &mine).is_err());
|
||||
assert!(onboarding_unlock_refusal(&s, "none", &mine).is_err());
|
||||
assert!(onboarding_unlock_refusal(&s, "missing", &mine).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_boundary_bundle_names_an_administrator_without_the_admin_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_bundle(dir.path(), Deployment::Boundary, ACCOUNT, REGION, &boundary_vars(REGION)).unwrap();
|
||||
let readme = fs::read_to_string(dir.path().join("README.txt")).unwrap();
|
||||
assert!(readme.contains("account administrator"), "{readme}");
|
||||
assert!(readme.contains("WITHOUT"), "{readme}");
|
||||
assert!(!readme.contains("that carry the Triple-C environment-admin"), "{readme}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_and_update_are_refused_under_a_held_lock() {
|
||||
use EnvironmentAction::*;
|
||||
|
||||
@@ -618,6 +618,7 @@ pub fn run() {
|
||||
commands::environment_commands::unlock_aws_state,
|
||||
commands::environment_commands::follow_aws_deployment,
|
||||
commands::environment_commands::cancel_aws_deployment,
|
||||
commands::environment_commands::push_aws_saved_state,
|
||||
commands::environment_commands::onboard_aws_user,
|
||||
commands::environment_commands::deploy_aws_permissions_boundary,
|
||||
commands::environment_commands::save_aws_admin_bundle,
|
||||
|
||||
@@ -419,4 +419,131 @@ describe("EnvironmentsPanel", () => {
|
||||
await screen.findByText("The state bucket name triple-c-tfstate-123456789012-eu-west-1 is already taken by another AWS account."),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
it("explains an environment managed elsewhere and an incomplete one", async () => {
|
||||
backend(() =>
|
||||
scan({
|
||||
environments: [
|
||||
env({ name: "shared", state: { state: "externally_managed" }, actions: ["join"] }),
|
||||
env({ name: "half", state: { state: "incomplete", lock: null }, actions: ["repair", "destroy"], info: null, onboarding: null }),
|
||||
],
|
||||
}),
|
||||
);
|
||||
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
|
||||
await open();
|
||||
const shared = await screen.findByTestId("env-shared");
|
||||
expect(within(shared).getByText("Managed outside this account's Triple-C state")).toBeInTheDocument();
|
||||
expect(within(shared).getByText(/can't be updated from here/)).toBeInTheDocument();
|
||||
const half = screen.getByTestId("env-half");
|
||||
expect(within(half).getByText(/The last change didn't finish/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("disables Repair and Destroy while a lock is held, saying Unlock first", async () => {
|
||||
const lock = { who: "bob@desk", created: "x", operation: "OperationTypeApply", age_secs: 3 * 3600, local_process: false };
|
||||
backend(() =>
|
||||
scan({ environments: [env({ state: { state: "incomplete", lock }, actions: ["repair", "destroy", "unlock"], info: null, onboarding: null })] }),
|
||||
);
|
||||
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
|
||||
await open();
|
||||
const row = await screen.findByTestId("env-dev");
|
||||
expect(within(row).getByRole("button", { name: "Repair dev" })).toBeDisabled();
|
||||
expect(within(row).getByRole("button", { name: "Destroy dev" })).toBeDisabled();
|
||||
expect(within(row).getByRole("button", { name: "Unlock dev" })).toBeEnabled();
|
||||
expect(within(row).getByText("Unlock first")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("an incomplete onboarding keeps Join and offers its own Unlock", async () => {
|
||||
const lock = { who: "me@old", created: "x", operation: "OperationTypeApply", age_secs: 3 * 3600, local_process: false };
|
||||
backend(
|
||||
() =>
|
||||
scan({
|
||||
environments: [env({ onboarding: { state: "incomplete", lock }, onboarding_actions: ["unlock"] })],
|
||||
}),
|
||||
(cmd) => {
|
||||
if (cmd === "unlock_aws_state") return undefined;
|
||||
throw new Error(`unexpected ${cmd}`);
|
||||
},
|
||||
);
|
||||
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
|
||||
await open();
|
||||
const row = await screen.findByTestId("env-dev");
|
||||
expect(within(row).getByText("Onboarding incomplete")).toBeInTheDocument();
|
||||
expect(within(row).getByText(/Your last onboarding didn't finish/)).toBeInTheDocument();
|
||||
expect(within(row).getByRole("button", { name: "Join dev" })).toBeDisabled();
|
||||
fireEvent.click(within(row).getByRole("button", { name: "Unlock my onboarding to dev" }));
|
||||
const dialog = screen.getByRole("dialog", { name: "Unlock your onboarding to dev" });
|
||||
expect(within(dialog).getByText(/me@old/)).toBeInTheDocument();
|
||||
fireEvent.change(within(dialog).getByLabelText(/Type dev to confirm/), { target: { value: "dev" } });
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Unlock" }));
|
||||
await waitFor(() =>
|
||||
expect(invoke).toHaveBeenCalledWith("unlock_aws_state", {
|
||||
connectionId: "h1",
|
||||
region: "eu-west-1",
|
||||
stateKey: "users/dev/abc123abc123/terraform.tfstate",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("pushes a saved state back from the environment and the onboarding rows", async () => {
|
||||
backend(
|
||||
() =>
|
||||
scan({
|
||||
environments: [
|
||||
env({ name: "a", state: { state: "incomplete", lock: null }, actions: ["push_state"], info: null, onboarding: null }),
|
||||
env({ name: "b", onboarding: { state: "incomplete", lock: null }, onboarding_actions: ["push_state"] }),
|
||||
],
|
||||
}),
|
||||
(cmd) => {
|
||||
if (cmd === "push_aws_saved_state") return "p1";
|
||||
throw new Error(`unexpected ${cmd}`);
|
||||
},
|
||||
);
|
||||
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
|
||||
await open();
|
||||
const a = await screen.findByTestId("env-a");
|
||||
expect(within(a).getByText(/couldn't save its state/)).toBeInTheDocument();
|
||||
fireEvent.click(within(a).getByRole("button", { name: "Push saved state of a" }));
|
||||
await waitFor(() =>
|
||||
expect(invoke).toHaveBeenCalledWith("push_aws_saved_state", {
|
||||
connectionId: "h1",
|
||||
region: "eu-west-1",
|
||||
stateKey: "environments/a/terraform.tfstate",
|
||||
}),
|
||||
);
|
||||
const b = screen.getByTestId("env-b");
|
||||
// Join would only be refused until the saved state is back.
|
||||
expect(within(b).getByRole("button", { name: "Join b" })).toBeDisabled();
|
||||
fireEvent.click(within(b).getByRole("button", { name: "Push saved state of my onboarding to b" }));
|
||||
await waitFor(() =>
|
||||
expect(invoke).toHaveBeenCalledWith("push_aws_saved_state", {
|
||||
connectionId: "h1",
|
||||
region: "eu-west-1",
|
||||
stateKey: "users/b/abc123abc123/terraform.tfstate",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("follows an onboarding running on this machine", async () => {
|
||||
backend(
|
||||
() =>
|
||||
scan({
|
||||
environments: [env({ onboarding: { state: "in_progress", lock: null }, onboarding_actions: ["follow"] })],
|
||||
}),
|
||||
async (cmd) => {
|
||||
if (cmd === "follow_aws_deployment") {
|
||||
emit(progress({ op_id: "f2", state_key: "users/dev/abc123abc123/terraform.tfstate", events: [tofuEvent("joining line")] }));
|
||||
return "f2";
|
||||
}
|
||||
throw new Error(`unexpected ${cmd}`);
|
||||
},
|
||||
);
|
||||
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
|
||||
await open();
|
||||
expect(await screen.findByText("joining line")).toBeInTheDocument();
|
||||
expect(invoke).toHaveBeenCalledWith("follow_aws_deployment", {
|
||||
connectionId: "h1",
|
||||
region: "eu-west-1",
|
||||
stateKey: "users/dev/abc123abc123/terraform.tfstate",
|
||||
});
|
||||
expect(within(screen.getByTestId("env-dev")).getByRole("button", { name: "Follow my onboarding to dev" })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
detectAwsEnvironments,
|
||||
followAwsDeployment,
|
||||
onboardAwsUser,
|
||||
pushAwsSavedState,
|
||||
repairAwsEnvironment,
|
||||
unlockAwsState,
|
||||
updateAwsEnvironment,
|
||||
@@ -15,6 +16,7 @@ import type {
|
||||
DetectedEnvironment,
|
||||
EnvironmentScan,
|
||||
HostConnection,
|
||||
LockInfo,
|
||||
ModuleKind,
|
||||
NetworkChoice,
|
||||
PermissionSummary,
|
||||
@@ -132,7 +134,14 @@ export default function EnvironmentsPanel({
|
||||
const [deployOpen, setDeployOpen] = useState(false);
|
||||
const [repairOf, setRepairOf] = useState<string | null>(null);
|
||||
const [destroyOf, setDestroyOf] = useState<{ name: string; region: string } | null>(null);
|
||||
const [unlockOf, setUnlockOf] = useState<{ env: DetectedEnvironment; region: string } | null>(null);
|
||||
/** An Unlock waiting for its typed confirmation: an environment's lock or the caller's onboarding's. */
|
||||
const [unlockOf, setUnlockOf] = useState<{
|
||||
name: string;
|
||||
region: string;
|
||||
stateKey: string;
|
||||
lock: LockInfo | null;
|
||||
onboarding: boolean;
|
||||
} | null>(null);
|
||||
const [bundle, setBundle] = useState<Bundle | null>(null);
|
||||
const [copyNote, setCopyNote] = useState<string | null>(null);
|
||||
const request = useRef(0);
|
||||
@@ -178,17 +187,21 @@ export default function EnvironmentsPanel({
|
||||
[start],
|
||||
);
|
||||
|
||||
// Reattach to a deploy running on this machine (a re-follow replays its whole log).
|
||||
// Reattach to a deploy (or the caller's onboarding) running on this machine;
|
||||
// a re-follow replays its whole log.
|
||||
useEffect(() => {
|
||||
if (!scan) return;
|
||||
for (const e of scan.environments) {
|
||||
const key = environmentStateKey(e.name);
|
||||
const reattach = (name: string, key: string, label: string) => {
|
||||
const seen = runKey(scan.region, key);
|
||||
if (e.actions.includes("follow") && !runs[seen] && !followed.current.has(seen)) {
|
||||
if (!runs[seen] && !followed.current.has(seen)) {
|
||||
followed.current.add(seen);
|
||||
void launch(scan.region, e.name, key, `Deploy of ${e.name}`, () =>
|
||||
followAwsDeployment(connection.id, scan.region, key),
|
||||
);
|
||||
void launch(scan.region, name, key, label, () => followAwsDeployment(connection.id, scan.region, key));
|
||||
}
|
||||
};
|
||||
for (const e of scan.environments) {
|
||||
if (e.actions.includes("follow")) reattach(e.name, environmentStateKey(e.name), `Deploy of ${e.name}`);
|
||||
if (e.onboarding_actions.includes("follow")) {
|
||||
reattach(e.name, onboardingStateKey(e.name, scan.owner_key), `Joining ${e.name}`);
|
||||
}
|
||||
}
|
||||
}, [scan, runs, launch, connection.id]);
|
||||
@@ -251,7 +264,19 @@ export default function EnvironmentsPanel({
|
||||
const status = stateStatus(e.state);
|
||||
const lock = stateLock(e.state);
|
||||
const has = (a: DetectedEnvironment["actions"][number]) => e.actions.includes(a);
|
||||
const mine = (a: DetectedEnvironment["actions"][number]) => e.onboarding_actions.includes(a);
|
||||
const onboarding = e.onboarding?.state;
|
||||
const myKey = onboardingStateKey(e.name, found.owner_key);
|
||||
const myLock =
|
||||
e.onboarding && (e.onboarding.state === "incomplete" || e.onboarding.state === "in_progress")
|
||||
? e.onboarding.lock
|
||||
: null;
|
||||
// Someone else's run holds the state: a re-apply or destroy would only
|
||||
// fail inside its run, so those wait for Unlock.
|
||||
const lockHeld = !!lock && !lock.local_process;
|
||||
// Join re-applies the onboarding: not under a held lock, nor before a
|
||||
// saved state is pushed back.
|
||||
const joinBlocked = (!!myLock && !myLock.local_process) || mine("push_state");
|
||||
const busy = stale || !!pending[rowKey(at, e.name)];
|
||||
const rowError = rowErrors[rowKey(at, e.name)];
|
||||
const isWaiting = waiting.has(rowKey(at, e.name));
|
||||
@@ -283,16 +308,102 @@ export default function EnvironmentsPanel({
|
||||
{e.state.state === "unreadable_record" && (
|
||||
<div className="text-[var(--error)]">The environment's record can't be used: {e.state.reason}</div>
|
||||
)}
|
||||
{e.state.state === "externally_managed" && (
|
||||
<div className="text-[var(--text-secondary)]">
|
||||
Its OpenTofu state isn't in this region's Triple-C state bucket (deployed from a bundle with another
|
||||
bucket, or you can't read it), so it can't be updated from here.
|
||||
</div>
|
||||
)}
|
||||
{e.state.state === "incomplete" && (
|
||||
<div className="text-[var(--text-secondary)]">
|
||||
{lockHeld
|
||||
? "The last change didn't finish: its run stopped while holding the state lock. Unlock first, then Repair."
|
||||
: "The last change didn't finish: the deployment has state but no working environment record."}
|
||||
</div>
|
||||
)}
|
||||
{has("push_state") && (
|
||||
<div className="text-[var(--error)]">
|
||||
The last run on this machine couldn't save its state (OpenTofu kept it in errored.tfstate). Push it back
|
||||
before anything else runs here.
|
||||
</div>
|
||||
)}
|
||||
{onboarding === "incomplete" && (
|
||||
<div className="text-[var(--text-secondary)]">
|
||||
{myLock && !myLock.local_process
|
||||
? `Your last onboarding didn't finish and still holds its state lock (${lockLine(myLock)}). Unlock it, then Join again to finish.`
|
||||
: mine("push_state")
|
||||
? "Your last onboarding didn't finish and couldn't save its state; push the saved state back, then Join again."
|
||||
: "Your last onboarding didn't finish; Join again to finish it."}
|
||||
</div>
|
||||
)}
|
||||
{!isAdmin && isWaiting && onboarding !== "joined" && (
|
||||
<div className="text-[var(--text-secondary)]">Waiting for an admin to onboard you</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-1.5 flex-wrap">
|
||||
{has("join") && onboarding !== "joined" && onboarding !== "in_progress" && (
|
||||
<Button size="sm" variant="primary" disabled={busy} aria-label={`Join ${e.name}`} onClick={() => join(found, e)}>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="primary"
|
||||
disabled={busy || joinBlocked}
|
||||
aria-label={`Join ${e.name}`}
|
||||
onClick={() => join(found, e)}
|
||||
>
|
||||
{!isAdmin && isWaiting ? "Show onboarding bundle" : "Join"}
|
||||
</Button>
|
||||
)}
|
||||
{mine("follow") && (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
aria-label={`Follow my onboarding to ${e.name}`}
|
||||
onClick={() =>
|
||||
void launch(at, e.name, myKey, `Joining ${e.name}`, () => followAwsDeployment(connection.id, at, myKey))
|
||||
}
|
||||
>
|
||||
Follow
|
||||
</Button>
|
||||
)}
|
||||
{mine("push_state") && (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
aria-label={`Push saved state of my onboarding to ${e.name}`}
|
||||
onClick={() =>
|
||||
void launch(at, e.name, myKey, `Push of the saved state of joining ${e.name}`, () =>
|
||||
pushAwsSavedState(connection.id, at, myKey),
|
||||
)
|
||||
}
|
||||
>
|
||||
Push saved state
|
||||
</Button>
|
||||
)}
|
||||
{mine("unlock") && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
disabled={busy}
|
||||
aria-label={`Unlock my onboarding to ${e.name}`}
|
||||
onClick={() => setUnlockOf({ name: e.name, region: at, stateKey: myKey, lock: myLock, onboarding: true })}
|
||||
>
|
||||
Unlock onboarding
|
||||
</Button>
|
||||
)}
|
||||
{has("push_state") && (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
aria-label={`Push saved state of ${e.name}`}
|
||||
onClick={() => {
|
||||
const key = environmentStateKey(e.name);
|
||||
void launch(at, e.name, key, `Push of the saved state of ${e.name}`, () =>
|
||||
pushAwsSavedState(connection.id, at, key),
|
||||
);
|
||||
}}
|
||||
>
|
||||
Push saved state
|
||||
</Button>
|
||||
)}
|
||||
{has("follow") && (
|
||||
<Button
|
||||
size="sm"
|
||||
@@ -323,7 +434,7 @@ export default function EnvironmentsPanel({
|
||||
{has("repair") && (
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
disabled={busy || lockHeld}
|
||||
aria-label={`Repair ${e.name}`}
|
||||
onClick={() => (e.info ? void repair(at, e.name) : setRepairOf(e.name))}
|
||||
>
|
||||
@@ -331,15 +442,32 @@ export default function EnvironmentsPanel({
|
||||
</Button>
|
||||
)}
|
||||
{has("unlock") && (
|
||||
<Button size="sm" variant="danger" disabled={busy} aria-label={`Unlock ${e.name}`} onClick={() => setUnlockOf({ env: e, region: at })}>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
disabled={busy}
|
||||
aria-label={`Unlock ${e.name}`}
|
||||
onClick={() =>
|
||||
setUnlockOf({ name: e.name, region: at, stateKey: environmentStateKey(e.name), lock, onboarding: false })
|
||||
}
|
||||
>
|
||||
Unlock
|
||||
</Button>
|
||||
)}
|
||||
{has("destroy") && (
|
||||
<Button size="sm" variant="danger" disabled={busy} aria-label={`Destroy ${e.name}`} onClick={() => setDestroyOf({ name: e.name, region: at })}>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="danger"
|
||||
disabled={busy || lockHeld}
|
||||
aria-label={`Destroy ${e.name}`}
|
||||
onClick={() => setDestroyOf({ name: e.name, region: at })}
|
||||
>
|
||||
Destroy
|
||||
</Button>
|
||||
)}
|
||||
{lockHeld && (has("repair") || has("destroy")) && (
|
||||
<span className="self-center text-xs text-[var(--text-secondary)]">Unlock first</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{rowError && (
|
||||
@@ -466,13 +594,13 @@ export default function EnvironmentsPanel({
|
||||
)}
|
||||
{unlockOf && (
|
||||
<TypedConfirmModal
|
||||
title={`Unlock ${unlockOf.env.name}`}
|
||||
name={unlockOf.env.name}
|
||||
title={unlockOf.onboarding ? `Unlock your onboarding to ${unlockOf.name}` : `Unlock ${unlockOf.name}`}
|
||||
name={unlockOf.name}
|
||||
confirmLabel="Unlock"
|
||||
onClose={() => setUnlockOf(null)}
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
await unlockAwsState(connection.id, unlockOf.region, environmentStateKey(unlockOf.env.name));
|
||||
await unlockAwsState(connection.id, unlockOf.region, unlockOf.stateKey);
|
||||
} catch (e) {
|
||||
return toAwsError(e);
|
||||
}
|
||||
@@ -481,7 +609,7 @@ export default function EnvironmentsPanel({
|
||||
}}
|
||||
>
|
||||
{(() => {
|
||||
const lock = stateLock(unlockOf.env.state);
|
||||
const lock = unlockOf.lock;
|
||||
return lock ? (
|
||||
<p>
|
||||
Held by <span className="font-mono text-[var(--text-primary)]">{lock.who || "unknown"}</span> since{" "}
|
||||
|
||||
@@ -86,7 +86,9 @@ export function stateStatus(s: EnvironmentState): { tone: StatusTone; label: str
|
||||
case "incomplete":
|
||||
return { tone: "error", label: "Incomplete" };
|
||||
case "externally_managed":
|
||||
return { tone: "ok", label: "Available" };
|
||||
// Its state isn't in this region's Triple-C bucket (an admin bundle's
|
||||
// own bucket, by hand, or not readable here), so Update isn't offered.
|
||||
return { tone: "ok", label: "Managed outside this account's Triple-C state" };
|
||||
case "unreadable_record":
|
||||
return { tone: "error", label: "Unreadable record" };
|
||||
}
|
||||
|
||||
@@ -51,6 +51,8 @@ export function env(over: Partial<DetectedEnvironment> = {}): DetectedEnvironmen
|
||||
actions: ["join"],
|
||||
info: info(over.name ?? "dev"),
|
||||
onboarding: { state: "not_joined" },
|
||||
onboarding_actions: [],
|
||||
onboarded_users: 0,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -103,6 +103,9 @@ export const followAwsDeployment = (connectionId: string, region: string, stateK
|
||||
invoke<string>("follow_aws_deployment", { connectionId, region, stateKey });
|
||||
export const cancelAwsDeployment = (connectionId: string, region: string, stateKey: string) =>
|
||||
invoke<void>("cancel_aws_deployment", { connectionId, region, stateKey });
|
||||
/** Push `errored.tfstate` (a failed run's unsaved state) back to the bucket; resolves to an op id like a deploy. */
|
||||
export const pushAwsSavedState = (connectionId: string, region: string, stateKey: string) =>
|
||||
invoke<string>("push_aws_saved_state", { connectionId, region, stateKey });
|
||||
export const onboardAwsUser = (connectionId: string, region: string, environment: string) =>
|
||||
invoke<string>("onboard_aws_user", { connectionId, region, environment });
|
||||
export const deployAwsPermissionsBoundary = (connectionId: string, region: string) =>
|
||||
|
||||
@@ -1234,13 +1234,15 @@ export type EnvironmentState =
|
||||
| { state: "externally_managed" }
|
||||
| { state: "unreadable_record"; reason: string };
|
||||
|
||||
export type EnvironmentAction = "join" | "update" | "repair" | "destroy" | "follow" | "unlock";
|
||||
/** `push_state`: push the state a failed run on this machine couldn't save (`errored.tfstate`) back to the bucket. */
|
||||
export type EnvironmentAction = "join" | "update" | "repair" | "destroy" | "follow" | "unlock" | "push_state";
|
||||
|
||||
/** `incomplete`: the last onboarding run didn't finish (Join re-applies and finishes it). */
|
||||
export type OnboardingState =
|
||||
| { state: "joined" }
|
||||
| { state: "not_joined" }
|
||||
| { state: "in_progress" }
|
||||
| { state: "incomplete" };
|
||||
| { state: "in_progress"; lock: LockInfo | null }
|
||||
| { state: "incomplete"; lock: LockInfo | null };
|
||||
|
||||
export type Knowable = "yes" | "no" | "unknown";
|
||||
|
||||
@@ -1251,6 +1253,10 @@ export interface DetectedEnvironment {
|
||||
actions: EnvironmentAction[];
|
||||
info: EnvironmentInfo | null;
|
||||
onboarding: OnboardingState | null;
|
||||
/** What the caller can do with their own onboarding's run: `follow`, `unlock`, `push_state`. */
|
||||
onboarding_actions: EnvironmentAction[];
|
||||
/** Users onboarded to it (non-empty `users/<env>/…` states); null when the bucket can't be listed. */
|
||||
onboarded_users: number | null;
|
||||
}
|
||||
|
||||
export interface EnvironmentScan {
|
||||
|
||||
+36
-9
@@ -232,6 +232,12 @@ it is unpacked), and an admin can run the very same files by hand from a bundle.
|
||||
| `terraform/environment` | what every user shares: ECS cluster (Fargate, Fargate Spot), the tasks security group (no inbound rules), KMS key and alias, log group `/triple-c/<env>`, the network (`network_mode`: `public`, `private-nat`, `existing`) and, last, the record `/triple-c/environments/<env>` | `environments/<env>/terraform.tfstate` |
|
||||
| `terraform/user-onboard` | one user's task and execution roles (with the boundary) and their own EFS file system, its `-efs` security group, two mount targets and a file-system policy that admits only their task role | `users/<env>/<owner key>/terraform.tfstate` |
|
||||
|
||||
The **owner key** is the first 12 hex characters of `sha256("<region>:<aws:userid>")`; it names
|
||||
the user's roles, `triple-c-<env>-<owner key>-task` and `-exec` (a `UserId` holds a `:`, which
|
||||
role names reject). The region is in it because IAM role names are account-wide while
|
||||
environments are regional: the same user in an environment of the same name in two regions gets
|
||||
two sets of roles. The module checks the key against `region` and `owner_id`.
|
||||
|
||||
Every module pins the AWS provider (`hashicorp/aws` 6.73.0, hashes in `.terraform.lock.hcl`),
|
||||
sets `region` explicitly, never overrides an endpoint, and tags everything through `default_tags`
|
||||
(`triple-c:component`, plus the environment, owner and template version). The onboarding module
|
||||
@@ -239,30 +245,46 @@ reads the environment only from its record, never from its state.
|
||||
|
||||
**The state bucket** is `triple-c-tfstate-<account>-<region>`, one per account and region. The app
|
||||
creates it on the first deploy (versioning, SSE-S3, all four public-access blocks, a TLS-only
|
||||
bucket policy, tagged `triple-c:component=state`); every call carries `expected_bucket_owner`, so a
|
||||
bucket policy, tagged `triple-c:component=state`; the tag goes on the create itself, which the
|
||||
admin policy requires). An existing bucket policy is kept: the TLS-only statement is added to it
|
||||
when missing, never put over an organisation's own statements. Every call carries `expected_bucket_owner`, so a
|
||||
bucket of that name in another account is refused, never used. Locking is S3-native
|
||||
(`use_lockfile = true`): a run holds `<state key>.tflock`, and a held lock is what "deploying"
|
||||
means to every other copy of the app. The app removes a stale lock (older than two hours, an
|
||||
environment's only) with a conditional delete on the lock's ETag, so a lock taken since is never
|
||||
means to every other copy of the app. The app removes a stale lock (older than two hours: an
|
||||
environment's, or the caller's own onboarding's) with a conditional delete on the lock's ETag, so a lock taken since is never
|
||||
removed. `tofu destroy` leaves an *empty* state object behind; detection reads an empty state as
|
||||
no deployment at all.
|
||||
|
||||
**How the app runs a deployment.** It writes the module into a work folder
|
||||
(`<app data>/triple-c/aws/work/<bucket>/<state key>/`) with `backend.hcl` and
|
||||
`terraform.tfvars.json`, then starts a detached runner (the app binary re-executed with
|
||||
`--tofu-runner`) that runs `tofu init` and `tofu apply` (or `destroy`) in its own process group,
|
||||
`--tofu-runner`) that runs `tofu init` and `tofu apply` (or `destroy`) in its own session,
|
||||
logging to `apply.log`. Closing the app does not stop it; the next start reattaches by following the
|
||||
log. Cancel interrupts OpenTofu, which stops gracefully and saves its state. OpenTofu's environment
|
||||
log. Cancel interrupts OpenTofu, which stops gracefully and saves its state. Cancel is not
|
||||
available on Windows yet (a run there goes on to the end). If OpenTofu cannot save the state after
|
||||
a run it keeps it in `errored.tfstate` in the work folder; the run ends with an error saying so,
|
||||
nothing else is started for that deployment until it is pushed back, and **Push saved state** on
|
||||
the row runs `tofu state push errored.tfstate` through the same runner (by hand: `tofu init
|
||||
-backend-config=backend.hcl`, then `tofu state push errored.tfstate`, from the work folder). OpenTofu's environment
|
||||
is built from scratch: no inherited `AWS_*`, `TF_*` or `TOFU_*` variables, the connection's profile
|
||||
name or its keys (in the environment only, never in arguments or files), and the app's own CLI
|
||||
config, so a `~/.tofurc` cannot redirect provider downloads. The app destroys only an incomplete
|
||||
deployment (state without a record, or a failed apply); a working environment is removed by an
|
||||
admin with `tofu destroy` from a bundle.
|
||||
deployment (state without a record, or a failed apply), and never while any user's onboarding
|
||||
state for it remains; a working environment is removed by an admin with `tofu destroy` from a
|
||||
bundle.
|
||||
|
||||
**Onboarding detection.** A user is *Joined* when their task role exists and, where the bucket is
|
||||
readable, their state holds the module's `onboarding_complete` output, which depends on every
|
||||
resource the module creates, so a run that failed part-way never writes it. A partial state, a
|
||||
failed (or errored) run on this machine, or a stale lock reads as *Incomplete*, and Join (an
|
||||
idempotent re-apply) stays offered to finish it; Follow, Unlock and Push saved state work on the
|
||||
user's own onboarding as on an environment.
|
||||
|
||||
**Admin bundles.** When the signed-in identity cannot deploy (or the admin prefers to), the app
|
||||
saves a folder with the module, `backend.hcl`, `terraform.tfvars.json` and a `README.txt` holding
|
||||
the exact commands. By hand, with credentials carrying the admin files (OpenTofu or Terraform 1.10
|
||||
or later):
|
||||
or later); the permissions-boundary bundle instead needs an account administrator **without** the
|
||||
admin files attached, since their Deny on the boundary policy applies to anyone holding them:
|
||||
|
||||
```sh
|
||||
cd <bundle folder>
|
||||
@@ -272,7 +294,12 @@ tofu apply # or: tofu destroy
|
||||
|
||||
Remove every user's onboarding before destroying their environment. With Terraform, first run
|
||||
`terraform providers lock` for your platforms (the lock file carries OpenTofu's registry hashes).
|
||||
The bundle's `README.txt` also shows how to create the state bucket by hand if the app never has.
|
||||
The bundle's `README.txt` also shows how to create the state bucket by hand if the app never has,
|
||||
exactly as the app configures it: `create-bucket` with the `triple-c:component=state` tag in its
|
||||
`--create-bucket-configuration` (the admin policy allows the create only with that tag in the
|
||||
request, so a later `put-bucket-tagging` would not do; this needs an AWS CLI v2 whose
|
||||
`create-bucket` accepts `Tags`), then versioning, SSE-S3, the public-access block and the TLS-only
|
||||
bucket policy.
|
||||
|
||||
## Invariants the modules must keep (phase 4)
|
||||
|
||||
|
||||
@@ -61,6 +61,17 @@ resource "aws_security_group" "tasks" {
|
||||
cidr_blocks = ["0.0.0.0/0"]
|
||||
ipv6_cidr_blocks = ["::/0"]
|
||||
}
|
||||
|
||||
lifecycle {
|
||||
# Empty lists (a new VPC) pass: only an existing network is looked up.
|
||||
precondition {
|
||||
condition = (
|
||||
alltrue([for s in data.aws_subnet.existing : s.vpc_id == var.vpc_id])
|
||||
&& length(distinct([for s in data.aws_subnet.existing : s.availability_zone])) == length(data.aws_subnet.existing)
|
||||
)
|
||||
error_message = "The existing network's two subnets must both be in vpc_id and in different availability zones."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resource "aws_kms_key" "this" {
|
||||
|
||||
@@ -22,6 +22,15 @@ locals {
|
||||
)
|
||||
}
|
||||
|
||||
# An existing network is the user's, taken by id: look the subnets up so the
|
||||
# task security group's precondition (main.tf) can refuse subnets outside
|
||||
# var.vpc_id or both in one availability zone before anything is built --
|
||||
# the same check the onboarding module makes of the record.
|
||||
data "aws_subnet" "existing" {
|
||||
count = var.network_mode == "existing" ? 2 : 0
|
||||
id = var.subnet_ids[count.index]
|
||||
}
|
||||
|
||||
# The subnets' AZs must not move once chosen: a changed availability_zone
|
||||
# replaces the subnet (and the ENIs, NAT gateway, associations and record
|
||||
# hanging off it). So the list is not filtered on `state` -- a temporary
|
||||
|
||||
@@ -17,3 +17,22 @@ output "file_system_arn" {
|
||||
output "efs_security_group_id" {
|
||||
value = aws_security_group.efs.id
|
||||
}
|
||||
|
||||
# Written only when every resource above was applied: a run that fails
|
||||
# part-way never evaluates it, so the app reads its absence from the state
|
||||
# as "the last onboarding didn't finish" (Incomplete, Join re-applies)
|
||||
# rather than Joined. Keep depends_on listing every resource in the module.
|
||||
output "onboarding_complete" {
|
||||
value = true
|
||||
depends_on = [
|
||||
aws_efs_file_system.this,
|
||||
aws_security_group.efs,
|
||||
aws_efs_mount_target.this,
|
||||
aws_efs_file_system_policy.this,
|
||||
aws_iam_role.task,
|
||||
aws_iam_role_policy.task,
|
||||
aws_iam_role_policy.task_bedrock,
|
||||
aws_iam_role.exec,
|
||||
aws_iam_role_policy.exec,
|
||||
]
|
||||
}
|
||||
@@ -40,12 +40,12 @@ variable "owner_id" {
|
||||
}
|
||||
|
||||
variable "owner_key" {
|
||||
description = "The first 12 hex characters of sha256(owner_id); names the user's roles, which reject the ':' in owner_id."
|
||||
description = "The first 12 hex characters of sha256(\"<region>:<owner_id>\"); names the user's roles, which reject the ':' in owner_id. The region is included because role names are account-wide and environments are regional."
|
||||
type = string
|
||||
|
||||
validation {
|
||||
condition = can(regex("^[0-9a-f]{12}$", var.owner_key)) && var.owner_key == substr(sha256(var.owner_id), 0, 12)
|
||||
error_message = "owner_key must be the first 12 hex characters of sha256(owner_id)."
|
||||
condition = can(regex("^[0-9a-f]{12}$", var.owner_key)) && var.owner_key == substr(sha256("${var.region}:${var.owner_id}"), 0, 12)
|
||||
error_message = "owner_key must be the first 12 hex characters of sha256(\"<region>:<owner_id>\")."
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ Phase 4 added these decisions:
|
||||
exact commands (`tofu init -backend-config=backend.hcl`, then `tofu apply`; Terraform 1.10+
|
||||
works too).
|
||||
- **D6. The app destroys only incomplete deployments** (state without an environment record, or
|
||||
a failed apply). A working environment is destroyed by an admin with `tofu destroy` from a
|
||||
a failed apply), and never while any user's onboarding state for the environment remains. A working environment is destroyed by an admin with `tofu destroy` from a
|
||||
bundle, which is the irreversible case.
|
||||
- **D7. The admin tier spans several policy files** (`environment-admin.json` and
|
||||
`environment-admin-network.json`), all required; `aws_policy_document` returns every file of a
|
||||
@@ -65,13 +65,20 @@ Phase 4 added these decisions:
|
||||
only environments that have a record.
|
||||
- **D9. One state key per deployment**, in the per-account, per-region bucket
|
||||
`triple-c-tfstate-<account>-<region>`: `environments/<env>/terraform.tfstate`,
|
||||
`users/<env>/<ownerkey>/terraform.tfstate`, `boundary/terraform.tfstate`. The lock is the
|
||||
`users/<env>/<ownerkey>/terraform.tfstate`, `boundary/terraform.tfstate`. The owner key is the
|
||||
first 12 hex characters of `sha256("<region>:<aws:userid>")` and also names the user's roles
|
||||
(`triple-c-<env>-<ownerkey>-task|exec`): role names are account-global and environments
|
||||
regional, so the region is part of it (the same user and environment name in two regions must
|
||||
not collide). The lock is the
|
||||
matching `.tflock` object (S3-native locking, `use_lockfile = true`); a held lock is a deploy in
|
||||
progress, and its `Who`/`Created`/`Operation` are shown.
|
||||
- **D10. Applies are detached.** `tofu apply` runs in its own process group, output to
|
||||
`<workdir>/apply.log`, PID in `<workdir>/apply.pid`. Closing the app doesn't interrupt it; on the
|
||||
next run the app sees the live runner or the held lock and reattaches by following the log. It
|
||||
interrupts only when the user presses Cancel, and OpenTofu then stops gracefully and saves state.
|
||||
- **D10. Applies are detached.** `tofu apply` runs in its own session, output to
|
||||
`<workdir>/apply.log`, PID in `<workdir>/apply.pid` (liveness is the runner's `apply.lock`). A
|
||||
run that can't save its state leaves `errored.tfstate`; nothing else starts there until it is
|
||||
pushed back (Push saved state: `tofu state push errored.tfstate` through the same runner).
|
||||
Closing the app doesn't interrupt it; on the next run the app sees the live runner or the held
|
||||
lock and reattaches by following the log. It interrupts only when the user presses Cancel (not
|
||||
on Windows yet), and OpenTofu then stops gracefully and saves state.
|
||||
|
||||
### Non-goals (v1)
|
||||
|
||||
|
||||
Reference in new issue
Block a user