carlos / platform Public

Merge branch 'region-ha-p3b-t3' into region-ha-p3b-build

Paul Campbell pushed by claude agent, operated by paul@keymail.dev 43177b608d7da6f625c2031aaae2460784acd57b parent 9dfeecaparent 741a8e4
39 files changed, +2,343 −48
  • docs/site/cli.md +3 −1
  • infra/modules/region-host/group-init.sh.tftpl +190 −4
  • infra/modules/region-host/group.tf +2 −0
  • infra/modules/region-host/tests/group.tftest.hcl +19 −0
  • infra/modules/region-host/variables.tf +2 −1
  • internal/awsregiongroup/complete.go +52 −0
  • internal/awsregiongroup/complete_test.go +83 −0
  • internal/host/agent.go +28 −2
  • internal/host/bootstrap.go +22 −0
  • internal/host/boxrecord.go +18 −1
  • internal/host/group_admission.go +84 −16
  • internal/host/group_admission_test.go +1 −1
  • internal/host/group_boot.go +139 −0
  • internal/host/group_boot_test.go +209 −0
  • internal/host/group_config.go +16 −0
  • internal/host/group_config_linux.go +71 −0
  • internal/host/group_config_other.go +7 −0
  • internal/host/group_config_test.go +64 −0
  • internal/host/group_departure_test.go +114 −0
  • internal/host/group_install.go +25 −0
  • internal/host/group_receipt.go +158 −0
  • internal/host/group_receipt_linux.go +110 −0
  • internal/host/group_receipt_other.go +7 −0
  • internal/host/group_receipt_test.go +110 −0
  • internal/host/hadepartures.go +32 −1
  • internal/host/hadepartures_production_test.go +69 −2
  • internal/host/hadepartures_scan.go +15 −0
  • internal/host/hadepartures_wiring.go +11 −1
  • internal/host/installchannel.go +70 −9
  • internal/host/installchannel_test.go +68 −0
  • internal/host/units/carlos-edge-group.conf +6 −0
  • internal/hostenv/awsssm.go +57 −4
  • internal/hostenv/cli.go +47 −3
  • internal/hostenv/group.go +192 −0
  • internal/hostenv/group_linux.go +55 −0
  • internal/hostenv/group_linux_test.go +44 −0
  • internal/hostenv/group_other.go +12 −0
  • internal/hostenv/group_test.go +124 −0
  • scripts/region_group_contract_test.py +7 −2
