diff --git a/.ci_cd/aws/monitoring-network/README.md b/.ci_cd/aws/monitoring-network/README.md new file mode 100644 index 0000000000..10cb4ec263 --- /dev/null +++ b/.ci_cd/aws/monitoring-network/README.md @@ -0,0 +1,462 @@ +# Shared customer monitoring network + +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). + +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. 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 + +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 currently +checks configuration only; network operations 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 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 | +| ------------------------------ | ------------------------------------------------------------ | +| 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 +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. + +## 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 +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}" \ + --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 read-only lookup and its manual +workflow are implemented below. + +## Read-only configuration lookup + +`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, +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 +bash .ci_cd/aws/monitoring-network/connection.sh \ + "${CONNECTION_NAME:?Set the approved connection name}" \ + --profile "${CENTRAL_PROFILE:?Set the central AWS profile}" +``` + +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 +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. +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. + +## 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. +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. +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 and route-provisioning IAM templates +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 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. 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 +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` | `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 | +| `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 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. +- 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. + +## 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. + +## 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 resolved connection input | +| `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 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. + +## Validation and next steps + +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 +``` + +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. +Do not broaden permissions preemptively when diagnosing a failed check. + +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: + +- [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) +- [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) +- [Manual dispatch and default-branch prerequisite](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow) 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/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/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/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/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" + ] + } +} 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_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() 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..7a84ffd7a4 --- /dev/null +++ b/.ci_cd/aws/monitoring-network/tests/test_connection.py @@ -0,0 +1,264 @@ +"""Read-only lookup and input validation, with no AWS access.""" +import copy +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +import yaml + +ROOT = Path(__file__).resolve().parents[1] + + +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), + } + + 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()) + + 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 = ["--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): + 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 = [ + ((), []), (("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.reject_settings(settings) + for side in ("customer", "monitoring"): + settings = copy.deepcopy(self.settings) + del settings[side]["vpc_id"] + self.reject_settings(settings) + + 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.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), ("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_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" + 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__": + unittest.main() 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() 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() diff --git a/.github/workflows/monitoring-network.yml b/.github/workflows/monitoring-network.yml new file mode 100644 index 0000000000..634d228cfa --- /dev/null +++ b/.github/workflows/monitoring-network.yml @@ -0,0 +1,83 @@ +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 + runs-on: ubuntu-latest + timeout-minutes: 20 + environment: monitoring-network + permissions: + contents: read + id-token: write + 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: + 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: | + 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: | + 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 + 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