From 23ef38a03ccc1f9a84290176b78196ab0e2ac720 Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:54:15 +0100 Subject: [PATCH 01/13] Add scoped customer monitoring network provisioning role --- .ci_cd/aws/monitoring-network/README.md | 129 +++++++++++++ .../cloudformation-customer-role.yml | 180 ++++++++++++++++++ .../monitoring-network/tests/requirements.txt | 1 + .../tests/test_customer_role.py | 141 ++++++++++++++ 4 files changed, 451 insertions(+) create mode 100644 .ci_cd/aws/monitoring-network/README.md create mode 100644 .ci_cd/aws/monitoring-network/cloudformation-customer-role.yml create mode 100644 .ci_cd/aws/monitoring-network/tests/requirements.txt create mode 100644 .ci_cd/aws/monitoring-network/tests/test_customer_role.py diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md new file mode 100644 index 0000000000..fdd5c02ea0 --- /dev/null +++ b/.ci_cd/aws/monitoring-network/README.md @@ -0,0 +1,129 @@ +# Shared customer monitoring network + +This implements the customer side of [#3365](https://github.com/openremote/core/issues/3365). +Shared peering/routes are account/VPC infrastructure. Staging and production reuse +one connection; no per-environment enable flag belongs here. Per-host access is +[#3402](https://github.com/openremote/core/issues/3402). + +Current slice: the customer provisioning role and its offline validation. Peering and +route templates, central return-route permissions and the reusable workflow follow +separately. Do not run a live migration from this directory yet. + +## Identities and ownership + +Use one dedicated GitHub OIDC role per customer connection. Its exact repository and +GitHub environment are trusted; `monitoring-network` is the proposed environment name. +The existing account OIDC provider is a prerequisite, normally deployed through CfCT. +Protect the environment and its deployment branches in GitHub: environment-based OIDC +trust does not itself restrict a job to main or to one workflow file. There are no PATs +or AWS keys in this design. + +The role operates one named CloudFormation networking stack using the role's temporary +credentials. No CloudFormation service role is used or passed. This same customer role +is the `RequesterRoleName` in the central acceptance template. A separate central role +accepts the peering; it does not administer routes. Central return routes need separate +permissions and their own stack, which this template does not grant. + +The central acceptance template lives in the infrastructure repository. This core template neither +copies it nor provisions IAM in the central account. Application and Alloy deployment +roles are unchanged. + +## Bootstrap order + +A privileged operator provisions IAM prerequisites; the networking workflow cannot +create or update its own role. + +1. Agree the customer role name, customer stack name and protected GitHub environment. +2. In the central account, provision the acceptance stack for this customer account, + exact role name and VPC pair. Its account-plus-PrincipalArn trust permits this + ordering before the customer role exists. Retain the acceptance-role ARN output. +3. In the customer account, review and deploy `cloudformation-customer-role.yml` with + that ARN and the approved parameters. This requires `CAPABILITY_NAMED_IAM`. +4. Later, use the returned role ARN from the customer workflow. Verify OIDC identity, + role assumption and the actual CloudFormation path on a disposable connection + before migrating the existing shared peering. + +The networking stack name must differ from the IAM prerequisite stack name, the +standard VPC stack and application stacks. It must be new, or demonstrably owned by +this integration. Do not reuse an unrelated existing stack or one with a stored +CloudFormation service-role ARN. CloudFormation can reuse a previously assigned +service role; the future workflow must reject that situation before writes. + +## Parameters + +| Parameter | Meaning | +| ----------------------- | -------------------------------------------------------------------------- | +| `RoleName` | Exact pathless customer role name; must match the central acceptance trust | +| `GitHubRepository` | Exact customer `owner/repository`, not the reusable core repository | +| `GitHubEnvironment` | Protected account-level environment; default `monitoring-network` | +| `NetworkStackName` | Exact dedicated customer peering/routes stack name | +| `CustomerVpcId` | Existing customer VPC in this account/region | +| `CustomerRouteTableIds` | Explicit list of existing route-table IDs in that VPC | +| `MonitoringVpcArn` | Exact monitoring VPC ARN in the same region/partition | +| `AcceptanceRoleArn` | Output of the matching central acceptance stack | + +Commercial AWS is the initial supported partition. Bootstrap review and later workflow +validation must check that the monitoring VPC and acceptance role refer to the intended +central account, and that the route tables belong to the customer VPC. These parameters +are non-secret but are approval boundaries: changing them can broaden permissions. + +## Permission boundaries and limits + +- Network inspection is read-only across the customer account in the selected region; + EC2 Describe operations require resource `*`. This is not limited to one VPC. +- CloudFormation operations are scoped to one exact stack name. Create/update use + change sets; direct CreateStack/UpdateStack and passing a service role are not granted. + `DeleteChangeSet` permits discarding unused proposals without changing resources. + `DeleteStack` is not granted: tearing down shared networking uses an authorized + operator AWS session and the reviewed cleanup procedure. Continuing a failed + rollback remains an explicit operation, not an automatic workflow action. + Underlying EC2 deletion permissions remain necessary for resource replacement and + rollback; removing `DeleteStack` does not prevent a change set from deleting resources. +- `sts:AssumeRole` targets only the approved central acceptance role ARN. +- Peering creation is constrained to the customer requester VPC and exact monitoring + accepter VPC. It must include the tag `openremote:monitoring-network` with the + networking stack name. The later connection template must supply that tag on creation. +- Peering deletion requires the same VPC pair and ownership tag. This deliberately does + not authorize deleting the old, untagged, reverse-direction experimental peering. + Its migration remains a separate reviewed operator action. +- Other tags on an owned peering can be updated; the ownership tag cannot be changed + or removed through the tagging permissions. No VPC, subnet, route-table, SG or NACL + creation/deletion privileges are granted. +- Route writes require both the configured VPC and an explicitly listed route-table + ID. EC2 authorizes route changes at the **table**, not destination-CIDR level: this + role can change other route entries within an approved table. Reviewed templates, + conflict detection, change sets and workflow access controls protect those entries; + do not describe IAM as enforcing only the monitoring destination. No table itself + can be created, deleted or reassociated by this role. + +EC2 write permissions are usable directly as well as through CloudFormation; this +role is a trusted provisioning identity, not a sandbox for arbitrary workflow code. +It cannot modify IAM, secrets, host services or central routes with the policies here. +Do not add an administrator policy or reuse a broad existing deployment role to bypass +validation failures. + +## Validation and next steps + +From the core repository root: + +```sh +uv run --no-project --with-requirements .ci_cd/aws/monitoring-network/tests/requirements.txt python -B -m unittest discover -s .ci_cd/aws/monitoring-network/tests -v +uv tool run cfn-lint .ci_cd/aws/monitoring-network/cloudformation-customer-role.yml +``` + +Offline tests protect the intended trust and permission boundaries. Lint validates +the CloudFormation schema. They do not prove AWS authorization, SCPs, the provider's +tag-on-create behavior, rollback or role-assumption behavior. Validate those using the +actual role and disposable resources when the connection template/workflow are ready. +Do not broaden permissions preemptively when diagnosing a failed check. + +This change has no downstream application/API effect and requires no changes to +Extensions or existing application workflows. A generic custom-project caller/example +and maintained operator documentation accompany the later reusable networking workflow. + +References: + +- [Core CI/CD conventions](https://docs.openremote.io/docs/developer-guide/ci-cd-pipeline/) +- [CloudFormation temporary credentials and service roles](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-servicerole.html) +- [EC2 resource and condition-key support](https://docs.aws.amazon.com/service-authorization/latest/reference/list_ec2.html) +- [CloudFormation action/resource scopes](https://docs.aws.amazon.com/service-authorization/latest/reference/list_cloudformation.html) diff --git a/.ci_cd/aws/monitoring-network/cloudformation-customer-role.yml b/.ci_cd/aws/monitoring-network/cloudformation-customer-role.yml new file mode 100644 index 0000000000..e369e9fcd3 --- /dev/null +++ b/.ci_cd/aws/monitoring-network/cloudformation-customer-role.yml @@ -0,0 +1,180 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: Dedicated GitHub OIDC role for one customer monitoring network stack + +Parameters: + RoleName: + Type: String + Description: Pathless role name also configured on the central acceptance stack + AllowedPattern: "[A-Za-z0-9+=,.@_-]+" + MaxLength: 64 + GitHubRepository: + Type: String + Description: Exact owner/repository of the customer workflow caller + AllowedPattern: "[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+" + GitHubEnvironment: + Type: String + Default: monitoring-network + Description: Account-level GitHub environment; configure its protection and branch rules separately + AllowedPattern: "[A-Za-z0-9_-]+" + MaxLength: 255 + NetworkStackName: + Type: String + Description: Exact dedicated customer peering/routes stack name, different from this IAM stack + AllowedPattern: "[A-Za-z][A-Za-z0-9-]*" + MaxLength: 128 + CustomerVpcId: + Type: AWS::EC2::VPC::Id + Description: Existing customer VPC; this role cannot create or replace it + CustomerRouteTableIds: + Type: CommaDelimitedList + AllowedPattern: "rtb-([0-9a-f]{8}|[0-9a-f]{17})" + Description: Explicit existing customer route tables whose route entries may be managed + MonitoringVpcArn: + Type: String + Description: Exact monitoring VPC ARN in the same region and partition + AllowedPattern: "arn:aws:ec2:[a-z0-9-]+:[0-9]{12}:vpc/vpc-([0-9a-f]{8}|[0-9a-f]{17})" + AcceptanceRoleArn: + Type: String + Description: PeeringAcceptanceRoleArn output from the approved central acceptance stack + AllowedPattern: "arn:aws:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_/-]+" + +# The account-wide GitHub OIDC provider is an existing prerequisite, managed by CfCT. +# This role uses its own credentials through CloudFormation, not a service role. +Resources: + CustomerNetworkRole: + Type: AWS::IAM::Role + Properties: + RoleName: !Ref RoleName + Description: Provisions only the configured customer monitoring connection + MaxSessionDuration: 3600 + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: + Federated: !Sub "arn:${AWS::Partition}:iam::${AWS::AccountId}:oidc-provider/token.actions.githubusercontent.com" + Action: sts:AssumeRoleWithWebIdentity + Condition: + StringEquals: + token.actions.githubusercontent.com:aud: sts.amazonaws.com + token.actions.githubusercontent.com:sub: !Sub "repo:${GitHubRepository}:environment:${GitHubEnvironment}" + Policies: + - PolicyName: CustomerMonitoringNetwork + PolicyDocument: + Version: "2012-10-17" + Statement: + - Sid: InspectRegionalNetwork + Effect: Allow + Action: + - ec2:DescribeVpcs + - ec2:DescribeVpcAttribute + - ec2:DescribeVpcPeeringConnections + - ec2:DescribeRouteTables + - ec2:DescribeSubnets + - ec2:DescribeNetworkAcls + - ec2:DescribeSecurityGroups + Resource: "*" + Condition: + StringEquals: + aws:RequestedRegion: !Ref AWS::Region + - Sid: PreviewDedicatedStack + Effect: Allow + Action: cloudformation:CreateChangeSet + Resource: !Sub "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/${NetworkStackName}/*" + Condition: + "Null": + cloudformation:RoleArn: "true" + - Sid: OperateDedicatedStack + Effect: Allow + Action: + - cloudformation:DescribeStacks + - cloudformation:DescribeStackEvents + - cloudformation:DescribeStackResources + - cloudformation:ListStackResources + - cloudformation:GetTemplate + - cloudformation:ListChangeSets + - cloudformation:DescribeChangeSet + - cloudformation:ExecuteChangeSet + - cloudformation:DeleteChangeSet + - cloudformation:ContinueUpdateRollback + - cloudformation:TagResource + - cloudformation:UntagResource + Resource: !Sub "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/${NetworkStackName}/*" + - Sid: AssumeCentralAcceptanceRole + Effect: Allow + Action: sts:AssumeRole + Resource: !Ref AcceptanceRoleArn + - Sid: RequestFromCustomerVpc + Effect: Allow + Action: ec2:CreateVpcPeeringConnection + Resource: !Sub "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${CustomerVpcId}" + - Sid: CreateConfiguredPeering + Effect: Allow + Action: ec2:CreateVpcPeeringConnection + Resource: !Sub "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc-peering-connection/*" + Condition: + ArnEquals: + ec2:RequesterVpc: !Sub "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${CustomerVpcId}" + ec2:AccepterVpc: !Ref MonitoringVpcArn + StringEquals: + aws:RequestTag/openremote:monitoring-network: !Ref NetworkStackName + - Sid: TagPeeringOnCreation + Effect: Allow + Action: ec2:CreateTags + Resource: !Sub "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc-peering-connection/*" + Condition: + StringEquals: + ec2:CreateAction: CreateVpcPeeringConnection + aws:RequestTag/openremote:monitoring-network: !Ref NetworkStackName + - Sid: UpdateOwnedPeeringTags + Effect: Allow + Action: + - ec2:CreateTags + - ec2:DeleteTags + Resource: !Sub "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc-peering-connection/*" + Condition: + StringEquals: + ec2:ResourceTag/openremote:monitoring-network: !Ref NetworkStackName + ForAllValues:StringNotEquals: + aws:TagKeys: openremote:monitoring-network + - Sid: DeleteOwnedConfiguredPeering + Effect: Allow + Action: ec2:DeleteVpcPeeringConnection + Resource: !Sub "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc-peering-connection/*" + Condition: + ArnEquals: + ec2:RequesterVpc: !Sub "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${CustomerVpcId}" + ec2:AccepterVpc: !Ref MonitoringVpcArn + StringEquals: + ec2:ResourceTag/openremote:monitoring-network: !Ref NetworkStackName + - Sid: ManageRoutesInApprovedTables + Effect: Allow + Action: + - ec2:CreateRoute + - ec2:ReplaceRoute + - ec2:DeleteRoute + Resource: !Sub "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:route-table/*" + Condition: + ArnEquals: + ec2:Vpc: !Sub "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${CustomerVpcId}" + StringEquals: + ec2:RouteTableID: !Ref CustomerRouteTableIds + Tags: + - Key: Component + Value: monitoring-network + - Key: NetworkStack + Value: !Ref NetworkStackName + +Outputs: + CustomerNetworkRoleArn: + Description: Role to assume through GitHub OIDC for the customer networking workflow + Value: !GetAtt CustomerNetworkRole.Arn + CustomerNetworkRoleName: + Description: RequesterRoleName for the central acceptance prerequisite + Value: !Ref CustomerNetworkRole + TrustedGitHubSubject: + Description: Exact repository/environment subject authorized by this role + Value: !Sub "repo:${GitHubRepository}:environment:${GitHubEnvironment}" + NetworkStackName: + Description: Dedicated customer networking stack this role may operate + Value: !Ref NetworkStackName diff --git a/.ci_cd/aws/monitoring-network/tests/requirements.txt b/.ci_cd/aws/monitoring-network/tests/requirements.txt new file mode 100644 index 0000000000..f62ce0c56d --- /dev/null +++ b/.ci_cd/aws/monitoring-network/tests/requirements.txt @@ -0,0 +1 @@ +PyYAML==6.0.3 diff --git a/.ci_cd/aws/monitoring-network/tests/test_customer_role.py b/.ci_cd/aws/monitoring-network/tests/test_customer_role.py new file mode 100644 index 0000000000..87efca54bf --- /dev/null +++ b/.ci_cd/aws/monitoring-network/tests/test_customer_role.py @@ -0,0 +1,141 @@ +"""Offline policy guardrails, not an IAM authorization simulator.""" +import re +import unittest +from pathlib import Path + +import yaml + + +class TemplateLoader(yaml.SafeLoader): + pass + + +def intrinsic(loader, tag, node): + return {"Ref" if tag == "Ref" else "Fn::" + tag: loader.construct_scalar(node)} + + +TemplateLoader.add_multi_constructor("!", intrinsic) +TEMPLATE = Path(__file__).resolve().parents[1] / "cloudformation-customer-role.yml" +STACK_ARN = "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/${NetworkStackName}/*" +VPC_ARN = "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${CustomerVpcId}" +PEER_ARN = "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:vpc-peering-connection/*" + + +class CustomerRoleTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.template = yaml.load(TEMPLATE.read_text(), Loader=TemplateLoader) + cls.role = cls.template["Resources"]["CustomerNetworkRole"]["Properties"] + cls.statements = cls.role["Policies"][0]["PolicyDocument"]["Statement"] + cls.by_sid = {statement["Sid"]: statement for statement in cls.statements} + + def test_oidc_trust_is_exact_repository_environment_and_audience(self): + trust = self.role["AssumeRolePolicyDocument"]["Statement"] + self.assertEqual(len(trust), 1) + self.assertEqual(trust[0]["Effect"], "Allow") + self.assertEqual(trust[0]["Action"], "sts:AssumeRoleWithWebIdentity") + self.assertEqual(trust[0]["Principal"], {"Federated": {"Fn::Sub": + "arn:${AWS::Partition}:iam::${AWS::AccountId}:oidc-provider/token.actions.githubusercontent.com"}}) + self.assertEqual(trust[0]["Condition"], {"StringEquals": { + "token.actions.githubusercontent.com:aud": "sts.amazonaws.com", + "token.actions.githubusercontent.com:sub": {"Fn::Sub": + "repo:${GitHubRepository}:environment:${GitHubEnvironment}"}}}) + + def test_only_one_role_and_no_privilege_administration(self): + self.assertEqual(set(self.template["Resources"]), {"CustomerNetworkRole"}) + self.assertEqual(self.template["Resources"]["CustomerNetworkRole"]["Type"], "AWS::IAM::Role") + self.assertNotIn("ManagedPolicyArns", self.role) + self.assertEqual(len(self.role["Policies"]), 1) + actions = set() + for statement in self.statements: + self.assertEqual(statement["Effect"], "Allow") + self.assertNotIn("NotAction", statement) + self.assertNotIn("NotResource", statement) + values = statement["Action"] + actions.update([values] if isinstance(values, str) else values) + self.assertFalse(any("*" in action for action in actions)) + self.assertEqual({a for a in actions if not a.startswith(("ec2:", "cloudformation:"))}, {"sts:AssumeRole"}) + ec2_writes = {a for a in actions if a.startswith("ec2:") and not a.startswith("ec2:Describe")} + self.assertEqual(ec2_writes, { + "ec2:CreateVpcPeeringConnection", "ec2:DeleteVpcPeeringConnection", + "ec2:CreateTags", "ec2:DeleteTags", "ec2:CreateRoute", "ec2:ReplaceRoute", "ec2:DeleteRoute"}) + self.assertEqual(self.by_sid["AssumeCentralAcceptanceRole"]["Resource"], {"Ref": "AcceptanceRoleArn"}) + + def test_cloudformation_is_one_stack_using_change_sets_without_service_role(self): + actions = set() + for statement in self.statements: + values = statement["Action"] + values = [values] if isinstance(values, str) else values + if any(a.startswith("cloudformation:") for a in values): + self.assertEqual(statement["Resource"], {"Fn::Sub": STACK_ARN}) + actions.update(values) + self.assertIn("cloudformation:CreateChangeSet", actions) + self.assertIn("cloudformation:ExecuteChangeSet", actions) + self.assertIn("cloudformation:DeleteChangeSet", actions) + self.assertNotIn("cloudformation:DeleteStack", actions) + self.assertNotIn("cloudformation:CreateStack", actions) + self.assertNotIn("cloudformation:UpdateStack", actions) + self.assertEqual(self.by_sid["PreviewDedicatedStack"]["Condition"], {"Null": {"cloudformation:RoleArn": "true"}}) + + def test_peering_writes_bind_both_vpcs_and_connection_ownership(self): + self.assertEqual(self.by_sid["RequestFromCustomerVpc"]["Resource"], {"Fn::Sub": VPC_ARN}) + for sid in ("CreateConfiguredPeering", "DeleteOwnedConfiguredPeering"): + statement = self.by_sid[sid] + self.assertEqual(statement["Resource"], {"Fn::Sub": PEER_ARN}) + self.assertEqual(statement["Condition"]["ArnEquals"], { + "ec2:RequesterVpc": {"Fn::Sub": VPC_ARN}, + "ec2:AccepterVpc": {"Ref": "MonitoringVpcArn"}}) + self.assertEqual(self.by_sid["CreateConfiguredPeering"]["Condition"]["StringEquals"], { + "aws:RequestTag/openremote:monitoring-network": {"Ref": "NetworkStackName"}}) + self.assertEqual(self.by_sid["DeleteOwnedConfiguredPeering"]["Condition"]["StringEquals"], { + "ec2:ResourceTag/openremote:monitoring-network": {"Ref": "NetworkStackName"}}) + self.assertEqual(self.by_sid["TagPeeringOnCreation"]["Condition"]["StringEquals"], { + "ec2:CreateAction": "CreateVpcPeeringConnection", + "aws:RequestTag/openremote:monitoring-network": {"Ref": "NetworkStackName"}}) + self.assertEqual(self.by_sid["UpdateOwnedPeeringTags"]["Condition"], { + "StringEquals": {"ec2:ResourceTag/openremote:monitoring-network": {"Ref": "NetworkStackName"}}, + "ForAllValues:StringNotEquals": {"aws:TagKeys": "openremote:monitoring-network"}}) + + def test_route_writes_require_vpc_and_explicit_table_list(self): + routes = self.by_sid["ManageRoutesInApprovedTables"] + self.assertEqual(routes["Resource"], {"Fn::Sub": + "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:route-table/*"}) + self.assertEqual(routes["Condition"], { + "ArnEquals": {"ec2:Vpc": {"Fn::Sub": VPC_ARN}}, + "StringEquals": {"ec2:RouteTableID": {"Ref": "CustomerRouteTableIds"}}}) + broad = [s for s in self.statements if s["Resource"] == "*"] + self.assertEqual(len(broad), 1) + self.assertTrue(all(a.startswith("ec2:Describe") for a in broad[0]["Action"])) + self.assertEqual(broad[0]["Condition"], {"StringEquals": {"aws:RequestedRegion": {"Ref": "AWS::Region"}}}) + + def test_inputs_reject_wildcards_and_ambiguous_identifiers(self): + parameters = self.template["Parameters"] + self.assertEqual({name for name, value in parameters.items() if "Default" in value}, {"GitHubEnvironment"}) + self.assertEqual(parameters["CustomerVpcId"]["Type"], "AWS::EC2::VPC::Id") + self.assertEqual(parameters["CustomerRouteTableIds"]["Type"], "CommaDelimitedList") + table_pattern = parameters["CustomerRouteTableIds"]["AllowedPattern"] + self.assertIsNotNone(re.fullmatch(table_pattern, "rtb-0123456789abcdef0")) + for table in ("*", "rtb-*", "rtb-xyz", "", "rtb-123"): + self.assertIsNone(re.fullmatch(table_pattern, table)) + accepted = { + "RoleName": "monitoring-network-provisioning", + "GitHubRepository": "example/customer", + "GitHubEnvironment": "monitoring-network", + "NetworkStackName": "monitoring-network-primary", + "MonitoringVpcArn": "arn:aws:ec2:eu-west-1:123456789012:vpc/vpc-0123456789abcdef0", + "AcceptanceRoleArn": "arn:aws:iam::123456789012:role/monitoring-acceptance", + } + for name, value in accepted.items(): + pattern = parameters[name]["AllowedPattern"] + with self.subTest(parameter=name): + self.assertIsNotNone(re.fullmatch(pattern, value)) + self.assertIsNone(re.fullmatch(pattern, "*")) + self.assertIsNone(re.fullmatch(pattern, value + "*")) + self.assertIsNone(re.fullmatch(pattern, "")) + for value in ("path/role", "role?", "arn:aws:iam::123456789012:role/name"): + self.assertIsNone(re.fullmatch(parameters["RoleName"]["AllowedPattern"], value)) + self.assertIsNone(re.fullmatch(parameters["GitHubEnvironment"]["AllowedPattern"], "monitoring:production")) + + +if __name__ == "__main__": + unittest.main() From 8b9cfb13aad9bb78b6ac2d4e0a4c418f91416dd2 Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:51:10 +0100 Subject: [PATCH 02/13] Add customer monitoring peering and route template --- .ci_cd/aws/monitoring-network/README.md | 60 ++++++++++++++-- .../cloudformation-customer-network.yml | 70 +++++++++++++++++++ .../tests/test_customer_network.py | 68 ++++++++++++++++++ 3 files changed, 191 insertions(+), 7 deletions(-) create mode 100644 .ci_cd/aws/monitoring-network/cloudformation-customer-network.yml create mode 100644 .ci_cd/aws/monitoring-network/tests/test_customer_network.py diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md index fdd5c02ea0..f9b77948ee 100644 --- a/.ci_cd/aws/monitoring-network/README.md +++ b/.ci_cd/aws/monitoring-network/README.md @@ -5,9 +5,9 @@ Shared peering/routes are account/VPC infrastructure. Staging and production reu one connection; no per-environment enable flag belongs here. Per-host access is [#3402](https://github.com/openremote/core/issues/3402). -Current slice: the customer provisioning role and its offline validation. Peering and -route templates, central return-route permissions and the reusable workflow follow -separately. Do not run a live migration from this directory yet. +Available: the customer provisioning role and customer peering/routes template. +Central return routes, their permissions and the reusable workflow follow separately. +Do not run a live migration from this directory yet. ## Identities and ownership @@ -82,7 +82,7 @@ are non-secret but are approval boundaries: changing them can broaden permission - `sts:AssumeRole` targets only the approved central acceptance role ARN. - Peering creation is constrained to the customer requester VPC and exact monitoring accepter VPC. It must include the tag `openremote:monitoring-network` with the - networking stack name. The later connection template must supply that tag on creation. + networking stack name. The connection template supplies that tag on creation. - Peering deletion requires the same VPC pair and ownership tag. This deliberately does not authorize deleting the old, untagged, reverse-direction experimental peering. Its migration remains a separate reviewed operator action. @@ -102,17 +102,61 @@ It cannot modify IAM, secrets, host services or central routes with the policies Do not add an administrator policy or reuse a broad existing deployment role to bypass validation failures. +## Customer connection template + +`cloudformation-customer-network.yml` creates one peering requested by the customer +VPC and one IPv4 route per explicitly listed customer route table. It references +existing VPCs/tables; it creates no security groups, default routes or host resources. +Staging and production share this stack. Central return routes are a separate stack; +customer stack success alone does not establish working connectivity. + +Use the exact `NetworkStackName` approved in the customer IAM stack. The peering's +ownership tag uses that stack name. Supply these parameters, without defaults: + +| Parameter | Meaning | +| --- | --- | +| `CustomerVpcId` | Same requester VPC as the provisioning role | +| `CustomerRouteTableIds` | Nonempty list of unique, approved customer table IDs | +| `MonitoringAccountId` | Central account owning the monitoring VPC | +| `MonitoringVpcId` | Accepter VPC; account, region and ID must match the role's `MonitoringVpcArn` | +| `MonitoringVpcCidr` | Exact canonical IPv4 CIDR of that VPC, /16 through /28 | +| `AcceptanceRoleArn` | Same central acceptance role approved in the customer IAM stack | + +The template supports same-region commercial AWS connections and one monitoring IPv4 +CIDR. Parameter patterns check syntax, not live ownership, CIDR overlap or existing +routes. Before execution, the operator/future workflow must verify those facts and +that the acceptance role belongs to the monitoring account. In particular, reject an +existing connection between the VPCs or a route for the monitoring destination unless +it is already owned by this stack. Existing manual resources require the separately +reviewed migration; this template does not adopt them or delete conflicts. + +Routes use CloudFormation's built-in `Fn::ForEach` with `AWS::LanguageExtensions`. +Logical IDs derive from table IDs rather than list positions. Reordering a list +therefore keeps resource identities; removing a table deletes its managed route. +The peering reference makes routes depend on the connection. Changing either VPC +replaces the peering and can interrupt monitoring; review such changes explicitly. + +For every create/update, supply the **source template** when creating the change set. +Do not select “Use existing template” or use `--use-previous-template`: the language +transform can otherwise reuse the old resolved parameter values. Review the processed +change set for one peering plus the intended routes. No custom macro, Lambda or +local template generator is required. The networking template creates no IAM resources. + +Keep the standard developers-VPC connection and all unrelated routes untouched. A +failed operation is inspected through CloudFormation events; follow the reviewed +operator recovery procedure rather than deleting routes or retrying blindly. + ## Validation and next steps From the core repository root: ```sh uv run --no-project --with-requirements .ci_cd/aws/monitoring-network/tests/requirements.txt python -B -m unittest discover -s .ci_cd/aws/monitoring-network/tests -v -uv tool run cfn-lint .ci_cd/aws/monitoring-network/cloudformation-customer-role.yml +uv tool run cfn-lint .ci_cd/aws/monitoring-network/cloudformation-customer-*.yml ``` -Offline tests protect the intended trust and permission boundaries. Lint validates -the CloudFormation schema. They do not prove AWS authorization, SCPs, the provider's +Offline tests protect the intended trust, permission and resource boundaries. Lint +validates the CloudFormation schema. They do not prove AWS authorization, SCPs, the provider's tag-on-create behavior, rollback or role-assumption behavior. Validate those using the actual role and disposable resources when the connection template/workflow are ready. Do not broaden permissions preemptively when diagnosing a failed check. @@ -127,3 +171,5 @@ References: - [CloudFormation temporary credentials and service roles](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-servicerole.html) - [EC2 resource and condition-key support](https://docs.aws.amazon.com/service-authorization/latest/reference/list_ec2.html) - [CloudFormation action/resource scopes](https://docs.aws.amazon.com/service-authorization/latest/reference/list_cloudformation.html) +- [Native CloudFormation route iteration](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-foreach.html) +- [Language transform update considerations](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/transform-aws-languageextensions.html) diff --git a/.ci_cd/aws/monitoring-network/cloudformation-customer-network.yml b/.ci_cd/aws/monitoring-network/cloudformation-customer-network.yml new file mode 100644 index 0000000000..1976b8cefe --- /dev/null +++ b/.ci_cd/aws/monitoring-network/cloudformation-customer-network.yml @@ -0,0 +1,70 @@ +AWSTemplateFormatVersion: "2010-09-09" +Transform: AWS::LanguageExtensions +Description: Shared customer monitoring peering and explicit customer routes + +Parameters: + CustomerVpcId: + Type: AWS::EC2::VPC::Id + Description: Existing customer requester VPC in this account and region + CustomerRouteTableIds: + Type: CommaDelimitedList + AllowedPattern: "rtb-([0-9a-f]{8}|[0-9a-f]{17})" + Description: Unique existing customer route tables approved by the provisioning role + MonitoringAccountId: + Type: String + AllowedPattern: "[0-9]{12}" + Description: Account owning the monitoring VPC and acceptance role + MonitoringVpcId: + Type: String + AllowedPattern: "vpc-([0-9a-f]{8}|[0-9a-f]{17})" + Description: Existing monitoring accepter VPC in the same region + MonitoringVpcCidr: + Type: String + AllowedPattern: '((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])/(1[6-9]|2[0-8])' + Description: Exact canonical IPv4 VPC CIDR for monitoring, /16 through /28; verify against AWS before applying + AcceptanceRoleArn: + Type: String + AllowedPattern: "arn:aws:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_/-]+" + Description: Approved central acceptance role for this customer role and VPC pair + +Resources: + MonitoringPeering: + Type: AWS::EC2::VPCPeeringConnection + Properties: + VpcId: !Ref CustomerVpcId + PeerOwnerId: !Ref MonitoringAccountId + PeerVpcId: !Ref MonitoringVpcId + PeerRegion: !Ref AWS::Region + PeerRoleArn: !Ref AcceptanceRoleArn + Tags: + # Must match NetworkStackName in the customer provisioning role. + - Key: openremote:monitoring-network + Value: !Ref AWS::StackName + - Key: Name + Value: !Ref AWS::StackName + + # Table-derived logical IDs keep routes stable when the list is reordered. + # &{} allows the hyphen in EC2 route-table IDs. + "Fn::ForEach::CustomerRoutes": + - RouteTableId + - !Ref CustomerRouteTableIds + - "MonitoringRoute&{RouteTableId}": + Type: AWS::EC2::Route + Properties: + RouteTableId: "${RouteTableId}" + DestinationCidrBlock: !Ref MonitoringVpcCidr + VpcPeeringConnectionId: !Ref MonitoringPeering + +Outputs: + PeeringConnectionId: + Description: Connection ID for the separate central return-routes stack + Value: !Ref MonitoringPeering + CustomerVpcId: + Value: !Ref CustomerVpcId + CustomerRouteTableIds: + Value: + Fn::Join: [",", !Ref CustomerRouteTableIds] + MonitoringVpcId: + Value: !Ref MonitoringVpcId + MonitoringVpcCidr: + Value: !Ref MonitoringVpcCidr diff --git a/.ci_cd/aws/monitoring-network/tests/test_customer_network.py b/.ci_cd/aws/monitoring-network/tests/test_customer_network.py new file mode 100644 index 0000000000..ec066ebb38 --- /dev/null +++ b/.ci_cd/aws/monitoring-network/tests/test_customer_network.py @@ -0,0 +1,68 @@ +"""Offline resource boundaries; live peering acceptance is validated separately.""" +import re +import unittest +from pathlib import Path + +import yaml + +from test_customer_role import TemplateLoader + + +class CustomerNetworkTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + path = Path(__file__).resolve().parents[1] / "cloudformation-customer-network.yml" + cls.template = yaml.load(path.read_text(), Loader=TemplateLoader) + + def test_only_customer_peering_and_explicit_destination_routes(self): + resources = self.template["Resources"] + self.assertEqual(set(resources), {"MonitoringPeering", "Fn::ForEach::CustomerRoutes"}) + self.assertEqual(resources["MonitoringPeering"]["Type"], "AWS::EC2::VPCPeeringConnection") + self.assertEqual(resources["MonitoringPeering"]["Properties"], { + "VpcId": {"Ref": "CustomerVpcId"}, + "PeerOwnerId": {"Ref": "MonitoringAccountId"}, + "PeerVpcId": {"Ref": "MonitoringVpcId"}, + "PeerRegion": {"Ref": "AWS::Region"}, + "PeerRoleArn": {"Ref": "AcceptanceRoleArn"}, + "Tags": [ + {"Key": "openremote:monitoring-network", "Value": {"Ref": "AWS::StackName"}}, + {"Key": "Name", "Value": {"Ref": "AWS::StackName"}}, + ], + }) + self.assertEqual(self.template["Transform"], "AWS::LanguageExtensions") + identifier, collection, fragment = resources["Fn::ForEach::CustomerRoutes"] + self.assertEqual(identifier, "RouteTableId") + self.assertEqual(collection, {"Ref": "CustomerRouteTableIds"}) + self.assertEqual(fragment, {"MonitoringRoute&{RouteTableId}": { + "Type": "AWS::EC2::Route", + "Properties": { + "RouteTableId": "${RouteTableId}", + "DestinationCidrBlock": {"Ref": "MonitoringVpcCidr"}, + "VpcPeeringConnectionId": {"Ref": "MonitoringPeering"}, + }, + }}) + self.assertEqual(self.template["Outputs"]["PeeringConnectionId"]["Value"], {"Ref": "MonitoringPeering"}) + + def test_required_inputs_match_role_boundaries(self): + parameters = self.template["Parameters"] + self.assertFalse(any("Default" in p for p in parameters.values())) + self.assertEqual(parameters["CustomerVpcId"]["Type"], "AWS::EC2::VPC::Id") + self.assertEqual(parameters["CustomerRouteTableIds"]["Type"], "CommaDelimitedList") + role_path = Path(__file__).resolve().parents[1] / "cloudformation-customer-role.yml" + role_parameters = yaml.load(role_path.read_text(), Loader=TemplateLoader)["Parameters"] + for key in ("CustomerRouteTableIds", "AcceptanceRoleArn"): + self.assertEqual(parameters[key]["AllowedPattern"], role_parameters[key]["AllowedPattern"]) + patterns = {name: p["AllowedPattern"] for name, p in parameters.items() if "AllowedPattern" in p} + for name, pattern in patterns.items(): + with self.subTest(parameter=name): + self.assertIsNone(re.fullmatch(pattern, "")) + self.assertIsNone(re.fullmatch(pattern, "*")) + cidr = patterns["MonitoringVpcCidr"] + for value in ("10.20.0.0/16", "172.20.0.0/20", "192.168.0.0/28"): + self.assertIsNotNone(re.fullmatch(cidr, value)) + for value in ("0.0.0.0/0", "10.20.0.0/8", "10.20.0.0/33", "999.1.1.1/16", "::/0"): + self.assertIsNone(re.fullmatch(cidr, value)) + + +if __name__ == "__main__": + unittest.main() From 1d74048db93ee695c5b1d4212d1e290f8b8cd737 Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:01:56 +0100 Subject: [PATCH 03/13] Document monitoring network configuration and operator interface --- .ci_cd/aws/monitoring-network/README.md | 77 +++++++++++++++++-- .../monitoring-network.example.json | 22 ++++++ 2 files changed, 91 insertions(+), 8 deletions(-) create mode 100644 .ci_cd/aws/monitoring-network/monitoring-network.example.json diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md index f9b77948ee..1a8388ad5f 100644 --- a/.ci_cd/aws/monitoring-network/README.md +++ b/.ci_cd/aws/monitoring-network/README.md @@ -9,6 +9,67 @@ Available: the customer provisioning role and customer peering/routes template. Central return routes, their permissions and the reusable workflow follow separately. Do not run a live migration from this directory yet. +## Operator interface and customer configuration + +The following is the interface to implement; the networking workflow is not available +yet. CloudFormation parameters are an internal interface, not a form operators fill +out on every run. + +The customer workflow form should contain only: + +| Control | Operator choice | +| -------------------------------------------- | ------------------------------ | +| GitHub's existing workflow revision selector | The reviewed customer revision | +| Action | `preview` (default) or `apply` | + +The thin caller fixes the configuration path to `.ci_cd/aws/monitoring-network.json`, +the GitHub environment to `monitoring-network`, and the reusable core workflow to a +reviewed commit. Those are maintained in Git, not entered per run. There is no +staging/production choice, free-form AWS resource input or teardown action. + +Copy [monitoring-network.example.json](monitoring-network.example.json) into the +customer repository at that configuration path during onboarding. All IDs/ARNs in +the example are illustrative. Maintain one file for the shared customer connection; +it changes when the intended topology or approved roles change, not when a VM is +replaced. The example describes the proposed workflow configuration, not a file +accepted by CloudFormation directly. + +| Configuration | Set once / maintained by | Workflow responsibility | +| ------------------------------ | ------------------------------------------ | ---------------------------------------------------------------------------------------------- | +| Region and VPC IDs | Account/network owner | Verify both VPCs exist in the intended accounts and region | +| Explicit route-table lists | Account/network owner | Verify membership, uniqueness and existing route ownership; never silently include every table | +| Stack names | Provisioning setup | Match IAM scopes; reject unrelated stacks or stored service roles | +| Customer provisioning-role ARN | Customer IAM stack output | Authenticate and verify the expected account/role | +| Central provisioning-role ARN | Central IAM setup, still to be implemented | Obtain separate central inspection/route permissions; do not reuse the acceptance role | +| Acceptance-role ARN | Central acceptance stack output | Pass to the customer peering template; verify its account matches the monitoring account | + +Do not duplicate account IDs, CIDRs or the peering ID in this file. Account IDs can +be derived from the role ARNs and checked against authenticated identities. Read the +actual IPv4 VPC CIDRs from AWS, check for overlap and include them in the preview. +Pass the new peering ID from the customer stack output to the central route stack. +The first version supports one IPv4 CIDR per VPC; ambiguous/multiple CIDRs require +an explicit design decision rather than selecting the first returned value. + +The central provisioning-role field identifies the separate identity needed by the +workflow; its trust and permission design is still pending. This example neither +grants that access nor settles how the workflow acquires it. The account-level +GitHub environment and IAM prerequisites are one-time setup, like the configuration. + +`preview` validates the configuration and live state, then reports the VPC pair, +destinations, exact route tables and CloudFormation changes without executing them. +For a new connection, the central change set needs the new peering ID: preview must +show the intended return routes and clearly mark that change set as pending. + +`apply` revalidates the selected committed configuration against current AWS state +and creates/executes change sets in customer-then-central order. It does not replay a +previous preview run: operators should select the same reviewed customer revision, +whose caller also pins core. Each run reports both revisions. Separate account steps +are not atomic; a failure reports the completed stage and failed stack/events for +operator review. No automatic cross-account undo is added. + +Initial IAM setup and the one-time migration remain separate reviewed operations. +Routine runs should require only an action choice and review of the resulting report. + ## Identities and ownership Use one dedicated GitHub OIDC role per customer connection. Its exact repository and @@ -113,14 +174,14 @@ customer stack success alone does not establish working connectivity. Use the exact `NetworkStackName` approved in the customer IAM stack. The peering's ownership tag uses that stack name. Supply these parameters, without defaults: -| Parameter | Meaning | -| --- | --- | -| `CustomerVpcId` | Same requester VPC as the provisioning role | -| `CustomerRouteTableIds` | Nonempty list of unique, approved customer table IDs | -| `MonitoringAccountId` | Central account owning the monitoring VPC | -| `MonitoringVpcId` | Accepter VPC; account, region and ID must match the role's `MonitoringVpcArn` | -| `MonitoringVpcCidr` | Exact canonical IPv4 CIDR of that VPC, /16 through /28 | -| `AcceptanceRoleArn` | Same central acceptance role approved in the customer IAM stack | +| Parameter | Meaning | +| ----------------------- | ----------------------------------------------------------------------------- | +| `CustomerVpcId` | Same requester VPC as the provisioning role | +| `CustomerRouteTableIds` | Nonempty list of unique, approved customer table IDs | +| `MonitoringAccountId` | Central account owning the monitoring VPC | +| `MonitoringVpcId` | Accepter VPC; account, region and ID must match the role's `MonitoringVpcArn` | +| `MonitoringVpcCidr` | Exact canonical IPv4 CIDR of that VPC, /16 through /28 | +| `AcceptanceRoleArn` | Same central acceptance role approved in the customer IAM stack | The template supports same-region commercial AWS connections and one monitoring IPv4 CIDR. Parameter patterns check syntax, not live ownership, CIDR overlap or existing diff --git a/.ci_cd/aws/monitoring-network/monitoring-network.example.json b/.ci_cd/aws/monitoring-network/monitoring-network.example.json new file mode 100644 index 0000000000..8389319796 --- /dev/null +++ b/.ci_cd/aws/monitoring-network/monitoring-network.example.json @@ -0,0 +1,22 @@ +{ + "region": "eu-west-1", + "customer": { + "stack_name": "monitoring-network-primary", + "provisioning_role_arn": "arn:aws:iam::111111111111:role/monitoring-network-provisioning", + "vpc_id": "vpc-11111111111111111", + "route_table_ids": [ + "rtb-11111111111111111", + "rtb-22222222222222222" + ] + }, + "monitoring": { + "stack_name": "monitoring-network-customer-primary", + "provisioning_role_arn": "arn:aws:iam::222222222222:role/monitoring-network-customer-primary", + "acceptance_role_arn": "arn:aws:iam::222222222222:role/monitoring-acceptance-customer-primary", + "vpc_id": "vpc-22222222222222222", + "route_table_ids": [ + "rtb-33333333333333333", + "rtb-44444444444444444" + ] + } +} From 525c0c40bcb6bfcfe9dd653e2418b62631aceed7 Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:03:26 +0100 Subject: [PATCH 04/13] Add central monitoring return-route template --- .ci_cd/aws/monitoring-network/README.md | 42 +++++++++++++-- .../cloudformation-central-routes.yml | 39 ++++++++++++++ .../tests/test_central_routes.py | 51 +++++++++++++++++++ 3 files changed, 129 insertions(+), 3 deletions(-) create mode 100644 .ci_cd/aws/monitoring-network/cloudformation-central-routes.yml create mode 100644 .ci_cd/aws/monitoring-network/tests/test_central_routes.py diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md index 1a8388ad5f..e27b56b40e 100644 --- a/.ci_cd/aws/monitoring-network/README.md +++ b/.ci_cd/aws/monitoring-network/README.md @@ -5,8 +5,8 @@ Shared peering/routes are account/VPC infrastructure. Staging and production reu one connection; no per-environment enable flag belongs here. Per-host access is [#3402](https://github.com/openremote/core/issues/3402). -Available: the customer provisioning role and customer peering/routes template. -Central return routes, their permissions and the reusable workflow follow separately. +Available: the customer provisioning role, customer peering/routes template and central +return-routes template. Central route permissions and the reusable workflow follow separately. Do not run a live migration from this directory yet. ## Operator interface and customer configuration @@ -207,13 +207,49 @@ Keep the standard developers-VPC connection and all unrelated routes untouched. failed operation is inspected through CloudFormation events; follow the reviewed operator recovery procedure rather than deleting routes or retrying blindly. +## Central return-routes template + +`cloudformation-central-routes.yml` runs in the monitoring account, with a separate +stack for each customer connection. It creates only route entries in the explicitly +approved monitoring tables. It neither owns nor deletes the customer peering, route +tables, VPCs or security groups. + +The workflow will supply its three parameters automatically: + +| Parameter | Source | +| ------------------------- | ------------------------------------------------------------- | +| `MonitoringRouteTableIds` | `monitoring.route_table_ids` in customer configuration | +| `CustomerVpcCidr` | Verified customer VPC CIDR read from AWS | +| `PeeringConnectionId` | `PeeringConnectionId` output of the customer networking stack | + +Before execution, verify the authenticated monitoring account, table membership, +canonical customer CIDR and an **active** peering with the expected customer requester +and monitoring accepter VPCs. Refuse unmanaged/conflicting routes for that destination; +manual migration remains separate. The template's parameter patterns cannot check +these live facts. Since the peering is in another account/stack, its ID is an input, +not a CloudFormation dependency or cross-account export. + +Use `monitoring.stack_name` for this stack. Submit the source template on every update, +as for the customer template. Reordering tables preserves route identities; removing +a table removes that managed route. Changing the destination replaces route resources; +changing the peering target redirects them and requires an explicit connectivity review. +CloudFormation failure/rollback affects this stack, not the already completed customer +stack. Inspect both accounts before retrying. For eventual teardown, remove central +return routes before deleting the customer connection using an authorized operator session. + +The central provisioning role is **not implemented yet**. EC2 route authorization is +at table level here too: approved tables can also hold routes for other customers. +The IAM/trust design must make that shared-table access explicit; a customer-specific +stack name alone does not restrict direct EC2 writes to one customer's CIDR. Keep this +permission review separate from the acceptance role and from the route-only template. + ## Validation and next steps From the core repository root: ```sh uv run --no-project --with-requirements .ci_cd/aws/monitoring-network/tests/requirements.txt python -B -m unittest discover -s .ci_cd/aws/monitoring-network/tests -v -uv tool run cfn-lint .ci_cd/aws/monitoring-network/cloudformation-customer-*.yml +uv tool run cfn-lint .ci_cd/aws/monitoring-network/cloudformation-*.yml ``` Offline tests protect the intended trust, permission and resource boundaries. Lint diff --git a/.ci_cd/aws/monitoring-network/cloudformation-central-routes.yml b/.ci_cd/aws/monitoring-network/cloudformation-central-routes.yml new file mode 100644 index 0000000000..94822a3568 --- /dev/null +++ b/.ci_cd/aws/monitoring-network/cloudformation-central-routes.yml @@ -0,0 +1,39 @@ +AWSTemplateFormatVersion: "2010-09-09" +Transform: AWS::LanguageExtensions +Description: Explicit central return routes for one customer monitoring connection + +Parameters: + MonitoringRouteTableIds: + Type: CommaDelimitedList + AllowedPattern: "rtb-([0-9a-f]{8}|[0-9a-f]{17})" + Description: Unique existing route tables in the monitoring VPC approved for this connection + CustomerVpcCidr: + Type: String + AllowedPattern: '((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])/(1[6-9]|2[0-8])' + Description: Exact canonical customer IPv4 VPC CIDR, /16 through /28; verify against AWS before applying + PeeringConnectionId: + Type: String + AllowedPattern: "pcx-([0-9a-f]{8}|[0-9a-f]{17})" + Description: Active connection ID from the approved customer networking stack output + +Resources: + # The peering belongs to the customer stack and must already be active. + # Table-derived logical IDs keep routes stable when the list is reordered. + "Fn::ForEach::MonitoringRoutes": + - RouteTableId + - !Ref MonitoringRouteTableIds + - "CustomerRoute&{RouteTableId}": + Type: AWS::EC2::Route + Properties: + RouteTableId: "${RouteTableId}" + DestinationCidrBlock: !Ref CustomerVpcCidr + VpcPeeringConnectionId: !Ref PeeringConnectionId + +Outputs: + PeeringConnectionId: + Value: !Ref PeeringConnectionId + CustomerVpcCidr: + Value: !Ref CustomerVpcCidr + MonitoringRouteTableIds: + Value: + Fn::Join: [",", !Ref MonitoringRouteTableIds] diff --git a/.ci_cd/aws/monitoring-network/tests/test_central_routes.py b/.ci_cd/aws/monitoring-network/tests/test_central_routes.py new file mode 100644 index 0000000000..6e5dd71fc2 --- /dev/null +++ b/.ci_cd/aws/monitoring-network/tests/test_central_routes.py @@ -0,0 +1,51 @@ +"""Keep the central stack limited to explicit return-route entries.""" +import re +import unittest +from pathlib import Path + +import yaml + +from test_customer_role import TemplateLoader + + +class CentralRoutesTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + root = Path(__file__).resolve().parents[1] + cls.template = yaml.load((root / "cloudformation-central-routes.yml").read_text(), Loader=TemplateLoader) + cls.customer = yaml.load((root / "cloudformation-customer-network.yml").read_text(), Loader=TemplateLoader) + + def test_only_return_routes_with_external_peering(self): + self.assertEqual(self.template["Transform"], "AWS::LanguageExtensions") + self.assertEqual(self.template["Resources"], { + "Fn::ForEach::MonitoringRoutes": [ + "RouteTableId", + {"Ref": "MonitoringRouteTableIds"}, + {"CustomerRoute&{RouteTableId}": { + "Type": "AWS::EC2::Route", + "Properties": { + "RouteTableId": "${RouteTableId}", + "DestinationCidrBlock": {"Ref": "CustomerVpcCidr"}, + "VpcPeeringConnectionId": {"Ref": "PeeringConnectionId"}, + }, + }}, + ], + }) + self.assertEqual(self.template["Outputs"]["PeeringConnectionId"]["Value"], {"Ref": "PeeringConnectionId"}) + + def test_required_inputs_share_customer_validation(self): + parameters = self.template["Parameters"] + self.assertEqual(set(parameters), {"MonitoringRouteTableIds", "CustomerVpcCidr", "PeeringConnectionId"}) + self.assertFalse(any("Default" in p for p in parameters.values())) + self.assertEqual(parameters["MonitoringRouteTableIds"]["Type"], "CommaDelimitedList") + for central, customer in (("MonitoringRouteTableIds", "CustomerRouteTableIds"), ("CustomerVpcCidr", "MonitoringVpcCidr")): + self.assertEqual(parameters[central]["AllowedPattern"], self.customer["Parameters"][customer]["AllowedPattern"]) + pattern = parameters["PeeringConnectionId"]["AllowedPattern"] + for value in ("pcx-12345678", "pcx-0123456789abcdef0"): + self.assertIsNotNone(re.fullmatch(pattern, value)) + for value in ("", "*", "pcx-*", "pcx-xyz", "vpc-0123456789abcdef0"): + self.assertIsNone(re.fullmatch(pattern, value)) + + +if __name__ == "__main__": + unittest.main() From 1c89ff96dcbcb7a328db2bb24d06413a6f7c082d Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:15:45 +0100 Subject: [PATCH 05/13] Align monitoring networking with central account provisioning --- .ci_cd/aws/monitoring-network/README.md | 186 +++++++++++++----------- 1 file changed, 100 insertions(+), 86 deletions(-) diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md index e27b56b40e..03720d8848 100644 --- a/.ci_cd/aws/monitoring-network/README.md +++ b/.ci_cd/aws/monitoring-network/README.md @@ -1,6 +1,6 @@ # Shared customer monitoring network -This implements the customer side of [#3365](https://github.com/openremote/core/issues/3365). +This implements shared customer-to-monitoring networking for [#3365](https://github.com/openremote/core/issues/3365). Shared peering/routes are account/VPC infrastructure. Staging and production reuse one connection; no per-environment enable flag belongs here. Per-host access is [#3402](https://github.com/openremote/core/issues/3402). @@ -9,99 +9,112 @@ Available: the customer provisioning role, customer peering/routes template and return-routes template. Central route permissions and the reusable workflow follow separately. Do not run a live migration from this directory yet. -## Operator interface and customer configuration - -The following is the interface to implement; the networking workflow is not available -yet. CloudFormation parameters are an internal interface, not a form operators fill -out on every run. - -The customer workflow form should contain only: - -| Control | Operator choice | -| -------------------------------------------- | ------------------------------ | -| GitHub's existing workflow revision selector | The reviewed customer revision | -| Action | `preview` (default) or `apply` | - -The thin caller fixes the configuration path to `.ci_cd/aws/monitoring-network.json`, -the GitHub environment to `monitoring-network`, and the reusable core workflow to a -reviewed commit. Those are maintained in Git, not entered per run. There is no -staging/production choice, free-form AWS resource input or teardown action. - -Copy [monitoring-network.example.json](monitoring-network.example.json) into the -customer repository at that configuration path during onboarding. All IDs/ARNs in -the example are illustrative. Maintain one file for the shared customer connection; -it changes when the intended topology or approved roles change, not when a VM is -replaced. The example describes the proposed workflow configuration, not a file -accepted by CloudFormation directly. - -| Configuration | Set once / maintained by | Workflow responsibility | -| ------------------------------ | ------------------------------------------ | ---------------------------------------------------------------------------------------------- | -| Region and VPC IDs | Account/network owner | Verify both VPCs exist in the intended accounts and region | -| Explicit route-table lists | Account/network owner | Verify membership, uniqueness and existing route ownership; never silently include every table | -| Stack names | Provisioning setup | Match IAM scopes; reject unrelated stacks or stored service roles | -| Customer provisioning-role ARN | Customer IAM stack output | Authenticate and verify the expected account/role | -| Central provisioning-role ARN | Central IAM setup, still to be implemented | Obtain separate central inspection/route permissions; do not reuse the acceptance role | -| Acceptance-role ARN | Central acceptance stack output | Pass to the customer peering template; verify its account matches the monitoring account | - -Do not duplicate account IDs, CIDRs or the peering ID in this file. Account IDs can -be derived from the role ARNs and checked against authenticated identities. Read the -actual IPv4 VPC CIDRs from AWS, check for overlap and include them in the preview. -Pass the new peering ID from the customer stack output to the central route stack. -The first version supports one IPv4 CIDR per VPC; ambiguous/multiple CIDRs require -an explicit design decision rather than selecting the first returned value. - -The central provisioning-role field identifies the separate identity needed by the -workflow; its trust and permission design is still pending. This example neither -grants that access nor settles how the workflow acquires it. The account-level -GitHub environment and IAM prerequisites are one-time setup, like the configuration. - -`preview` validates the configuration and live state, then reports the VPC pair, -destinations, exact route tables and CloudFormation changes without executing them. -For a new connection, the central change set needs the new peering ID: preview must -show the intended return routes and clearly mark that change set as pending. - -`apply` revalidates the selected committed configuration against current AWS state -and creates/executes change sets in customer-then-central order. It does not replay a -previous preview run: operators should select the same reviewed customer revision, -whose caller also pins core. Each run reports both revisions. Separate account steps -are not atomic; a failure reports the completed stage and failed stack/events for -operator review. No automatic cross-account undo is added. - -Initial IAM setup and the one-time migration remain separate reviewed operations. -Routine runs should require only an action choice and review of the resulting report. +## Provisioning ownership + +The operation is centrally initiated in **core**, following the existing +[Provision Account workflow](../../../.github/workflows/provision-account.yml) +and [account provisioning script](../provision_account.sh). Infrastructure owns +central IAM prerequisites; core owns the reusable networking templates and operation +for both AWS accounts. A template's target account does not determine its repository. + +Today, account provisioning creates the standard customer VPC and its developers-VPC +peering through CloudFormation. It then adds the developers-side return route directly +with the AWS CLI. That block runs only when creating a new VPC, and its peering lookup +selects the first match for the requester. Monitoring integration must handle existing +VPCs too and identify the exact connection, preserving the standard developers peering. +Both sides of the new monitoring connection will be managed by CloudFormation. + +The target is one operation called from account provisioning, plus a standalone core +workflow for existing accounts and retries. Customer application/Alloy workflows do +not provision this shared connection or receive central route-writing permissions. +The earlier customer-repository caller design is superseded. The workflow and account +integration are not implemented yet; the existing account workflow is unchanged. + +## Operator interface and connection configuration + +The standalone core workflow will expose: + +| Control | Operator choice | +| --- | --- | +| GitHub's workflow revision selector | Reviewed core revision | +| Account/connection | Approved customer connection, normally identified by account name | +| Action | `preview` (default) or `apply` | + +There is no staging/production selector, free-form AWS resource form or teardown action. +Normal account provisioning already knows the customer account and should pass it to +the same operation. No separate customer workflow or repository access token is needed. + +[monitoring-network.example.json](monitoring-network.example.json) describes the +**resolved operation input**, with illustrative IDs/ARNs. It is not a CloudFormation +parameter file and is not installed in each customer repository. Maintain the approved +connection settings centrally; choose their storage/lookup mechanism when implementing +the entry point, using existing account provisioning conventions where practical. +Do not add a new private-repository checkout dependency merely to read this input. + +| Input | Source / responsibility | +| --- | --- | +| Region and VPC IDs | Existing account/VPC records or new VPC provisioning results | +| Explicit route-table lists | Approved topology; validate membership and uniqueness | +| Stack names | Provisioning conventions, matching the dedicated IAM scopes | +| Customer provisioning-role ARN | Customer IAM prerequisite output | +| Central provisioning-role ARN | Central IAM prerequisite output; design pending | +| Acceptance-role ARN | Central acceptance stack output | + +For a new account, resolve the connection after its VPC and IAM prerequisites exist. +For an existing account, use approved existing resources. Both paths pass the same +input structure to the networking operation. Resolving new resource IDs must not +silently add every table in a VPC or broaden existing IAM scopes. + +Derive account IDs from the role ARNs and verify authenticated identities. Read IPv4 +CIDRs from AWS rather than duplicating them in configuration; check overlap and show +them in preview. Initially support one IPv4 CIDR per VPC. Pass the resulting peering +ID from the customer stack output to the central stack automatically. + +`preview` validates live state and reports both accounts, the VPC pair, tables, +destinations and available change sets without executing them. For a new connection, +the central change set needs the new peering ID; show its intended routes and mark +that change set as pending until the ID exists. + +`apply` revalidates and creates/executes change sets in customer-then-central order. +It does not replay a previous preview: use the same reviewed core revision and approved +connection settings. Record the revision and resolved non-secret input in the run's +artifacts. Separate account steps are not atomic; report successful stages and failed +stack/events for operator review, without automatic cross-account undo. ## Identities and ownership -Use one dedicated GitHub OIDC role per customer connection. Its exact repository and -GitHub environment are trusted; `monitoring-network` is the proposed environment name. -The existing account OIDC provider is a prerequisite, normally deployed through CfCT. -Protect the environment and its deployment branches in GitHub: environment-based OIDC -trust does not itself restrict a job to main or to one workflow file. There are no PATs -or AWS keys in this design. - -The role operates one named CloudFormation networking stack using the role's temporary -credentials. No CloudFormation service role is used or passed. This same customer role -is the `RequesterRoleName` in the central acceptance template. A separate central role -accepts the peering; it does not administer routes. Central return routes need separate -permissions and their own stack, which this template does not grant. - -The central acceptance template lives in the infrastructure repository. This core template neither -copies it nor provisions IAM in the central account. Application and Alloy deployment -roles are unchanged. +Use dedicated network-provisioning identities controlled by the central core workflow. +The target authentication is GitHub OIDC with an exact `openremote/core` repository +and protected `monitoring-network` environment. Environment/branch protection is +configured separately. Do not add AWS keys or grant customer-repository jobs access +to the central route role. The existing account workflow currently uses AWS credential +secrets; adopting OIDC for its broader account-creation duties is a separate decision. + +The customer role operates one customer networking stack with temporary caller +credentials, without a CloudFormation service role. It is the `RequesterRoleName` +trusted by the central acceptance role. The acceptance role only accepts the approved +VPC pair; a separate central provisioning identity operates the return-route stack. +Its authentication and scoped permissions remain to be implemented and validated. + +`cloudformation-customer-role.yml` supports exact repository/environment trust. For +this centrally run design, set `GitHubRepository` to `openremote/core`, even though +the role is deployed in the customer account. The account-local OIDC provider is a +prerequisite. The central acceptance template and future central provisioning IAM +live in infrastructure. Application and Alloy identities remain unchanged. ## Bootstrap order A privileged operator provisions IAM prerequisites; the networking workflow cannot create or update its own role. -1. Agree the customer role name, customer stack name and protected GitHub environment. +1. Agree the connection, customer role/stack names and protected core GitHub environment. 2. In the central account, provision the acceptance stack for this customer account, exact role name and VPC pair. Its account-plus-PrincipalArn trust permits this ordering before the customer role exists. Retain the acceptance-role ARN output. 3. In the customer account, review and deploy `cloudformation-customer-role.yml` with that ARN and the approved parameters. This requires `CAPABILITY_NAMED_IAM`. -4. Later, use the returned role ARN from the customer workflow. Verify OIDC identity, - role assumption and the actual CloudFormation path on a disposable connection +4. Later, use the returned role ARN from the centrally run core workflow. Verify OIDC + identity, role assumption and the actual CloudFormation path on a disposable connection before migrating the existing shared peering. The networking stack name must differ from the IAM prerequisite stack name, the @@ -115,7 +128,7 @@ service role; the future workflow must reject that situation before writes. | Parameter | Meaning | | ----------------------- | -------------------------------------------------------------------------- | | `RoleName` | Exact pathless customer role name; must match the central acceptance trust | -| `GitHubRepository` | Exact customer `owner/repository`, not the reusable core repository | +| `GitHubRepository` | `openremote/core` for the centrally initiated workflow | | `GitHubEnvironment` | Protected account-level environment; default `monitoring-network` | | `NetworkStackName` | Exact dedicated customer peering/routes stack name | | `CustomerVpcId` | Existing customer VPC in this account/region | @@ -218,7 +231,7 @@ The workflow will supply its three parameters automatically: | Parameter | Source | | ------------------------- | ------------------------------------------------------------- | -| `MonitoringRouteTableIds` | `monitoring.route_table_ids` in customer configuration | +| `MonitoringRouteTableIds` | `monitoring.route_table_ids` in resolved connection input | | `CustomerVpcCidr` | Verified customer VPC CIDR read from AWS | | `PeeringConnectionId` | `PeeringConnectionId` output of the customer networking stack | @@ -239,7 +252,7 @@ return routes before deleting the customer connection using an authorized operat The central provisioning role is **not implemented yet**. EC2 route authorization is at table level here too: approved tables can also hold routes for other customers. -The IAM/trust design must make that shared-table access explicit; a customer-specific +Restrict this access to the centrally controlled provisioning workflow. A customer-specific stack name alone does not restrict direct EC2 writes to one customer's CIDR. Keep this permission review separate from the acceptance role and from the route-only template. @@ -258,9 +271,10 @@ tag-on-create behavior, rollback or role-assumption behavior. Validate those usi actual role and disposable resources when the connection template/workflow are ready. Do not broaden permissions preemptively when diagnosing a failed check. -This change has no downstream application/API effect and requires no changes to -Extensions or existing application workflows. A generic custom-project caller/example -and maintained operator documentation accompany the later reusable networking workflow. +These templates have no downstream application/API effect and require no changes to +Extensions or customer application/Alloy callers. The account-provisioning integration +and standalone core workflow will share this operation. This README is their maintained +operator reference; no customer-project caller is required for shared networking. References: From be4f1a4250356a3ed1e6aec19b5191b0c01d762e Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:30:19 +0100 Subject: [PATCH 06/13] Document central route provisioning identity --- .ci_cd/aws/monitoring-network/README.md | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md index 03720d8848..0d2c298008 100644 --- a/.ci_cd/aws/monitoring-network/README.md +++ b/.ci_cd/aws/monitoring-network/README.md @@ -6,7 +6,8 @@ one connection; no per-environment enable flag belongs here. Per-host access is [#3402](https://github.com/openremote/core/issues/3402). Available: the customer provisioning role, customer peering/routes template and central -return-routes template. Central route permissions and the reusable workflow follow separately. +return-routes template. Central IAM templates are prepared in infrastructure; workflow +execution and live validation remain pending. Do not run a live migration from this directory yet. ## Provisioning ownership @@ -57,7 +58,7 @@ Do not add a new private-repository checkout dependency merely to read this inpu | Explicit route-table lists | Approved topology; validate membership and uniqueness | | Stack names | Provisioning conventions, matching the dedicated IAM scopes | | Customer provisioning-role ARN | Customer IAM prerequisite output | -| Central provisioning-role ARN | Central IAM prerequisite output; design pending | +| Central provisioning-role ARN | Central infrastructure IAM stack output | | Acceptance-role ARN | Central acceptance stack output | For a new account, resolve the connection after its VPC and IAM prerequisites exist. @@ -94,12 +95,15 @@ The customer role operates one customer networking stack with temporary caller credentials, without a CloudFormation service role. It is the `RequesterRoleName` trusted by the central acceptance role. The acceptance role only accepts the approved VPC pair; a separate central provisioning identity operates the return-route stack. -Its authentication and scoped permissions remain to be implemented and validated. +Infrastructure's `grafana/networking/cloudformation-central-route-role.yml` defines +that identity with exact core/environment OIDC trust; deployment and live validation +remain pending. The workflow obtains each account's credentials separately through +OIDC; the central role does not assume the customer role. `cloudformation-customer-role.yml` supports exact repository/environment trust. For this centrally run design, set `GitHubRepository` to `openremote/core`, even though the role is deployed in the customer account. The account-local OIDC provider is a -prerequisite. The central acceptance template and future central provisioning IAM +prerequisite. The central acceptance and route-provisioning IAM templates live in infrastructure. Application and Alloy identities remain unchanged. ## Bootstrap order @@ -250,8 +254,9 @@ CloudFormation failure/rollback affects this stack, not the already completed cu stack. Inspect both accounts before retrying. For eventual teardown, remove central return routes before deleting the customer connection using an authorized operator session. -The central provisioning role is **not implemented yet**. EC2 route authorization is -at table level here too: approved tables can also hold routes for other customers. +The central provisioning-role template is prepared in infrastructure. EC2 route +authorization is at table level here too: approved tables can also hold routes for +other customers. Restrict this access to the centrally controlled provisioning workflow. A customer-specific stack name alone does not restrict direct EC2 writes to one customer's CIDR. Keep this permission review separate from the acceptance role and from the route-only template. From 7553bc1c2ad9cb428de88a6b1f749bd3ed4208e4 Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:34:04 +0100 Subject: [PATCH 07/13] Document central monitoring connection settings in Parameter Store --- .ci_cd/aws/monitoring-network/README.md | 78 +++++++++++++++++++++++-- 1 file changed, 72 insertions(+), 6 deletions(-) diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md index 0d2c298008..66ecf9d4e3 100644 --- a/.ci_cd/aws/monitoring-network/README.md +++ b/.ci_cd/aws/monitoring-network/README.md @@ -48,9 +48,12 @@ the same operation. No separate customer workflow or repository access token is [monitoring-network.example.json](monitoring-network.example.json) describes the **resolved operation input**, with illustrative IDs/ARNs. It is not a CloudFormation parameter file and is not installed in each customer repository. Maintain the approved -connection settings centrally; choose their storage/lookup mechanism when implementing -the entry point, using existing account provisioning conventions where practical. -Do not add a new private-repository checkout dependency merely to read this input. +connection settings in central Parameter Store at +`/Monitoring/Connections/`, as a Standard `String` with data type `text` +containing that JSON. The initial lookup region is `eu-west-1`; the JSON region must +match. This follows the central `/Account-Ids/` convention used by +[get_account_id.sh](../get_account_id.sh), without its write/fallback behavior. +There is no private-repository checkout dependency or deployment journal. | Input | Source / responsibility | | --- | --- | @@ -82,6 +85,65 @@ connection settings. Record the revision and resolved non-secret input in the ru artifacts. Separate account steps are not atomic; report successful stages and failed stack/events for operator review, without automatic cross-account undo. +## Publishing connection settings + +An authorized operator creates or edits the parameter in the **central developers +account**, after reviewing the VPC/table inventory and IAM stack outputs. The future +account-provisioning integration will assemble the same JSON after creating those +prerequisites. Routine Preview/Apply runs only read it; missing configuration is an +error, not a request to discover resources and create a parameter automatically. + +In the AWS console, select `eu-west-1`, open Systems Manager → Parameter Store, and +create `/Monitoring/Connections/` with tier **Standard**, type **String**, +data type **text**, and the reviewed JSON as its value. Use **Edit** for later changes. +This setting contains identifiers, not passwords; Alloy credentials remain separate. + +Alternatively, from the core repository root, copy the example to a local file: + +```sh +cp .ci_cd/aws/monitoring-network/monitoring-network.example.json /tmp/connection.json +``` + +Replace **every illustrative ID/ARN and stack name** with the reviewed values before +publishing. Set `CENTRAL_PROFILE` to your authorized central AWS CLI profile and +`CONNECTION_NAME` to the approved account/connection name. Use a single name without +slashes, colons or wildcard characters. Validate JSON syntax, then create it: + +```sh +python3 -m json.tool /tmp/connection.json > /dev/null +aws --profile "${CENTRAL_PROFILE:?Set the central AWS profile}" --region eu-west-1 \ + ssm put-parameter \ + --name "/Monitoring/Connections/${CONNECTION_NAME:?Set the connection name}" \ + --type String --data-type text --tier Standard \ + --value file:///tmp/connection.json --no-overwrite +``` + +Syntax validation does not verify AWS identities or topology. For an existing parameter, +first read its current value into a separate local file: + +```sh +aws --profile "${CENTRAL_PROFILE:?}" --region eu-west-1 ssm get-parameter \ + --name "/Monitoring/Connections/${CONNECTION_NAME:?}" \ + --query Parameter.Value --output text > /tmp/connection-before.json +cp /tmp/connection-before.json /tmp/connection.json +``` + +Edit `/tmp/connection.json`, validate it and review +`diff -u /tmp/connection-before.json /tmp/connection.json`. Then repeat the put command +with `--overwrite` instead of `--no-overwrite`. Coordinate edits with other operators: +this is an overwrite, not a conditional update against the version you read. +Publishing creates a new parameter version; it does **not** change peering or routes. +Run Preview and review its input/change sets before Apply once the workflow is ready. + +Infrastructure's `grafana/networking/cloudformation-config-reader-role.yml` supplies +one shared read-only OIDC role. Its ARN goes in the protected core environment variable +`MONITORING_NETWORK_CONFIG_ROLE_ARN`. The workflow will read the named parameter once +per run, retain its name/version and resolved non-secret input in the run artifacts, +then obtain customer and central deployment credentials separately through OIDC. +It will not reread a newer parameter halfway through an operation. Preview and Apply +are separate runs; Apply must report the version it uses. The reader cannot write +parameters or assume the deployment roles. The lookup implementation remains pending. + ## Identities and ownership Use dedicated network-provisioning identities controlled by the central core workflow. @@ -117,9 +179,11 @@ create or update its own role. ordering before the customer role exists. Retain the acceptance-role ARN output. 3. In the customer account, review and deploy `cloudformation-customer-role.yml` with that ARN and the approved parameters. This requires `CAPABILITY_NAMED_IAM`. -4. Later, use the returned role ARN from the centrally run core workflow. Verify OIDC - identity, role assumption and the actual CloudFormation path on a disposable connection - before migrating the existing shared peering. +4. In the central account, provision the connection's central route role and the shared + configuration reader from infrastructure. Set the reader ARN in the protected core + environment and publish the connection JSON using the reviewed role outputs. +5. Later, validate OIDC identities, parameter lookup and the actual CloudFormation path + on a disposable connection before migrating the existing shared peering. The networking stack name must differ from the IAM prerequisite stack name, the standard VPC stack and application stacks. It must be new, or demonstrably owned by @@ -289,3 +353,5 @@ References: - [CloudFormation action/resource scopes](https://docs.aws.amazon.com/service-authorization/latest/reference/list_cloudformation.html) - [Native CloudFormation route iteration](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-foreach.html) - [Language transform update considerations](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/transform-aws-languageextensions.html) +- [Creating Parameter Store parameters](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-create-console.html) +- [CLI parameter creation and updates](https://docs.aws.amazon.com/cli/latest/reference/ssm/put-parameter.html) From d64877387897bb8aececb17aa1851e5b36dd04c5 Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:44:12 +0100 Subject: [PATCH 08/13] Read and validate monitoring connection settings from SSM --- .ci_cd/aws/monitoring-network/README.md | 46 +++++- .ci_cd/aws/monitoring-network/connection.py | 142 +++++++++++++++++ .../tests/test_connection.py | 144 ++++++++++++++++++ 3 files changed, 329 insertions(+), 3 deletions(-) create mode 100644 .ci_cd/aws/monitoring-network/connection.py create mode 100644 .ci_cd/aws/monitoring-network/tests/test_connection.py diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md index 66ecf9d4e3..b060952deb 100644 --- a/.ci_cd/aws/monitoring-network/README.md +++ b/.ci_cd/aws/monitoring-network/README.md @@ -6,8 +6,8 @@ one connection; no per-environment enable flag belongs here. Per-host access is [#3402](https://github.com/openremote/core/issues/3402). Available: the customer provisioning role, customer peering/routes template and central -return-routes template. Central IAM templates are prepared in infrastructure; workflow -execution and live validation remain pending. +return-routes template, plus read-only configuration lookup. Central IAM templates are +prepared in infrastructure; workflow execution and live validation remain pending. Do not run a live migration from this directory yet. ## Provisioning ownership @@ -142,7 +142,47 @@ per run, retain its name/version and resolved non-secret input in the run artifa then obtain customer and central deployment credentials separately through OIDC. It will not reread a newer parameter halfway through an operation. Preview and Apply are separate runs; Apply must report the version it uses. The reader cannot write -parameters or assume the deployment roles. The lookup implementation remains pending. +parameters or assume the deployment roles. The read-only lookup is implemented below; workflow integration remains pending. + +## Read-only configuration lookup + +`connection.py` uses Python's standard library and the AWS CLI. It reads the caller +account and exactly one named parameter in `eu-west-1`, validates the JSON, and prints +one resolved JSON object containing `parameter` (name, ARN, version), derived +`accounts`, and `connection`. It writes no files or AWS resources, assumes no roles, +and does not change application or monitoring containers. + +After the reader role and a reviewed parameter exist, a local operator can run from +the core repository root with an authorized central profile: + +```sh +python3 -B .ci_cd/aws/monitoring-network/connection.py \ + "${CONNECTION_NAME:?Set the approved connection name}" \ + --profile "${CENTRAL_PROFILE:?Set the central AWS profile}" +``` + +The future workflow will first authenticate as the configuration-reader role through +OIDC and call the same command without `--profile`. It will retain the successful JSON +output as its input artifact. `MONITORING_NETWORK_CONFIG_ROLE_ARN` is used by that +future authentication step; this script does not log in or read that variable itself. + +Exit `0` means configuration lookup and structural validation succeeded. Exit `2` +means an invalid name, AWS read failure, or rejected configuration; diagnostics go to +stderr and no resolved JSON is printed. There is no automatic parameter creation, +account discovery or fallback. AWS failures identify the failed operation without +printing raw parameter values; investigate the named read with ordinary AWS tools. + +Validation rejects missing/unknown or duplicate JSON fields, invalid stack/role/VPC +IDs, empty/duplicate route-table lists, unsupported regions, and account mismatches. +All roles currently use pathless names, matching the prerequisite templates. Customer +and monitoring accounts must differ; the monitoring and acceptance roles must belong +to the authenticated configuration account and be separate roles. The parameter must +be `String`/`text` with the requested name, account and region and a positive version. + +This is **not a networking Preview**. It does not verify role existence/permissions, +VPC CIDRs, route-table ownership, existing peerings/routes, or CloudFormation state. +Those live checks belong to the next operation slice. Neither a successful lookup nor +a parameter update authorizes skipping review of the eventual change sets. ## Identities and ownership diff --git a/.ci_cd/aws/monitoring-network/connection.py b/.ci_cd/aws/monitoring-network/connection.py new file mode 100644 index 0000000000..b5c9115172 --- /dev/null +++ b/.ci_cd/aws/monitoring-network/connection.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Read and validate approved connection settings; never change AWS resources.""" +import argparse +import json +import re +import subprocess +import sys + +REGION = "eu-west-1" +PARAMETER_PREFIX = "/Monitoring/Connections/" + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def matches(value, pattern): + return isinstance(value, str) and re.fullmatch(pattern, value) is not None + + +def unique_object(pairs): + result = {} + for key, value in pairs: + require(key not in result, "JSON contains a duplicate field") + result[key] = value + return result + + +def read_json(value): + require(isinstance(value, str), "Expected JSON text") + try: + return json.loads(value, object_pairs_hook=unique_object) + except json.JSONDecodeError as error: + raise ValueError("Invalid JSON syntax") from error + + +def fields(value, expected, location): + require(isinstance(value, dict) and set(value) == set(expected), + f"{location} must contain exactly: {', '.join(sorted(expected))}") + + +def role_account(value, location): + require(matches(value, r"arn:aws:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_-]{1,64}"), + f"{location} must be a commercial AWS IAM ARN with a pathless role name") + return value.split(":")[4] + + +def validate_connection(connection, central_account): + fields(connection, {"region", "customer", "monitoring"}, "Connection") + require(connection["region"] == REGION, f"region must be {REGION}") + accounts = {} + for side in ("customer", "monitoring"): + expected = {"stack_name", "provisioning_role_arn", "vpc_id", "route_table_ids"} + if side == "monitoring": + expected.add("acceptance_role_arn") + settings = connection[side] + fields(settings, expected, side) + require(matches(settings["stack_name"], r"[A-Za-z][A-Za-z0-9-]{0,127}"), + f"{side}.stack_name must be a valid CloudFormation stack name") + accounts[side] = role_account(settings["provisioning_role_arn"], + f"{side}.provisioning_role_arn") + require(matches(settings["vpc_id"], r"vpc-([0-9a-f]{8}|[0-9a-f]{17})"), + f"{side}.vpc_id must be a VPC ID") + tables = settings["route_table_ids"] + require(isinstance(tables, list) and bool(tables), + f"{side}.route_table_ids must be a nonempty list") + require(all(matches(table, r"rtb-([0-9a-f]{8}|[0-9a-f]{17})") for table in tables), + f"{side}.route_table_ids must contain only route-table IDs") + require(len(set(tables)) == len(tables), f"{side}.route_table_ids contains duplicates") + require(accounts["monitoring"] == central_account, + "Monitoring role account must match the authenticated configuration account") + require(accounts["customer"] != accounts["monitoring"], + "Customer and monitoring accounts must be different") + monitoring = connection["monitoring"] + require(role_account(monitoring["acceptance_role_arn"], "monitoring.acceptance_role_arn") + == accounts["monitoring"], "Acceptance role must belong to the monitoring account") + require(monitoring["acceptance_role_arn"] != monitoring["provisioning_role_arn"], + "Acceptance and central provisioning roles must be separate") + return accounts + + +def aws_json(service, operation, *arguments, profile=None): + command = ["aws", "--region", REGION, "--output", "json", "--no-cli-pager"] + if profile: + command += ["--profile", profile] + command += [service, operation, *arguments] + try: + result = subprocess.run(command, check=True, capture_output=True, text=True, timeout=60) + except FileNotFoundError as error: + raise ValueError("AWS CLI is not installed") from error + except subprocess.TimeoutExpired as error: + raise ValueError(f"AWS {service} {operation} timed out") from error + except subprocess.CalledProcessError as error: + # Never echo the parameter response or arbitrary CLI output into failure logs. + raise ValueError(f"AWS {service} {operation} failed; check credentials, permissions and parameter name") from error + return read_json(result.stdout) + + +def lookup(name, profile=None): + require(matches(name, r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}"), + "Connection name must be 1–128 letters, digits, dots, underscores or hyphens, starting with a letter or digit") + identity = aws_json("sts", "get-caller-identity", profile=profile) + require(isinstance(identity, dict) and matches(identity.get("Account"), r"[0-9]{12}"), + "AWS caller identity did not return an account ID") + account = identity["Account"] + name = PARAMETER_PREFIX + name + response = aws_json("ssm", "get-parameter", "--name", name, profile=profile) + parameter = response.get("Parameter") if isinstance(response, dict) else None + require(isinstance(parameter, dict), "SSM response is missing Parameter") + arn = f"arn:aws:ssm:{REGION}:{account}:parameter{name}" + require(parameter.get("Name") == name and parameter.get("ARN") == arn, + "SSM parameter name, account or region does not match the requested configuration") + require(parameter.get("Type") == "String" and parameter.get("DataType") == "text", + "Connection parameter must be String with data type text") + version = parameter.get("Version") + require(type(version) is int and version > 0, "SSM parameter has no valid version") + connection = read_json(parameter.get("Value")) + accounts = validate_connection(connection, account) + return { + "parameter": {"name": name, "arn": arn, "version": version}, + "accounts": accounts, + "connection": connection, + } + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("connection", help="Approved account/connection name, not a parameter path") + parser.add_argument("--profile", help="Optional local AWS CLI profile; workflows use existing OIDC credentials") + args = parser.parse_args(argv) + try: + resolved = lookup(args.connection, args.profile) + except (ValueError, OSError) as error: + print(f"Connection lookup failed: {error}", file=sys.stderr) + return 2 + print(json.dumps(resolved, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.ci_cd/aws/monitoring-network/tests/test_connection.py b/.ci_cd/aws/monitoring-network/tests/test_connection.py new file mode 100644 index 0000000000..ead54d4d17 --- /dev/null +++ b/.ci_cd/aws/monitoring-network/tests/test_connection.py @@ -0,0 +1,144 @@ +"""Read-only lookup and input validation, with no AWS access.""" +import copy +import importlib.util +import io +import json +import subprocess +import unittest +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("connection", ROOT / "connection.py") +connection = importlib.util.module_from_spec(spec) +spec.loader.exec_module(connection) + + +class ConnectionTest(unittest.TestCase): + def setUp(self): + self.settings = json.loads((ROOT / "monitoring-network.example.json").read_text()) + self.account = "222222222222" + self.name = "/Monitoring/Connections/example-customer" + self.parameter = { + "Name": self.name, + "ARN": f"arn:aws:ssm:eu-west-1:{self.account}:parameter{self.name}", + "Type": "String", "DataType": "text", "Version": 7, + "Value": json.dumps(self.settings), + } + + def test_lookup_reads_one_parameter_and_records_exact_version_without_mutation(self): + def run(command, **kwargs): + if "get-caller-identity" in command: + payload = {"Account": self.account} + else: + self.assertIn("get-parameter", command) + payload = {"Parameter": self.parameter} + return subprocess.CompletedProcess(command, 0, json.dumps(payload)) + + with patch.object(connection.subprocess, "run", side_effect=run) as aws: + result = connection.lookup("example-customer", "central") + self.assertEqual(result["connection"], self.settings) + self.assertEqual(result["parameter"], { + "name": self.name, "arn": self.parameter["ARN"], "version": 7, + }) + self.assertEqual(result["accounts"], {"customer": "111111111111", "monitoring": self.account}) + prefix = ["aws", "--region", "eu-west-1", "--output", "json", "--no-cli-pager", "--profile", "central"] + self.assertEqual([call.args[0] for call in aws.call_args_list], [ + prefix + ["sts", "get-caller-identity"], + prefix + ["ssm", "get-parameter", "--name", self.name], + ]) + + def test_invalid_connection_names_make_no_aws_calls(self): + with patch.object(connection, "aws_json") as aws: + for name in ("", "../other", "/other", "customer:1", "*", "--name", "bad\nname", "x" * 129): + with self.subTest(name=name), self.assertRaises(ValueError): + connection.lookup(name) + aws.assert_not_called() + + def test_rejects_bad_structure_identifiers_and_duplicate_tables(self): + cases = [ + ((), []), (("region",), "us-east-1"), (("customer",), None), + (("customer", "stack_name"), "bad/stack"), + (("customer", "vpc_id"), "vpc-*"), + (("customer", "provisioning_role_arn"), "arn:aws:sts::111111111111:assumed-role/name/session"), + (("customer", "route_table_ids"), []), + (("customer", "route_table_ids"), [False]), + (("customer", "route_table_ids"), ["rtb-11111111", "rtb-11111111"]), + (("customer", "route_table_ids"), "rtb-11111111"), + (("monitoring", "route_table_ids"), ["rtb-*"]), + ] + for path, value in cases: + settings = copy.deepcopy(self.settings) + if path: + parent = settings + for key in path[:-1]: + parent = parent[key] + parent[path[-1]] = value + else: + settings = value + with self.subTest(path=path, value=value), self.assertRaises(ValueError): + connection.validate_connection(settings, self.account) + for side in ("customer", "monitoring"): + settings = copy.deepcopy(self.settings) + del settings[side]["vpc_id"] + with self.assertRaises(ValueError): + connection.validate_connection(settings, self.account) + + def test_rejects_mismatched_accounts_and_combined_acceptance_role(self): + cases = [ + ("monitoring", "provisioning_role_arn", "arn:aws:iam::333333333333:role/routes"), + ("customer", "provisioning_role_arn", "arn:aws:iam::222222222222:role/customer"), + ("monitoring", "acceptance_role_arn", "arn:aws:iam::111111111111:role/accept"), + ("monitoring", "acceptance_role_arn", self.settings["monitoring"]["provisioning_role_arn"]), + ] + for side, field, value in cases: + settings = copy.deepcopy(self.settings) + settings[side][field] = value + with self.subTest(field=field, value=value), self.assertRaises(ValueError): + connection.validate_connection(settings, self.account) + + def test_rejects_wrong_parameter_envelope(self): + for field, value in (("Name", "/other"), ("ARN", "arn:aws:ssm:us-east-1:222222222222:parameter/other"), + ("Type", "SecureString"), ("DataType", "aws:ec2:image"), + ("Version", True), ("Version", 0), ("Value", "not JSON")): + parameter = dict(self.parameter, **{field: value}) + with self.subTest(field=field), patch.object(connection, "aws_json", side_effect=[ + {"Account": self.account}, {"Parameter": parameter}]), self.assertRaises(ValueError): + connection.lookup("example-customer") + + def test_rejects_duplicate_json_fields(self): + for value in ('{"region":"eu-west-1","region":"eu-west-1"}', '{"customer":{"vpc_id":"a","vpc_id":"b"}}'): + with self.assertRaisesRegex(ValueError, "duplicate field"): + connection.read_json(value) + + def test_failure_produces_no_resolved_output_or_unknown_field_values(self): + for target in (None, "customer", "monitoring"): + settings = copy.deepcopy(self.settings) + (settings if target is None else settings[target])["password"] = "do-not-print-this" + parameter = dict(self.parameter, Value=json.dumps(settings)) + output, errors = io.StringIO(), io.StringIO() + with patch.object(connection, "aws_json", side_effect=[ + {"Account": self.account}, {"Parameter": parameter}]), redirect_stdout(output), redirect_stderr(errors): + self.assertEqual(connection.main(["example-customer"]), 2) + self.assertEqual(output.getvalue(), "") + self.assertNotIn("do-not-print-this", errors.getvalue()) + self.assertIn("must contain exactly", errors.getvalue()) + + def test_aws_failure_or_timeout_stops_without_fallback(self): + for error in (FileNotFoundError(), subprocess.TimeoutExpired("aws", 60), + subprocess.CalledProcessError(254, "aws", stderr="do-not-print-this")): + with self.subTest(error=type(error)), patch.object(connection.subprocess, "run", side_effect=error) as aws: + with self.assertRaises(ValueError) as caught: + connection.lookup("example-customer") + self.assertNotIn("do-not-print-this", str(caught.exception)) + self.assertEqual(aws.call_count, 1) + with patch.object(connection, "aws_json", side_effect=[ + {"Account": self.account}, ValueError("Parameter not found")]) as aws: + with self.assertRaisesRegex(ValueError, "Parameter not found"): + connection.lookup("example-customer") + self.assertEqual(aws.call_count, 2) + + +if __name__ == "__main__": + unittest.main() From 593beb485febcd2016ae37da5bc327ca1c93ed01 Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:27:20 +0100 Subject: [PATCH 09/13] Add manual OIDC workflow to check monitoring connection settings --- .ci_cd/aws/monitoring-network/README.md | 73 ++++++++++++++++--- .github/workflows/monitoring-network.yml | 90 ++++++++++++++++++++++++ 2 files changed, 155 insertions(+), 8 deletions(-) create mode 100644 .github/workflows/monitoring-network.yml diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md index b060952deb..8bc8f490ac 100644 --- a/.ci_cd/aws/monitoring-network/README.md +++ b/.ci_cd/aws/monitoring-network/README.md @@ -7,7 +7,8 @@ one connection; no per-environment enable flag belongs here. Per-host access is Available: the customer provisioning role, customer peering/routes template and central return-routes template, plus read-only configuration lookup. Central IAM templates are -prepared in infrastructure; workflow execution and live validation remain pending. +prepared in infrastructure. A manual core workflow can check configuration; network +Preview/Apply and live validation remain pending. Do not run a live migration from this directory yet. ## Provisioning ownership @@ -28,8 +29,9 @@ Both sides of the new monitoring connection will be managed by CloudFormation. The target is one operation called from account provisioning, plus a standalone core workflow for existing accounts and retries. Customer application/Alloy workflows do not provision this shared connection or receive central route-writing permissions. -The earlier customer-repository caller design is superseded. The workflow and account -integration are not implemented yet; the existing account workflow is unchanged. +The earlier customer-repository caller design is superseded. The workflow currently +checks configuration only; network operations and account integration are not +implemented yet. The existing account workflow is unchanged. ## Operator interface and connection configuration @@ -142,7 +144,8 @@ per run, retain its name/version and resolved non-secret input in the run artifa then obtain customer and central deployment credentials separately through OIDC. It will not reread a newer parameter halfway through an operation. Preview and Apply are separate runs; Apply must report the version it uses. The reader cannot write -parameters or assume the deployment roles. The read-only lookup is implemented below; workflow integration remains pending. +parameters or assume the deployment roles. The read-only lookup and its manual +workflow are implemented below. ## Read-only configuration lookup @@ -161,10 +164,10 @@ python3 -B .ci_cd/aws/monitoring-network/connection.py \ --profile "${CENTRAL_PROFILE:?Set the central AWS profile}" ``` -The future workflow will first authenticate as the configuration-reader role through -OIDC and call the same command without `--profile`. It will retain the successful JSON -output as its input artifact. `MONITORING_NETWORK_CONFIG_ROLE_ARN` is used by that -future authentication step; this script does not log in or read that variable itself. +The manual workflow authenticates as the configuration-reader role through OIDC and +calls the same command without `--profile`. It retains successful JSON output as an +artifact. `MONITORING_NETWORK_CONFIG_ROLE_ARN` is used by the workflow authentication +step; this script does not log in or read that variable itself. Exit `0` means configuration lookup and structural validation succeeded. Exit `2` means an invalid name, AWS read failure, or rejected configuration; diagnostics go to @@ -184,6 +187,58 @@ VPC CIDRs, route-table ownership, existing peerings/routes, or CloudFormation st Those live checks belong to the next operation slice. Neither a successful lookup nor a parameter update authorizes skipping review of the eventual change sets. +## Manual workflow: configuration check + +[Monitoring Network](../../../.github/workflows/monitoring-network.yml) is the initial +entry point for the eventual Preview/Apply operation. Currently it **only reads and +validates configuration**. It is manually dispatched in `openremote/core`, uses the +fixed `monitoring-network` GitHub environment, and has one input: `ACCOUNT_NAME`. +There is no network action selector yet, no automatic push/PR trigger, and no customer +caller. Network deployment roles are not assumed by this job. + +Before the first live run: + +1. Review and deploy infrastructure's configuration-reader IAM template in the central + account in `eu-west-1`, using the existing GitHub OIDC provider. Verify the exact + core/environment subject format; the template uses the repository-name subject. + If core uses immutable-ID subjects, review the exact trust adjustment first. +2. Create/protect core's `monitoring-network` GitHub environment. Restrict deployment + branches to reviewed code and configure the required operator review. Set its + variable `MONITORING_NETWORK_CONFIG_ROLE_ARN` to the reader stack's output. Match + this workflow's fixed environment when provisioning the reader role. +3. Publish the approved connection parameter as described above. The complete schema + is required. This check does not confirm that the deployment roles or VPCs exist; + use reviewed prerequisite outputs for the actual connection, not example values. +4. Make the workflow available on core's default branch through normal review/merge. + GitHub requires that for `workflow_dispatch`. A branch-only workflow cannot be + dispatched just by adding `--ref`; after it exists on the default branch, select a + reviewed test branch allowed by the environment. Do not add a push trigger or widen + OIDC trust to bypass this prerequisite. + +In core's Actions tab select **Monitoring Network → Run workflow**, choose the reviewed +branch and enter the approved account/connection name. Approve the environment job if +required. The job authenticates through OIDC, reads the parameter once and produces: + +- A successful **Read and validate connection settings** step. +- A summary showing the parameter name/version, core revision and both accounts. +- An artifact containing `monitoring-connection.json` and `monitoring-core-revision.txt`, + retained for seven days. These contain non-secret infrastructure identifiers and are + visible to users with access to the run/artifacts; never put credentials in this JSON. + +Compare these results with the approved parameter. There is no CloudFormation change +set, route modification, peering operation or host restart in this workflow. A failed +lookup stops the job before summary/artifact upload. Correct the reported prerequisite +or parameter before rerunning; failure is not a reason to broaden IAM permissions. + +Once a successful read is confirmed, dispatch a **nonexistent name under the same +namespace**: authentication should succeed, lookup should fail, and no resolved-input +artifact should be uploaded. An invalid name such as `invalid/name` should also fail. +These checks do not prove denial outside the prefix, because the script rejects such +names before calling AWS. Review the deployed reader policy and validate forbidden +reads/writes separately using IAM policy simulation; do not attempt a real write as +an authorization test. Live validation is pending and must be recorded before this +workflow is accepted for operational use. + ## Identities and ownership Use dedicated network-provisioning identities controlled by the central core workflow. @@ -372,6 +427,7 @@ From the core repository root: ```sh uv run --no-project --with-requirements .ci_cd/aws/monitoring-network/tests/requirements.txt python -B -m unittest discover -s .ci_cd/aws/monitoring-network/tests -v uv tool run cfn-lint .ci_cd/aws/monitoring-network/cloudformation-*.yml +go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.7 -shellcheck= -pyflakes= .github/workflows/monitoring-network.yml ``` Offline tests protect the intended trust, permission and resource boundaries. Lint @@ -395,3 +451,4 @@ References: - [Language transform update considerations](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/transform-aws-languageextensions.html) - [Creating Parameter Store parameters](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-create-console.html) - [CLI parameter creation and updates](https://docs.aws.amazon.com/cli/latest/reference/ssm/put-parameter.html) +- [Manual dispatch and default-branch prerequisite](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow) diff --git a/.github/workflows/monitoring-network.yml b/.github/workflows/monitoring-network.yml new file mode 100644 index 0000000000..f0011ec682 --- /dev/null +++ b/.github/workflows/monitoring-network.yml @@ -0,0 +1,90 @@ +name: Monitoring Network +run-name: Check monitoring connection settings + +on: + workflow_dispatch: + inputs: + ACCOUNT_NAME: + description: "Approved account/connection name (configuration lookup only)" + required: true + type: string + +permissions: + contents: read + +# First slice of the networking operation: no Preview/Apply or network writes yet. +jobs: + configuration: + name: Read connection settings + if: github.repository == 'openremote/core' + runs-on: ubuntu-latest + timeout-minutes: 5 + environment: monitoring-network + permissions: + contents: read + id-token: write + defaults: + run: + shell: bash + steps: + - name: Checkout selected core revision + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Check configuration reader role + id: reader + env: + READER_ROLE_ARN: ${{ vars.MONITORING_NETWORK_CONFIG_ROLE_ARN }} + run: | + if [[ ! "$READER_ROLE_ARN" =~ ^arn:aws:iam::([0-9]{12}):role/[A-Za-z0-9+=,.@_-]{1,64}$ ]]; then + echo '::error::Set MONITORING_NETWORK_CONFIG_ROLE_ARN to the configuration reader role ARN in the monitoring-network environment.' + exit 1 + fi + echo "account=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT" + + - name: Authenticate configuration reader through OIDC + uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0 + with: + aws-region: eu-west-1 + role-to-assume: ${{ vars.MONITORING_NETWORK_CONFIG_ROLE_ARN }} + allowed-account-ids: ${{ steps.reader.outputs.account }} + role-session-name: monitoring-config-${{ github.run_id }} + role-duration-seconds: 900 + unset-current-credentials: true + + - name: Read and validate connection settings + env: + CONNECTION_NAME: ${{ inputs.ACCOUNT_NAME }} + run: | + python3 -B .ci_cd/aws/monitoring-network/connection.py "$CONNECTION_NAME" \ + > "$RUNNER_TEMP/monitoring-connection.json" + printf '%s\n' "$GITHUB_SHA" > "$RUNNER_TEMP/monitoring-core-revision.txt" + + - name: Summarize configuration check + run: | + python3 - <<'PY' + import json + import os + from pathlib import Path + + result = json.loads((Path(os.environ["RUNNER_TEMP"]) / "monitoring-connection.json").read_text()) + parameter = result["parameter"] + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: + summary.write("## Monitoring connection settings\n\n") + summary.write(f"Parameter: `{parameter['name']}` (version {parameter['version']})\n\n") + summary.write(f"Core revision: `{os.environ['GITHUB_SHA']}`\n\n") + summary.write(f"Customer account: `{result['accounts']['customer']}`\n\n") + summary.write(f"Monitoring account: `{result['accounts']['monitoring']}`\n\n") + summary.write("Configuration lookup passed. No network preview or changes were performed.\n") + PY + + - name: Save resolved input and core revision + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: monitoring-connection-${{ github.run_id }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/monitoring-connection.json + ${{ runner.temp }}/monitoring-core-revision.txt + if-no-files-found: error + retention-days: 7 From b03e2e4e013155a40c0362acbb53892624e8b3f4 Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:38:33 +0100 Subject: [PATCH 10/13] Linting --- .ci_cd/aws/monitoring-network/README.md | 30 ++++++++++++------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md index 8bc8f490ac..eab43ec40d 100644 --- a/.ci_cd/aws/monitoring-network/README.md +++ b/.ci_cd/aws/monitoring-network/README.md @@ -37,11 +37,11 @@ implemented yet. The existing account workflow is unchanged. The standalone core workflow will expose: -| Control | Operator choice | -| --- | --- | -| GitHub's workflow revision selector | Reviewed core revision | -| Account/connection | Approved customer connection, normally identified by account name | -| Action | `preview` (default) or `apply` | +| Control | Operator choice | +| ----------------------------------- | ----------------------------------------------------------------- | +| GitHub's workflow revision selector | Reviewed core revision | +| Account/connection | Approved customer connection, normally identified by account name | +| Action | `preview` (default) or `apply` | There is no staging/production selector, free-form AWS resource form or teardown action. Normal account provisioning already knows the customer account and should pass it to @@ -57,14 +57,14 @@ match. This follows the central `/Account-Ids/` convention used by [get_account_id.sh](../get_account_id.sh), without its write/fallback behavior. There is no private-repository checkout dependency or deployment journal. -| Input | Source / responsibility | -| --- | --- | -| Region and VPC IDs | Existing account/VPC records or new VPC provisioning results | -| Explicit route-table lists | Approved topology; validate membership and uniqueness | -| Stack names | Provisioning conventions, matching the dedicated IAM scopes | -| Customer provisioning-role ARN | Customer IAM prerequisite output | -| Central provisioning-role ARN | Central infrastructure IAM stack output | -| Acceptance-role ARN | Central acceptance stack output | +| Input | Source / responsibility | +| ------------------------------ | ------------------------------------------------------------ | +| Region and VPC IDs | Existing account/VPC records or new VPC provisioning results | +| Explicit route-table lists | Approved topology; validate membership and uniqueness | +| Stack names | Provisioning conventions, matching the dedicated IAM scopes | +| Customer provisioning-role ARN | Customer IAM prerequisite output | +| Central provisioning-role ARN | Central infrastructure IAM stack output | +| Acceptance-role ARN | Central acceptance stack output | For a new account, resolve the connection after its VPC and IAM prerequisites exist. For an existing account, use approved existing resources. Both paths pass the same @@ -291,7 +291,7 @@ service role; the future workflow must reject that situation before writes. | Parameter | Meaning | | ----------------------- | -------------------------------------------------------------------------- | | `RoleName` | Exact pathless customer role name; must match the central acceptance trust | -| `GitHubRepository` | `openremote/core` for the centrally initiated workflow | +| `GitHubRepository` | `openremote/core` for the centrally initiated workflow | | `GitHubEnvironment` | Protected account-level environment; default `monitoring-network` | | `NetworkStackName` | Exact dedicated customer peering/routes stack name | | `CustomerVpcId` | Existing customer VPC in this account/region | @@ -394,7 +394,7 @@ The workflow will supply its three parameters automatically: | Parameter | Source | | ------------------------- | ------------------------------------------------------------- | -| `MonitoringRouteTableIds` | `monitoring.route_table_ids` in resolved connection input | +| `MonitoringRouteTableIds` | `monitoring.route_table_ids` in resolved connection input | | `CustomerVpcCidr` | Verified customer VPC CIDR read from AWS | | `PeeringConnectionId` | `PeeringConnectionId` output of the customer networking stack | From e980e586692c75dc191f7285cb16b3ef98f364c3 Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:21:12 +0100 Subject: [PATCH 11/13] Update .github/workflows/monitoring-network.yml Co-authored-by: Dennis Kuijs --- .github/workflows/monitoring-network.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/monitoring-network.yml b/.github/workflows/monitoring-network.yml index f0011ec682..541923fc04 100644 --- a/.github/workflows/monitoring-network.yml +++ b/.github/workflows/monitoring-network.yml @@ -79,7 +79,7 @@ jobs: summary.write("Configuration lookup passed. No network preview or changes were performed.\n") PY - - name: Save resolved input and core revision + - name: Archive monitoring connection and core revision uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: monitoring-connection-${{ github.run_id }}-${{ github.run_attempt }} From 1795bc6029b2f5a13f6f2abc357f0b0ed8a010a1 Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:25:05 +0100 Subject: [PATCH 12/13] Pipeline improvements based on review feedback --- .github/workflows/monitoring-network.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/monitoring-network.yml b/.github/workflows/monitoring-network.yml index 541923fc04..dc8426fef6 100644 --- a/.github/workflows/monitoring-network.yml +++ b/.github/workflows/monitoring-network.yml @@ -16,17 +16,17 @@ permissions: jobs: configuration: name: Read connection settings - if: github.repository == 'openremote/core' runs-on: ubuntu-latest - timeout-minutes: 5 + timeout-minutes: 20 environment: monitoring-network permissions: contents: read id-token: write - defaults: - run: - shell: bash steps: + - name: Check if core repo + id: is_core_repo + uses: openremote/core/.github/actions/check-if-core-repo@357f1387fbc99e7a59752a62064f0bdade57612d + - name: Checkout selected core revision uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: From ca3b64544f50ccce08819f25a760c905482626ae Mon Sep 17 00:00:00 2001 From: Eric Bariaux <375613+ebariaux@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:53:31 +0100 Subject: [PATCH 13/13] Converted Python used in workflow to bash. Keep python for local testing --- .ci_cd/aws/monitoring-network/README.md | 18 +- .ci_cd/aws/monitoring-network/connection.py | 142 ---------- .ci_cd/aws/monitoring-network/connection.sh | 148 +++++++++++ .../tests/test_connection.py | 242 +++++++++++++----- .github/workflows/monitoring-network.yml | 25 +- 5 files changed, 351 insertions(+), 224 deletions(-) delete mode 100644 .ci_cd/aws/monitoring-network/connection.py create mode 100644 .ci_cd/aws/monitoring-network/connection.sh diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md index eab43ec40d..10cb4ec263 100644 --- a/.ci_cd/aws/monitoring-network/README.md +++ b/.ci_cd/aws/monitoring-network/README.md @@ -112,7 +112,7 @@ publishing. Set `CENTRAL_PROFILE` to your authorized central AWS CLI profile and slashes, colons or wildcard characters. Validate JSON syntax, then create it: ```sh -python3 -m json.tool /tmp/connection.json > /dev/null +jq -e -s 'length == 1 and (.[0] | type == "object")' /tmp/connection.json > /dev/null aws --profile "${CENTRAL_PROFILE:?Set the central AWS profile}" --region eu-west-1 \ ssm put-parameter \ --name "/Monitoring/Connections/${CONNECTION_NAME:?Set the connection name}" \ @@ -149,7 +149,9 @@ workflow are implemented below. ## Read-only configuration lookup -`connection.py` uses Python's standard library and the AWS CLI. It reads the caller +`connection.sh` uses Bash, jq (1.6 or later), `timeout` and the AWS CLI. These tools +are available on the workflow's Ubuntu runner; local operators must also have them +on `PATH`. Python is used only for offline tests. The script reads the caller account and exactly one named parameter in `eu-west-1`, validates the JSON, and prints one resolved JSON object containing `parameter` (name, ARN, version), derived `accounts`, and `connection`. It writes no files or AWS resources, assumes no roles, @@ -159,7 +161,7 @@ After the reader role and a reviewed parameter exist, a local operator can run f the core repository root with an authorized central profile: ```sh -python3 -B .ci_cd/aws/monitoring-network/connection.py \ +bash .ci_cd/aws/monitoring-network/connection.sh \ "${CONNECTION_NAME:?Set the approved connection name}" \ --profile "${CENTRAL_PROFILE:?Set the central AWS profile}" ``` @@ -174,6 +176,8 @@ means an invalid name, AWS read failure, or rejected configuration; diagnostics stderr and no resolved JSON is printed. There is no automatic parameter creation, account discovery or fallback. AWS failures identify the failed operation without printing raw parameter values; investigate the named read with ordinary AWS tools. +Each AWS call has a 60-second timeout, followed by a five-second forced-kill grace +period if needed. Validation rejects missing/unknown or duplicate JSON fields, invalid stack/role/VPC IDs, empty/duplicate route-table lists, unsupported regions, and account mismatches. @@ -422,15 +426,19 @@ permission review separate from the acceptance role and from the route-only temp ## Validation and next steps -From the core repository root: +From the core repository root, with Bash, jq and `timeout` available on `PATH`: ```sh +bash -n .ci_cd/aws/monitoring-network/connection.sh +shellcheck .ci_cd/aws/monitoring-network/connection.sh uv run --no-project --with-requirements .ci_cd/aws/monitoring-network/tests/requirements.txt python -B -m unittest discover -s .ci_cd/aws/monitoring-network/tests -v uv tool run cfn-lint .ci_cd/aws/monitoring-network/cloudformation-*.yml go run github.com/rhysd/actionlint/cmd/actionlint@v1.7.7 -shellcheck= -pyflakes= .github/workflows/monitoring-network.yml ``` -Offline tests protect the intended trust, permission and resource boundaries. Lint +Python offline tests exercise the real Bash lookup with a fake AWS CLI, check the +workflow summary, and protect the intended trust, permission and resource boundaries. +The lookup tests do not need AWS credentials or access. ShellCheck checks the script; lint validates the CloudFormation schema. They do not prove AWS authorization, SCPs, the provider's tag-on-create behavior, rollback or role-assumption behavior. Validate those using the actual role and disposable resources when the connection template/workflow are ready. diff --git a/.ci_cd/aws/monitoring-network/connection.py b/.ci_cd/aws/monitoring-network/connection.py deleted file mode 100644 index b5c9115172..0000000000 --- a/.ci_cd/aws/monitoring-network/connection.py +++ /dev/null @@ -1,142 +0,0 @@ -#!/usr/bin/env python3 -"""Read and validate approved connection settings; never change AWS resources.""" -import argparse -import json -import re -import subprocess -import sys - -REGION = "eu-west-1" -PARAMETER_PREFIX = "/Monitoring/Connections/" - - -def require(condition, message): - if not condition: - raise ValueError(message) - - -def matches(value, pattern): - return isinstance(value, str) and re.fullmatch(pattern, value) is not None - - -def unique_object(pairs): - result = {} - for key, value in pairs: - require(key not in result, "JSON contains a duplicate field") - result[key] = value - return result - - -def read_json(value): - require(isinstance(value, str), "Expected JSON text") - try: - return json.loads(value, object_pairs_hook=unique_object) - except json.JSONDecodeError as error: - raise ValueError("Invalid JSON syntax") from error - - -def fields(value, expected, location): - require(isinstance(value, dict) and set(value) == set(expected), - f"{location} must contain exactly: {', '.join(sorted(expected))}") - - -def role_account(value, location): - require(matches(value, r"arn:aws:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_-]{1,64}"), - f"{location} must be a commercial AWS IAM ARN with a pathless role name") - return value.split(":")[4] - - -def validate_connection(connection, central_account): - fields(connection, {"region", "customer", "monitoring"}, "Connection") - require(connection["region"] == REGION, f"region must be {REGION}") - accounts = {} - for side in ("customer", "monitoring"): - expected = {"stack_name", "provisioning_role_arn", "vpc_id", "route_table_ids"} - if side == "monitoring": - expected.add("acceptance_role_arn") - settings = connection[side] - fields(settings, expected, side) - require(matches(settings["stack_name"], r"[A-Za-z][A-Za-z0-9-]{0,127}"), - f"{side}.stack_name must be a valid CloudFormation stack name") - accounts[side] = role_account(settings["provisioning_role_arn"], - f"{side}.provisioning_role_arn") - require(matches(settings["vpc_id"], r"vpc-([0-9a-f]{8}|[0-9a-f]{17})"), - f"{side}.vpc_id must be a VPC ID") - tables = settings["route_table_ids"] - require(isinstance(tables, list) and bool(tables), - f"{side}.route_table_ids must be a nonempty list") - require(all(matches(table, r"rtb-([0-9a-f]{8}|[0-9a-f]{17})") for table in tables), - f"{side}.route_table_ids must contain only route-table IDs") - require(len(set(tables)) == len(tables), f"{side}.route_table_ids contains duplicates") - require(accounts["monitoring"] == central_account, - "Monitoring role account must match the authenticated configuration account") - require(accounts["customer"] != accounts["monitoring"], - "Customer and monitoring accounts must be different") - monitoring = connection["monitoring"] - require(role_account(monitoring["acceptance_role_arn"], "monitoring.acceptance_role_arn") - == accounts["monitoring"], "Acceptance role must belong to the monitoring account") - require(monitoring["acceptance_role_arn"] != monitoring["provisioning_role_arn"], - "Acceptance and central provisioning roles must be separate") - return accounts - - -def aws_json(service, operation, *arguments, profile=None): - command = ["aws", "--region", REGION, "--output", "json", "--no-cli-pager"] - if profile: - command += ["--profile", profile] - command += [service, operation, *arguments] - try: - result = subprocess.run(command, check=True, capture_output=True, text=True, timeout=60) - except FileNotFoundError as error: - raise ValueError("AWS CLI is not installed") from error - except subprocess.TimeoutExpired as error: - raise ValueError(f"AWS {service} {operation} timed out") from error - except subprocess.CalledProcessError as error: - # Never echo the parameter response or arbitrary CLI output into failure logs. - raise ValueError(f"AWS {service} {operation} failed; check credentials, permissions and parameter name") from error - return read_json(result.stdout) - - -def lookup(name, profile=None): - require(matches(name, r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}"), - "Connection name must be 1–128 letters, digits, dots, underscores or hyphens, starting with a letter or digit") - identity = aws_json("sts", "get-caller-identity", profile=profile) - require(isinstance(identity, dict) and matches(identity.get("Account"), r"[0-9]{12}"), - "AWS caller identity did not return an account ID") - account = identity["Account"] - name = PARAMETER_PREFIX + name - response = aws_json("ssm", "get-parameter", "--name", name, profile=profile) - parameter = response.get("Parameter") if isinstance(response, dict) else None - require(isinstance(parameter, dict), "SSM response is missing Parameter") - arn = f"arn:aws:ssm:{REGION}:{account}:parameter{name}" - require(parameter.get("Name") == name and parameter.get("ARN") == arn, - "SSM parameter name, account or region does not match the requested configuration") - require(parameter.get("Type") == "String" and parameter.get("DataType") == "text", - "Connection parameter must be String with data type text") - version = parameter.get("Version") - require(type(version) is int and version > 0, "SSM parameter has no valid version") - connection = read_json(parameter.get("Value")) - accounts = validate_connection(connection, account) - return { - "parameter": {"name": name, "arn": arn, "version": version}, - "accounts": accounts, - "connection": connection, - } - - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("connection", help="Approved account/connection name, not a parameter path") - parser.add_argument("--profile", help="Optional local AWS CLI profile; workflows use existing OIDC credentials") - args = parser.parse_args(argv) - try: - resolved = lookup(args.connection, args.profile) - except (ValueError, OSError) as error: - print(f"Connection lookup failed: {error}", file=sys.stderr) - return 2 - print(json.dumps(resolved, indent=2)) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/.ci_cd/aws/monitoring-network/connection.sh b/.ci_cd/aws/monitoring-network/connection.sh new file mode 100644 index 0000000000..bf55e95cc3 --- /dev/null +++ b/.ci_cd/aws/monitoring-network/connection.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# Read and validate approved connection settings; never change AWS resources. +set -euo pipefail +export LC_ALL=C + +fail() { + printf 'Connection lookup failed: %s\n' "$1" >&2 + exit 2 +} + +usage() { + printf '%s\n' 'Usage: connection.sh [--profile PROFILE] CONNECTION' \ + 'Read one approved connection from central SSM using existing AWS credentials.' +} + +connection_name='' +profile='' +while (($#)); do + case "$1" in + -h|--help) usage; exit 0 ;; + --profile) + (($# >= 2)) && [[ -n "$2" ]] || fail '--profile requires a value' + profile=$2 + shift 2 + ;; + --profile=*) + profile=${1#--profile=} + [[ -n "$profile" ]] || fail '--profile requires a value' + shift + ;; + -*) fail 'Unknown option; use --help for usage' ;; + *) + [[ -z "$connection_name" ]] || fail 'Expected only one connection name' + connection_name=$1 + shift + ;; + esac +done +[[ "$connection_name" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$ ]] || + fail 'Connection name must be 1-128 letters, digits, dots, underscores or hyphens, starting with a letter or digit' +for tool in aws jq timeout; do + command -v "$tool" >/dev/null 2>&1 || fail "Required command is not installed: $tool" +done + +region=eu-west-1 +parameter_name="/Monitoring/Connections/$connection_name" +aws_command=(aws --region "$region" --output json --no-cli-pager) +if [[ -n "$profile" ]]; then + aws_command+=(--profile "$profile") +fi + +# jq normally keeps the last duplicate key. Streaming preserves every occurrence. +# A scalar/empty container completes at its path; a nonempty container completes +# at the parent of the closing event's path. Each completed path must be unique. +# Multiple JSON documents repeat the root path; empty input has no paths. +unique_json() { + jq -e --stream --slurp ' + map(if length == 1 then .[0][:-1] else .[0] end) + | length > 0 and (length == (unique | length)) + ' >/dev/null 2>&1 +} + +aws_json() { + local response status + if response=$(timeout -k 5 60 "${aws_command[@]}" "$@" 2>/dev/null); then + printf '%s\n' "$response" | unique_json || fail "AWS $1 $2 returned invalid or ambiguous JSON" + printf '%s\n' "$response" + else + status=$? + if [[ "$status" == 124 || "$status" == 137 ]]; then + fail "AWS $1 $2 timed out" + fi + fail "AWS $1 $2 failed; check credentials, permissions and parameter name" + fi +} + +identity=$(aws_json sts get-caller-identity) +account=$(printf '%s\n' "$identity" | jq -er ' + .Account | select(type == "string") | select(test("^[0-9]{12}\\z")) +' 2>/dev/null) || fail 'AWS caller identity did not return an account ID' +response=$(aws_json ssm get-parameter --name "$parameter_name") +parameter_arn="arn:aws:ssm:$region:$account:parameter$parameter_name" +printf '%s\n' "$response" | jq -e --arg name "$parameter_name" --arg arn "$parameter_arn" ' + .Parameter | type == "object" and .Name == $name and .ARN == $arn +' >/dev/null 2>&1 || fail 'SSM parameter name, account or region does not match the requested configuration' +printf '%s\n' "$response" | jq -e ' + .Parameter | .Type == "String" and .DataType == "text" and (.Value | type == "string") +' >/dev/null 2>&1 || fail 'Connection parameter must be String with data type text' +printf '%s\n' "$response" | jq -e ' + .Parameter.Version | type == "number" and . > 0 and . == floor +' >/dev/null 2>&1 || fail 'SSM parameter has no valid version' + +# Validate the raw parameter value before fromjson can collapse duplicate fields. +printf '%s\n' "$response" | jq -r '.Parameter.Value' | unique_json || + fail 'Connection value must be one JSON document without duplicate fields' +config=$(printf '%s\n' "$response" | jq -ce '.Parameter.Value | fromjson' 2>/dev/null) || + fail 'Invalid connection JSON' +printf '%s\n' "$config" | jq -e 'type == "object" and keys == ["customer", "monitoring", "region"]' >/dev/null 2>&1 || + fail 'Connection must contain exactly: customer, monitoring, region' +printf '%s\n' "$config" | jq -e --arg region "$region" '.region == $region' >/dev/null || + fail "region must be $region" + +role_pattern='^arn:aws:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_-]{1,64}\z' +for side in customer monitoring; do + settings=$(printf '%s\n' "$config" | jq -c --arg side "$side" '.[$side]') + printf '%s\n' "$settings" | jq -e --arg side "$side" ' + type == "object" and keys == + ((["stack_name", "provisioning_role_arn", "vpc_id", "route_table_ids"] + + if $side == "monitoring" then ["acceptance_role_arn"] else [] end) | sort) + ' >/dev/null 2>&1 || fail "$side has missing or unknown fields" + printf '%s\n' "$settings" | jq -e ' + .stack_name | type == "string" and test("^[A-Za-z][A-Za-z0-9-]{0,127}\\z") + ' >/dev/null 2>&1 || fail "$side.stack_name must be a valid CloudFormation stack name" + printf '%s\n' "$settings" | jq -e --arg pattern "$role_pattern" ' + .provisioning_role_arn | type == "string" and test($pattern) + ' >/dev/null 2>&1 || fail "$side.provisioning_role_arn must be a commercial AWS IAM ARN with a pathless role name" + printf '%s\n' "$settings" | jq -e ' + .vpc_id | type == "string" and test("^vpc-([0-9a-f]{8}|[0-9a-f]{17})\\z") + ' >/dev/null 2>&1 || fail "$side.vpc_id must be a VPC ID" + printf '%s\n' "$settings" | jq -e ' + .route_table_ids | type == "array" and length > 0 + and all(.[]; type == "string" and test("^rtb-([0-9a-f]{8}|[0-9a-f]{17})\\z")) + and length == (unique | length) + ' >/dev/null 2>&1 || fail "$side.route_table_ids must be a nonempty list of unique route-table IDs" +done +printf '%s\n' "$config" | jq -e --arg pattern "$role_pattern" ' + .monitoring.acceptance_role_arn | type == "string" and test($pattern) +' >/dev/null 2>&1 || fail 'monitoring.acceptance_role_arn must be a commercial AWS IAM ARN with a pathless role name' +printf '%s\n' "$config" | jq -e --arg account "$account" ' + (.monitoring.provisioning_role_arn | split(":")[4]) == $account +' >/dev/null || fail 'Monitoring role account must match the authenticated configuration account' +printf '%s\n' "$config" | jq -e --arg account "$account" ' + (.customer.provisioning_role_arn | split(":")[4]) != $account +' >/dev/null || fail 'Customer and monitoring accounts must be different' +printf '%s\n' "$config" | jq -e --arg account "$account" ' + (.monitoring.acceptance_role_arn | split(":")[4]) == $account +' >/dev/null || fail 'Acceptance role must belong to the monitoring account' +printf '%s\n' "$config" | jq -e ' + .monitoring.acceptance_role_arn != .monitoring.provisioning_role_arn +' >/dev/null || fail 'Acceptance and central provisioning roles must be separate' + +# Emit only the complete validated result, preserving the existing artifact schema. +printf '%s\n' "$response" | jq --argjson connection "$config" ' + {parameter: {name: .Parameter.Name, arn: .Parameter.ARN, version: .Parameter.Version}, + accounts: {customer: ($connection.customer.provisioning_role_arn | split(":")[4]), + monitoring: ($connection.monitoring.provisioning_role_arn | split(":")[4])}, + connection: $connection} +' diff --git a/.ci_cd/aws/monitoring-network/tests/test_connection.py b/.ci_cd/aws/monitoring-network/tests/test_connection.py index ead54d4d17..7a84ffd7a4 100644 --- a/.ci_cd/aws/monitoring-network/tests/test_connection.py +++ b/.ci_cd/aws/monitoring-network/tests/test_connection.py @@ -1,18 +1,17 @@ """Read-only lookup and input validation, with no AWS access.""" import copy -import importlib.util -import io import json +import os +import shutil import subprocess +import sys +import tempfile import unittest -from contextlib import redirect_stderr, redirect_stdout from pathlib import Path -from unittest.mock import patch + +import yaml ROOT = Path(__file__).resolve().parents[1] -spec = importlib.util.spec_from_file_location("connection", ROOT / "connection.py") -connection = importlib.util.module_from_spec(spec) -spec.loader.exec_module(connection) class ConnectionTest(unittest.TestCase): @@ -27,34 +26,107 @@ def setUp(self): "Value": json.dumps(self.settings), } - def test_lookup_reads_one_parameter_and_records_exact_version_without_mutation(self): - def run(command, **kwargs): - if "get-caller-identity" in command: - payload = {"Account": self.account} - else: - self.assertIn("get-parameter", command) - payload = {"Parameter": self.parameter} - return subprocess.CompletedProcess(command, 0, json.dumps(payload)) + self.temp = tempfile.TemporaryDirectory(prefix="monitoring-connection-test-") + self.addCleanup(self.temp.cleanup) + self.fixture = Path(self.temp.name) + self.bin = self.fixture / "bin" + self.bin.mkdir() + # Isolate PATH: tests can never fall through to a real AWS executable. + for tool in ("jq", "timeout"): + executable = shutil.which(tool) + if not executable: + self.fail(f"Tests require {tool} on PATH") + (self.bin / tool).symlink_to(executable) + aws = self.bin / "aws" + aws.write_text(f"#!{sys.executable}\n" + r'''import json, os, sys +from pathlib import Path +root = Path(os.environ["AWS_TEST_FIXTURE"]) +args = sys.argv[1:] +with (root / "calls.jsonl").open("a") as log: + log.write(json.dumps(args) + "\n") +if "sts" in args and args[-2:] == ["sts", "get-caller-identity"]: + operation = "identity" +elif "ssm" in args and args[-4:-1] == ["ssm", "get-parameter", "--name"]: + operation = "parameter" +else: + sys.exit("Unexpected AWS operation") +if os.environ.get("AWS_TEST_FAIL") == operation: + print("do-not-print-this", file=sys.stderr) + sys.exit(254) +sys.stdout.write((root / (operation + ".json")).read_text()) +''') + aws.chmod(0o700) + self.env = dict(os.environ, PATH=str(self.bin), AWS_TEST_FIXTURE=str(self.fixture)) + self.env.pop("AWS_TEST_FAIL", None) + self.identity = json.dumps({"Account": self.account}) + + def run_lookup(self, *args, raw_response=None): + (self.fixture / "identity.json").write_text(self.identity) + (self.fixture / "parameter.json").write_text( + raw_response if raw_response is not None else json.dumps({"Parameter": self.parameter})) + (self.fixture / "calls.jsonl").write_text("") + return subprocess.run( + ["/bin/bash", str(ROOT / "connection.sh"), *(args or ["example-customer"])], + env=self.env, text=True, capture_output=True, timeout=10, + ) + + def calls(self): + return [json.loads(line) for line in (self.fixture / "calls.jsonl").read_text().splitlines()] + + def assert_rejected(self, result): + self.assertEqual(result.returncode, 2, result.stderr) + self.assertEqual(result.stdout, "") + self.assertIn("Connection lookup failed:", result.stderr) + self.assertNotIn("do-not-print-this", result.stderr) + + def reject_settings(self, settings): + self.parameter["Value"] = json.dumps(settings) + self.assert_rejected(self.run_lookup()) - with patch.object(connection.subprocess, "run", side_effect=run) as aws: - result = connection.lookup("example-customer", "central") + def test_lookup_reads_one_parameter_and_records_exact_version_without_mutation(self): + result = self.run_lookup("example-customer", "--profile", "central profile") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stderr, "") + result = json.loads(result.stdout) self.assertEqual(result["connection"], self.settings) self.assertEqual(result["parameter"], { "name": self.name, "arn": self.parameter["ARN"], "version": 7, }) self.assertEqual(result["accounts"], {"customer": "111111111111", "monitoring": self.account}) - prefix = ["aws", "--region", "eu-west-1", "--output", "json", "--no-cli-pager", "--profile", "central"] - self.assertEqual([call.args[0] for call in aws.call_args_list], [ + prefix = ["--region", "eu-west-1", "--output", "json", "--no-cli-pager", "--profile", "central profile"] + self.assertEqual(self.calls(), [ prefix + ["sts", "get-caller-identity"], prefix + ["ssm", "get-parameter", "--name", self.name], ]) + def test_workflow_summary_uses_the_resolved_artifact(self): + result = self.run_lookup() + self.assertEqual(result.returncode, 0, result.stderr) + (self.fixture / "monitoring-connection.json").write_text(result.stdout) + workflow = yaml.safe_load((ROOT.parents[2] / ".github/workflows/monitoring-network.yml").read_text()) + step = next(step for step in workflow["jobs"]["configuration"]["steps"] + if step["name"] == "Summarize configuration check") + summary = self.fixture / "summary.md" + revision = "a" * 40 + result = subprocess.run( + ["/bin/bash", "-euo", "pipefail", "-c", step["run"]], + env=dict(self.env, RUNNER_TEMP=str(self.fixture), GITHUB_SHA=revision, + GITHUB_STEP_SUMMARY=str(summary)), text=True, capture_output=True, timeout=10, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(summary.read_text(), + "## Monitoring connection settings\n\n" + f"Parameter: `{self.name}` (version 7)\n\n" + f"Core revision: `{revision}`\n\n" + "Customer account: `111111111111`\n\n" + "Monitoring account: `222222222222`\n\n" + "Configuration lookup passed. No network preview or changes were performed.\n") + def test_invalid_connection_names_make_no_aws_calls(self): - with patch.object(connection, "aws_json") as aws: - for name in ("", "../other", "/other", "customer:1", "*", "--name", "bad\nname", "x" * 129): - with self.subTest(name=name), self.assertRaises(ValueError): - connection.lookup(name) - aws.assert_not_called() + for name in ("", "../other", "/other", "customer:1", "*", "--name", "bad\nname", "x" * 129): + with self.subTest(name=name): + self.assert_rejected(self.run_lookup(name)) + self.assertEqual(self.calls(), []) def test_rejects_bad_structure_identifiers_and_duplicate_tables(self): cases = [ @@ -77,13 +149,12 @@ def test_rejects_bad_structure_identifiers_and_duplicate_tables(self): parent[path[-1]] = value else: settings = value - with self.subTest(path=path, value=value), self.assertRaises(ValueError): - connection.validate_connection(settings, self.account) + with self.subTest(path=path, value=value): + self.reject_settings(settings) for side in ("customer", "monitoring"): settings = copy.deepcopy(self.settings) del settings[side]["vpc_id"] - with self.assertRaises(ValueError): - connection.validate_connection(settings, self.account) + self.reject_settings(settings) def test_rejects_mismatched_accounts_and_combined_acceptance_role(self): cases = [ @@ -95,49 +166,98 @@ def test_rejects_mismatched_accounts_and_combined_acceptance_role(self): for side, field, value in cases: settings = copy.deepcopy(self.settings) settings[side][field] = value - with self.subTest(field=field, value=value), self.assertRaises(ValueError): - connection.validate_connection(settings, self.account) + with self.subTest(field=field, value=value): + self.reject_settings(settings) def test_rejects_wrong_parameter_envelope(self): + original = self.parameter.copy() for field, value in (("Name", "/other"), ("ARN", "arn:aws:ssm:us-east-1:222222222222:parameter/other"), ("Type", "SecureString"), ("DataType", "aws:ec2:image"), - ("Version", True), ("Version", 0), ("Value", "not JSON")): - parameter = dict(self.parameter, **{field: value}) - with self.subTest(field=field), patch.object(connection, "aws_json", side_effect=[ - {"Account": self.account}, {"Parameter": parameter}]), self.assertRaises(ValueError): - connection.lookup("example-customer") + ("Version", True), ("Version", 0), ("Version", 1.5), + ("Value", "not JSON"), ("Value", None)): + self.parameter = dict(original, **{field: value}) + with self.subTest(field=field, value=value): + self.assert_rejected(self.run_lookup()) - def test_rejects_duplicate_json_fields(self): - for value in ('{"region":"eu-west-1","region":"eu-west-1"}', '{"customer":{"vpc_id":"a","vpc_id":"b"}}'): - with self.assertRaisesRegex(ValueError, "duplicate field"): - connection.read_json(value) + def test_rejects_ambiguous_or_malformed_json_before_normalizing_it(self): + valid = json.dumps(self.settings) + for value in ( + valid.replace('"region":', '"region":"eu-west-1","region":'), + valid.replace('"vpc_id":', '"vpc_id":"vpc-12345678","vpc_id":', 1), + valid.replace('"customer":', '"customer":{"other":1},"customer":'), + valid.replace('"customer":', '"customer":{},"customer":'), + valid.replace('"route_table_ids":', '"route_table_ids":[],"route_table_ids":', 1), + valid.replace('"region":', r'"regio\u006e":"eu-west-1","region":'), + valid + valid, "", valid[:-1], + ): + with self.subTest(value=value): + self.parameter["Value"] = value + self.assert_rejected(self.run_lookup()) + self.parameter["Value"] = valid + for response in ( + '{"Parameter":{},' + json.dumps({"Parameter": self.parameter})[1:], + json.dumps({"Parameter": self.parameter}) * 2, + "", '{"Parameter":', + ): + with self.subTest(response=response): + self.assert_rejected(self.run_lookup(raw_response=response)) def test_failure_produces_no_resolved_output_or_unknown_field_values(self): for target in (None, "customer", "monitoring"): settings = copy.deepcopy(self.settings) (settings if target is None else settings[target])["password"] = "do-not-print-this" - parameter = dict(self.parameter, Value=json.dumps(settings)) - output, errors = io.StringIO(), io.StringIO() - with patch.object(connection, "aws_json", side_effect=[ - {"Account": self.account}, {"Parameter": parameter}]), redirect_stdout(output), redirect_stderr(errors): - self.assertEqual(connection.main(["example-customer"]), 2) - self.assertEqual(output.getvalue(), "") - self.assertNotIn("do-not-print-this", errors.getvalue()) - self.assertIn("must contain exactly", errors.getvalue()) - - def test_aws_failure_or_timeout_stops_without_fallback(self): - for error in (FileNotFoundError(), subprocess.TimeoutExpired("aws", 60), - subprocess.CalledProcessError(254, "aws", stderr="do-not-print-this")): - with self.subTest(error=type(error)), patch.object(connection.subprocess, "run", side_effect=error) as aws: - with self.assertRaises(ValueError) as caught: - connection.lookup("example-customer") - self.assertNotIn("do-not-print-this", str(caught.exception)) - self.assertEqual(aws.call_count, 1) - with patch.object(connection, "aws_json", side_effect=[ - {"Account": self.account}, ValueError("Parameter not found")]) as aws: - with self.assertRaisesRegex(ValueError, "Parameter not found"): - connection.lookup("example-customer") - self.assertEqual(aws.call_count, 2) + self.reject_settings(settings) + + def test_identifiers_must_match_in_full_including_control_characters(self): + for side in ("customer", "monitoring"): + for field in ("stack_name", "provisioning_role_arn", "vpc_id", "route_table_ids"): + for suffix in ("\n", "\u0000"): + settings = copy.deepcopy(self.settings) + if field == "route_table_ids": + settings[side][field][0] += suffix + else: + settings[side][field] += suffix + with self.subTest(side=side, field=field, suffix=suffix): + self.reject_settings(settings) + + def test_invalid_identity_stops_before_reading_parameter(self): + for value in ('{}', '{"Account":222222222222}', '{"Account":"222222222222\\n"}', + '{"Account":"111111111111","Account":"222222222222"}', 'null', 'not JSON'): + self.identity = value + with self.subTest(value=value): + self.assert_rejected(self.run_lookup()) + self.assertEqual(len(self.calls()), 1) + + def test_aws_failure_stops_without_fallback(self): + for operation, count in (("identity", 1), ("parameter", 2)): + self.env["AWS_TEST_FAIL"] = operation + with self.subTest(operation=operation): + self.assert_rejected(self.run_lookup()) + self.assertEqual(len(self.calls()), count) + + def test_timeout_is_bounded_and_reported_without_partial_output(self): + (self.bin / "timeout").unlink() + (self.bin / "timeout").write_text( + '#!/bin/sh\n[ "$1 $2 $3" = "-k 5 60" ] || exit 99\nexit 124\n') + (self.bin / "timeout").chmod(0o700) + result = self.run_lookup() + self.assert_rejected(result) + self.assertIn("timed out", result.stderr) + self.assertEqual(self.calls(), []) + + def test_missing_dependency_is_reported_before_any_aws_call(self): + for tool in ("aws", "jq", "timeout"): + path = self.bin / tool + saved = self.fixture / tool + path.rename(saved) + try: + with self.subTest(tool=tool): + result = self.run_lookup() + self.assert_rejected(result) + self.assertIn("Required command is not installed: " + tool, result.stderr) + self.assertEqual(self.calls(), []) + finally: + saved.rename(path) if __name__ == "__main__": diff --git a/.github/workflows/monitoring-network.yml b/.github/workflows/monitoring-network.yml index dc8426fef6..634d228cfa 100644 --- a/.github/workflows/monitoring-network.yml +++ b/.github/workflows/monitoring-network.yml @@ -57,27 +57,20 @@ jobs: env: CONNECTION_NAME: ${{ inputs.ACCOUNT_NAME }} run: | - python3 -B .ci_cd/aws/monitoring-network/connection.py "$CONNECTION_NAME" \ + bash .ci_cd/aws/monitoring-network/connection.sh "$CONNECTION_NAME" \ > "$RUNNER_TEMP/monitoring-connection.json" printf '%s\n' "$GITHUB_SHA" > "$RUNNER_TEMP/monitoring-core-revision.txt" - name: Summarize configuration check run: | - python3 - <<'PY' - import json - import os - from pathlib import Path - - result = json.loads((Path(os.environ["RUNNER_TEMP"]) / "monitoring-connection.json").read_text()) - parameter = result["parameter"] - with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: - summary.write("## Monitoring connection settings\n\n") - summary.write(f"Parameter: `{parameter['name']}` (version {parameter['version']})\n\n") - summary.write(f"Core revision: `{os.environ['GITHUB_SHA']}`\n\n") - summary.write(f"Customer account: `{result['accounts']['customer']}`\n\n") - summary.write(f"Monitoring account: `{result['accounts']['monitoring']}`\n\n") - summary.write("Configuration lookup passed. No network preview or changes were performed.\n") - PY + jq -r --arg revision "$GITHUB_SHA" ' + "## Monitoring connection settings\n", + "Parameter: `\(.parameter.name)` (version \(.parameter.version))\n", + "Core revision: `\($revision)`\n", + "Customer account: `\(.accounts.customer)`\n", + "Monitoring account: `\(.accounts.monitoring)`\n", + "Configuration lookup passed. No network preview or changes were performed." + ' "$RUNNER_TEMP/monitoring-connection.json" >> "$GITHUB_STEP_SUMMARY" - name: Archive monitoring connection and core revision uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2