diff --git a/docs/site/cli.md b/docs/site/cli.md
index a4bfa2ea2..e1c9b38b7 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -3005,7 +3005,9 @@ In a region with HA on, the boxes its Auto Scaling group launches set themselves
carlos system host-env write builds /etc/carlos/host.env from the deployment's parameters: SecureStrings in AWS SSM under /carlos/<deployment>/<region>/ and, for the values every region shares, /carlos/<deployment>/shared/. If a required value is missing, it stops and writes nothing.
-carlos system install-channel installs the release the box's channel names, as both carlos and carlos.prev, once it passes the published host floor. A box that already runs a release is refused: carlos system update moves it.
+For claim-free group boot, `host-env write --group --install` checks the root-owned group configuration, leaves out host-claim variables, writes the environment, then runs bootstrap and install-channel. The boot queue overrides a queue copied from a fixed box. Pools must be explicit and match the group configuration. `--install` requires `--group`.
+
+carlos system install-channel installs the release the box's channel names, as both carlos and carlos.prev, once it passes the published host floor. A box that already runs a release is refused: carlos system update moves it. A claim-free group can install when both the floor and its authorization are absent. A missing half or a failed read stops installation.
With --policy FILE, the armed policy carlos system claims run sign-policy wrote, it installs before the host floor is published. The policy's floor stands in for the published one, and once a floor is published the two must be the same. It also arms a box that carlos system update has already moved to the channel's release: carlos is left as it is, and carlos.prev, the release before, is replaced by it, so guard-arm finds the release in both. A box on another release, or with an armed guard, is still refused.
diff --git a/infra/modules/region-host/group-init.sh.tftpl b/infra/modules/region-host/group-init.sh.tftpl
index fecafb973..57de1c142 100644
--- a/infra/modules/region-host/group-init.sh.tftpl
+++ b/infra/modules/region-host/group-init.sh.tftpl
@@ -6,7 +6,193 @@ ${key}=${value}
export ${key}
%{ endfor ~}
-# TASK 3: harden, fetch and verify bootstrap, write root configuration,
-# install the pinned release, then start the guarded group agent.
-# Until those steps exist, leave the initial launch hook to ABANDON.
-exit 1
+# TASK 3: claim-free initial boot. No maintenance return controller runs here.
+# Bound the entire local boot, including package work. The signed pendingTime
+# below supplies the stricter original launch deadline for completion.
+if [ "$${CARLOS_GROUP_BOOT_BOUNDED:-}" != 1 ]; then
+ export CARLOS_GROUP_BOOT_BOUNDED=1
+ exec timeout 840 /bin/sh "$0"
+fi
+export DEBIAN_FRONTEND=noninteractive AWS_MAX_ATTEMPTS=1 AWS_RETRY_MODE=standard
+
+# Only root-owned real directories may hold boot inputs or executed bytes.
+python3 - <<'PY'
+import os, stat
+for path in ['/etc/apt/apt.conf.d', '/etc/needrestart/conf.d', '/etc/carlos', '/etc/chrony/conf.d', '/etc/systemd/system/carlos-edge.service.d', '/run/carlos-group-boot']:
+ fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY)
+ try:
+ for part in path.strip('/').split('/'):
+ try:
+ os.mkdir(part, 0o755, dir_fd=fd)
+ os.chmod(part, 0o755, dir_fd=fd, follow_symlinks=False)
+ except FileExistsError:
+ pass
+ child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
+ os.close(fd)
+ fd = child
+ st = os.fstat(fd)
+ if st.st_uid != 0 or st.st_mode & 0o022:
+ raise SystemExit('group_boot_directory')
+ finally:
+ os.close(fd)
+PY
+
+# disable unattended updates
+systemctl disable --now apt-daily.timer apt-daily-upgrade.timer
+systemctl mask --now apt-daily.timer apt-daily-upgrade.timer apt-daily.service apt-daily-upgrade.service unattended-upgrades.service
+python3 - <<'PY'
+import os
+files = {
+ '/etc/apt/apt.conf.d/99-carlos-group': 'APT::Periodic::Enable "0";\nUnattended-Upgrade::Automatic-Reboot "false";\n',
+ '/etc/needrestart/conf.d/carlos-group.conf': "$nrconf{restart} = 'l';\n",
+ '/etc/systemd/system/carlos-edge.service.d/50-group.conf': '[Unit]\nRequires=nftables.service\nAfter=nftables.service\n\n[Service]\nRestart=no\n',
+}
+for path, body in files.items():
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
+ os.fchmod(fd, 0o644)
+ with os.fdopen(fd, 'w') as f:
+ f.write(body)
+ f.flush()
+ os.fsync(f.fileno())
+PY
+export NEEDRESTART_MODE=l
+apt-get -q update
+apt-get -y -q install nftables chrony awscli
+getent passwd carlos >/dev/null || useradd --system --home-dir /data --shell /usr/sbin/nologin carlos
+CARLOS_UID=$(id -u carlos)
+export CARLOS_UID
+
+# harden metadata
+# Root and the service account need instance credentials. Tenant users and
+# forwarded namespace traffic cannot reach either metadata address.
+nft -f - <<NFT
+table inet carlos_group_imds {
+ chain output { type filter hook output priority -310; policy accept;
+ meta skuid != { 0, $CARLOS_UID } ip daddr 169.254.169.254 reject
+ meta skuid != { 0, $CARLOS_UID } ip6 daddr fd00:ec2::254 reject
+ }
+ chain forward { type filter hook forward priority -310; policy accept;
+ ip daddr 169.254.169.254 reject
+ ip6 daddr fd00:ec2::254 reject
+ }
+}
+NFT
+python3 - <<'PYCODE'
+import os, stat, subprocess
+body = subprocess.check_output(['nft', '-s', 'list', 'table', 'inet', 'carlos_group_imds'])
+path = '/etc/nftables.conf'
+st = os.lstat(path)
+if not stat.S_ISREG(st.st_mode) or st.st_uid != 0 or st.st_mode & 0o022 or st.st_nlink != 1:
+ raise SystemExit('group_boot_nft_config')
+tmp = '/etc/.carlos-group-nftables'
+fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
+os.fchmod(fd, 0o644)
+with os.fdopen(fd, 'wb') as f:
+ f.write(body)
+ f.flush()
+ os.fsync(f.fileno())
+os.replace(tmp, path)
+fd = os.open('/etc', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+os.fsync(fd)
+os.close(fd)
+PYCODE
+systemctl enable nftables.service
+systemctl restart nftables.service
+nft list table inet carlos_group_imds >/dev/null
+
+# configure chrony
+printf '%s\n' 'server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4' > /run/carlos-group-boot/chrony.conf
+install -o root -g root -m 0644 /run/carlos-group-boot/chrony.conf /etc/chrony/conf.d/carlos-group.conf
+systemctl enable --now chrony.service
+chronyc waitsync 20 2
+
+# fetch verified bootstrap
+# The three boot values are read once; ordinary SSM enumeration is separate.
+python3 - <<'PY'
+import base64, datetime, hashlib, ipaddress, json, os, re, subprocess, time, urllib.request
+E = os.environ
+work = '/run/carlos-group-boot/'
+prefix = '/carlos/' + E['CARLOS_DEPLOYMENT'] + '/' + E['CARLOS_REGION'] + '/boot/'
+def aws(*args, region=None):
+ return json.loads(subprocess.check_output(['aws', '--region', region or E['AWS_REGION'], '--cli-connect-timeout', '2', '--cli-read-timeout', '60', *args, '--output', 'json'], timeout=90))
+def write(path, body, mode=0o644):
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
+ os.fchmod(fd, mode)
+ with os.fdopen(fd, 'wb') as f:
+ f.write(body)
+ f.flush()
+ os.fsync(f.fileno())
+names = [E['CARLOS_BOOTSTRAP_OBJECT_KEY'], E['CARLOS_BOOTSTRAP_HASH_KEY'], prefix + 'CARLOS_TERMINATION_QUEUE_URL']
+response = aws('ssm', 'get-parameters', '--names', *names, '--with-decryption')
+params = response.get('Parameters', [])
+if response.get('InvalidParameters') or len(params) != len(names) or {p['Name'] for p in params} != set(names):
+ raise SystemExit('group_boot_parameters')
+values = {p['Name']: p['Value'] for p in params}
+obj = json.loads(values[names[0]])
+if set(obj) != {'key', 'version', 'known_readers', 'deployment_aws_region'} or not isinstance(obj['known_readers'], list) or len(obj['known_readers']) > 1000:
+ raise SystemExit('group_boot_object')
+if not obj['key'].startswith('bootstrap/' + E['CARLOS_DEPLOYMENT'] + '/' + E['CARLOS_REGION'] + '/') or not obj['version'] or obj['version'] == 'null':
+ raise SystemExit('group_boot_object')
+if not re.fullmatch('[a-z]{2}(-[a-z]+)+-[0-9]', obj['deployment_aws_region']):
+ raise SystemExit('group_boot_region')
+sha = values[names[1]]
+if not re.fullmatch('[0-9a-f]{64}', sha):
+ raise SystemExit('group_boot_hash')
+aws('s3api', 'get-object', '--bucket', E['CARLOS_DEPLOYMENT_BUCKET'], '--key', obj['key'], '--version-id', obj['version'], work + 'bootstrap', region=obj['deployment_aws_region'])
+with open(work + 'bootstrap', 'rb') as f:
+ if hashlib.file_digest(f, 'sha256').hexdigest() != sha:
+ raise SystemExit('group_boot_hash')
+os.chmod(work + 'bootstrap', 0o755)
+# Three IMDS requests, reused by the agent through the signed root snapshot.
+def imds(path, method='GET', headers=None):
+ request = urllib.request.Request('http://169.254.169.254' + path, method=method, headers=headers or {})
+ with urllib.request.urlopen(request, timeout=2) as response:
+ return response.read(65537)
+token = imds('/latest/api/token', 'PUT', {'X-aws-ec2-metadata-token-ttl-seconds': '60'}).decode().strip()
+headers = {'X-aws-ec2-metadata-token': token}
+doc = imds('/latest/dynamic/instance-identity/document', headers=headers)
+sig = b''.join(imds('/latest/dynamic/instance-identity/signature', headers=headers).split()).decode()
+identity = json.loads(doc)
+if identity['accountId'] != E['CARLOS_GROUP_ACCOUNT'] or identity['region'] != E['AWS_REGION']:
+ raise SystemExit('group_boot_identity')
+iid = identity['instanceId']
+ref = 'g-' + hashlib.sha256(('carlos-box-ref-v1|' + identity['accountId'] + '|' + iid).encode()).hexdigest()[:20]
+record = dict(v=1, box=ref, identity_document=base64.b64encode(doc).decode(), identity_signature=sig, written_at=datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'))
+write('/etc/carlos/group-identity.json', json.dumps(record, separators=(',', ':')).encode())
+boot_id = open('/proc/sys/kernel/random/boot_id').read().strip()
+deadline = int(datetime.datetime.fromisoformat(identity['pendingTime'].replace('Z', '+00:00')).timestamp()) + 900
+if time.time() >= deadline:
+ raise SystemExit('group_boot_deadline')
+# write immutable group configuration
+region = dict(v=1, region_code=E['CARLOS_REGION'], placement=E['CARLOS_PLACEMENT_REGION'])
+write('/etc/carlos/region-config.json', json.dumps(region, separators=(',', ':')).encode())
+ingress = aws('ssm', 'get-parameter', '--name', E['CARLOS_INGRESS_KEY'], '--with-decryption')
+if ingress['Parameter']['Name'] != E['CARLOS_INGRESS_KEY']:
+ raise SystemExit('group_boot_ingress')
+ips = json.loads(ingress['Parameter']['Value'])
+if not isinstance(ips, list) or not ips or len(ips) != len(set(ips)) or len(ips) > 16:
+ raise SystemExit('group_boot_ingress')
+for ip in ips:
+ address = ipaddress.ip_address(ip)
+ if address.version != 4 or not address.is_global:
+ raise SystemExit('group_boot_ingress')
+write('/etc/carlos/group-ingress.json', json.dumps(dict(v=1, region=E['CARLOS_REGION'], public_ips=ips), separators=(',', ':')).encode())
+marker = dict(v=1, data_bucket=E['CARLOS_GROUP_DATA_BUCKET'], deployment_aws_region=obj['deployment_aws_region'], account=identity['accountId'], aws_region=E['AWS_REGION'], region=E['CARLOS_REGION'], deployment=E['CARLOS_DEPLOYMENT'], bucket=E['CARLOS_DEPLOYMENT_BUCKET'], group=E['CARLOS_GROUP_NAME'], hook=E['CARLOS_LAUNCH_HOOK_NAME'], placement=E['CARLOS_PLACEMENT_REGION'], pools=E['CARLOS_POOLS'].split(','), known_readers=obj['known_readers'], release=E['CARLOS_RELEASE'], instance_id=iid, boot_id=boot_id, deadline=deadline, queue_url=values[names[2]])
+marker['config_digest'] = hashlib.sha256(json.dumps(marker, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
+write('/etc/carlos/group.json', json.dumps(marker, separators=(',', ':')).encode())
+PY
+
+# install dormant hairpin
+# Deliberate no-op until Task 5 supplies the rules and admission activation.
+# Task 4 supplies root restart authorization and preserves this drop-in.
+test "$(cat /etc/systemd/system/carlos-edge.service.d/50-group.conf)" = "$(printf '[Unit]\nRequires=nftables.service\nAfter=nftables.service\n\n[Service]\nRestart=no')"
+
+# bootstrap and install channel
+/run/carlos-group-boot/bootstrap system host-env write --group --deployment "$CARLOS_DEPLOYMENT" --region "$CARLOS_REGION" --aws-region "$AWS_REGION" --install
+# host.env is parsed as data by the verified binary; it is never sourced.
+
+# start guarded agent
+systemctl daemon-reload
+test "$(systemctl show carlos-edge.service --property=Restart --value)" = no
+systemctl start carlos-edge.service
+rm -rf /run/carlos-group-boot
diff --git a/infra/modules/region-host/group.tf b/infra/modules/region-host/group.tf
index d873bcd9d..c8db13566 100644
--- a/infra/modules/region-host/group.tf
+++ b/infra/modules/region-host/group.tf
@@ -188,6 +188,8 @@ resource "aws_launch_template" "group" {
CARLOS_BOOTSTRAP_OBJECT_KEY = "${local.group_ssm_path}/boot/bootstrap-object"
CARLOS_BOOTSTRAP_HASH_KEY = "${local.group_ssm_path}/boot/bootstrap-sha256"
CARLOS_INGRESS_KEY = "${local.group_ssm_path}/boot/ingress"
+ CARLOS_GROUP_DATA_BUCKET = trimprefix(var.data_bucket_arn, "arn:${data.aws_partition.current[0].partition}:s3:::")
+ CARLOS_GROUP_ACCOUNT = data.aws_caller_identity.current.account_id
CARLOS_GROUP_NAME = var.name
CARLOS_LAUNCH_HOOK_NAME = local.group_hook_name
CARLOS_TERMINATION_QUEUE_URL = aws_sqs_queue.terminations.id
diff --git a/infra/modules/region-host/tests/group.tftest.hcl b/infra/modules/region-host/tests/group.tftest.hcl
index bd949ce39..1f6342f94 100644
--- a/infra/modules/region-host/tests/group.tftest.hcl
+++ b/infra/modules/region-host/tests/group.tftest.hcl
@@ -397,3 +397,22 @@ override_data {
target = data.aws_ami.group
values = { id = "ami-0123456789abcdef0", root_device_name = "/dev/xvda", root_device_type = "ebs" }
}
+
+run "group_home_placement" {
+ command = plan
+ variables {
+ group_config = {
+ deployment = "dev"
+ region = "ie"
+ placement_region = ""
+ pools = ["default"]
+ ami_id = "ami-0123456789abcdef0"
+ release = "v0.100.0"
+ configuration_kms_key_arn = "arn:aws:kms:eu-west-1:123456789012:key/00000000-0000-0000-0000-000000000001"
+ }
+ }
+ assert {
+ condition = strcontains(base64decode(aws_launch_template.group[0].user_data), "CARLOS_PLACEMENT_REGION=''")
+ error_message = "group home placement must remain empty beside its canonical region"
+ }
+}
diff --git a/infra/modules/region-host/variables.tf b/infra/modules/region-host/variables.tf
index c7571f284..3d771b36e 100644
--- a/infra/modules/region-host/variables.tf
+++ b/infra/modules/region-host/variables.tf
@@ -292,8 +292,9 @@ variable "group_config" {
default = null
validation {
condition = var.mode != "group" || var.group_config == null ? true : (
- alltrue([for value in [var.group_config.deployment, var.group_config.region, var.group_config.placement_region] : can(regex("^[a-z][a-z0-9-]{0,31}$", value))]) &&
+ alltrue([for value in [var.group_config.deployment, var.group_config.region] : can(regex("^[a-z][a-z0-9-]{0,31}$", value))]) &&
var.group_config.region != "shared" &&
+ (var.group_config.placement_region == "" || var.group_config.placement_region == var.group_config.region) &&
length(var.group_config.pools) > 0 && alltrue([for pool in var.group_config.pools : can(regex("^[a-z][a-z0-9-]{0,31}$", pool))]) &&
can(regex("^ami-[0-9a-f]{17}$", var.group_config.ami_id)) &&
can(regex("^(v[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9.-]+)?|[0-9a-f]{64})$", var.group_config.release)) &&
diff --git a/internal/awsregiongroup/complete.go b/internal/awsregiongroup/complete.go
new file mode 100644
index 000000000..f8785e096
--- /dev/null
+++ b/internal/awsregiongroup/complete.go
@@ -0,0 +1,52 @@
+// Package awsregiongroup completes only a box's original launch action.
+package awsregiongroup
+
+import (
+ "context"
+ "errors"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/autoscaling"
+ "github.com/aws/smithy-go"
+ "github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/groupadmission"
+)
+
+var ErrRejected = errors.New("group_launch_rejected")
+var ErrIdentity = errors.New("group_launch_identity")
+
+type completeCall func(context.Context, *autoscaling.CompleteLifecycleActionInput, ...func(*autoscaling.Options)) (*autoscaling.CompleteLifecycleActionOutput, error)
+type Completer struct {
+ launch groupadmission.Launch
+ cloud boxid.Cloud
+ call completeCall
+}
+
+// New verifies the signed instance document against the root boot binding.
+// Keeping only this method value avoids retaining the whole ASG client API.
+func New(cfg aws.Config, raw []byte, verifier boxid.Verifier, expect boxid.Expect, launch groupadmission.Launch) (*Completer, error) {
+ evidence, err := verifier.Enroll(raw, expect)
+ if err != nil {
+ return nil, err
+ }
+ if launch.Instance != evidence.Cloud.InstanceID || launch.Instance != expect.TofuInstanceID || launch.Group == "" || launch.Hook != "carlos-initial-launch" || cfg.Region != evidence.Cloud.Region {
+ return nil, ErrIdentity
+ }
+ client := autoscaling.NewFromConfig(cfg, func(o *autoscaling.Options) { o.RetryMaxAttempts = 1 })
+ return &Completer{launch: launch, cloud: evidence.Cloud, call: client.CompleteLifecycleAction}, nil
+}
+func (c *Completer) Complete(ctx context.Context, l groupadmission.Launch) error {
+ if c == nil || c.call == nil || l != c.launch || !c.cloud.Complete() || l.Instance != c.cloud.InstanceID {
+ return ErrIdentity
+ }
+ _, err := c.call(ctx, &autoscaling.CompleteLifecycleActionInput{AutoScalingGroupName: aws.String(l.Group), LifecycleHookName: aws.String(l.Hook), InstanceId: aws.String(l.Instance), LifecycleActionResult: aws.String("CONTINUE")}, func(o *autoscaling.Options) { o.RetryMaxAttempts = 1 })
+ // Only explicit provider refusals prove that this attempt did not complete.
+ // Timeouts, transport loss, server errors and "no active hook" stay unknown.
+ var api smithy.APIError
+ if errors.As(err, &api) {
+ switch api.ErrorCode() {
+ case "Throttling", "ThrottlingException", "ResourceContention", "ResourceContentionFault", "AccessDenied", "AccessDeniedException":
+ return errors.Join(ErrRejected, err)
+ }
+ }
+ return err
+}
diff --git a/internal/awsregiongroup/complete_test.go b/internal/awsregiongroup/complete_test.go
new file mode 100644
index 000000000..311e5949c
--- /dev/null
+++ b/internal/awsregiongroup/complete_test.go
@@ -0,0 +1,83 @@
+package awsregiongroup
+
+import (
+ "context"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/service/autoscaling"
+ "github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/boxid/boxidtest"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+)
+
+func TestGroupComplete(t *testing.T) {
+ l := groupadmission.Launch{Group: "dev-ie", Hook: "carlos-initial-launch", Instance: "i-0123456789abcdef0"}
+ n := 0
+ c := &Completer{launch: l, cloud: boxid.Cloud{Provider: "aws", Account: "123456789012", Region: "eu-west-1", InstanceID: l.Instance}, call: func(ctx context.Context, in *autoscaling.CompleteLifecycleActionInput, opts ...func(*autoscaling.Options)) (*autoscaling.CompleteLifecycleActionOutput, error) {
+ n++
+ o := autoscaling.Options{}
+ for _, f := range opts {
+ f(&o)
+ }
+ if aws.ToString(in.InstanceId) != l.Instance || in.LifecycleActionToken != nil || aws.ToString(in.LifecycleActionResult) != "CONTINUE" || aws.ToString(in.AutoScalingGroupName) != l.Group || aws.ToString(in.LifecycleHookName) != l.Hook || o.RetryMaxAttempts != 1 {
+ t.Fatal(in, o.RetryMaxAttempts)
+ }
+ return &autoscaling.CompleteLifecycleActionOutput{}, nil
+ }}
+ if err := c.Complete(t.Context(), l); err != nil {
+ t.Fatal(err)
+ }
+ wrong := l
+ wrong.Instance = "i-other"
+ if c.Complete(t.Context(), wrong) == nil || n != 1 {
+ t.Fatal("wrong identity called AWS")
+ }
+}
+
+func TestGroupCompleteSignedIdentity(t *testing.T) {
+ signer := boxidtest.NewSigner(t)
+ _, raw := signer.Record(t, "self", "123456789012", "eu-west-1", "i-0123456789abcdef0")
+ launch := groupadmission.Launch{Group: "dev-ie", Hook: "carlos-initial-launch", Instance: "i-0123456789abcdef0"}
+ verifier := boxid.Verifier{Account: "123456789012", Certs: signer.Certs()}
+ expect := boxid.Expect{Box: "self", AWSRegion: "eu-west-1", TofuInstanceID: launch.Instance}
+ calls := 0
+ cfg := aws.Config{Region: "eu-west-1", Credentials: credentials.NewStaticCredentialsProvider("test", "test", ""), HTTPClient: groupHTTPFunc(func(r *http.Request) (*http.Response, error) {
+ calls++
+ return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`<CompleteLifecycleActionResponse xmlns="http://autoscaling.amazonaws.com/doc/2011-01-01/"><CompleteLifecycleActionResult/><ResponseMetadata><RequestId>test</RequestId></ResponseMetadata></CompleteLifecycleActionResponse>`))}, nil
+ })}
+ c, err := New(cfg, raw, verifier, expect, launch)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = c.Complete(t.Context(), launch); err != nil {
+ t.Fatal(err)
+ }
+ if calls != 1 {
+ t.Fatal(calls)
+ }
+ verifier.Account = "999999999999"
+ if _, err = New(cfg, raw, verifier, expect, launch); err == nil {
+ t.Fatal("foreign account")
+ }
+ verifier.Account = "123456789012"
+ expect.TofuInstanceID = "i-1123456789abcdef0"
+ if _, err = New(cfg, raw, verifier, expect, launch); err == nil {
+ t.Fatal("foreign iid")
+ }
+ expect.TofuInstanceID = launch.Instance
+ cfg.Region = "us-east-1"
+ if _, err = New(cfg, raw, verifier, expect, launch); err == nil {
+ t.Fatal("foreign region")
+ }
+ if calls != 1 {
+ t.Fatal("identity failures called provider")
+ }
+}
+
+type groupHTTPFunc func(*http.Request) (*http.Response, error)
+
+func (f groupHTTPFunc) Do(r *http.Request) (*http.Response, error) { return f(r) }
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 0a71009a4..703f6eea4 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -232,8 +232,27 @@ func dataDir() string {
// account or region IMDS did not answer within 2 seconds is asked for
// again every minute.
func RunAgent(args []string) {
+ groupBoot, err := loadGroupConfiguration(os.Getenv)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if groupBoot != nil {
+ if _, _, _, err = groupBootEvidence(*groupBoot); err != nil {
+ log.Fatal(err)
+ }
+ groupRef.Lock()
+ groupRef.ref = groupReferenceOf(groupBoot.Account, groupBoot.InstanceID)
+ groupRef.Unlock()
+ }
var self hafresh.Self
- identity := func() hafresh.Self { self = haSelfNow(os.Getenv, haIMDSClient); return self }
+ identity := func() hafresh.Self {
+ if groupBoot != nil {
+ self = hafresh.Self{Ref: groupReferenceOf(groupBoot.Account, groupBoot.InstanceID), IID: groupBoot.InstanceID, Account: groupBoot.Account, Region: groupBoot.AWSRegion, Boot: readBootID(bootIDPath)}
+ } else {
+ self = haSelfNow(os.Getenv, haIMDSClient)
+ }
+ return self
+ }
agentEntry(os.Getenv, resolveGroupBoxReference, groupReferenceBackoff, log.Printf, identity, func() {
startHASelfRetry(context.Background(), self, os.Getenv, haIMDSClient, time.Minute, lease.SetSelf)
runAgent(args, productionClaimFactory)
@@ -243,7 +262,14 @@ func RunAgent(args []string) {
func runAgent(args []string, buildClaims ClaimFactory) {
agentCtx, cancelAgent := context.WithCancel(context.Background())
defer cancelAgent()
+ groupBoot, err := loadGroupConfiguration(os.Getenv)
+ if err != nil {
+ log.Fatal(err)
+ }
admission := newFixedAdmission(os.Getenv, lbhealth.Default)
+ if err = configureGroupAdmission(agentCtx, admission, groupBoot); err != nil {
+ log.Fatal(err)
+ }
admissionOption := wireAgentAdmission(admission, nil, nil, nil)
if admission != nil {
armedFixedAdmission.Store(admission)
@@ -597,7 +623,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
}, reg) // the registry satisfies activator.DueStore directly
svc.DutyStore = reg
admissionOption = wireAgentAdmission(admission, svc, eb, func() hadeparture.Lifecycle {
- departures, departureLife, err = armHADepartures(agentCtx, departureArm{Getenv: os.Getenv, Registry: reg, Service: svc, Backend: eb, Confirmer: confirmer, Inventory: boxDepartureInventory, OpenStore: openDeployStore})
+ departures, departureLife, err = armHADepartures(agentCtx, departureArm{Admitted: func() bool { return admission == nil || admission.startAllowed() }, BeginWork: admission.beginDepartureWork, Getenv: os.Getenv, Registry: reg, Service: svc, Backend: eb, Confirmer: confirmer, Inventory: boxDepartureInventory, OpenStore: openDeployStore})
if err != nil {
log.Printf("ha_departure_init code=unavailable")
}
diff --git a/internal/host/bootstrap.go b/internal/host/bootstrap.go
index 48ed5652e..5c8b5eaad 100644
--- a/internal/host/bootstrap.go
+++ b/internal/host/bootstrap.go
@@ -12,6 +12,7 @@ package host
import (
"github.com/carlosframework/platform/internal/cliflag"
"github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/hostenv"
"bytes"
"embed"
@@ -311,7 +312,23 @@ func RunBootstrap(args []string) {
if *planJSON && filepath.Clean(*root) == "/" {
log.Fatal("bootstrap: -plan-json is for a staging root")
}
+ var group *hostenv.GroupConfig
+ if filepath.Clean(*root) == "/" {
+ var err error
+ group, err = loadGroupConfiguration(os.Getenv)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if group != nil {
+ if _, _, _, err = groupBootEvidence(*group); err != nil {
+ log.Fatal(err)
+ }
+ }
+ }
if *offcloud {
+ if group != nil {
+ log.Fatal(hostenv.ErrGroupConfig)
+ }
if err := bootstrapOffcloud(*root, consumers); err != nil {
log.Fatalf("bootstrap: %v", err)
}
@@ -320,6 +337,11 @@ func RunBootstrap(args []string) {
if err := bootstrapWith(*root, consumers, *planJSON); err != nil {
log.Fatalf("bootstrap: %v", err)
}
+ if group != nil {
+ if err := initializeGroupLaunch(*group); err != nil {
+ log.Fatal(err)
+ }
+ }
}
// repeatableFlag collects every occurrence of a string flag.
diff --git a/internal/host/boxrecord.go b/internal/host/boxrecord.go
index f220f1593..7280d5046 100644
--- a/internal/host/boxrecord.go
+++ b/internal/host/boxrecord.go
@@ -15,6 +15,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/hostenv"
"github.com/carlosframework/platform/internal/release"
)
@@ -176,7 +177,23 @@ func boxRecordLoop() {
// IMDS may not answer yet: that is a retry, never a refusal
// (boxreference.go).
box := metricsBoxLabel(os.Getenv, readMachineID())
- read := func() (boxid.Record, error) { return readIdentityRecord(client, imdsBase, box, time.Now()) }
+ read := func() (boxid.Record, error) {
+ if groupReferenced(os.Getenv) {
+ raw, err := hostenv.ReadGroupFile(groupIdentityPath, 0, 0644)
+ if err != nil {
+ return boxid.Record{}, err
+ }
+ var rec boxid.Record
+ if err = json.Unmarshal(raw, &rec); err != nil {
+ return rec, err
+ }
+ if rec.Box != box {
+ return rec, hostenv.ErrGroupConfig
+ }
+ return rec, nil
+ }
+ return readIdentityRecord(client, imdsBase, box, time.Now())
+ }
done, err := false, errors.New("this box's group reference could not be read")
if box != "" {
done, err = publishBoxRecord(ctx, store, box, read)
diff --git a/internal/host/group_admission.go b/internal/host/group_admission.go
index e970f6f1e..07269e836 100644
--- a/internal/host/group_admission.go
+++ b/internal/host/group_admission.go
@@ -23,7 +23,17 @@ import (
var armedFixedAdmission atomic.Pointer[fixedAdmission]
type fixedAdmission struct {
+ launchFailure string
+ workMu sync.Mutex
+ workCtx context.Context
+ workCancel context.CancelFunc
+ workWG sync.WaitGroup
group bool
+ launch *groupadmission.Launch
+ completer groupadmission.Completer
+ allowed atomic.Bool
+ openOnce sync.Once
+ knownReaders []string
readers func() edgesfile.ReaderSnapshot
readerSelf string
mu sync.Mutex
@@ -46,7 +56,7 @@ func newFixedAdmission(getenv func(string) string, health *lbhealth.State) *fixe
enabled, _ := strconv.ParseBool(getenv("CARLOS_REGION_HA"))
switch {
case getenv("CARLOS_BOX_REFERENCE") == "group":
- a.refusal = "tenant admission is closed. this release does not support admission for group boxes. remove CARLOS_BOX_REFERENCE=group or use a release that supports group admission"
+ a.refusal = "group_configuration_required"
case !enabled:
a.refusal = "tenant admission is closed. CARLOS_GROUP_ADMISSION=1 requires CARLOS_REGION_HA=true. set CARLOS_REGION_HA=true or remove CARLOS_GROUP_ADMISSION=1"
}
@@ -83,13 +93,16 @@ func (a *fixedAdmission) observe(f groupadmission.Facts) {
func (a *fixedAdmission) applyRole(role boxroles.Role, known bool) error {
a.mu.Lock()
defer a.mu.Unlock()
- if known && role != boxroles.Serve && role != boxroles.Drain && role != boxroles.Platform {
+ if known && ((a.group && role != boxroles.Serve) || (role != boxroles.Serve && role != boxroles.Drain && role != boxroles.Platform)) {
+ a.known = false
+ a.allowed.Store(false)
return errors.New("admission_invalid_role")
}
if known {
a.role = role
}
a.known = known
+ a.allowed.Store(!a.closed && a.refusal == "" && known && (!a.group || role == boxroles.Serve))
return nil
}
func (a *fixedAdmission) startAllowed() bool {
@@ -117,8 +130,8 @@ func (a *fixedAdmission) tick(ctx context.Context) {
return
}
a.mu.Lock()
- defer a.mu.Unlock()
if a.closed || a.refusal != "" {
+ a.mu.Unlock()
return
}
if a.life != nil {
@@ -128,42 +141,88 @@ func (a *fixedAdmission) tick(ctx context.Context) {
default:
}
}
- if !a.state.Admitted() && !a.groupReadersReady(time.Now()) {
- return
- }
- if !a.state.Ready() {
- a.logWaitingLocked(time.Now())
- return
- }
- a.health.SetHosting(true)
if a.state.Admitted() {
+ a.mu.Unlock()
return
}
- if !a.known {
+ if !a.state.Ready() || !a.known || (a.group && (a.launch == nil || a.completer == nil || a.role != boxroles.Serve)) {
a.logWaitingLocked(time.Now())
+ a.mu.Unlock()
return
}
- if err := a.state.Admit(ctx, nil, nil, func() bool { return len(a.health.Failing(time.Now())) == 0 }); err == nil {
- close(a.opened)
- log.Print("tenant admission is open. accepting tenant work")
+ a.health.SetHosting(true)
+ launch, complete := a.launch, a.completer
+ a.mu.Unlock()
+ // No orchestration lock spans the provider call. Close can win immediately.
+ if err := a.state.Admit(ctx, launch, complete, a.initialHealthy); err == nil {
+ a.mu.Lock()
+ if !a.closed {
+ a.openOnce.Do(func() { close(a.opened); log.Print("tenant admission is open. accepting tenant work") })
+ }
+ a.mu.Unlock()
} else {
+ a.mu.Lock()
+ if a.group && !errors.Is(err, groupadmission.ErrNotReady) {
+ code := groupLaunchFailureCode(err)
+ if code != a.launchFailure {
+ a.waitingAt = time.Time{}
+ }
+ a.launchFailure = code
+ }
a.logWaitingLocked(time.Now())
+ a.mu.Unlock()
}
}
+func (a *fixedAdmission) initialHealthy() bool {
+ return a.allowed.Load() && a.groupReadersReady(time.Now()) && len(a.health.Failing(time.Now())) == 0
+}
func (a *fixedAdmission) Close() {
if a == nil {
return
}
a.mu.Lock()
- defer a.mu.Unlock()
if a.closed {
+ a.mu.Unlock()
return
}
a.closed = true
+ a.allowed.Store(false)
a.state.Close()
a.health.SetHosting(false)
+ a.mu.Unlock()
+ a.workMu.Lock()
+ if a.workCancel != nil {
+ a.workCancel()
+ }
+ a.workMu.Unlock()
+ a.workWG.Wait()
log.Print("tenant admission is closed for shutdown")
}
+
+// Work is registered before mutation; shutdown closes admission, cancels and
+// joins registered import/ack operations before consumer shutdown proceeds.
+func (a *fixedAdmission) beginDepartureWork(parent context.Context) (context.Context, func(), bool) {
+ if a == nil {
+ return parent, func() {}, true
+ }
+ a.workMu.Lock()
+ defer a.workMu.Unlock()
+ if !a.startAllowed() {
+ return parent, func() {}, false
+ }
+ if a.workCtx == nil {
+ a.workCtx, a.workCancel = context.WithCancel(context.Background())
+ }
+ ctx, cancel := context.WithCancel(a.workCtx)
+ stop := context.AfterFunc(parent, cancel)
+ if parent.Err() != nil {
+ cancel()
+ stop()
+ return ctx, func() {}, false
+ }
+ a.workWG.Add(1)
+ return ctx, func() { stop(); cancel(); a.workWG.Done() }, true
+}
func (a *fixedAdmission) armRoles(ctx context.Context, getenv func(string) string, ref string) {
if a == nil {
return
@@ -245,6 +304,12 @@ func (a *fixedAdmission) logWaitingLocked(now time.Time) {
if !a.known {
missing = append(missing, "KnownRole")
}
+ if a.group && a.launchFailure != "" {
+ missing = append(missing, a.launchFailure)
+ }
+ if a.group && !a.groupReadersReady(now) {
+ missing = append(missing, "GroupReadersReady")
+ }
for _, failure := range a.health.Failing(now) {
missing = append(missing, string(failure))
}
@@ -264,6 +329,9 @@ func (a *fixedAdmission) groupReadersReady(now time.Time) bool {
read = cachedGroupReaders
}
snapshot := read()
+ if a.knownReaders != nil {
+ snapshot.KnownReaders = append([]string(nil), a.knownReaders...)
+ }
if self == "" {
self = snapshot.Self
}
diff --git a/internal/host/group_admission_test.go b/internal/host/group_admission_test.go
index b0526e3f1..3ca20d135 100644
--- a/internal/host/group_admission_test.go
+++ b/internal/host/group_admission_test.go
@@ -73,7 +73,7 @@ func TestAdmissionFixedOptIn(t *testing.T) {
return admissionEnv(k)
}
a := newFixedAdmission(get, admissionHealth())
- if !strings.Contains(a.refusal, "does not support admission for group boxes") {
+ if !strings.Contains(a.refusal, "group_configuration_required") {
t.Fatal(a.refusal)
}
}
diff --git a/internal/host/group_boot.go b/internal/host/group_boot.go
new file mode 100644
index 000000000..4c70c2f71
--- /dev/null
+++ b/internal/host/group_boot.go
@@ -0,0 +1,139 @@
+package host
+
+import (
+ "context"
+ "errors"
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/carlosframework/platform/internal/awsregiongroup"
+ "github.com/carlosframework/platform/internal/awsterminations"
+ "github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/hostenv"
+ "github.com/carlosframework/platform/internal/rootaws"
+ "os"
+ "strings"
+ "time"
+)
+
+const groupUnitPath = "/etc/systemd/system/carlos-edge.service.d/50-group.conf"
+const groupUnitProtection = "[Unit]\nRequires=nftables.service\nAfter=nftables.service\n\n[Service]\nRestart=no\n"
+const groupIdentityPath = "/etc/carlos/group-identity.json"
+
+func validateGroupSwitches(getenv func(string) string) error {
+ if getenv("CARLOS_GROUP_ADMISSION") == "1" && (getenv("CARLOS_HIBERNATE_BUCKET") == "" || getenv("CARLOS_HIBERNATE_REGION") == "") {
+ return hostenv.ErrGroupConfig
+ }
+ if !groupReferenced(getenv) {
+ return nil
+ }
+ if getenv("CARLOS_GROUP_ADMISSION") != "1" || getenv("CARLOS_REGION_HA") != "true" || getenv("CARLOS_CHANGE_INDEX") != "read" {
+ return hostenv.ErrGroupConfig
+ }
+ for _, k := range append(append([]string{}, hostenv.Required...), hostenv.Optional...) {
+ if strings.HasPrefix(k, "CARLOS_HOST_CLAIM") && getenv(k) != "" {
+ return hostenv.ErrGroupConfig
+ }
+ }
+ return nil
+}
+
+// Every production group entry proves the immutable marker and its companion
+// configuration. A present marker cannot fall back to fixed mode via flags.
+func loadGroupConfiguration(getenv func(string) string) (*hostenv.GroupConfig, error) {
+ raw, err := hostenv.ReadGroupFile(hostenv.GroupConfigPath, 0, 0644)
+ if errors.Is(err, os.ErrNotExist) && !groupReferenced(getenv) {
+ return nil, validateGroupSwitches(getenv)
+ }
+ if err != nil {
+ return nil, err
+ }
+ c, err := hostenv.ParseGroupConfig(raw)
+ if err != nil {
+ return nil, err
+ }
+ if err = validateGroupEnvironment(c, getenv); err != nil {
+ return nil, err
+ }
+ regionRaw, err := hostenv.ReadGroupFile(roleRegionConfigPath, 0, 0644)
+ if err != nil {
+ return nil, err
+ }
+ region, err := parseRoleRegionConfig(regionRaw, *c.Placement)
+ if err != nil || region.RegionCode != c.Region {
+ return nil, errors.Join(hostenv.ErrGroupConfig, err)
+ }
+ unit, err := hostenv.ReadGroupFile(groupUnitPath, 0, 0644)
+ if err != nil || string(unit) != groupUnitProtection {
+ return nil, errors.Join(hostenv.ErrGroupConfig, err)
+ }
+ return &c, nil
+}
+func groupBootEvidence(c hostenv.GroupConfig) ([]byte, boxid.Verifier, boxid.Expect, error) {
+ raw, err := hostenv.ReadGroupFile(groupIdentityPath, 0, 0644)
+ if err != nil {
+ return nil, boxid.Verifier{}, boxid.Expect{}, err
+ }
+ certs, err := boxid.EmbeddedCerts()
+ if err != nil {
+ return nil, boxid.Verifier{}, boxid.Expect{}, err
+ }
+ v := boxid.Verifier{Account: c.Account, Certs: certs}
+ expect := boxid.Expect{Box: groupReferenceOf(c.Account, c.InstanceID), AWSRegion: c.AWSRegion, TofuInstanceID: c.InstanceID}
+ if _, err = v.Enroll(raw, expect); err != nil {
+ return nil, v, expect, err
+ }
+ return raw, v, expect, nil
+}
+func configureGroupAdmission(ctx context.Context, a *fixedAdmission, c *hostenv.GroupConfig) error {
+ if c == nil {
+ return nil
+ }
+ if c.BootID != readBootID(bootIDPath) {
+ return hostenv.ErrGroupConfig
+ }
+ if a == nil || !a.group {
+ return hostenv.ErrGroupConfig
+ }
+ raw, v, expect, err := groupBootEvidence(*c)
+ if err != nil {
+ return err
+ }
+ cfg, err := rootaws.LoadDefaultConfig(ctx, awsconfig.WithRegion(c.AWSRegion), awsconfig.WithRetryMaxAttempts(1))
+ if err != nil {
+ return err
+ }
+ binding := groupReceiptBinding{Account: c.Account, Region: c.AWSRegion, Instance: c.InstanceID, Group: c.Group, Hook: c.Hook, Digest: c.ConfigDigest}
+ launch := binding.launch()
+ adapter, err := awsregiongroup.New(cfg, raw, v, expect, launch)
+ if err != nil {
+ return err
+ }
+ a.launch = &launch
+ a.completer = &groupReceiptCompleter{dir: groupReceiptDir, binding: binding, bootID: readBootID(bootIDPath), complete: adapter, now: time.Now, wait: groupLaunchWait, eligible: a.initialHealthy}
+ a.readerSelf = expect.Box
+ a.knownReaders = append([]string{}, c.KnownReaders...)
+ a.refusal = ""
+ return nil
+}
+
+func validateGroupEnvironment(c hostenv.GroupConfig, getenv func(string) string) error {
+ if !groupReferenced(getenv) {
+ return hostenv.ErrGroupConfig
+ }
+ if err := validateGroupSwitches(getenv); err != nil {
+ return err
+ }
+ if getenv("CARLOS_TERMINATION_QUEUE_URL") != c.QueueURL {
+ return hostenv.ErrGroupConfig
+ }
+ if err := awsterminations.ValidateURL(c.QueueURL, boxid.Cloud{Provider: "aws", Account: c.Account, Region: c.AWSRegion, InstanceID: c.InstanceID}); err != nil {
+ return err
+ }
+ env := map[string]string{}
+ for _, k := range append(append(append([]string{}, hostenv.Required...), hostenv.Optional...), "AWS_REGION", "CARLOS_POOLS") {
+ if v := getenv(k); v != "" {
+ env[k] = v
+ }
+ }
+ _, err := hostenv.AssembleGroup(nil, env, c, c.QueueURL)
+ return err
+}
diff --git a/internal/host/group_boot_test.go b/internal/host/group_boot_test.go
new file mode 100644
index 000000000..9de60e57a
--- /dev/null
+++ b/internal/host/group_boot_test.go
@@ -0,0 +1,209 @@
+package host
+
+import (
+ "context"
+ "github.com/carlosframework/platform/internal/boxroles"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "os"
+ "strings"
+ "testing"
+ "time"
+)
+
+func readyGroupAdmission(t *testing.T) *fixedAdmission {
+ t.Helper()
+ a := newFixedAdmission(admissionEnv, admissionHealth())
+ a.group = true
+ a.launch = &groupadmission.Launch{Group: "g", Hook: "h", Instance: "i"}
+ a.completer = groupCompleteFunc(func(context.Context, groupadmission.Launch) error { return nil })
+ a.readers = func() edgesfile.ReaderSnapshot {
+ return edgesfile.ReaderSnapshot{Complete: true, CheckedAt: time.Now().Add(-time.Second), Self: "self", KnownReaders: []string{}}
+ }
+ a.readerSelf = "self"
+ _ = a.applyRole(boxroles.Serve, true)
+ a.observe(groupadmission.Facts{EnvLoaded: true, Reconciled: true, RolePublished: true})
+ return a
+}
+func TestGroupAdmissionLifecycle(t *testing.T) {
+ a := readyGroupAdmission(t)
+ started := make(chan struct{})
+ a.setLifecycle(admissionLife{started: started})
+ calls := 0
+ a.completer = groupCompleteFunc(func(context.Context, groupadmission.Launch) error {
+ calls++
+ if a.state.Admitted() {
+ t.Fatal("early ack")
+ }
+ return nil
+ })
+ a.tick(t.Context())
+ if calls != 0 {
+ t.Fatal("fake Started")
+ }
+ close(started)
+ a.tick(t.Context())
+ if calls != 1 || !a.startAllowed() {
+ t.Fatal("not admitted", calls, a.state.Facts())
+ }
+ a.tick(t.Context())
+ if calls != 1 {
+ t.Fatal("duplicate completion")
+ }
+ for _, role := range []boxroles.Role{boxroles.Drain, boxroles.Platform} {
+ if a.applyRole(role, true) == nil {
+ t.Fatal("group role", role)
+ }
+ }
+ t.Run("nil launch", func(t *testing.T) {
+ b := readyGroupAdmission(t)
+ b.observe(groupadmission.Facts{TerminationStarted: true})
+ b.launch = nil
+ b.tick(t.Context())
+ if b.state.Admitted() {
+ t.Fatal("nil launch admitted")
+ }
+ })
+ t.Run("close in flight", func(t *testing.T) {
+ b := readyGroupAdmission(t)
+ b.observe(groupadmission.Facts{TerminationStarted: true})
+ entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
+ b.completer = groupCompleteFunc(func(context.Context, groupadmission.Launch) error { close(entered); <-release; return nil })
+ go func() { b.tick(t.Context()); close(done) }()
+ <-entered
+ closed := make(chan struct{})
+ go func() { b.Close(); close(closed) }()
+ select {
+ case <-closed:
+ case <-time.After(time.Second):
+ close(release)
+ t.Fatal("host mutex held across cloud call")
+ }
+ close(release)
+ <-done
+ b.tick(t.Context())
+ if b.startAllowed() || b.state.Admitted() {
+ t.Fatal("shutdown reopened")
+ }
+ })
+}
+func TestGroupAdmissionNoHibernate(t *testing.T) {
+ if validateGroupSwitches(func(k string) string {
+ if k == "CARLOS_BOX_REFERENCE" {
+ return "group"
+ }
+ return admissionEnv(k)
+ }) == nil {
+ t.Fatal("missing hibernate accepted")
+ }
+}
+func TestGroupBootOrder(t *testing.T) {
+ b, err := os.ReadFile("../../infra/modules/region-host/group-init.sh.tftpl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ last := -1
+ for _, s := range []string{"# disable unattended updates", "# harden metadata", "# configure chrony", "# fetch verified bootstrap", "# write immutable group configuration", "# install dormant hairpin", "# bootstrap and install channel", "# start guarded agent"} {
+ n := strings.Index(string(b), s)
+ if n <= last {
+ t.Fatalf("missing or unordered stage %s", s)
+ }
+ last = n
+ }
+}
+func TestGroupInitNoAutoRestart(t *testing.T) {
+ b, err := os.ReadFile("../../infra/modules/region-host/group-init.sh.tftpl")
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := string(b)
+ for _, needle := range []string{"systemctl enable nftables.service", "/etc/nftables.conf", "Requires=nftables.service", "After=nftables.service"} {
+ if !strings.Contains(s, needle) {
+ t.Fatal("metadata gate must survive reboot", needle)
+ }
+ }
+ drop, err := os.ReadFile("units/carlos-edge-group.conf")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(drop) != groupUnitProtection {
+ t.Fatal("group drop-in source differs")
+ }
+
+ for _, needle := range []string{"apt-daily.timer", "apt-daily-upgrade.timer", "apt-daily.service", "apt-daily-upgrade.service", "unattended-upgrades.service", "APT::Periodic::Enable \"0\"", "Unattended-Upgrade::Automatic-Reboot \"false\"", "$nrconf{restart} = 'l'", "Restart=no"} {
+ if !strings.Contains(s, needle) {
+ t.Fatal(needle)
+ }
+ }
+ if strings.Index(s, "systemctl mask") > strings.Index(s, "apt-get -y -q install") {
+ t.Fatal("packages before masks")
+ }
+}
+
+func TestGroupAdmissionFactsAndReceipt(t *testing.T) {
+ for _, missing := range []string{"env", "reconcile", "publication", "consumer", "health", "readers", "none"} {
+ t.Run(missing, func(t *testing.T) {
+ a := readyGroupAdmission(t)
+ a.state = groupadmission.State{}
+ facts := groupadmission.Facts{EnvLoaded: true, Reconciled: true, RolePublished: true, TerminationStarted: true}
+ switch missing {
+ case "env":
+ facts.EnvLoaded = false
+ case "reconcile":
+ facts.Reconciled = false
+ case "publication":
+ facts.RolePublished = false
+ case "consumer":
+ facts.TerminationStarted = false
+ case "health":
+ a.health.SetActivator(func() time.Time { return time.Time{} })
+ case "readers":
+ a.knownReaders = []string{"missing-fixed"}
+ }
+ calls := 0
+ c := groupLaunchFixture(t, func(context.Context, groupadmission.Launch) error { calls++; return nil })
+ launch := c.binding.launch()
+ a.launch = &launch
+ a.completer = c
+ a.observe(facts)
+ a.tick(t.Context())
+ want := 0
+ if missing == "none" {
+ want = 1
+ }
+ if calls != want || a.state.Admitted() != (want == 1) {
+ t.Fatalf("calls %d want %d admitted %t", calls, want, a.state.Admitted())
+ }
+ if missing == "none" {
+ // A new process may suppress only the original completion. Publication
+ // and every other local startup fact must recur before it opens.
+ b := readyGroupAdmission(t)
+ b.launch = &launch
+ b.completer = c
+ b.state = groupadmission.State{}
+ b.observe(groupadmission.Facts{EnvLoaded: true, Reconciled: true, TerminationStarted: true})
+ b.tick(t.Context())
+ if b.state.Admitted() || calls != 1 {
+ t.Fatal("receipt bypassed publication")
+ }
+ b.EdgesPublished(boxroles.Booting, false, false)
+ b.tick(t.Context())
+ if !b.state.Admitted() || calls != 1 {
+ t.Fatal("original receipt not reused")
+ }
+ }
+ })
+ }
+ t.Run("post call health", func(t *testing.T) {
+ a := readyGroupAdmission(t)
+ a.observe(groupadmission.Facts{TerminationStarted: true})
+ a.completer = groupCompleteFunc(func(context.Context, groupadmission.Launch) error {
+ a.health.SetActivator(func() time.Time { return time.Time{} })
+ return nil
+ })
+ a.tick(t.Context())
+ if a.state.Admitted() {
+ t.Fatal("opened after health dropped")
+ }
+ })
+}
diff --git a/internal/host/group_config.go b/internal/host/group_config.go
new file mode 100644
index 000000000..33e01f30f
--- /dev/null
+++ b/internal/host/group_config.go
@@ -0,0 +1,16 @@
+package host
+
+import (
+ "bytes"
+ "encoding/json"
+ "io"
+)
+
+func strictGroupJSON(b []byte, out any) error {
+ d := json.NewDecoder(bytes.NewReader(b))
+ d.DisallowUnknownFields()
+ if len(b) > 65536 || d.Decode(out) != nil || d.Decode(new(any)) != io.EOF {
+ return errGroupLaunch
+ }
+ return nil
+}
diff --git a/internal/host/group_config_linux.go b/internal/host/group_config_linux.go
new file mode 100644
index 000000000..96d957864
--- /dev/null
+++ b/internal/host/group_config_linux.go
@@ -0,0 +1,71 @@
+//go:build linux
+
+package host
+
+import (
+ "encoding/json"
+ "github.com/carlosframework/platform/internal/hostenv"
+ "golang.org/x/sys/unix"
+ "os"
+ "path/filepath"
+ "time"
+)
+
+// Root only creates the initial journal. It never opens or interprets an agent
+// receipt, including during maintenance. Existing state requires the operator.
+func initializeGroupLaunch(c hostenv.GroupConfig) error {
+ if c.BootID != readBootID(bootIDPath) || !time.Now().Before(time.Unix(c.Deadline, 0)) {
+ return errGroupLaunch
+ }
+ uid, gid, err := bootstrapOwner(serviceUser, serviceUser)
+ if err != nil {
+ return err
+ }
+ parent := filepath.Dir(groupReceiptDir)
+ if err = bootstrapMakeDir(parent, 0755); err != nil {
+ return err
+ }
+ if err = ownDir(parent, uid, gid); err != nil {
+ return err
+ }
+ fd, err := bootstrapOpenDir(parent)
+ if err != nil {
+ return err
+ }
+ defer unix.Close(fd)
+ if err = unix.Mkdirat(fd, "group-admission", 0700); err != nil {
+ return err
+ }
+ dir, err := unix.Openat(fd, "group-admission", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return err
+ }
+ defer unix.Close(dir)
+ leaf, err := unix.Openat(dir, "attempt.json", unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600)
+ if err != nil {
+ return err
+ }
+ f := os.NewFile(uintptr(leaf), "attempt.json")
+ defer f.Close()
+ j := groupLaunchJournal{V: 1, Binding: groupReceiptBinding{Account: c.Account, Region: c.AWSRegion, Instance: c.InstanceID, Group: c.Group, Hook: c.Hook, Digest: c.ConfigDigest}, BootID: c.BootID, Deadline: c.Deadline}
+ b, err := json.Marshal(j)
+ if err != nil {
+ return err
+ }
+ if _, err = f.Write(b); err != nil {
+ return err
+ }
+ if err = f.Chown(uid, gid); err != nil {
+ return err
+ }
+ if err = f.Sync(); err != nil {
+ return err
+ }
+ if err = unix.Fchown(dir, uid, gid); err != nil {
+ return err
+ }
+ if err = unix.Fsync(dir); err != nil {
+ return err
+ }
+ return unix.Fsync(fd)
+}
diff --git a/internal/host/group_config_other.go b/internal/host/group_config_other.go
new file mode 100644
index 000000000..77b6f69f1
--- /dev/null
+++ b/internal/host/group_config_other.go
@@ -0,0 +1,7 @@
+//go:build !linux
+
+package host
+
+import "github.com/carlosframework/platform/internal/hostenv"
+
+func initializeGroupLaunch(hostenv.GroupConfig) error { return errGroupLaunch }
diff --git a/internal/host/group_config_test.go b/internal/host/group_config_test.go
new file mode 100644
index 000000000..f78bccd3b
--- /dev/null
+++ b/internal/host/group_config_test.go
@@ -0,0 +1,64 @@
+package host
+
+import (
+ "encoding/json"
+ "github.com/carlosframework/platform/internal/hostenv"
+ "testing"
+ "time"
+)
+
+func groupConfigFixture() (hostenv.GroupConfig, map[string]string) {
+ p := ""
+ c := hostenv.GroupConfig{V: 1, Account: "123456789012", AWSRegion: "eu-west-1", DeploymentAWSRegion: "us-east-1", Region: "ie", Deployment: "dev", Bucket: "deploy", DataBucket: "data", Group: "dev-ie", Hook: "carlos-initial-launch", Placement: &p, Pools: []string{"hapair"}, KnownReaders: []string{"fixed"}, Release: "v1.2.3", InstanceID: "i-0123456789abcdef0", BootID: "boot", Deadline: time.Now().Add(time.Minute).Unix(), QueueURL: "https://sqs.eu-west-1.amazonaws.com/123456789012/group-queue"}
+ c.ConfigDigest = c.Digest()
+ env := map[string]string{}
+ for _, k := range hostenv.Required {
+ env[k] = "v"
+ }
+ for k := range env {
+ if len(k) >= 17 && k[:17] == "CARLOS_HOST_CLAIM" {
+ delete(env, k)
+ }
+ }
+ delete(env, "CARLOS_HOST_CLAIM")
+ delete(env, "CARLOS_HOST_CLAIM_ORIGINS")
+ env["CARLOS_REGION"] = ""
+ env["CARLOS_DEPLOYMENT_BUCKET"] = "deploy"
+ env["AWS_REGION"] = "us-east-1"
+ env["CARLOS_HIBERNATE_REGION"] = "eu-west-1"
+ env["CARLOS_HIBERNATE_BUCKET"] = "data"
+ env["CARLOS_REGION_HA"] = "true"
+ env["CARLOS_CHANGE_INDEX"] = "read"
+ env["CARLOS_POOLS"] = "hapair"
+ env["CARLOS_BOX_REFERENCE"] = "group"
+ env["CARLOS_GROUP_ADMISSION"] = "1"
+ env["CARLOS_TERMINATION_QUEUE_URL"] = c.QueueURL
+ return c, env
+}
+func TestGroupConfiguration(t *testing.T) {
+ c, env := groupConfigFixture()
+ raw, _ := json.Marshal(c)
+ if _, err := hostenv.ParseGroupConfig(raw); err != nil {
+ t.Fatal(err)
+ }
+ get := func(k string) string { return env[k] }
+ if err := validateGroupEnvironment(c, get); err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range []string{"CARLOS_BOX_REFERENCE", "CARLOS_GROUP_ADMISSION", "CARLOS_REGION_HA", "CARLOS_CHANGE_INDEX", "CARLOS_POOLS", "CARLOS_TERMINATION_QUEUE_URL", "CARLOS_HOST_CLAIM", "CARLOS_HIBERNATE_BUCKET", "AWS_REGION"} {
+ old := env[k]
+ env[k] = "wrong"
+ if k == "CARLOS_HIBERNATE_BUCKET" {
+ env[k] = ""
+ }
+ if err := validateGroupEnvironment(c, get); err == nil {
+ t.Fatal(k)
+ }
+ env[k] = old
+ }
+ c.KnownReaders = []string{"different"}
+ raw, _ = json.Marshal(c)
+ if _, err := hostenv.ParseGroupConfig(raw); err == nil {
+ t.Fatal("inventory not bound by digest")
+ }
+}
diff --git a/internal/host/group_departure_test.go b/internal/host/group_departure_test.go
new file mode 100644
index 000000000..bee7391bd
--- /dev/null
+++ b/internal/host/group_departure_test.go
@@ -0,0 +1,114 @@
+package host
+
+import (
+ "context"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "github.com/carlosframework/platform/internal/hadeparture"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type groupHintQueue struct {
+ once sync.Once
+ deletes atomic.Int32
+ message hadeparture.Message
+}
+
+func (q *groupHintQueue) Receive(ctx context.Context, _ time.Duration) ([]hadeparture.Message, error) {
+ var first bool
+ q.once.Do(func() { first = true })
+ if first {
+ return []hadeparture.Message{q.message}, nil
+ }
+ <-ctx.Done()
+ return nil, ctx.Err()
+}
+func (q *groupHintQueue) Delete(context.Context, string) error { q.deletes.Add(1); return nil }
+func TestGroupDepartureAdmission(t *testing.T) {
+ t.Run("shared visibility and production import", func(t *testing.T) { testDepartureWiringImportMode(t, true) })
+ for _, body := range []string{string(terminationHint("i-1123456789abcdef0")), `invalid`} {
+ t.Run(body, func(t *testing.T) {
+ cfg, _, _ := departureArmFixture(t)
+ a := readyGroupAdmission(t)
+ cfg.Admitted = a.startAllowed
+ cfg.BeginWork = a.beginDepartureWork
+ q := &groupHintQueue{message: hadeparture.Message{ID: "hint", Receipt: "receipt", Body: []byte(body)}}
+ cfg.MakeQueue = func(context.Context) (hadeparture.Queue, error) { return q, nil }
+ c, life, err := armHADepartures(t.Context(), cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer life.Stop(context.Background())
+ select {
+ case <-life.Started():
+ case <-time.After(3 * time.Second):
+ t.Fatal("journal receive must close Started")
+ }
+ if _, err = c.ScanPass(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = c.adoptMeasured(t.Context(), provision.DepartureHost{}, registry.HADeparture{}, hafresh.View{}); err == nil {
+ t.Fatal("closed import")
+ }
+ _ = c.ackIID(t.Context(), "i-1123456789abcdef0")
+ if q.deletes.Load() != 0 {
+ t.Fatal("closed ack")
+ }
+ if len(c.cfg.Inventory().Records) != 0 {
+ t.Fatal("fixture")
+ }
+ a.setLifecycle(life)
+ a.tick(t.Context())
+ if !a.startAllowed() {
+ t.Fatal("did not admit after durable receive")
+ }
+ if err = c.record(t.Context(), q.message); err != nil {
+ t.Fatal(err)
+ }
+ a.Close()
+ if q.deletes.Load() > 1 {
+ t.Fatal("duplicate ack")
+ }
+ if err = life.Stop(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case <-life.Done():
+ default:
+ t.Fatal("Done synthesized")
+ }
+ })
+ }
+ t.Run("close joins import", func(t *testing.T) {
+ a := readyGroupAdmission(t)
+ a.observe(groupadmission.Facts{TerminationStarted: true})
+ a.tick(t.Context())
+ ctx, done, ok := a.beginDepartureWork(t.Context())
+ if !ok {
+ t.Fatal("not open")
+ }
+ closed := make(chan struct{})
+ go func() { a.Close(); close(closed) }()
+ select {
+ case <-ctx.Done():
+ case <-time.After(time.Second):
+ t.Fatal("import not cancelled")
+ }
+ select {
+ case <-closed:
+ t.Fatal("did not join import")
+ default:
+ }
+ done()
+ select {
+ case <-closed:
+ case <-time.After(time.Second):
+ t.Fatal("close not joined")
+ }
+ })
+}
diff --git a/internal/host/group_install.go b/internal/host/group_install.go
new file mode 100644
index 000000000..5a1b43649
--- /dev/null
+++ b/internal/host/group_install.go
@@ -0,0 +1,25 @@
+package host
+
+import (
+ "context"
+ "crypto/ed25519"
+ awsconfig "github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/rootaws"
+ "github.com/carlosframework/platform/internal/s3compat"
+ "os"
+)
+
+func openGroupInstallStore(ctx context.Context) (release.Store, ed25519.PublicKey, error) {
+ cfg, err := rootaws.LoadDefaultConfig(ctx, awsconfig.WithRegion(os.Getenv("AWS_REGION")), awsconfig.WithRetryMaxAttempts(1))
+ if err != nil {
+ return nil, nil, err
+ }
+ pub, err := release.ParsePublicKey(os.Getenv("CARLOS_RELEASE_PUBKEY"), "CARLOS_RELEASE_PUBKEY")
+ if err != nil {
+ return nil, nil, err
+ }
+ client := s3.NewFromConfig(cfg, s3compat.Options(), func(o *s3.Options) { o.RetryMaxAttempts = 1 })
+ return &release.S3Store{Client: client, Bucket: os.Getenv("CARLOS_DEPLOYMENT_BUCKET")}, pub, nil
+}
diff --git a/internal/host/group_receipt.go b/internal/host/group_receipt.go
new file mode 100644
index 000000000..3cf40d0bd
--- /dev/null
+++ b/internal/host/group_receipt.go
@@ -0,0 +1,158 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "github.com/carlosframework/platform/internal/awsregiongroup"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "os"
+ "sync"
+ "time"
+)
+
+const groupReceiptDir = "/data/carlos/group-admission"
+
+var errGroupLaunch = errors.New("group_launch_unacknowledged")
+var errGroupLaunchUnknown = errors.New("group_launch_outcome_unknown")
+var errGroupLaunchExhausted = errors.New("group_launch_attempts_exhausted")
+var errGroupLaunchReceipt = errors.New("group_launch_receipt_invalid")
+var errGroupLaunchExpired = errors.New("group_launch_deadline_passed")
+
+type groupReceiptBinding struct {
+ Account string `json:"account"`
+ Region string `json:"region"`
+ Instance string `json:"instance"`
+ Group string `json:"group"`
+ Hook string `json:"hook"`
+ Digest string `json:"digest"`
+}
+
+func (b groupReceiptBinding) launch() groupadmission.Launch {
+ return groupadmission.Launch{Group: b.Group, Hook: b.Hook, Instance: b.Instance}
+}
+
+type groupLaunchJournal struct {
+ V int `json:"v"`
+ Binding groupReceiptBinding `json:"binding"`
+ BootID string `json:"boot_id"`
+ Deadline int64 `json:"deadline"`
+ Attempts int `json:"attempts"`
+ Unknown bool `json:"unknown"`
+ Next int64 `json:"next"`
+}
+type groupLaunchReceipt struct {
+ V int `json:"v"`
+ Binding groupReceiptBinding `json:"binding"`
+ Acknowledged bool `json:"acknowledged"`
+}
+
+// This is agent-owned state. No root entry reads it or uses it as a permit.
+type groupReceiptCompleter struct {
+ eligible func() bool
+ mu sync.Mutex
+ dir string
+ binding groupReceiptBinding
+ bootID string
+ complete groupadmission.Completer
+ now func() time.Time
+ wait func(context.Context, time.Duration) error
+}
+
+func (c *groupReceiptCompleter) Complete(ctx context.Context, l groupadmission.Launch) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if l != c.binding.launch() || c.complete == nil {
+ return errGroupLaunch
+ }
+ return withGroupReceiptLock(c.dir, func() error { return c.completeLocked(ctx, l) })
+}
+func (c *groupReceiptCompleter) completeLocked(ctx context.Context, l groupadmission.Launch) error {
+ var receipt groupLaunchReceipt
+ err := readGroupReceiptFile(c.dir, "receipt.json", &receipt)
+ if err == nil {
+ if receipt.V != 1 || !receipt.Acknowledged || receipt.Binding != c.binding {
+ return errGroupLaunchReceipt
+ }
+ return nil // Suppresses the original action only. Readiness still recurs.
+ }
+ if !errors.Is(err, os.ErrNotExist) {
+ return errors.Join(errGroupLaunchReceipt, err)
+ }
+ var j groupLaunchJournal
+ if err := readGroupReceiptFile(c.dir, "attempt.json", &j); err != nil {
+ return errors.Join(errGroupLaunchReceipt, err)
+ }
+ if j.V != 1 || j.Binding != c.binding || j.BootID != c.bootID || j.Attempts < 0 || j.Attempts > 4 {
+ return errGroupLaunchReceipt
+ }
+ if j.Unknown {
+ return errGroupLaunchUnknown
+ }
+ for j.Attempts < 4 {
+ now := c.now()
+ if ctx.Err() != nil || !now.Before(time.Unix(j.Deadline, 0)) {
+ return errGroupLaunchExpired
+ }
+ if pause := time.Unix(0, j.Next).Sub(now); pause > 0 {
+ if err := c.wait(ctx, pause); err != nil {
+ return err
+ }
+ }
+ if !c.now().Add(2 * time.Second).Before(time.Unix(j.Deadline, 0)) {
+ return errGroupLaunchExpired
+ }
+ if c.eligible != nil && !c.eligible() {
+ return errGroupLaunch
+ }
+ j.Attempts++
+ j.Unknown = true
+ if err := writeGroupReceiptFile(c.dir, "attempt.json", j); err != nil {
+ return err
+ }
+ call, cancel := context.WithTimeout(ctx, 2*time.Second)
+ err := c.complete.Complete(call, l)
+ // A nil response after our deadline is not an acknowledgment.
+ if err == nil {
+ err = call.Err()
+ }
+ cancel()
+ if err == nil {
+ if err := writeGroupReceiptFile(c.dir, "receipt.json", groupLaunchReceipt{V: 1, Binding: c.binding, Acknowledged: true}); err != nil {
+ return errors.Join(errGroupLaunchUnknown, err)
+ }
+ return nil
+ }
+ if !errors.Is(err, awsregiongroup.ErrRejected) {
+ return errors.Join(errGroupLaunchUnknown, err)
+ }
+ j.Unknown = false
+ j.Next = c.now().Add(time.Second * time.Duration(1<<uint(j.Attempts-1))).UnixNano()
+ if e := writeGroupReceiptFile(c.dir, "attempt.json", j); e != nil {
+ return e
+ }
+ }
+ return errGroupLaunchExhausted
+}
+func groupLaunchWait(ctx context.Context, d time.Duration) error {
+ t := time.NewTimer(d)
+ defer t.Stop()
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-t.C:
+ return nil
+ }
+}
+func decodeGroupReceipt(b []byte, out any) error {
+ // Re-marshal equality is not required; unknown fields still refuse.
+ return strictGroupJSON(b, out)
+}
+
+func groupLaunchFailureCode(err error) string {
+ for _, code := range []error{errGroupLaunchUnknown, errGroupLaunchExhausted, errGroupLaunchReceipt, errGroupLaunchExpired} {
+ if errors.Is(err, code) {
+ return code.Error()
+ }
+ }
+ return "group_launch_unacknowledged"
+}
diff --git a/internal/host/group_receipt_linux.go b/internal/host/group_receipt_linux.go
new file mode 100644
index 000000000..46d977c0a
--- /dev/null
+++ b/internal/host/group_receipt_linux.go
@@ -0,0 +1,110 @@
+//go:build linux
+
+package host
+
+import (
+ "crypto/rand"
+ "encoding/json"
+ "golang.org/x/sys/unix"
+ "io"
+ "os"
+)
+
+func openGroupReceiptDir(path string) (int, error) {
+ fd, err := unix.Openat2(unix.AT_FDCWD, path, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_NO_MAGICLINKS})
+ if err != nil {
+ return -1, err
+ }
+ var st unix.Stat_t
+ if unix.Fstat(fd, &st) != nil || st.Mode&0777 != 0700 || int(st.Uid) != os.Geteuid() {
+ unix.Close(fd)
+ return -1, errGroupLaunch
+ }
+ return fd, nil
+}
+func groupReceiptLeaf(dir int, name string, flags int) (*os.File, error) {
+ fd, err := unix.Openat(dir, name, flags|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0600)
+ if err != nil {
+ return nil, err
+ }
+ f := os.NewFile(uintptr(fd), name)
+ var st unix.Stat_t
+ if unix.Fstat(fd, &st) != nil || st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0777 != 0600 || int(st.Uid) != os.Geteuid() || st.Nlink != 1 || st.Size > 65536 {
+ f.Close()
+ return nil, errGroupLaunch
+ }
+ return f, nil
+}
+func withGroupReceiptLock(path string, run func() error) error {
+ dir, err := openGroupReceiptDir(path)
+ if err != nil {
+ return err
+ }
+ defer unix.Close(dir)
+ f, err := groupReceiptLeaf(dir, "lock", unix.O_RDWR|unix.O_CREAT)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ if err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
+ return err
+ }
+ defer unix.Flock(int(f.Fd()), unix.LOCK_UN)
+ return run()
+}
+func readGroupReceiptFile(path, name string, out any) error {
+ dir, err := openGroupReceiptDir(path)
+ if err != nil {
+ return err
+ }
+ defer unix.Close(dir)
+ f, err := groupReceiptLeaf(dir, name, unix.O_RDONLY)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ b, err := io.ReadAll(io.LimitReader(f, 65537))
+ if err != nil {
+ return err
+ }
+ return decodeGroupReceipt(b, out)
+}
+func writeGroupReceiptFile(path, name string, value any) error {
+ dir, err := openGroupReceiptDir(path)
+ if err != nil {
+ return err
+ }
+ defer unix.Close(dir)
+ // Refuse unsafe existing leaves even though rename itself follows no link.
+ f, err := groupReceiptLeaf(dir, name, unix.O_RDONLY)
+ if err == nil {
+ f.Close()
+ } else if !os.IsNotExist(err) {
+ return err
+ }
+ b, err := json.Marshal(value)
+ if err != nil {
+ return err
+ }
+ tmp := ".receipt-" + rand.Text()
+ f, err = groupReceiptLeaf(dir, tmp, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL)
+ if err != nil {
+ return err
+ }
+ defer unix.Unlinkat(dir, tmp, 0)
+ if _, err = f.Write(b); err != nil {
+ f.Close()
+ return err
+ }
+ if err = f.Sync(); err != nil {
+ f.Close()
+ return err
+ }
+ if err = f.Close(); err != nil {
+ return err
+ }
+ if err = unix.Renameat(dir, tmp, dir, name); err != nil {
+ return err
+ }
+ return unix.Fsync(dir)
+}
diff --git a/internal/host/group_receipt_other.go b/internal/host/group_receipt_other.go
new file mode 100644
index 000000000..9d6200113
--- /dev/null
+++ b/internal/host/group_receipt_other.go
@@ -0,0 +1,7 @@
+//go:build !linux
+
+package host
+
+func withGroupReceiptLock(string, func() error) error { return errGroupLaunch }
+func readGroupReceiptFile(string, string, any) error { return errGroupLaunch }
+func writeGroupReceiptFile(string, string, any) error { return errGroupLaunch }
diff --git a/internal/host/group_receipt_test.go b/internal/host/group_receipt_test.go
new file mode 100644
index 000000000..12ff7ac06
--- /dev/null
+++ b/internal/host/group_receipt_test.go
@@ -0,0 +1,110 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "github.com/carlosframework/platform/internal/awsregiongroup"
+ "github.com/carlosframework/platform/internal/groupadmission"
+ "os"
+ "path/filepath"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type groupCompleteFunc func(context.Context, groupadmission.Launch) error
+
+func (f groupCompleteFunc) Complete(c context.Context, l groupadmission.Launch) error { return f(c, l) }
+func groupLaunchFixture(t *testing.T, call groupCompleteFunc) *groupReceiptCompleter {
+ t.Helper()
+ dir := t.TempDir()
+ if err := os.Chmod(dir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ b := groupReceiptBinding{Account: "123456789012", Region: "eu-west-1", Instance: "i-0123456789abcdef0", Group: "dev-ie", Hook: "carlos-initial-launch", Digest: "digest"}
+ j := groupLaunchJournal{V: 1, Binding: b, BootID: "boot", Deadline: time.Now().Add(time.Minute).Unix()}
+ if err := writeGroupReceiptFile(dir, "attempt.json", j); err != nil {
+ t.Fatal(err)
+ }
+ return &groupReceiptCompleter{dir: dir, binding: b, bootID: "boot", complete: call, now: time.Now, wait: func(context.Context, time.Duration) error { return nil }}
+}
+func TestGroupAdmissionReceiptCrash(t *testing.T) {
+ for _, mode := range []string{"success", "lost", "persist", "rejected", "absent", "corrupt", "identity", "boot"} {
+ t.Run(mode, func(t *testing.T) {
+ var n atomic.Int32
+ c := groupLaunchFixture(t, func(context.Context, groupadmission.Launch) error {
+ n.Add(1)
+ switch mode {
+ case "lost":
+ return errors.New("response lost")
+ case "rejected":
+ return awsregiongroup.ErrRejected
+ }
+ return nil
+ })
+ // The persistence case creates a directory at the receipt leaf after the call.
+ if mode == "persist" {
+ c.complete = groupCompleteFunc(func(context.Context, groupadmission.Launch) error {
+ n.Add(1)
+ return os.Mkdir(filepath.Join(c.dir, "receipt.json"), 0700)
+ })
+ }
+ switch mode {
+ case "absent":
+ os.Remove(filepath.Join(c.dir, "attempt.json"))
+ case "corrupt":
+ os.WriteFile(filepath.Join(c.dir, "attempt.json"), []byte("bad"), 0600)
+ case "identity":
+ c.binding.Instance = "other"
+ case "boot":
+ c.bootID = "other"
+ }
+ err := c.Complete(t.Context(), c.binding.launch())
+ if (err == nil) != (mode == "success") {
+ t.Fatal(mode, err)
+ }
+ // A new wrapper cannot reset attempts or resolve an ambiguous result.
+ again := &groupReceiptCompleter{dir: c.dir, binding: c.binding, bootID: c.bootID, complete: c.complete, now: c.now, wait: c.wait}
+ err = again.Complete(t.Context(), c.binding.launch())
+ want := int32(1)
+ if mode == "rejected" {
+ want = 4
+ }
+ if mode == "absent" || mode == "corrupt" || mode == "identity" || mode == "boot" {
+ want = 0
+ }
+ if n.Load() != want || (err == nil) != (mode == "success") {
+ t.Fatalf("calls=%d want=%d err=%v", n.Load(), want, err)
+ }
+ })
+ }
+}
+
+func TestGroupReceiptReuse(t *testing.T) {
+ for _, field := range []string{"account", "region", "iid", "group", "hook", "digest"} {
+ t.Run(field, func(t *testing.T) {
+ calls := 0
+ c := groupLaunchFixture(t, func(context.Context, groupadmission.Launch) error { calls++; return nil })
+ if err := c.Complete(t.Context(), c.binding.launch()); err != nil {
+ t.Fatal(err)
+ }
+ switch field {
+ case "account":
+ c.binding.Account = "other"
+ case "region":
+ c.binding.Region = "other"
+ case "iid":
+ c.binding.Instance = "other"
+ case "group":
+ c.binding.Group = "other"
+ case "hook":
+ c.binding.Hook = "other"
+ case "digest":
+ c.binding.Digest = "other"
+ }
+ if c.Complete(t.Context(), c.binding.launch()) == nil || calls != 1 {
+ t.Fatal("foreign receipt reused")
+ }
+ })
+ }
+}
diff --git a/internal/host/hadepartures.go b/internal/host/hadepartures.go
index 8a4734360..12c4424fd 100644
--- a/internal/host/hadepartures.go
+++ b/internal/host/hadepartures.go
@@ -55,6 +55,8 @@ func departureCoverageGap(h provision.DepartureHost, s hadeparture.Scope) bool {
}
type DepartureConfig struct {
+ Admitted func() bool
+ BeginWork func(context.Context) (context.Context, func(), bool)
Registry *registry.Registry
OpenStore func(context.Context) (release.Store, error)
NewReader func(context.Context, string) (DepartureLockReader, error)
@@ -153,7 +155,15 @@ func (c *Controller) Start(ctx context.Context, makeQueue func(context.Context)
func (c *Controller) record(ctx context.Context, m hadeparture.Message) error {
iid, err := awsterminations.Hint(m.Body, departureCloud(c.cfg.Self))
if err != nil {
+ if !c.admitted() {
+ return c.cfg.Registry.RecordTermination(ctx, m.ID, m.Body, c.now())
+ }
if m.Receipt != "" {
+ ctx, done, ok := c.beginWork(ctx)
+ if !ok {
+ return nil
+ }
+ defer done()
return c.consumer.DeleteReceipt(ctx, m.Receipt)
}
return nil
@@ -172,7 +182,7 @@ func (c *Controller) record(ctx context.Context, m hadeparture.Message) error {
c.receipts[iid] = m.Receipt
}
c.receiptMu.Unlock()
- if c.cfg.Identities != nil {
+ if c.admitted() && c.cfg.Identities != nil {
if o, ok, e := c.cfg.Identities.Resolve(ctx, "", iid); e == nil && ok {
if d, e := c.cfg.Registry.Departure(ctx, departureID(c.cfg.DeploymentBucket, o.Box)); e == nil && d.Phase == "complete" {
return c.ackDeparture(ctx, d)
@@ -300,6 +310,11 @@ func (c *Controller) work(ctx context.Context) error {
}
}
func (c *Controller) step(ctx context.Context) error {
+ ctx, done, ok := c.beginWork(ctx)
+ if !ok {
+ return nil
+ }
+ defer done()
ctx, cancel := context.WithTimeout(ctx, 25*time.Second)
defer cancel()
c.mu.Lock()
@@ -515,6 +530,11 @@ func (c *Controller) step(ctx context.Context) error {
}
func (c *Controller) ackIID(ctx context.Context, iid string) error {
+ ctx, done, ok := c.beginWork(ctx)
+ if !ok {
+ return errDeparturePending
+ }
+ defer done()
c.receiptMu.Lock()
receipt := c.receipts[iid]
c.receiptMu.Unlock()
@@ -544,3 +564,14 @@ func (c *Controller) ackDeparture(ctx context.Context, d registry.HADeparture) e
}
return c.ackIID(ctx, d.Box.InstanceID)
}
+
+func (c *Controller) admitted() bool { return c.cfg.Admitted == nil || c.cfg.Admitted() }
+func (c *Controller) beginWork(ctx context.Context) (context.Context, func(), bool) {
+ if ctx.Err() != nil || !c.admitted() {
+ return ctx, func() {}, false
+ }
+ if c.cfg.BeginWork != nil {
+ return c.cfg.BeginWork(ctx)
+ }
+ return ctx, func() {}, true
+}
diff --git a/internal/host/hadepartures_production_test.go b/internal/host/hadepartures_production_test.go
index 943a6c1b4..36d0e2d96 100644
--- a/internal/host/hadepartures_production_test.go
+++ b/internal/host/hadepartures_production_test.go
@@ -34,6 +34,7 @@ type departureSQSTransport struct {
queue, body string
attrs, receives, deletes int
ready chan struct{}
+ redeliver bool
}
func (q *departureSQSTransport) Do(r *http.Request) (*http.Response, error) {
@@ -53,7 +54,8 @@ func (q *departureSQSTransport) Do(r *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("queue_contract")
}
q.receives++
- if q.receives == 1 {
+ if q.receives == 1 || q.redeliver {
+ q.redeliver = false
if q.body != "" {
raw, _ := json.Marshal(map[string]any{"Messages": []map[string]string{{"MessageId": "event", "ReceiptHandle": q.queue, "Body": q.body}}})
body = string(raw)
@@ -115,7 +117,8 @@ func TestHADepartureProductionWiring(t *testing.T) {
t.Run("two_fixed_receivers", testDepartureTwoQueueImporters)
}
-func testDepartureWiringImport(t *testing.T) {
+func testDepartureWiringImport(t *testing.T) { testDepartureWiringImportMode(t, false) }
+func testDepartureWiringImportMode(t *testing.T, group bool) {
t.Cleanup(lease.ProcessStateForTest())
previous := metricsDepartures.Load()
t.Cleanup(func() { metricsDepartures.Store(previous) })
@@ -191,6 +194,50 @@ func testDepartureWiringImport(t *testing.T) {
fx.PutLock("instances/"+rt.Host, marker)
q := &departureSQSTransport{queue: "receiver-self", body: string(terminationHint("i-1123456789abcdef0"))}
a.MakeQueue = func(ctx context.Context) (hadeparture.Queue, error) { return q.open(ctx, departureCloud(a.Self)) }
+ var admission *fixedAdmission
+ if group {
+ // B receives the shared receipt first, but may only journal it.
+ b, _, _ := departureArmFixture(t)
+ bGate := readyGroupAdmission(t)
+ b.Admitted = bGate.startAllowed
+ b.BeginWork = bGate.beginDepartureWork
+ b.MakeQueue = func(ctx context.Context) (hadeparture.Queue, error) { return q.open(ctx, departureCloud(b.Self)) }
+ bc, bl, e := armHADepartures(t.Context(), b)
+ if e != nil {
+ t.Fatal(e)
+ }
+ select {
+ case <-bl.Started():
+ case <-time.After(3 * time.Second):
+ t.Fatal("closed B did not journal")
+ }
+ if _, e = bc.ScanPass(t.Context()); e != nil {
+ t.Fatal(e)
+ }
+ if _, e = bc.cfg.Adopt(t.Context(), provision.DepartureHost{Host: rt.Host}, registry.HADeparture{}, hafresh.View{}); e == nil {
+ t.Fatal("closed B imported")
+ }
+ _, _, deleted := q.counts()
+ if deleted != 0 {
+ t.Fatal("closed B acknowledged")
+ }
+ pending, e := b.Registry.PendingTerminations(t.Context(), time.Now().Add(time.Hour), 10)
+ if e != nil || len(pending) != 1 {
+ t.Fatal("B lost durable hint", pending, e)
+ }
+ // Failed B stops without importing or acknowledging. Visibility expiry
+ // makes the SAME shared queue message available to C.
+ bGate.Close()
+ if e = bl.Stop(t.Context()); e != nil {
+ t.Fatal(e)
+ }
+ q.mu.Lock()
+ q.redeliver = true
+ q.mu.Unlock()
+ admission = readyGroupAdmission(t)
+ a.Admitted = admission.startAllowed
+ a.BeginWork = admission.beginDepartureWork
+ }
c, life, err := armHADepartures(t.Context(), a)
if err != nil {
t.Fatal(err)
@@ -200,6 +247,17 @@ func testDepartureWiringImport(t *testing.T) {
case <-time.After(3 * time.Second):
t.Fatal("real queue adapter failed startup")
}
+ if group {
+ _, _, deleted := q.counts()
+ if deleted != 0 {
+ t.Fatal("closed C acknowledged")
+ }
+ admission.setLifecycle(life)
+ admission.tick(t.Context())
+ if !admission.startAllowed() {
+ t.Fatal("C not admitted")
+ }
+ }
if err = life.Stop(context.Background()); err != nil {
t.Fatal(err)
}
@@ -275,9 +333,18 @@ func testDepartureWiringImport(t *testing.T) {
if _, err = a.Registry.MarkTimerFired(rt.Host, "reminder", "original", due, "ok", 0, 0, 0, 0); err != nil {
t.Fatal(err)
}
+ if group {
+ admission.Close()
+ }
if err = c.record(t.Context(), hadeparture.Message{ID: "duplicate", Receipt: q.queue, Body: terminationHint(obs.Box.InstanceID)}); err != nil {
t.Fatal(err)
}
+ if group {
+ _, _, deleted := q.counts()
+ if deleted != 1 {
+ t.Fatal("closed completed replay acknowledged")
+ }
+ }
timer, err = a.Registry.GetTimer(rt.Host, "reminder")
if err != nil || timer.NextAt != 0 {
t.Fatal("redelivery overwrote completed timer", timer, err)
diff --git a/internal/host/hadepartures_scan.go b/internal/host/hadepartures_scan.go
index fbdbbb08a..f280c95e1 100644
--- a/internal/host/hadepartures_scan.go
+++ b/internal/host/hadepartures_scan.go
@@ -75,6 +75,11 @@ func unrelatedDepartureLock(v hafresh.View, ref, iid string) bool {
}
func scanDigest(v any) string { b, _ := json.Marshal(v); return fmt.Sprintf("%x", sha256.Sum256(b)) }
func (c *Controller) ScanPass(ctx context.Context) (bool, error) {
+ ctx, done, ok := c.beginWork(ctx)
+ if !ok {
+ return false, nil
+ }
+ defer done()
c.scanMu.Lock()
defer c.scanMu.Unlock()
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
@@ -354,6 +359,11 @@ func (c *Controller) Complete(ctx context.Context, id string) error {
return c.complete(ctx, id)
}
func (c *Controller) complete(ctx context.Context, id string) (result error) {
+ ctx, done, allowed := c.beginWork(ctx)
+ if !allowed {
+ return errDeparturePending
+ }
+ defer done()
d, err := c.cfg.Registry.Departure(ctx, id)
if err != nil {
return err
@@ -542,6 +552,11 @@ func departurePermissionFault(err error) bool {
}
func (c *Controller) adoptMeasured(ctx context.Context, h provision.DepartureHost, d registry.HADeparture, v hafresh.View) (activator.AdoptResult, error) {
+ ctx, done, ok := c.beginWork(ctx)
+ if !ok {
+ return activator.Deferred, errDeparturePending
+ }
+ defer done()
began := time.Now()
result, err := c.cfg.Adopt(ctx, h, d, v)
code := "deferred"
diff --git a/internal/host/hadepartures_wiring.go b/internal/host/hadepartures_wiring.go
index 1ccfa3ec4..c1c9a8230 100644
--- a/internal/host/hadepartures_wiring.go
+++ b/internal/host/hadepartures_wiring.go
@@ -30,6 +30,8 @@ const departureBindingsEnv = "CARLOS_HA_FIXED_BOX_IDENTITIES"
var boxDepartureInventory = &provision.DepartureInventory{}
type departureArm struct {
+ Admitted func() bool
+ BeginWork func(context.Context) (context.Context, func(), bool)
Getenv func(string) string
Registry *registry.Registry
Service *activator.Service
@@ -52,6 +54,9 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
log.Printf("Termination recovery has not started: %s.", stage)
return nil, nil, &hadeparture.InitError{Stage: stage, Err: err}
}
+ if groupReferenced(a.Getenv) && (a.Admitted == nil || a.BeginWork == nil) {
+ return fail("admission", errDepartureScope)
+ }
if a.Registry == nil || a.Service == nil || a.Backend == nil || a.Confirmer == nil || a.Inventory == nil || a.OpenStore == nil {
return fail("dependencies", errDepartureScope)
}
@@ -105,7 +110,7 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
return api, nil
}
}
- c, err := NewController(DepartureConfig{Registry: a.Registry, OpenStore: a.OpenStore, NewReader: defaultDepartureReader, Prefix: func(host string) string { return activator.HibernatePrefix(a.Backend.Cfg.Prefix, host) }, Identities: repo, Confirmer: a.Confirmer, Cache: cache, ProofStore: a.ProofStore, Self: a.Self, DeploymentBucket: a.Getenv("CARLOS_DEPLOYMENT_BUCKET"), Inventory: func() provision.InventorySnapshot { return departureInventorySnapshot(a.Inventory) }, Policy: func() LocalPolicy {
+ c, err := NewController(DepartureConfig{Admitted: a.Admitted, BeginWork: a.BeginWork, Registry: a.Registry, OpenStore: a.OpenStore, NewReader: defaultDepartureReader, Prefix: func(host string) string { return activator.HibernatePrefix(a.Backend.Cfg.Prefix, host) }, Identities: repo, Confirmer: a.Confirmer, Cache: cache, ProofStore: a.ProofStore, Self: a.Self, DeploymentBucket: a.Getenv("CARLOS_DEPLOYMENT_BUCKET"), Inventory: func() provision.InventorySnapshot { return departureInventorySnapshot(a.Inventory) }, Policy: func() LocalPolicy {
return LocalPolicy{Scope: a.Self.Scope, Pools: provision.ParseBoxPools(a.Getenv("CARLOS_POOLS"))}
}, Invalidate: a.Service.InvalidateDutyHolder, PageIdentity: func(ctx context.Context, h registry.HAPendingTermination, code string) error {
return PageOperator(ctx, alerting.LevelWarning, "ha_departure_pending", fmt.Sprintf("code=%s account=%s region=%s iid=%s", code, h.Account, h.Region, h.IID))
@@ -183,6 +188,11 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
}
c.cfg.ValidateSuccessor = a.Service.AdoptionIdentity
c.cfg.Adopt = func(ctx context.Context, h provision.DepartureHost, d registry.HADeparture, v hafresh.View) (activator.AdoptResult, error) {
+ ctx, done, allowed := c.beginWork(ctx)
+ if !allowed {
+ return activator.Deferred, errDeparturePending
+ }
+ defer done()
rt, err := a.Registry.Get(h.Host)
if err != nil {
return activator.Deferred, err
diff --git a/internal/host/installchannel.go b/internal/host/installchannel.go
index 9410b90e4..721cc1fad 100644
--- a/internal/host/installchannel.go
+++ b/internal/host/installchannel.go
@@ -83,10 +83,12 @@ func channelIdentityPath(optDir string) string {
// pointer's store, and own hands a directory tree to the service user
// (ownByService); both are seams for tests.
type channelInstall struct {
- a *systemApplier
- bucket string
- fetchTo func(ctx context.Context, s release.Store, key, dst, sha string) error
- own func(path string) error
+ expectedRelease string
+ group bool
+ a *systemApplier
+ bucket string
+ fetchTo func(ctx context.Context, s release.Store, key, dst, sha string) error
+ own func(path string) error
// policy is --policy's file, byte for byte; nil without the flag.
policy []byte
// identity is --identity's file, byte for byte; set with policy and
@@ -130,6 +132,11 @@ func RunSystemInstallChannel(args []string) {
fmt.Fprintln(os.Stderr, installChannelNotRoot)
os.Exit(1)
}
+ group, err := loadGroupConfiguration(os.Getenv)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
channel, invalid := systemChannel(os.Getenv)
if invalid != "" {
fmt.Fprintln(os.Stderr, fmt.Sprintf("%s=%q is not a channel, so nothing was installed", systemChannelEnv, invalid))
@@ -141,6 +148,9 @@ func RunSystemInstallChannel(args []string) {
os.Exit(1)
}
in := newChannelInstall(channel, policy, identity)
+ if group != nil {
+ in.expectedRelease = group.Release
+ }
got, err := in.run(context.Background())
if err != nil {
fmt.Fprintln(os.Stderr, err)
@@ -182,6 +192,11 @@ func newChannelInstall(channel string, policy, identity []byte) channelInstall {
policy: policy,
identity: identity,
}
+ if groupReferenced(os.Getenv) {
+ in.group = true
+ in.a.rootMoves = rootMovesFloorIdentity
+ in.a.openStore = openGroupInstallStore
+ }
if policy != nil {
in.a.rootMoves = rootMovesFloorIdentity
}
@@ -298,6 +313,9 @@ func (in channelInstall) install(ctx context.Context) (channelInstalled, error)
if !ok {
return got, fmt.Errorf("the %s channel names %s with no artifact for %s, so nothing was installed", a.channel, p.Current.Version, a.platform)
}
+ if in.group && in.expectedRelease != "" && in.expectedRelease != p.Current.ReleaseTag && in.expectedRelease != art.SHA256 {
+ return got, errGroupLaunch
+ }
// A box whose guard is armed takes releases only through an update.
guard := hostfloor.Disk{Dir: systemGuardDir(a.optDir), Bucket: in.bucket, PublicKey: pub}
if policy, _, err := guard.Load(); err == nil && policy.Mode != "unpublished" {
@@ -312,6 +330,14 @@ func (in channelInstall) install(ctx context.Context) (channelInstalled, error)
if applied != nil && applied.Version != p.Current.Version {
return got, fmt.Errorf("this box already runs %s, so carlos system update installs its releases", applied.Version)
}
+ if in.group {
+ if policy != nil {
+ return got, errGroupLaunch
+ }
+ if _, required, err := a.rootMoves.read(); err != nil || required {
+ return got, errors.Join(errGroupLaunch, err)
+ }
+ }
wire, tag, err := in.checkFloor(ctx, p, art, pub, policy, policyFloor)
if err != nil {
return got, err
@@ -333,7 +359,7 @@ func (in channelInstall) install(ctx context.Context) (channelInstalled, error)
}
}
already := systemCacheHolds(systemBinaryPath(a.optDir), art.SHA256) && systemCacheHolds(systemPrevPath(a.optDir), art.SHA256) &&
- systemCacheHolds(channelIdentityPath(a.optDir), hostfloor.Digest(wire))
+ ((in.group && wire == nil) || systemCacheHolds(channelIdentityPath(a.optDir), hostfloor.Digest(wire)))
if applied != nil {
// applied.json is the last thing a run writes, so a box with one is
// either this install, complete, or a box an update has since
@@ -413,8 +439,10 @@ func (in channelInstall) install(ctx context.Context) (channelInstalled, error)
return got, err
}
}
- if err := hostfloor.Durable(channelIdentityPath(a.optDir), wire, 0o644); err != nil {
- return got, err
+ if wire != nil {
+ if err := hostfloor.Durable(channelIdentityPath(a.optDir), wire, 0o644); err != nil {
+ return got, err
+ }
}
seen, err := readSystemSeen(a.optDir)
if err != nil {
@@ -453,6 +481,8 @@ func (in channelInstall) checkFloor(ctx context.Context, p *release.SystemPointe
if wire, tag, err = in.channelIdentity(ctx, s, p, art, pub); err != nil {
return nil, "", err
}
+ } else if in.group {
+ return in.checkGroupInstallFloor(ctx, p, art, pub)
} else {
raw, _, err := s.Get(ctx, hostfloor.Key)
if errors.Is(err, os.ErrNotExist) {
@@ -646,8 +676,10 @@ func (in channelInstall) refreshPrev(ctx context.Context, p *release.SystemPoint
return got, fmt.Errorf("%s does not hold %s after the copy", slot, p.Current.Version)
}
}
- if err := hostfloor.Durable(channelIdentityPath(a.optDir), wire, 0o644); err != nil {
- return got, err
+ if wire != nil {
+ if err := hostfloor.Durable(channelIdentityPath(a.optDir), wire, 0o644); err != nil {
+ return got, err
+ }
}
got.Replaced = replaced
return got, nil
@@ -678,3 +710,32 @@ func (in channelInstall) cacheDir(version string) error {
}
return nil
}
+
+// Both halves are observed once. Only two genuine absences permit no-floor
+// installation; an unreadable half or a torn publication cannot downgrade it.
+func (in channelInstall) checkGroupInstallFloor(ctx context.Context, p *release.SystemPointer, art release.SystemArtifact, pub ed25519.PublicKey) ([]byte, string, error) {
+ raw, _, fe := in.a.store.Get(ctx, hostfloor.Key)
+ auth, _, ae := in.a.store.Get(ctx, hostfloor.AuthKey)
+ if errors.Is(fe, os.ErrNotExist) && errors.Is(ae, os.ErrNotExist) {
+ return nil, p.Current.ReleaseTag, nil
+ }
+ if fe != nil || ae != nil {
+ return nil, "", errors.Join(errGroupLaunch, fe, ae)
+ }
+ floor, err := hostfloor.Verify(pub, in.bucket, raw, auth)
+ if err != nil {
+ return nil, "", err
+ }
+ key, err := release.IdentityKey(p.Current.ReleaseTag)
+ if err != nil {
+ return nil, "", err
+ }
+ wire, _, err := in.a.store.Get(ctx, key)
+ if err != nil {
+ return nil, "", err
+ }
+ if err = hostfloor.CheckImage(pub, floor, wire, p.Current.Version, in.a.platform, art.SHA256); err != nil {
+ return nil, "", err
+ }
+ return wire, p.Current.ReleaseTag, nil
+}
diff --git a/internal/host/installchannel_test.go b/internal/host/installchannel_test.go
index 7030681d1..f34ac0b73 100644
--- a/internal/host/installchannel_test.go
+++ b/internal/host/installchannel_test.go
@@ -471,3 +471,71 @@ func TestInstallChannelRefusesASymlinkedSlot(t *testing.T) {
}
}
}
+
+func TestGroupInstallFloor(t *testing.T) {
+ for _, floor := range []string{"", "v1.2.0", "v9.0.0"} {
+ t.Run(floor, func(t *testing.T) {
+ f := newChannelFixture(t, floor)
+ f.in.group = true
+ _, err := f.in.run(t.Context())
+ if (err != nil) != (floor == "v9.0.0") {
+ t.Fatal(err)
+ }
+ })
+ }
+ for _, key := range []string{hostfloor.Key, hostfloor.AuthKey} {
+ f := newChannelFixture(t, "v1.2.0")
+ f.in.group = true
+ if err := f.store.Delete(t.Context(), key); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.in.run(t.Context()); err == nil {
+ t.Fatal("half floor accepted", key)
+ }
+ }
+}
+
+type groupFloorObservationStore struct {
+ release.Store
+ fail string
+ counts map[string]int
+}
+
+func (s *groupFloorObservationStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ s.counts[key]++
+ if key == s.fail {
+ return nil, "", errors.New("read failed")
+ }
+ return s.Store.Get(ctx, key)
+}
+func TestGroupInstallFloorObservation(t *testing.T) {
+ for _, fail := range []string{"", hostfloor.Key, hostfloor.AuthKey} {
+ f := newChannelFixture(t, "")
+ f.in.group = true
+ store := &groupFloorObservationStore{Store: f.store, fail: fail, counts: map[string]int{}}
+ f.a.openStore = func(context.Context) (release.Store, ed25519.PublicKey, error) { return store, f.pub, nil }
+ _, err := f.in.run(t.Context())
+ if (err == nil) != (fail == "") {
+ t.Fatal(fail, err)
+ }
+ if store.counts[hostfloor.Key] != 1 || store.counts[hostfloor.AuthKey] != 1 {
+ t.Fatal("floor halves observed more than once", store.counts)
+ }
+ if fail == "" && f.fetches != 1 {
+ t.Fatal("artifact not verified")
+ }
+ }
+ for _, kind := range []string{"required", "unreadable"} {
+ f := newChannelFixture(t, "")
+ f.in.group = true
+ f.a.rootMoves = func() (rootFloorIdentity, bool, error) {
+ if kind == "unreadable" {
+ return rootFloorIdentity{}, false, os.ErrPermission
+ }
+ return rootFloorIdentity{}, true, nil
+ }
+ if _, err := f.in.run(t.Context()); err == nil || f.fetches != 0 {
+ t.Fatal("guard participation bypassed")
+ }
+ }
+}
diff --git a/internal/host/units/carlos-edge-group.conf b/internal/host/units/carlos-edge-group.conf
new file mode 100644
index 000000000..ea32c9a0d
--- /dev/null
+++ b/internal/host/units/carlos-edge-group.conf
@@ -0,0 +1,6 @@
+[Unit]
+Requires=nftables.service
+After=nftables.service
+
+[Service]
+Restart=no
diff --git a/internal/hostenv/awsssm.go b/internal/hostenv/awsssm.go
index 9f190fabf..5c09b5b8e 100644
--- a/internal/hostenv/awsssm.go
+++ b/internal/hostenv/awsssm.go
@@ -9,6 +9,7 @@ import (
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/ssm"
ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types"
+ "github.com/carlosframework/platform/internal/rootaws"
)
// The AWS adapter for Params (region HA spec 2 §25): SSM Parameter Store
@@ -23,9 +24,11 @@ import (
// html/template is linked in: about 5 MB of linux/arm64 binary (discussion
// #275, .amadan/ci.d/20-cross@5). A method value keeps the one call alone.
type ssmParams struct {
- getByPath getParametersByPathFunc
- put func(context.Context, *ssm.PutParameterInput, ...func(*ssm.Options)) (*ssm.PutParameterOutput, error)
- kmsKey string
+ getByPath getParametersByPathFunc
+ put func(context.Context, *ssm.PutParameterInput, ...func(*ssm.Options)) (*ssm.PutParameterOutput, error)
+ kmsKey string
+ group bool
+ pages, values int
}
// getParametersByPathFunc is ssm.GetParametersByPathAPIClient over one
@@ -39,11 +42,21 @@ func (f getParametersByPathFunc) GetParametersByPath(ctx context.Context, in *ss
// openSSMParams opens SSM in awsRegion ("" is the SDK's default region).
// kmsKey is the key Set encrypts with.
func openSSMParams(ctx context.Context, awsRegion, kmsKey string) (Params, error) {
+ return openSSMParamsMode(ctx, awsRegion, kmsKey, false)
+}
+func openSSMParamsMode(ctx context.Context, awsRegion, kmsKey string, group bool) (Params, error) {
var opts []func(*config.LoadOptions) error
if awsRegion != "" {
opts = append(opts, config.WithRegion(awsRegion))
}
- cfg, err := config.LoadDefaultConfig(ctx, opts...)
+ if group {
+ opts = append(opts, config.WithRetryMaxAttempts(1))
+ }
+ load := config.LoadDefaultConfig
+ if group {
+ load = rootaws.LoadDefaultConfig
+ }
+ cfg, err := load(ctx, opts...)
if err != nil {
return nil, err
}
@@ -52,12 +65,16 @@ func openSSMParams(ctx context.Context, awsRegion, kmsKey string) (Params, error
getByPath: getParametersByPathFunc(client.GetParametersByPath),
put: client.PutParameter,
kmsKey: kmsKey,
+ group: group,
}, nil
}
// ByPath reads every parameter one level under prefix, decrypted, page by
// page. Any failed page fails the whole read.
func (p *ssmParams) ByPath(ctx context.Context, prefix string) (map[string]string, error) {
+ if p.group {
+ return p.groupByPath(ctx, prefix)
+ }
out := map[string]string{}
pages := ssm.NewGetParametersByPathPaginator(p.getByPath, &ssm.GetParametersByPathInput{
Path: aws.String(strings.TrimSuffix(prefix, "/")),
@@ -115,3 +132,39 @@ func (p *ssmParams) SetNew(ctx context.Context, name, value string) error {
}
return err
}
+
+func (p *ssmParams) groupByPath(ctx context.Context, prefix string) (map[string]string, error) {
+ out := map[string]string{}
+ var token *string
+ for {
+ if p.pages >= 20 {
+ return nil, ErrGroupConfig
+ }
+ p.pages++
+ page, err := p.getByPath(ctx, &ssm.GetParametersByPathInput{Path: aws.String(strings.TrimSuffix(prefix, "/")), Recursive: aws.Bool(false), WithDecryption: aws.Bool(true), MaxResults: aws.Int32(10), NextToken: token}, func(o *ssm.Options) { o.RetryMaxAttempts = 1 })
+ if err != nil {
+ return nil, err
+ }
+ if page == nil {
+ return nil, ErrGroupConfig
+ }
+ for _, v := range page.Parameters {
+ p.values++
+ if p.values > 100 {
+ return nil, ErrGroupConfig
+ }
+ k, ok := strings.CutPrefix(aws.ToString(v.Name), prefix)
+ if !ok || k == "" || strings.Contains(k, "/") || v.Value == nil {
+ return nil, ErrGroupConfig
+ }
+ if _, dup := out[k]; dup {
+ return nil, ErrConflict
+ }
+ out[k] = *v.Value
+ }
+ if aws.ToString(page.NextToken) == "" {
+ return out, nil
+ }
+ token = page.NextToken
+ }
+}
diff --git a/internal/hostenv/cli.go b/internal/hostenv/cli.go
index 671079b88..3514dd280 100644
--- a/internal/hostenv/cli.go
+++ b/internal/hostenv/cli.go
@@ -8,6 +8,7 @@ import (
"io"
"os"
"path/filepath"
+ "strings"
)
// carlos system host-env write|seed (region HA spec 2 §5 step 2).
@@ -18,7 +19,7 @@ import (
// - seed is the operator's: it writes a box's existing host.env into
// the parameter layout, once per region.
-const hostEnvUsage = `usage: carlos system host-env write --deployment <name> --region <code> [--aws-region <region>]
+const hostEnvUsage = `usage: carlos system host-env write --deployment <name> --region <code> [--aws-region <region>] [--group [--install]]
carlos system host-env seed --deployment <name> --region <code> --kms-key <key> [--aws-region <region>] [--from <path>]
write build host.env from the deployment's parameters (root)
@@ -35,7 +36,17 @@ var openParams = openSSMParams
// RunSystemHostEnv is `carlos system host-env`.
func RunSystemHostEnv(args []string) {
- if err := runHostEnv(context.Background(), args, os.Stdout, os.Geteuid(), openParams); err != nil {
+ group := false
+ for _, arg := range args {
+ if arg == "--group" || arg == "-group" || strings.HasPrefix(arg, "--group=") || strings.HasPrefix(arg, "-group=") {
+ group = true
+ }
+ }
+ opener := openParams
+ if group {
+ opener = func(ctx context.Context, r, k string) (Params, error) { return openSSMParamsMode(ctx, r, k, true) }
+ }
+ if err := runHostEnv(context.Background(), args, os.Stdout, os.Geteuid(), opener); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
@@ -53,19 +64,47 @@ func runHostEnv(ctx context.Context, args []string, out io.Writer, euid int, ope
awsRegion := fs.String("aws-region", "", "")
kmsKey := fs.String("kms-key", "", "")
from := fs.String("from", Path, "")
+ group := fs.Bool("group", false, "")
+ install := fs.Bool("install", false, "")
if err := fs.Parse(args[1:]); err != nil || fs.NArg() != 0 || *deployment == "" || *region == "" {
return usageError()
}
+ if (*group && verb != "write") || (*install && !*group) {
+ return usageError()
+ }
switch verb {
case "write":
if euid != 0 {
return errors.New("carlos system host-env write runs as root: it writes a root-owned file")
}
+ var c GroupConfig
+ var err error
+ if *group {
+ raw, e := ReadGroupFile(GroupConfigPath, 0, 0644)
+ if e != nil {
+ return e
+ }
+ c, err = ParseGroupConfig(raw)
+ if err != nil {
+ return err
+ }
+ if c.Deployment != *deployment || c.Region != *region || c.AWSRegion != *awsRegion {
+ return ErrGroupConfig
+ }
+ }
p, err := open(ctx, *awsRegion, "")
if err != nil {
return err
}
- body, err := Fetch(ctx, p, *deployment, *region)
+ var body []byte
+ if *group {
+ if s, ok := p.(*ssmParams); ok {
+ s.group = true
+ }
+ body, err = FetchGroup(ctx, p, c)
+ } else {
+ body, err = Fetch(ctx, p, *deployment, *region)
+ }
if err != nil {
return fmt.Errorf("host.env was not written: %w", err)
}
@@ -75,6 +114,11 @@ func runHostEnv(ctx context.Context, args []string, out io.Writer, euid int, ope
if err := writeHostEnv(hostEnvRoot, body); err != nil {
return fmt.Errorf("host.env was not written: %w", err)
}
+ if *install {
+ if err := installGroup(ctx, body); err != nil {
+ return err
+ }
+ }
fmt.Fprintln(out, wroteFileLine(filepath.Join(hostEnvRoot, Path), *region))
return nil
default:
diff --git a/internal/hostenv/group.go b/internal/hostenv/group.go
new file mode 100644
index 000000000..6007a4d9f
--- /dev/null
+++ b/internal/hostenv/group.go
@@ -0,0 +1,192 @@
+package hostenv
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "slices"
+ "strings"
+ "time"
+)
+
+const GroupConfigPath = "/etc/carlos/group.json"
+
+// GroupConfig is installed by root before bootstrap. Placement may be the
+// empty home placement; Region is always the canonical deployment region.
+type GroupConfig struct {
+ DataBucket string `json:"data_bucket"`
+ DeploymentAWSRegion string `json:"deployment_aws_region"`
+ QueueURL string `json:"queue_url"`
+ V int `json:"v"`
+ Account string `json:"account"`
+ AWSRegion string `json:"aws_region"`
+ Region string `json:"region"`
+ Deployment string `json:"deployment"`
+ Bucket string `json:"bucket"`
+ Group string `json:"group"`
+ Hook string `json:"hook"`
+ Placement *string `json:"placement"`
+ Pools []string `json:"pools"`
+ KnownReaders []string `json:"known_readers"`
+ Release string `json:"release"`
+ InstanceID string `json:"instance_id"`
+ BootID string `json:"boot_id"`
+ Deadline int64 `json:"deadline"`
+ ConfigDigest string `json:"config_digest"`
+}
+
+var ErrGroupConfig = errors.New("group_config_invalid")
+
+func (c GroupConfig) Validate() error {
+ if c.V != 1 || len(c.Account) != 12 || strings.Trim(c.Account, "0123456789") != "" || !scopeName.MatchString(c.DeploymentAWSRegion) || !scopeName.MatchString(c.AWSRegion) || !scopeName.MatchString(c.Region) || c.Region == SharedScope || !scopeName.MatchString(c.Deployment) || c.Bucket == "" || c.DataBucket == "" || !scopeName.MatchString(c.Group) || c.Hook != "carlos-initial-launch" || c.Placement == nil || (*c.Placement != "" && *c.Placement != c.Region) || c.Release == "" || len(c.Pools) == 0 || c.KnownReaders == nil {
+ return ErrGroupConfig
+ }
+ for _, list := range [][]string{c.Pools, c.KnownReaders} {
+ seen := map[string]bool{}
+ for _, x := range list {
+ if !scopeName.MatchString(x) || seen[x] {
+ return ErrGroupConfig
+ }
+ seen[x] = true
+ }
+ }
+ if slices.Contains(c.Pools, "hapair") && c.Deployment != "dev" {
+ return ErrGroupConfig
+ }
+ return nil
+}
+
+func (c GroupConfig) Digest() string {
+ c.ConfigDigest = ""
+ b, _ := json.Marshal(c)
+ var m map[string]any
+ _ = json.Unmarshal(b, &m)
+ delete(m, "config_digest")
+ b, _ = json.Marshal(m)
+ sum := sha256.Sum256(b)
+ return hex.EncodeToString(sum[:])
+}
+
+func ParseGroupConfig(b []byte) (GroupConfig, error) {
+ var c GroupConfig
+ d := json.NewDecoder(bytes.NewReader(b))
+ d.DisallowUnknownFields()
+ if len(b) > 65536 || d.Decode(&c) != nil || d.Decode(new(any)) != io.EOF {
+ return c, ErrGroupConfig
+ }
+ if err := c.Validate(); err != nil {
+ return c, err
+ }
+ if !bindingIID.MatchString(c.InstanceID) || c.BootID == "" || c.Deadline <= 0 || c.ConfigDigest != c.Digest() {
+ return c, ErrGroupConfig
+ }
+ return c, nil
+}
+
+// AssembleGroup has its own allowlist; the fixed/claims selection is unchanged.
+// The boot queue wins after selection, even over a copied fixed-box value.
+func AssembleGroup(shared, regional map[string]string, c GroupConfig, queue string) (map[string]string, error) {
+ if err := c.Validate(); err != nil {
+ return nil, err
+ }
+ env := map[string]string{}
+ for _, src := range []map[string]string{shared, regional} {
+ for k, v := range src {
+ if strings.HasPrefix(k, "CARLOS_HOST_CLAIM") || k == BoxReference || !ValidKey(k) {
+ continue
+ }
+ if _, dup := env[k]; dup {
+ return nil, fmt.Errorf("%w: %s", ErrConflict, k)
+ }
+ if !Allowed(k) && k != "AWS_REGION" && k != "CARLOS_POOLS" {
+ return nil, fmt.Errorf("%w: %s", ErrValue, k)
+ }
+ env[k] = v
+ }
+ }
+ for _, k := range Required {
+ if strings.HasPrefix(k, "CARLOS_HOST_CLAIM") || k == "CARLOS_REGION" {
+ continue
+ }
+ if env[k] == "" {
+ return nil, fmt.Errorf("%w: %s", ErrMissing, k)
+ }
+ }
+ pools := strings.Split(env["CARLOS_POOLS"], ",")
+ want := slices.Clone(c.Pools)
+ slices.Sort(want)
+ slices.Sort(pools)
+ if !slices.Equal(pools, want) || env["CARLOS_REGION"] != *c.Placement || env["AWS_REGION"] != c.DeploymentAWSRegion || env["CARLOS_HIBERNATE_REGION"] != c.AWSRegion || env["CARLOS_HIBERNATE_BUCKET"] != c.DataBucket || (env["CARLOS_AWS_REGION"] != "" && env["CARLOS_AWS_REGION"] != c.AWSRegion) || env["CARLOS_DEPLOYMENT_BUCKET"] != c.Bucket || env["CARLOS_REGION_HA"] != "true" || env["CARLOS_GROUP_ADMISSION"] != "1" || env["CARLOS_CHANGE_INDEX"] != "read" || queue == "" {
+ return nil, ErrGroupConfig
+ }
+ env["CARLOS_TERMINATION_QUEUE_URL"] = queue
+ env[BoxReference] = GroupReference
+ if _, err := Render(env); err != nil {
+ return nil, err
+ }
+ return env, nil
+}
+
+func FetchGroup(ctx context.Context, p Params, c GroupConfig) ([]byte, error) {
+ sp, err := Prefix(c.Deployment, SharedScope)
+ if err != nil {
+ return nil, err
+ }
+ rp, err := Prefix(c.Deployment, c.Region)
+ if err != nil {
+ return nil, err
+ }
+ shared, err := p.ByPath(ctx, sp)
+ if err != nil {
+ return nil, err
+ }
+ regional, err := p.ByPath(ctx, rp)
+ if err != nil {
+ return nil, err
+ }
+ env, err := AssembleGroup(shared, regional, c, c.QueueURL)
+ if err != nil {
+ return nil, err
+ }
+ return Render(env)
+}
+
+// installGroup executes the verified bootstrap with parsed environment values.
+// It never evaluates the file through a shell, and strips inherited authority.
+func installGroup(ctx context.Context, body []byte) error {
+ env, err := Parse(body)
+ if err != nil {
+ return err
+ }
+ if _, err = Render(env); err != nil {
+ return err
+ }
+ binary, err := os.Executable()
+ if err != nil {
+ return err
+ }
+ childEnv := []string{"PATH=/usr/sbin:/usr/bin:/sbin:/bin", "HOME=/root", "AWS_MAX_ATTEMPTS=1", "AWS_RETRY_MODE=standard"}
+ for _, k := range sortedKeys(env) {
+ childEnv = append(childEnv, k+"="+env[k])
+ }
+ ctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
+ defer cancel()
+ for _, args := range [][]string{{"bootstrap"}, {"system", "install-channel"}} {
+ cmd := exec.CommandContext(ctx, binary, args...)
+ cmd.Env = childEnv
+ cmd.Dir = "/"
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ if err = cmd.Run(); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/hostenv/group_linux.go b/internal/hostenv/group_linux.go
new file mode 100644
index 000000000..cc2fc5f28
--- /dev/null
+++ b/internal/hostenv/group_linux.go
@@ -0,0 +1,55 @@
+//go:build linux
+
+package hostenv
+
+import (
+ "golang.org/x/sys/unix"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// ReadGroupFile holds each directory by descriptor and refuses writable
+// parents, links and nonregular leaves. Agent callers require owner zero.
+func ReadGroupFile(path string, owner int, mode os.FileMode) ([]byte, error) {
+ return readGroupFileAt("/", path, owner, mode)
+}
+func readGroupFileAt(root, path string, owner int, mode os.FileMode) ([]byte, error) {
+ if !filepath.IsAbs(path) || filepath.Clean(path) != path {
+ return nil, ErrGroupConfig
+ }
+ fd, err := unix.Openat2(unix.AT_FDCWD, root, &unix.OpenHow{Flags: unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC, Resolve: unix.RESOLVE_NO_SYMLINKS})
+ if err != nil {
+ return nil, err
+ }
+ defer func() { unix.Close(fd) }()
+ var anchor unix.Stat_t
+ if unix.Fstat(fd, &anchor) != nil || (anchor.Uid != 0 && int(anchor.Uid) != owner) || anchor.Mode&0022 != 0 {
+ return nil, ErrGroupConfig
+ }
+ parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
+ for _, part := range parts[:len(parts)-1] {
+ next, e := unix.Openat(fd, part, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
+ if e != nil {
+ return nil, e
+ }
+ unix.Close(fd)
+ fd = next
+ var st unix.Stat_t
+ if unix.Fstat(fd, &st) != nil || (st.Uid != 0 && int(st.Uid) != owner) || st.Mode&0022 != 0 {
+ return nil, ErrGroupConfig
+ }
+ }
+ leaf, err := unix.Openat(fd, parts[len(parts)-1], unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0)
+ if err != nil {
+ return nil, err
+ }
+ f := os.NewFile(uintptr(leaf), path)
+ defer f.Close()
+ var st unix.Stat_t
+ if unix.Fstat(leaf, &st) != nil || int(st.Uid) != owner || st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0777 != uint32(mode) || st.Nlink != 1 || st.Size > 65536 {
+ return nil, ErrGroupConfig
+ }
+ return io.ReadAll(io.LimitReader(f, 65537))
+}
diff --git a/internal/hostenv/group_linux_test.go b/internal/hostenv/group_linux_test.go
new file mode 100644
index 000000000..c98a707cf
--- /dev/null
+++ b/internal/hostenv/group_linux_test.go
@@ -0,0 +1,44 @@
+//go:build linux
+
+package hostenv
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestGroupConfigSafeFiles(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.Chmod(dir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ file := filepath.Join(dir, "marker")
+ if err := os.WriteFile(file, []byte("{}"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readGroupFileAt(dir, "/marker", os.Geteuid(), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(file, 0666); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readGroupFileAt(dir, "/marker", os.Geteuid(), 0644); err == nil {
+ t.Fatal("writable marker")
+ }
+ os.Chmod(file, 0644)
+ link := filepath.Join(dir, "link")
+ if err := os.Symlink(file, link); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := readGroupFileAt(dir, "/link", os.Geteuid(), 0644); err == nil {
+ t.Fatal("symlink marker")
+ }
+ if err := os.Chmod(dir, 0777); err != nil {
+ t.Fatal(err)
+ }
+ defer os.Chmod(dir, 0700)
+ if _, err := readGroupFileAt(dir, "/marker", os.Geteuid(), 0644); err == nil {
+ t.Fatal("writable parent")
+ }
+}
diff --git a/internal/hostenv/group_other.go b/internal/hostenv/group_other.go
new file mode 100644
index 000000000..db0c32e60
--- /dev/null
+++ b/internal/hostenv/group_other.go
@@ -0,0 +1,12 @@
+//go:build !linux
+
+package hostenv
+
+import "os"
+
+func ReadGroupFile(path string, _ int, _ os.FileMode) ([]byte, error) {
+ if _, err := os.Lstat(path); err != nil {
+ return nil, err
+ }
+ return nil, ErrGroupConfig
+}
diff --git a/internal/hostenv/group_test.go b/internal/hostenv/group_test.go
new file mode 100644
index 000000000..3e2442e14
--- /dev/null
+++ b/internal/hostenv/group_test.go
@@ -0,0 +1,124 @@
+package hostenv
+
+import (
+ "context"
+ "fmt"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/ssm"
+ ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types"
+ "strings"
+ "testing"
+)
+
+func groupEnvFixture() (GroupConfig, map[string]string) {
+ placement := ""
+ c := GroupConfig{V: 1, Account: "123456789012", AWSRegion: "eu-west-1", DeploymentAWSRegion: "us-east-1", Region: "ie", Deployment: "dev", Bucket: "deploy", DataBucket: "data", Group: "dev-ie", Hook: "carlos-initial-launch", Placement: &placement, Pools: []string{"hapair"}, KnownReaders: []string{"fixed"}, Release: "v1.2.3"}
+ env := map[string]string{}
+ for _, k := range Required {
+ env[k] = "value"
+ }
+ env["CARLOS_REGION"] = ""
+ env["CARLOS_REGION_HA"] = "true"
+ env["CARLOS_GROUP_ADMISSION"] = "1"
+ env["CARLOS_CHANGE_INDEX"] = "read"
+ env["CARLOS_POOLS"] = "hapair"
+ env["AWS_REGION"] = "us-east-1"
+ env["CARLOS_DEPLOYMENT_BUCKET"] = "deploy"
+ env["CARLOS_HIBERNATE_REGION"] = "eu-west-1"
+ env["CARLOS_HIBERNATE_BUCKET"] = "data"
+ return c, env
+}
+func TestGroupHostEnvNoClaims(t *testing.T) {
+ c, env := groupEnvFixture()
+ env["CARLOS_HOST_CLAIM_UNKNOWN"] = "true"
+ env["CARLOS_TERMINATION_QUEUE_URL"] = "fixed-queue"
+ got, err := AssembleGroup(nil, env, c, "group-queue")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for k := range got {
+ if strings.HasPrefix(k, "CARLOS_HOST_CLAIM") {
+ t.Fatal(k)
+ }
+ }
+ if got["CARLOS_TERMINATION_QUEUE_URL"] != "group-queue" {
+ t.Fatal("boot queue must override seeded fixed queue")
+ }
+ if got[BoxReference] != GroupReference {
+ t.Fatal(got)
+ }
+}
+func TestGroupHostEnvPools(t *testing.T) {
+ for _, value := range []string{"", "shared", "hapair,hapair", "../x", "hapair,shared"} {
+ c, env := groupEnvFixture()
+ env["CARLOS_POOLS"] = value
+ if _, err := AssembleGroup(nil, env, c, "queue"); err == nil {
+ t.Fatal(value)
+ }
+ }
+ c, env := groupEnvFixture()
+ c.Deployment = "prod"
+ if _, err := AssembleGroup(nil, env, c, "queue"); err == nil {
+ t.Fatal("hapair outside dev")
+ }
+}
+func TestGroupHostEnvRegions(t *testing.T) {
+ for _, key := range []string{"CARLOS_REGION", "AWS_REGION", "CARLOS_DEPLOYMENT_BUCKET", "CARLOS_HIBERNATE_REGION", "CARLOS_REGION_HA", "CARLOS_CHANGE_INDEX", "CARLOS_GROUP_ADMISSION"} {
+ c, env := groupEnvFixture()
+ env[key] = "wrong"
+ if _, err := AssembleGroup(nil, env, c, "queue"); err == nil {
+ t.Fatal(key)
+ }
+ }
+ c, env := groupEnvFixture()
+ if _, err := AssembleGroup(map[string]string{"CARLOS_POOLS": "hapair"}, env, c, "queue"); err == nil {
+ t.Fatal("duplicate accepted")
+ }
+}
+
+func TestGroupBootRequestBudgetSSM(t *testing.T) {
+ for _, mode := range []string{"empty-pages", "values", "duplicate", "nested", "two-scopes"} {
+ t.Run(mode, func(t *testing.T) {
+ calls := 0
+ p := &ssmParams{group: true, getByPath: func(_ context.Context, in *ssm.GetParametersByPathInput, opts ...func(*ssm.Options)) (*ssm.GetParametersByPathOutput, error) {
+ calls++
+ o := ssm.Options{}
+ for _, f := range opts {
+ f(&o)
+ }
+ if aws.ToInt32(in.MaxResults) != 10 || aws.ToBool(in.Recursive) || !aws.ToBool(in.WithDecryption) || o.RetryMaxAttempts != 1 {
+ t.Fatal("SSM budget configuration", in, o.RetryMaxAttempts)
+ }
+ out := &ssm.GetParametersByPathOutput{NextToken: aws.String("next")}
+ switch mode {
+ case "empty-pages":
+ case "duplicate":
+ out.Parameters = []ssmtypes.Parameter{{Name: aws.String("/prefix/A"), Value: aws.String("v")}}
+ case "nested":
+ out.Parameters = []ssmtypes.Parameter{{Name: aws.String("/prefix/boot/A"), Value: aws.String("v")}}
+ case "values", "two-scopes":
+ for n := 0; n < 10; n++ {
+ out.Parameters = append(out.Parameters, ssmtypes.Parameter{Name: aws.String(fmt.Sprintf("/prefix/K%d_%d", calls, n)), Value: aws.String("v")})
+ }
+ if mode == "two-scopes" && calls == 6 {
+ out.NextToken = nil
+ }
+ }
+ return out, nil
+ }}
+ _, err := p.ByPath(t.Context(), "/prefix/")
+ if mode == "two-scopes" {
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = p.ByPath(t.Context(), "/prefix/")
+ }
+ if err == nil || calls > 20 || p.values > 101 {
+ t.Fatal(mode, calls, p.values, err)
+ }
+ if mode == "empty-pages" && calls != 20 {
+ t.Fatal(calls)
+ }
+ })
+ }
+}
diff --git a/scripts/region_group_contract_test.py b/scripts/region_group_contract_test.py
index ee567697d..7e14af4c1 100644
--- a/scripts/region_group_contract_test.py
+++ b/scripts/region_group_contract_test.py
@@ -3,6 +3,8 @@
Pass region-host's event file. The fixed snapshot was generated from the
Task 2 base commit using fixed_state_unchanged, with the same mock region.
"""
+import ast
+import re
import base64
import fnmatch
import json
@@ -213,9 +215,12 @@ def audit_group(plan, dns):
assert not allowed(statements, 'route53:ChangeResourceRecordSets', 'arn:aws:route53:::hostedzone/ZTESTDNS', dict(ctx, **{'route53:ChangeResourceRecordSetsRecordTypes': ['A']}))
script = base64.b64decode(resources['aws_launch_template.group[0]']['user_data']).decode()
subprocess.run(['sh', '-n'], input=script, text=True, check=True)
+ for label, block in re.findall(r"python3 - <<'(PY[A-Z]*)'\n(.*?)\n\1", script, re.S):
+ ast.parse(block)
assert 'CARLOS_BOOTSTRAP_OBJECT_KEY=\'/carlos/dev/ie/boot/bootstrap-object\'' in script
assert 'CARLOS_TERMINATION_QUEUE_URL=\'' + queue['id'] + "'" in script
- assert script.rstrip().endswith('exit 1'), 'Task 3 must replace the fail-closed placeholder'
+ assert '# start guarded agent' in script and 'system host-env write --group' in script
+ assert script.index('systemctl mask') < script.index('apt-get -y -q install')
print('group combined policies, managed inheritance, denial witnesses and boot shell passed')
@@ -236,7 +241,7 @@ def main(path):
elif run == 'group_boot_quotes':
resources = {r['address']: r['values'] for r in plan['planned_values']['root_module']['resources']}
script = base64.b64decode(resources['aws_launch_template.group[0]']['user_data']).decode()
- script = script.replace('\nexit 1', '\nprintf \'%s\' "$CARLOS_TERMINATION_QUEUE_URL"')
+ script = script.split('# TASK 3:', 1)[0] + '\nprintf \'%s\' "$CARLOS_TERMINATION_QUEUE_URL"'
result = subprocess.run(['sh'], input=script, text=True, capture_output=True, check=True)
assert result.stdout == resources['aws_sqs_queue.terminations']['id'], result.stdout
print('group boot values remain literal under shell quote and command substitution probes')