region HA P3b-2 ops: approved maintenance session document (B2)
Add an account-owned root session document restricted to the operator frame. Keep witness harness commands disabled unless an exact bundle digest is configured, and reuse the existing operator frame in the harness helper.
11 files changed,
+652
−0
infra/modules/region-group-operator-document/README.md+121 −0infra/modules/region-group-operator-document/harness-pattern.txt+1 −0infra/modules/region-group-operator-document/main.tf+32 −0infra/modules/region-group-operator-document/outputs.tf+19 −0infra/modules/region-group-operator-document/tests/document.tftest.hcl+129 −0infra/modules/region-group-operator-document/text.json+5 −0infra/modules/region-group-operator-document/tool-pattern.txt+1 −0infra/modules/region-group-operator-document/variables.tf+30 −0infra/modules/region-group-operator-document/versions.tf+9 −0scripts/region_group_document_test.py+227 −0scripts/region_group_frames.py+78 −0
diff --git a/infra/modules/region-group-operator-document/README.md b/infra/modules/region-group-operator-document/README.md| new file mode 100644 |
| index 000000000..8979a57ee |
| --- /dev/null |
| +++ b/infra/modules/region-group-operator-document/README.md |
| @@ -0,0 +1,121 @@ |
| +# Group maintenance session document |
| + |
| +Create an account-owned Systems Manager (SSM) document for attended group |
| +maintenance. It accepts the operator's framed commands and runs them as root. |
| +Pass its ARN to the existing region-host input: |
| + |
| +```hcl |
| +module "maintenance_document" { |
| + source = "../region-group-operator-document" |
| + name = "example-group-maintenance" |
| +} |
| + |
| +# In the region-host module call: |
| +# group_operator_session_document_arn = module.maintenance_document.arn |
| +``` |
| + |
| +Use the document's `name` in the operator configuration. The module also |
| +exports `arn`, `document_version` (the latest version), `hash` and the rendered |
| +JSON `content`. Record the selected document content and version before the |
| +maintenance window. The document has one String parameter, `command`, uses |
| +`NonInteractiveCommands`, and sets Linux `runAsElevated` to true. |
| + |
| +This document grants root to anyone allowed to StartSession with it on a |
| +target. The region-host operator policy limits targets to the group's tagged |
| +instances. The document itself does not select targets or grant IAM access. |
| +Review both the document and that policy before deployment. |
| + |
| +The optional `description` and `tags` inputs carry no deployment defaults. |
| +Names use 3 to 128 letters, digits, underscores, dots or hyphens; `AWS-` |
| +prefixes and `SSM-SessionManagerRunShell` are refused. |
| + |
| +## Command contract |
| + |
| +`tool-pattern.txt` and `harness-pattern.txt` are the only pattern sources. |
| +The module reads them with `file()` and anchors the selected branches as |
| +`^T$` or `^(T|H)$`. Their shell quoting matches Python `shlex.quote`, including |
| +its treatment of each single quote. Both branches use this script, with |
| +`NONCE` replaced by 32 lowercase hexadecimal characters: |
| + |
| +```sh |
| +[ "$(id -u)" = 0 ] || exit 77; printf '\nNONCE:BEGIN\n'; (INNER); result=$?; printf '\nNONCE:END:%s\n' "$result" |
| +``` |
| + |
| +The script is shell-quoted as one argument after this exact prefix: |
| + |
| +```sh |
| +/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c |
| +``` |
| + |
| +Branch T accepts these inner commands. `SHA` is 64 lowercase hexadecimal |
| +characters, and `B64` contains only `A-Z`, `a-z`, `0-9`, `+`, `/` and `=`. |
| +The permit payload must be nonempty; the root maintenance verb validates |
| +the decoded permit. |
| + |
| +```sh |
| +/opt/carlos/carlos system group-maintenance status |
| +/opt/carlos/carlos system group-maintenance prepare --sha256 SHA |
| +printf %s B64 | base64 -d | /opt/carlos/carlos system group-maintenance permit && /opt/carlos/carlos system group-maintenance status |
| +/opt/carlos/carlos system group-maintenance revoke |
| +/usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance apply |
| +/usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance rollback |
| +``` |
| + |
| +Branch H is test apparatus for an attended dev witness. It is absent unless |
| +`harness_bundle_sha256` is set to the approved bundle's 64-character lowercase |
| +hexadecimal SHA256 digest. Set it only for that witness window. During cleanup, |
| +set it back to `null` and deploy a document version without Branch H. |
| + |
| +The B5 harness implements this exact install command. `SHA` is the literal |
| +configured digest, and `B64` is 1 to 60,000 characters from the alphabet above: |
| + |
| +```sh |
| +umask 077 && mkdir -p -m 0700 /run/carlos-p3b2-fault && printf %s B64 > /run/carlos-p3b2-fault/bundle.b64 && base64 -d /run/carlos-p3b2-fault/bundle.b64 > /run/carlos-p3b2-fault/bundle.tar && [ "$(sha256sum /run/carlos-p3b2-fault/bundle.tar | cut -c1-64)" = SHA ] && mkdir -p -m 0700 /usr/local/lib/carlos-p3b2-fault && tar --no-same-owner --no-same-permissions -x -f /run/carlos-p3b2-fault/bundle.tar -C /usr/local/lib/carlos-p3b2-fault && /bin/sh /usr/local/lib/carlos-p3b2-fault/fault.sh install |
| +``` |
| + |
| +The cap leaves space for framing within SSM's 65,535-character parameter limit: |
| +[https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartSession.html](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartSession.html). |
| +The pattern expresses that range with chunks of at most 1,000 characters, |
| +so no counted repetition exceeds RE2's limit. Base64 syntax and archive contents |
| +still need validation during bundle preparation. Pin only a reviewed bundle. |
| + |
| +Branch H also accepts `/bin/sh /usr/local/lib/carlos-p3b2-fault/fault.sh` |
| +followed by `status`, `disarm`, `remove` or `uninstall`, without arguments. |
| +The remaining forms are: |
| + |
| +```sh |
| +/bin/sh /usr/local/lib/carlos-p3b2-fault/fault.sh arm-fault --iid IID --boot BOOT --transaction TRANSACTION --minutes MINUTES |
| +/bin/sh /usr/local/lib/carlos-p3b2-fault/fault.sh arm-pause --iid IID --boot BOOT --transaction TRANSACTION --minutes MINUTES |
| +``` |
| + |
| +`IID` is `i-` followed by 8 or 17 lowercase hexadecimal digits. `BOOT` has |
| +lowercase hexadecimal UUID shape, `8-4-4-4-12`. `TRANSACTION` is 1 to 80 letters, |
| +digits, underscores or hyphens. `MINUTES` is 1 to 999 without leading zeros. |
| +Argument order and spaces are fixed. The harness must validate the supplied |
| +identity and transaction against the member before arming a fault. |
| + |
| +Use `scripts/region_group_frames.py` to build H commands without executing them: |
| +`install_command(bundle_b64, sha256, nonce)` and |
| +`harness_command(verb, nonce, *, iid=None, boot=None, transaction=None, minutes=None)`. |
| +The latter requires all four keyword fields for arm commands and refuses them |
| +for other verbs. The helper derives its frame from the real operator's status |
| +command, so the framing stays shared without editing the operator. |
| + |
| +## Offline checks |
| + |
| +From the repository root: |
| + |
| +```sh |
| +python3 -m unittest scripts/region_group_document_test.py |
| +tofu -chdir=infra/modules/region-group-operator-document init -backend=false |
| +tofu -chdir=infra/modules/region-group-operator-document test |
| +``` |
| + |
| +Python checks the shared patterns against real operator output and rejects |
| +altered commands. The OpenTofu tests use a mock AWS provider. These checks do |
| +not establish live SSM validation, elevation or IAM enforcement; retain those |
| +checks in the approved witness window. |
| + |
| +Operator-facing diagnostics are centralized in `text.json` and the helper's |
| +`TEXT` table. The document description is the configurable `description` |
| +input, with its generic default in `variables.tf`. |
diff --git a/infra/modules/region-group-operator-document/harness-pattern.txt b/infra/modules/region-group-operator-document/harness-pattern.txt| new file mode 100644 |
| index 000000000..2c9db6887 |
| --- /dev/null |
| +++ b/infra/modules/region-group-operator-document/harness-pattern.txt |
| @@ -0,0 +1 @@ |
| +/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((umask 077 && mkdir -p -m 0700 /run/carlos-p3b2-fault && printf %s [A-Za-z0-9+/=]{1,1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}([A-Za-z0-9+/=]{1000}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1}){0,1} > /run/carlos-p3b2-fault/bundle\.b64 && base64 -d /run/carlos-p3b2-fault/bundle\.b64 > /run/carlos-p3b2-fault/bundle\.tar && \[ "\$\(sha256sum /run/carlos-p3b2-fault/bundle\.tar \| cut -c1-64\)" = HARNESS_SHA256 \] && mkdir -p -m 0700 /usr/local/lib/carlos-p3b2-fault && tar --no-same-owner --no-same-permissions -x -f /run/carlos-p3b2-fault/bundle\.tar -C /usr/local/lib/carlos-p3b2-fault && /bin/sh /usr/local/lib/carlos-p3b2-fault/fault\.sh install|/bin/sh /usr/local/lib/carlos-p3b2-fault/fault\.sh ((status|disarm|remove|uninstall)|(arm-fault|arm-pause) --iid i-([0-9a-f]{8}|[0-9a-f]{17}) --boot [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} --transaction [A-Za-z0-9_-]{1,80} --minutes [1-9][0-9]{0,2}))\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"' |
diff --git a/infra/modules/region-group-operator-document/main.tf b/infra/modules/region-group-operator-document/main.tf| new file mode 100644 |
| index 000000000..5522f8631 |
| --- /dev/null |
| +++ b/infra/modules/region-group-operator-document/main.tf |
| @@ -0,0 +1,32 @@ |
| +locals { |
| + TEXT = jsondecode(file("${path.module}/text.json")) |
| + tool_pattern = trimspace(file("${path.module}/tool-pattern.txt")) |
| + harness_pattern = var.harness_bundle_sha256 == null ? null : replace(trimspace(file("${path.module}/harness-pattern.txt")), "HARNESS_SHA256", var.harness_bundle_sha256) |
| + allowed_pattern = local.harness_pattern == null ? "^${local.tool_pattern}$" : "^(${local.tool_pattern}|${local.harness_pattern})$" |
| + content = jsonencode({ |
| + schemaVersion = "1.0" |
| + description = var.description |
| + sessionType = "NonInteractiveCommands" |
| + parameters = { |
| + command = { |
| + type = "String" |
| + description = local.TEXT.command |
| + allowedPattern = local.allowed_pattern |
| + } |
| + } |
| + properties = { |
| + linux = { |
| + commands = "{{ command }}" |
| + runAsElevated = true |
| + } |
| + } |
| + }) |
| +} |
| + |
| +resource "aws_ssm_document" "maintenance" { |
| + name = var.name |
| + document_type = "Session" |
| + document_format = "JSON" |
| + content = local.content |
| + tags = var.tags |
| +} |
diff --git a/infra/modules/region-group-operator-document/outputs.tf b/infra/modules/region-group-operator-document/outputs.tf| new file mode 100644 |
| index 000000000..d5c59e2fa |
| --- /dev/null |
| +++ b/infra/modules/region-group-operator-document/outputs.tf |
| @@ -0,0 +1,19 @@ |
| +output "arn" { |
| + value = aws_ssm_document.maintenance.arn |
| +} |
| + |
| +output "name" { |
| + value = aws_ssm_document.maintenance.name |
| +} |
| + |
| +output "document_version" { |
| + value = aws_ssm_document.maintenance.latest_version |
| +} |
| + |
| +output "hash" { |
| + value = aws_ssm_document.maintenance.hash |
| +} |
| + |
| +output "content" { |
| + value = aws_ssm_document.maintenance.content |
| +} |
diff --git a/infra/modules/region-group-operator-document/tests/document.tftest.hcl b/infra/modules/region-group-operator-document/tests/document.tftest.hcl| new file mode 100644 |
| index 000000000..e48dc4f68 |
| --- /dev/null |
| +++ b/infra/modules/region-group-operator-document/tests/document.tftest.hcl |
| @@ -0,0 +1,129 @@ |
| +mock_provider "aws" { |
| + mock_resource "aws_ssm_document" { |
| + defaults = { |
| + arn = "arn:aws:ssm:eu-west-1:123456789012:document/example-maintenance" |
| + latest_version = "2" |
| + hash = "example-hash" |
| + } |
| + } |
| +} |
| + |
| +variables { |
| + name = "example-maintenance" |
| +} |
| + |
| +run "tool_only" { |
| + command = apply |
| + assert { |
| + condition = aws_ssm_document.maintenance.document_type == "Session" && aws_ssm_document.maintenance.document_format == "JSON" |
| + error_message = "The document must be a JSON Session document." |
| + } |
| + assert { |
| + condition = jsondecode(output.content) == { |
| + schemaVersion = "1.0" |
| + description = var.description |
| + sessionType = "NonInteractiveCommands" |
| + parameters = { |
| + command = { |
| + type = "String" |
| + description = local.TEXT.command |
| + allowedPattern = "^${trimspace(file("${path.module}/tool-pattern.txt"))}$" |
| + } |
| + } |
| + properties = { linux = { commands = "{{ command }}", runAsElevated = true } } |
| + } |
| + error_message = "Only the framed command parameter may run, elevated and noninteractively." |
| + } |
| + assert { |
| + condition = !strcontains(jsondecode(output.content).parameters.command.allowedPattern, "carlos-p3b2-fault") && length(aws_ssm_document.maintenance.tags) == 0 |
| + error_message = "The harness branch must be absent by default." |
| + } |
| + assert { |
| + condition = output.arn == aws_ssm_document.maintenance.arn && output.name == var.name && output.document_version == aws_ssm_document.maintenance.latest_version && output.hash == aws_ssm_document.maintenance.hash |
| + error_message = "Outputs must expose the document identity, latest version and hash." |
| + } |
| + assert { |
| + condition = length(regexall(jsondecode(output.content).parameters.command.allowedPattern, "unframed")) == 0 |
| + error_message = "The tool pattern must compile under RE2 and refuse unframed input." |
| + } |
| +} |
| + |
| +run "with_harness" { |
| + command = apply |
| + variables { |
| + description = "Example attended witness" |
| + tags = { purpose = "witness" } |
| + harness_bundle_sha256 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" |
| + } |
| + assert { |
| + condition = jsondecode(output.content).parameters.command.allowedPattern == "^(${trimspace(file("${path.module}/tool-pattern.txt"))}|${replace(trimspace(file("${path.module}/harness-pattern.txt")), "HARNESS_SHA256", var.harness_bundle_sha256)})$" |
| + error_message = "The harness must use the file grammar with the exact pinned bundle digest." |
| + } |
| + assert { |
| + condition = jsondecode(output.content).description == var.description && aws_ssm_document.maintenance.tags == tomap(var.tags) |
| + error_message = "Description and tags must pass through unchanged." |
| + } |
| + assert { |
| + condition = !strcontains(output.content, "HARNESS_SHA256") && strcontains(output.content, var.harness_bundle_sha256) |
| + error_message = "The digest placeholder must be replaced." |
| + } |
| + assert { |
| + condition = length(regexall(jsondecode(output.content).parameters.command.allowedPattern, "unframed")) == 0 |
| + error_message = "The combined pattern must compile under RE2 and refuse unframed input." |
| + } |
| +} |
| + |
| +run "harness_removed" { |
| + command = apply |
| + variables { harness_bundle_sha256 = null } |
| + assert { |
| + condition = jsondecode(output.content).parameters.command.allowedPattern == "^${trimspace(file("${path.module}/tool-pattern.txt"))}$" |
| + error_message = "Removing the bundle digest must remove the harness branch." |
| + } |
| +} |
| + |
| +run "aws_name" { |
| + command = plan |
| + variables { name = "AWS-example" } |
| + expect_failures = [var.name] |
| +} |
| +run "default_shell_name" { |
| + command = plan |
| + variables { name = "SSM-SessionManagerRunShell" } |
| + expect_failures = [var.name] |
| +} |
| +run "invalid_name_characters" { |
| + command = plan |
| + variables { name = "example/name" } |
| + expect_failures = [var.name] |
| +} |
| +run "short_name" { |
| + command = plan |
| + variables { name = "ab" } |
| + expect_failures = [var.name] |
| +} |
| +run "long_name" { |
| + command = plan |
| + variables { name = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } |
| + expect_failures = [var.name] |
| +} |
| +run "uppercase_digest" { |
| + command = plan |
| + variables { harness_bundle_sha256 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" } |
| + expect_failures = [var.harness_bundle_sha256] |
| +} |
| +run "short_digest" { |
| + command = plan |
| + variables { harness_bundle_sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } |
| + expect_failures = [var.harness_bundle_sha256] |
| +} |
| +run "long_digest" { |
| + command = plan |
| + variables { harness_bundle_sha256 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } |
| + expect_failures = [var.harness_bundle_sha256] |
| +} |
| +run "empty_digest" { |
| + command = plan |
| + variables { harness_bundle_sha256 = "" } |
| + expect_failures = [var.harness_bundle_sha256] |
| +} |
diff --git a/infra/modules/region-group-operator-document/text.json b/infra/modules/region-group-operator-document/text.json| new file mode 100644 |
| index 000000000..768ea8446 |
| --- /dev/null |
| +++ b/infra/modules/region-group-operator-document/text.json |
| @@ -0,0 +1,5 @@ |
| +{ |
| + "command": "The framed group-maintenance command", |
| + "name": "Use 3 to 128 letters, digits, underscores, dots or hyphens. The name must not start with AWS- or equal SSM-SessionManagerRunShell.", |
| + "sha256": "Use null to disable the witness harness, or the bundle's 64-character lowercase hexadecimal SHA256 digest." |
| +} |
diff --git a/infra/modules/region-group-operator-document/tool-pattern.txt b/infra/modules/region-group-operator-document/tool-pattern.txt| new file mode 100644 |
| index 000000000..98a539ea0 |
| --- /dev/null |
| +++ b/infra/modules/region-group-operator-document/tool-pattern.txt |
| @@ -0,0 +1 @@ |
| +/usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root /bin/sh -c '\[ "\$\(id -u\)" = 0 \] \|\| exit 77; printf '"'"'\\n[0-9a-f]{32}:BEGIN\\n'"'"'; \((/opt/carlos/carlos system group-maintenance (status|revoke)|/opt/carlos/carlos system group-maintenance prepare --sha256 [0-9a-f]{64}|printf %s [A-Za-z0-9+/=]+ \| base64 -d \| /opt/carlos/carlos system group-maintenance permit && /opt/carlos/carlos system group-maintenance status|/usr/bin/timeout --signal=TERM --kill-after=30s 900s /opt/carlos/carlos system group-maintenance (apply|rollback))\); result=\$\?; printf '"'"'\\n[0-9a-f]{32}:END:%s\\n'"'"' "\$result"' |
diff --git a/infra/modules/region-group-operator-document/variables.tf b/infra/modules/region-group-operator-document/variables.tf| new file mode 100644 |
| index 000000000..cfc529470 |
| --- /dev/null |
| +++ b/infra/modules/region-group-operator-document/variables.tf |
| @@ -0,0 +1,30 @@ |
| +variable "name" { |
| + type = string |
| + nullable = false |
| + validation { |
| + condition = can(regex("^[A-Za-z0-9_.-]{3,128}$", var.name)) && !startswith(var.name, "AWS-") && var.name != "SSM-SessionManagerRunShell" |
| + error_message = jsondecode(file("${path.module}/text.json")).name |
| + } |
| +} |
| + |
| +variable "description" { |
| + type = string |
| + nullable = false |
| + default = "CARLOS group maintenance: one framed noninteractive command as root" |
| +} |
| + |
| +variable "tags" { |
| + type = map(string) |
| + nullable = false |
| + default = {} |
| +} |
| + |
| +variable "harness_bundle_sha256" { |
| + type = string |
| + nullable = true |
| + default = null |
| + validation { |
| + condition = var.harness_bundle_sha256 == null ? true : can(regex("^[0-9a-f]{64}$", var.harness_bundle_sha256)) |
| + error_message = jsondecode(file("${path.module}/text.json")).sha256 |
| + } |
| +} |
diff --git a/infra/modules/region-group-operator-document/versions.tf b/infra/modules/region-group-operator-document/versions.tf| new file mode 100644 |
| index 000000000..c028066c2 |
| --- /dev/null |
| +++ b/infra/modules/region-group-operator-document/versions.tf |
| @@ -0,0 +1,9 @@ |
| +terraform { |
| + required_version = ">= 1.10" |
| + required_providers { |
| + aws = { |
| + source = "hashicorp/aws" |
| + version = ">= 6.0" |
| + } |
| + } |
| +} |
diff --git a/scripts/region_group_document_test.py b/scripts/region_group_document_test.py| new file mode 100644 |
| index 000000000..57343abd8 |
| --- /dev/null |
| +++ b/scripts/region_group_document_test.py |
| @@ -0,0 +1,227 @@ |
| +"""Offline acceptance and refusal witnesses for the approved session grammar.""" |
| + |
| +import base64 |
| +from pathlib import Path |
| +import random |
| +import re |
| +import shlex |
| +import string |
| +import unittest |
| + |
| +from scripts import region_group_frames as frames |
| + |
| + |
| +MODULE = Path(__file__).resolve().parents[1] / "infra/modules/region-group-operator-document" |
| +SHA = "a" * 64 |
| +NONCE = "b" * 32 |
| +STATUS = "/opt/carlos/carlos system group-maintenance status" |
| +ARM = dict(iid="i-0123456789abcdef0", boot="01234567-89ab-cdef-0123-456789abcdef", |
| + transaction="witness_1-a", minutes=35) |
| + |
| + |
| +def pattern(sha256=None): |
| + tool = (MODULE / "tool-pattern.txt").read_text().strip() |
| + if sha256 is None: |
| + return re.compile("^" + tool + "$") |
| + harness = (MODULE / "harness-pattern.txt").read_text().strip().replace("HARNESS_SHA256", sha256) |
| + return re.compile("^(" + tool + "|" + harness + ")$") |
| + |
| + |
| +class DocumentPatternTests(unittest.TestCase): |
| + def setUp(self): |
| + self.tool = pattern() |
| + self.harness = pattern(SHA) |
| + |
| + def assertAccepted(self, command, harness=False): |
| + self.assertIsNotNone((self.harness if harness else self.tool).fullmatch(command), command[:200]) |
| + |
| + def assertRefused(self, command, harness=True): |
| + self.assertIsNone((self.harness if harness else self.tool).fullmatch(command), command[:200]) |
| + |
| + def test_every_real_tool_form(self): |
| + rng = random.Random(3512) |
| + for _ in range(40): |
| + nonce = "".join(rng.choices("0123456789abcdef", k=32)) |
| + sha = "".join(rng.choices("0123456789abcdef", k=64)) |
| + for verb in ("status", "prepare", "permit", "revoke", "apply", "rollback"): |
| + permit = dict(v=1, transaction="witness-1", iid=ARM["iid"], boot_id=ARM["boot"], |
| + action="apply", old_sha256=SHA, new_sha256=sha, phase="mutation") |
| + command = frames.roll.AWS.remote_command(dict(verb=verb, sha256=sha, permit=permit), nonce) |
| + with self.subTest(verb=verb, nonce=nonce): |
| + self.assertAccepted(command) |
| + self.assertAccepted(command, harness=True) |
| + |
| + def test_permit_payload_edges(self): |
| + payloads = [{}, {"x": ""}, {"x": "a"}, {"x": "ab"}, {"x": "abc"}, |
| + {"x": "'\" ; & | $ ` ( ) < > \n\r\\\x00"}, {"x": "\u2603"}, |
| + {"x": "z" * 45000}] |
| + for payload in payloads: |
| + command = frames.roll.AWS.remote_command(dict(verb="permit", permit=payload), NONCE) |
| + self.assertAccepted(command) |
| + self.assertLess(len(command), 65535) |
| + |
| + def test_frame_is_the_real_tool_frame(self): |
| + for nonce in (NONCE, "0" * 32, "1234567890abcdef" * 2): |
| + expected = frames.roll.AWS.remote_command({"verb": "status"}, nonce) |
| + self.assertEqual(frames.frame_command(STATUS, nonce), expected) |
| + inner = "/bin/sh /usr/local/lib/carlos-p3b2-fault/fault.sh status" |
| + actual = frames.harness_command("status", nonce) |
| + self.assertEqual(actual.replace(inner, STATUS), expected) |
| + # Re-quoting must preserve embedded quotes instead of opening another shell word. |
| + inner = "printf '%s' 'test'" |
| + framed = frames.frame_command(inner, NONCE) |
| + self.assertEqual(len(shlex.split(framed)), 7) |
| + self.assertIn("(" + inner + "); result=$?;", shlex.split(framed)[-1]) |
| + |
| + def test_all_harness_verbs_and_bounds(self): |
| + for verb in ("status", "disarm", "remove", "uninstall"): |
| + self.assertAccepted(frames.harness_command(verb, NONCE), harness=True) |
| + for verb in ("arm-fault", "arm-pause"): |
| + for iid in ("i-01234567", ARM["iid"]): |
| + for minutes in (1, 9, 10, 99, 100, 999): |
| + for transaction in ("a", "A_9-" * 20): |
| + args = dict(ARM, iid=iid, minutes=minutes, transaction=transaction) |
| + self.assertAccepted(frames.harness_command(verb, NONCE, **args), harness=True) |
| + rng = random.Random(60000) |
| + for size in (1, 4, 999, 1000, 1001, 1999, 2000, 2001, 59999, 60000): |
| + payload = "".join(rng.choices(string.ascii_letters + string.digits + "+/=", k=size)) |
| + command = frames.install_command(payload, SHA, NONCE) |
| + self.assertAccepted(command, harness=True) |
| + self.assertLessEqual(len(command), 65535) |
| + |
| + def test_harness_is_disabled_by_default(self): |
| + commands = [frames.install_command("YQ==", SHA, NONCE)] |
| + commands += [frames.harness_command(v, NONCE) for v in ("status", "disarm", "remove", "uninstall")] |
| + commands += [frames.harness_command(v, NONCE, **ARM) for v in ("arm-fault", "arm-pause")] |
| + for command in commands: |
| + self.assertRefused(command, harness=False) |
| + |
| + def test_tool_refusals(self): |
| + status = frames.roll.AWS.remote_command({"verb": "status"}, NONCE) |
| + prepare = frames.roll.AWS.remote_command(dict(verb="prepare", sha256=SHA), NONCE) |
| + apply = frames.roll.AWS.remote_command({"verb": "apply"}, NONCE) |
| + permit = frames.roll.AWS.remote_command(dict(verb="permit", permit={"v": 1}), NONCE) |
| + payload = base64.b64encode(frames.roll.encoded({"v": 1})).decode() |
| + timeout = "/usr/bin/timeout --signal=TERM --kill-after=30s 900s " |
| + bad = { |
| + "unframed": STATUS, |
| + "binary": status.replace("/opt/carlos/carlos", "/bin/id"), |
| + "path": status.replace("/opt/carlos/carlos", "/tmp/carlos"), |
| + "bare apply": frames.frame_command("/opt/carlos/carlos system apply", NONCE), |
| + "no env isolation": status.replace("env -i ", "env "), |
| + "extra variable": status.replace("env -i ", "env -i X=1 "), |
| + "different path": status.replace("PATH=/usr/sbin:/usr/bin:/sbin:/bin", "PATH=/tmp:/usr/bin"), |
| + "different home": status.replace("HOME=/root", "HOME=/tmp"), |
| + "bash": status.replace("/bin/sh -c", "/bin/bash -c"), |
| + "short nonce": status.replace(NONCE, "a" * 31), |
| + "long nonce": status.replace(NONCE, "a" * 33), |
| + "uppercase nonce": status.replace(NONCE, "B" * 32), |
| + "bad end nonce": status.replace(NONCE + ":END", "a" * 31 + ":END"), |
| + "upper sha": prepare.replace(SHA, "A" * 64), |
| + "short sha": prepare.replace(SHA, "a" * 63), |
| + "long sha": prepare.replace(SHA, "a" * 65), |
| + "permit quote": permit.replace(payload, payload + "'"), |
| + "permit space": permit.replace(payload, payload + " "), |
| + "empty permit": permit.replace(payload, ""), |
| + "no timeout": apply.replace(timeout, ""), |
| + "different timeout": apply.replace("900s", "901s"), |
| + "different signal": apply.replace("signal=TERM", "signal=KILL"), |
| + "different kill delay": apply.replace("30s", "31s"), |
| + "root guard removed": status.replace('[ "$(id -u)" = 0 ] || exit 77; ', ""), |
| + "root guard inverted": status.replace('" = 0 ]', '" = 1 ]'), |
| + "end status changed": status.replace('"$result"', '"0"'), |
| + "permit without status": permit.replace(" && " + STATUS, ""), |
| + } |
| + for addition in ("; id", " && id", " | sh", " $(id)", " `id`", "\nid", "\rid", " > /tmp/out"): |
| + bad["inner " + repr(addition)] = frames.frame_command(STATUS + addition, NONCE) |
| + for label, command in bad.items(): |
| + with self.subTest(case=label): |
| + self.assertRefused(command) |
| + self.assertGreaterEqual(len(bad), 25) |
| + |
| + def test_anchors_and_newlines(self): |
| + commands = [frames.roll.AWS.remote_command({"verb": "status"}, NONCE), |
| + frames.harness_command("status", NONCE)] |
| + for command in commands: |
| + for junk in ("junk", "; id", " && id", " | sh", " trailing"): |
| + # search exercises the anchors; fullmatch alone would hide their removal. |
| + self.assertIsNone(self.harness.search(junk + command)) |
| + self.assertIsNone(self.harness.search(command + junk)) |
| + for junk in ("\n", "\r", "\r\n", "\nsh"): |
| + self.assertRefused(command + junk) |
| + self.assertRefused(junk + command) |
| + status = commands[0] |
| + for index in range(len(status) + 1): |
| + self.assertRefused(status[:index] + "\n" + status[index:]) |
| + |
| + def test_harness_refusals(self): |
| + install = frames.install_command("YQ==", SHA, NONCE) |
| + arm = frames.harness_command("arm-fault", NONCE, **ARM) |
| + status = frames.harness_command("status", NONCE) |
| + bad = [install.replace(SHA, "b" * 64), install.replace(SHA, "A" * 64), |
| + install.replace("YQ==", "A" * 60001), install.replace("YQ==", ""), |
| + install.replace("YQ==", "Y Q=="), install.replace("YQ==", "Y'Q=="), |
| + install.replace("YQ==", "YQ==\n"), install.replace("umask 077", "umask 022"), |
| + install.replace("--no-same-owner ", ""), |
| + status.replace("fault.sh status", "fault.sh restart"), |
| + status.replace("/usr/local/lib/carlos-p3b2-fault", "/tmp/carlos-p3b2-fault"), |
| + status.replace("fault.sh status", "fault.sh install"), |
| + arm.replace("arm-fault", "arm-other"), arm + " --force"] |
| + for iid in ("i-1234567", "i-123456789", "i-" + "a" * 16, "i-" + "a" * 18, "i-" + "A" * 17): |
| + bad.append(arm.replace(ARM["iid"], iid)) |
| + for boot in (ARM["boot"].upper(), ARM["boot"][:-1], "boot", "0" * 36): |
| + bad.append(arm.replace(ARM["boot"], boot)) |
| + for transaction in ("", "x" * 81, "two words", "$(id)", "a.b", "a/b", "x\ny"): |
| + bad.append(arm.replace(ARM["transaction"], transaction)) |
| + for minutes in ("0", "00", "01", "1000", "-1", "+1", "1.5", "1;id"): |
| + bad.append(arm.replace("--minutes 35", "--minutes " + minutes)) |
| + for command in bad: |
| + self.assertRefused(command) |
| + |
| + def test_helper_refuses_invalid_fields(self): |
| + for bundle in ("", "A" * 60001, "YQ==\n", "a;id", "a'", None): |
| + with self.assertRaises(ValueError): |
| + frames.install_command(bundle, SHA, NONCE) |
| + for sha in ("a" * 63, "a" * 65, "A" * 64, SHA + "\n"): |
| + with self.assertRaises(ValueError): |
| + frames.install_command("YQ==", sha, NONCE) |
| + for nonce in ("a" * 31, "a" * 33, "A" * 32, NONCE + "\n"): |
| + with self.assertRaises(ValueError): |
| + frames.harness_command("status", nonce) |
| + for field, value in (("iid", "i-1"), ("boot", "boot"), ("transaction", "two words"), |
| + ("minutes", "01"), ("minutes", True), ("minutes", 1000)): |
| + with self.assertRaises(ValueError): |
| + frames.harness_command("arm-pause", NONCE, **dict(ARM, **{field: value})) |
| + with self.assertRaises(ValueError): |
| + frames.harness_command("restart", NONCE) |
| + with self.assertRaises(ValueError): |
| + frames.harness_command("status", NONCE, minutes=1) |
| + |
| + def test_pattern_uses_portable_constructs(self): |
| + # Restrict the regex operators and classes to the brief's shared dialect. |
| + for name in ("tool-pattern.txt", "harness-pattern.txt"): |
| + source = (MODULE / name).read_text().strip() |
| + tokens = list(source) |
| + index = 0 |
| + while index < len(tokens): |
| + char = tokens[index] |
| + if char == "\\": |
| + index += 1 |
| + self.assertIn(tokens[index], r"\.^$|?*+()[]{}") |
| + elif char == "[": |
| + end = source.index("]", index) |
| + self.assertIn(source[index:end + 1], ( |
| + "[0-9a-f]", "[A-Za-z0-9+/=]", "[A-Za-z0-9_-]", "[1-9]", "[0-9]")) |
| + index = end |
| + elif char == "{": |
| + end = source.index("}", index) |
| + counts = source[index + 1:end].split(",") |
| + self.assertTrue(all(c.isdecimal() and int(c) <= 1000 for c in counts)) |
| + index = end |
| + else: |
| + self.assertNotIn(char, ".?^$\n\r") |
| + index += 1 |
| + |
| + |
| +if __name__ == "__main__": |
| + unittest.main() |
diff --git a/scripts/region_group_frames.py b/scripts/region_group_frames.py| new file mode 100644 |
| index 000000000..d09c3dfe8 |
| --- /dev/null |
| +++ b/scripts/region_group_frames.py |
| @@ -0,0 +1,78 @@ |
| +"""Build witness commands using the attended operator's existing shell frame.""" |
| + |
| +import importlib.util |
| +from pathlib import Path |
| +import re |
| +import shlex |
| + |
| + |
| +_SPEC = importlib.util.spec_from_file_location( |
| + "region_group_frames_roll", Path(__file__).with_name("region-group-roll.py")) |
| +roll = importlib.util.module_from_spec(_SPEC) |
| +_SPEC.loader.exec_module(roll) |
| + |
| +MAX_BUNDLE_B64 = 60000 |
| +TEXT = { |
| + "nonce": "Use a 32-character lowercase hexadecimal nonce", |
| + "frame": "The maintenance command frame has changed", |
| + "bundle": "Use 1 to 60000 base64 characters for the witness bundle", |
| + "sha256": "Use a 64-character lowercase hexadecimal bundle SHA256 digest", |
| + "verb": "Use status, disarm, remove, uninstall, arm-fault or arm-pause", |
| + "arguments": "Only arm-fault and arm-pause accept identity and duration arguments", |
| + "iid": "Use an instance ID with 8 or 17 lowercase hexadecimal digits", |
| + "boot": "Use a lowercase UUID for the boot ID", |
| + "transaction": "Use 1 to 80 letters, digits, underscores or hyphens for the transaction", |
| + "minutes": "Use a duration from 1 to 999 minutes without leading zeros", |
| +} |
| + |
| + |
| +def _check(pattern, value, key): |
| + if not isinstance(value, str) or re.fullmatch(pattern, value) is None: |
| + raise ValueError(TEXT[key]) |
| + |
| + |
| +def frame_command(inner, nonce): |
| + """Reuse the status frame, replacing only its inner command before quoting.""" |
| + _check(r"[0-9a-f]{32}", nonce, "nonce") |
| + template = roll.AWS.remote_command({"verb": "status"}, nonce) |
| + script = shlex.split(template)[-1] |
| + quoted = shlex.quote(script) |
| + anchor = "/opt/carlos/carlos system group-maintenance status" |
| + if not template.endswith(quoted) or script.count(anchor) != 1: |
| + raise ValueError(TEXT["frame"]) |
| + return template[:-len(quoted)] + shlex.quote(script.replace(anchor, inner, 1)) |
| + |
| + |
| +def install_command(bundle_b64, sha256, nonce): |
| + """Frame the hash-pinned harness installation without executing it.""" |
| + if not isinstance(bundle_b64, str) or not 1 <= len(bundle_b64) <= MAX_BUNDLE_B64: |
| + raise ValueError(TEXT["bundle"]) |
| + _check(r"[A-Za-z0-9+/=]+", bundle_b64, "bundle") |
| + _check(r"[0-9a-f]{64}", sha256, "sha256") |
| + inner = ( |
| + "umask 077 && mkdir -p -m 0700 /run/carlos-p3b2-fault && printf %s " + bundle_b64 + |
| + " > /run/carlos-p3b2-fault/bundle.b64 && base64 -d /run/carlos-p3b2-fault/bundle.b64" |
| + " > /run/carlos-p3b2-fault/bundle.tar && [ \"$(sha256sum /run/carlos-p3b2-fault/bundle.tar" |
| + " | cut -c1-64)\" = " + sha256 + |
| + " ] && mkdir -p -m 0700 /usr/local/lib/carlos-p3b2-fault" |
| + " && tar --no-same-owner --no-same-permissions -x -f /run/carlos-p3b2-fault/bundle.tar" |
| + " -C /usr/local/lib/carlos-p3b2-fault" |
| + " && /bin/sh /usr/local/lib/carlos-p3b2-fault/fault.sh install") |
| + return frame_command(inner, nonce) |
| + |
| + |
| +def harness_command(verb, nonce, *, iid=None, boot=None, transaction=None, minutes=None): |
| + """Frame a harness control command; arm commands require all four fields.""" |
| + inner = "/bin/sh /usr/local/lib/carlos-p3b2-fault/fault.sh " |
| + if verb in {"status", "disarm", "remove", "uninstall"}: |
| + if any(value is not None for value in (iid, boot, transaction, minutes)): |
| + raise ValueError(TEXT["arguments"]) |
| + return frame_command(inner + verb, nonce) |
| + if verb not in {"arm-fault", "arm-pause"}: |
| + raise ValueError(TEXT["verb"]) |
| + _check(r"i-([0-9a-f]{8}|[0-9a-f]{17})", iid, "iid") |
| + _check(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", boot, "boot") |
| + _check(r"[A-Za-z0-9_-]{1,80}", transaction, "transaction") |
| + _check(r"[1-9][0-9]{0,2}", str(minutes), "minutes") |
| + return frame_command(inner + verb + " --iid " + iid + " --boot " + boot + |
| + " --transaction " + transaction + " --minutes " + str(minutes), nonce) |