From d16e49a541eb4716f33e58deb49da78664b826ab Mon Sep 17 00:00:00 2001 From: "eps-create-pull-request[bot]" <270920461+eps-create-pull-request[bot]@users.noreply.github.com> Date: Wed, 1 Apr 2026 14:03:13 +0000 Subject: [PATCH] Upgrade: [dependabot] - sync Copilot instructions --- .github/copilot-instructions.md | 25 +-- .../{SECURITY.md => security.instructions.md} | 5 +- ...NSTRUCTIONS-CDK.md => cdk.instructions.md} | 4 +- .../languages/cloudformation.instructions.md | 110 ++++++++++ .../languages/python.instructions.md | 93 ++++++++ .../languages/sam.instructions.md | 201 ++++++++++++++++++ .../languages/terraform.instructions.md | 147 +++++++++++++ ...PESCRIPT.md => typescript.instructions.md} | 4 +- .github/prompts/code_review.prompt.md | 61 ++++++ 9 files changed, 635 insertions(+), 15 deletions(-) rename .github/instructions/general/{SECURITY.md => security.instructions.md} (95%) rename .github/instructions/languages/{INSTRUCTIONS-CDK.md => cdk.instructions.md} (91%) create mode 100644 .github/instructions/languages/cloudformation.instructions.md create mode 100644 .github/instructions/languages/python.instructions.md create mode 100644 .github/instructions/languages/sam.instructions.md create mode 100644 .github/instructions/languages/terraform.instructions.md rename .github/instructions/languages/{INSTRUCTIONS-TYPESCRIPT.md => typescript.instructions.md} (95%) create mode 100644 .github/prompts/code_review.prompt.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 24bec283..5f48b1b2 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -2,19 +2,20 @@ - Follow clean code principles - Write comprehensive tests - Use meaningful variable names -- Use British English spelling + +## Project-Specific instructions +Check the following files for any project-specific coding standards or guidelines: +- .github/instructions/project/instructions.md +- If no project-specific conventions are defined there, use the general and language-specific best practices referenced below. +- Language-specific instructions may also be found in the language-specific instruction files listed below. Always check those for any additional guidelines or standards that may apply to your codebase. ## Language-Specific Instructions Always follow security best practices as outlined in: -- .github/instructions/general/SECURITY.md +- .github/instructions/general/security.instructions.md Follow additional language-specific guidelines in: -- .github/instructions/language-specific/INSTRUCTIONS-CDK.md -- .github/instructions/language-specific/INSTRUCTIONS-CLOUDFORMATION.md -- .github/instructions/language-specific/INSTRUCTIONS-JAVA.md -- .github/instructions/language-specific/INSTRUCTIONS-KOTLIN.md -- .github/instructions/language-specific/INSTRUCTIONS-PYTHON.md -- .github/instructions/language-specific/INSTRUCTIONS-TERRAFORM.md -- .github/instructions/language-specific/INSTRUCTIONS-SAM.md -- .github/instructions/language-specific/INSTRUCTIONS-TYPESCRIPT.md - -## Project-Specific Rules +- .github/instructions/languages/cdk.instructions.md +- .github/instructions/languages/cloudformation.instructions.md +- .github/instructions/languages/python.instructions.md +- .github/instructions/languages/terraform.instructions.md +- .github/instructions/languages/sam.instructions.md +- .github/instructions/languages/typescript.instructions.md diff --git a/.github/instructions/general/SECURITY.md b/.github/instructions/general/security.instructions.md similarity index 95% rename from .github/instructions/general/SECURITY.md rename to .github/instructions/general/security.instructions.md index 53a7a628..6e99c595 100644 --- a/.github/instructions/general/SECURITY.md +++ b/.github/instructions/general/security.instructions.md @@ -1,7 +1,10 @@ --- -applyTo: '*' +applyTo: '**/*' description: "Comprehensive secure coding instructions for all languages and frameworks, based on OWASP Top 10 and industry best practices." --- + +This file is mastered in https://github.com/NHSDigital/eps-copilot-instructions and is automatically synced to all EPS repositories. To suggest changes, please open an issue or pull request in the eps-copilot-instructions repository. + # Secure Coding and OWASP Guidelines ## Instructions diff --git a/.github/instructions/languages/INSTRUCTIONS-CDK.md b/.github/instructions/languages/cdk.instructions.md similarity index 91% rename from .github/instructions/languages/INSTRUCTIONS-CDK.md rename to .github/instructions/languages/cdk.instructions.md index cbff4e5a..b441a02f 100644 --- a/.github/instructions/languages/INSTRUCTIONS-CDK.md +++ b/.github/instructions/languages/cdk.instructions.md @@ -3,6 +3,8 @@ description: 'Guidelines for writing, reviewing, and maintaining AWS CDK (TypeSc applyTo: 'packages/cdk/**/*.ts' --- +This file is mastered in https://github.com/NHSDigital/eps-copilot-instructions and is automatically synced to all EPS repositories. To suggest changes, please open an issue or pull request in the eps-copilot-instructions repository. + # AWS CDK TypeScript Development This file provides instructions for generating, reviewing, and maintaining AWS CDK code in the `packages/cdk` folder. It covers best practices, code standards, architecture, and validation for infrastructure-as-code using AWS CDK in TypeScript. @@ -90,7 +92,7 @@ export class CptsApiAppStack extends Stack { ## Validation and Verification - Build: `make cdk-synth` -- Lint: `npm run lint --workspace packges/cdk` +- Lint: `npm run lint --workspace packages/cdk` ## Maintenance diff --git a/.github/instructions/languages/cloudformation.instructions.md b/.github/instructions/languages/cloudformation.instructions.md new file mode 100644 index 00000000..5d2802be --- /dev/null +++ b/.github/instructions/languages/cloudformation.instructions.md @@ -0,0 +1,110 @@ +--- +description: 'Guidelines for writing, reviewing, and maintaining cloudformation templates' +applyTo: 'cloudformation/**' +--- + +This file is mastered in https://github.com/NHSDigital/eps-copilot-instructions and is automatically synced to all EPS repositories. To suggest changes, please open an issue or pull request in the eps-copilot-instructions repository. + +## General +- Prefer YAML (not JSON). Follow existing style in [cloudformation/account_resources.yml](cloudformation/account_resources.yml), [cloudformation/ci_resources.yml](cloudformation/ci_resources.yml), [cloudformation/artillery_resources.yml](cloudformation/artillery_resources.yml), [cloudformation/account_resources_bootstrap.yml](cloudformation/account_resources_bootstrap.yml), [cloudformation/management.yml](cloudformation/management.yml). +- Always start with `AWSTemplateFormatVersion: "2010-09-09"`. +- Keep descriptions concise (> operator used only for multi‑line). +- Use logical region `eu-west-2` unless cross‑region behavior explicitly required. +- Maintain tagging pattern: version, stack, repo, cfnDriftDetectionGroup (see deployment scripts in [.github/scripts/release_code.sh](.github/scripts/release_code.sh) and [.github/scripts/create_changeset_existing_tags.sh](.github/scripts/create_changeset_existing_tags.sh)). + +## Parameters +- Reuse and align parameter naming with existing templates: `LogRetentionDays`, `Env`, `SplunkHECEndpoint`, `DeployDriftDetection`. +- For numeric retention days replicate allowed values list from [SAMtemplates/lambda_resources.yaml](SAMtemplates/lambda_resources.yaml) or [cloudformation/account_resources.yml](cloudformation/account_resources.yml). +- Use `CommaDelimitedList` for OIDC subject claim filters like in [cloudformation/ci_resources.yml](cloudformation/ci_resources.yml). + +## Conditions +- Follow pattern `ShouldDeployDriftDetection` (see [SAMtemplates/lambda_resources.yaml](SAMtemplates/lambda_resources.yaml)); avoid ad‑hoc condition names. +- If creating a never-used placeholder stack use pattern from [cloudformation/empty_stack.yml](cloudformation/empty_stack.yml). + +## IAM Policies +- Split large CloudFormation execution permissions across multiple managed policies (A, B, C, D) to keep each rendered size < 6144 chars (see check logic in [scripts/check_policy_length.py](scripts/check_policy_length.py)). +- Scope resources minimally; prefer specific ARNs (e.g. logs, KMS aliases) as in [cloudformation/account_resources.yml](cloudformation/account_resources.yml). +- When granting CloudFormation execution access: separate IAM‑focused policy (`GrantCloudFormationExecutionAccessIAMPolicy`) from broad service policies. +- Use exports for policy ARNs with naming `ci-resources:GrantCloudFormationExecutionAccessPolicyA` pattern. + +## KMS +- Alias naming: `alias/CloudwatchLogsKmsKeyAlias`, `alias/SecretsKMSKeyAlias`, `alias/ArtifactsBucketKMSKeyAlias` (see [cloudformation/account_resources.yml](cloudformation/account_resources.yml), [cloudformation/account_resources_bootstrap.yml](cloudformation/account_resources_bootstrap.yml)). +- Grant encrypt/decrypt explicitly for principals (e.g. API Gateway, Lambda) mirroring key policy blocks in [cloudformation/account_resources.yml](cloudformation/account_resources.yml). + +## Secrets / Parameters +- SecretsManager resources must depend on alias if needed (`DependsOn: SecretsKMSKeyKMSKeyAlias`) like in [cloudformation/account_resources_bootstrap.yml](cloudformation/account_resources_bootstrap.yml). +- Export secret IDs (not ARNs unless specifically required) using colon-separated naming with stack name (pattern in outputs section of account templates). +- Default placeholder value `ChangeMe` for bootstrap secrets. + +## S3 Buckets +- Apply `PublicAccessBlockConfiguration` and encryption blocks consistent with [cloudformation/account_resources.yml](cloudformation/account_resources.yml). +- Suppress guard rules using `Metadata.guard.SuppressedRules` where legacy exceptions exist (e.g. replication / logging) matching existing patterns. + +## Lambda / SAM +- Shared lambda resources belong in SAM template ([SAMtemplates/lambda_resources.yaml](SAMtemplates/lambda_resources.yaml)); CloudFormation templates should not duplicate build-specific metadata. +- Suppress cfn-guard rules where justified via `Metadata.guard.SuppressedRules` (e.g. `LAMBDA_INSIDE_VPC`, `LAMBDA_CONCURRENCY_CHECK`) only if precedent exists. + +## Exports & Cross Stack +- Output export naming pattern: `!Join [":", [!Ref "AWS::StackName", "ResourceLogicalName"]]`. +- Reference exports via `!ImportValue stack-name:ExportName` (see Proxygen role usage in [SAMtemplates/lambda_resources.yaml](SAMtemplates/lambda_resources.yaml)). +- Avoid changing existing export names (breaking downstream stacks and scripts). + +## OIDC / Roles +- Federated trust for GitHub actions must use conditions: + - `token.actions.githubusercontent.com:aud: sts.amazonaws.com` + - `ForAnyValue:StringLike token.actions.githubusercontent.com:sub: ` + (pattern in roles inside [cloudformation/ci_resources.yml](cloudformation/ci_resources.yml)). +- When adding a new OIDC role add matching parameter `ClaimFilters` and outputs `` and `Name`. + +## Drift Detection +- Tag stacks with `cfnDriftDetectionGroup` (deployment scripts handle this). Config rules should filter on `TagKey: cfnDriftDetectionGroup` and specific `TagValue` (patterns in [SAMtemplates/lambda_resources.yaml](SAMtemplates/lambda_resources.yaml)). +- Avoid duplicating rule identifiers; follow `${AWS::StackName}-CloudFormationDriftDetector-`. + +## Route53 +- Environment hosted zones template ([cloudformation/eps_environment_route53.yml](cloudformation/eps_environment_route53.yml)) uses parameter `environment`; management template updates NS records referencing environment zones. + +## Style / Lint / Guard +- Keep resources grouped with `#region` / `#endregion` comments as in existing templates for readability. +- Use `Metadata.cfn-lint.config.ignore_checks` only when upstream spec mismatch (example: W3037 in large policy templates). +- Ensure new templates pass `make lint-cloudformation` and `make cfn-guard` (scripts: [scripts/run_cfn_guard.sh](scripts/run_cfn_guard.sh)). + +## Naming Conventions +- Logical IDs: PascalCase (`ArtifactsBucketKMSKey`, `CloudFormationDeployRole`). +- Managed policy logical IDs end with `Policy` or `ManagedPolicy`. +- KMS Key alias logical IDs end with `Alias` (e.g. `CloudwatchLogsKmsKeyAlias`). +- Secrets logical IDs end with `Secret`. + +## Security +- Block public access for all buckets unless explicitly required. +- Encrypt logs with KMS key; provide alias export (see `CloudwatchLogsKmsKeyAlias`). +- Limit wildcard `Resource: "*"` where service requires (e.g. some IAM, CloudFormation actions). Prefer service/resource ARNs otherwise. + +## When Adding New Resource Types +- Update execution policies in [cloudformation/ci_resources.yml](cloudformation/ci_resources.yml) minimally; do not expand existing broad statements unnecessarily. +- Run policy length check (`make test` invokes [scripts/check_policy_length.py](scripts/check_policy_length.py)) after modifications. + +## Do Not +- Do not hardcode account IDs; use `${AWS::AccountId}`. +- Do not remove existing exports or rename keys. +- Do not inline large policy statements in a single managed policy if size risk exists. + +## Examples +- IAM Role with OIDC trust: replicate structure from `CloudFormationDeployRole` in [cloudformation/ci_resources.yml](cloudformation/ci_resources.yml). +- KMS key + alias + usage policy: follow `ArtifactsBucketKMSKey` block in [cloudformation/account_resources.yml](cloudformation/account_resources.yml). + +## Testing +- After changes: run `make lint-cloudformation` and `make cfn-guard`. +- For SAM-related cross-stack exports ensure `sam build` (see [Makefile](Makefile)) passes. + +## Automation Awareness +- Deployment scripts expect unchanged parameter names & export patterns (see [.github/scripts/execute_changeset.sh](.github/scripts/execute_changeset.sh), [.github/scripts/release_code.sh](.github/scripts/release_code.sh)). +- Changes to tagging keys must be reflected in release / changeset scripts; avoid unless necessary. + +## Preferred Patterns Summary +- Exports: colon join +- Tags: version, stack, repo, cfnDriftDetectionGroup +- Conditions: prefixed with `Should` +- Claim filter parameters: `ClaimFilters` +- Secrets: depend on KMS alias, default `ChangeMe` + +Use these rules to guide completions for any new or modified CloudFormation template in this repository. diff --git a/.github/instructions/languages/python.instructions.md b/.github/instructions/languages/python.instructions.md new file mode 100644 index 00000000..8a38f76d --- /dev/null +++ b/.github/instructions/languages/python.instructions.md @@ -0,0 +1,93 @@ +--- +description: 'Guidelines for writing high-quality, maintainable python code with best practices for logging, error handling, code organization, naming, formatting, and style.' +applyTo: '**/*.py' +--- + +This file is mastered in https://github.com/NHSDigital/eps-copilot-instructions and is automatically synced to all EPS repositories. To suggest changes, please open an issue or pull request in the eps-copilot-instructions repository. + +# Python Copilot Instructions + +These instructions are designed to guide GitHub Copilot in generating effective, maintainable, and domain-appropriate Python code. They are intended to be generic and applicable to a wide range of Python projects. + +## 1. Code Organization & Structure +- Organize code into logical modules and packages. Use directories such as `core/`, `services/`, `utils/` for separation of concerns. +- Place entry points (e.g., `handler.py`) at the top level of the main package. +- Use `__init__.py` files to define package boundaries and expose public APIs. +- Group related functions and classes together. Avoid large monolithic files. +- Store tests in a dedicated `tests/` directory, mirroring the structure of the main codebase. + +## 2. Naming Conventions +- Use `snake_case` for function and variable names. +- Use `PascalCase` for class names. +- Prefix private functions and variables with a single underscore (`_`). +- Name modules and packages using short, descriptive, lowercase names. +- Use clear, descriptive names for all symbols. Avoid abbreviations unless they are widely understood. + +## 3. Formatting & Style +- Follow [PEP 8](https://peps.python.org/pep-0008/) for code style and formatting. +- Use 4 spaces per indentation level. Do not use tabs. +- Limit lines to 120 characters. +- Use blank lines to separate functions, classes, and logical sections. +- Place imports at the top of each file, grouped by standard library, third-party, and local imports. +- Use single quotes for strings unless double quotes are required. +- Add docstrings to all public modules, classes, and functions. Use triple double quotes for docstrings. + +## 4. Logging Best Practices +- Use the standard `logging` library for all logging. +- Configure logging in the main entry point or via a dedicated utility module. +- Use appropriate log levels: `debug`, `info`, `warning`, `error`, `critical`. +- Avoid logging sensitive information. +- Include contextual information in log messages (e.g., function names, parameters, error details). +- Example: + ```python + import logging + logger = logging.getLogger(__name__) + logger.info('Processing event: %s', event) + ``` + +## 5. Error Handling Best Practices +- Use `try`/`except` blocks to handle exceptions gracefully. +- Catch specific exceptions rather than using bare `except`. +- Log exceptions with stack traces using `logger.exception()`. +- Raise custom exceptions for domain-specific errors. +- Validate inputs and fail fast with clear error messages. +- Example: + ```python + try: + result = process_event(event) + except ValueError as e: + logger.error('Invalid event: %s', e) + raise + ``` + +## 6. Testing Guidelines +- Write unit tests for all public functions and classes. +- Use `pytest` as the preferred testing framework. +- Name test files and functions using `test_` prefix. +- Use fixtures for setup and teardown. +- Mock external dependencies in tests. +- Ensure tests are isolated and repeatable. + +## 7. Dependency Management +- Use `pyproject.toml` to specify dependencies. +- Never use `requirements.txt` to specify dependencies. +- Pin versions for critical dependencies. +- Avoid unnecessary dependencies. + +## 8. Documentation +- Document all public APIs with clear docstrings. +- Use [Google](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) or [NumPy](https://numpydoc.readthedocs.io/en/latest/format.html) style for docstrings. +- Provide usage examples in README files. + +## 9. Security & Privacy +- Do not log or expose secrets, credentials, or sensitive data. +- Validate and sanitize all external inputs. +- Use environment variables for configuration secrets. + +## 10. General Guidelines +- Prefer readability and simplicity over cleverness. +- Refactor duplicated code into reusable functions or classes. +- Use type hints for function signatures and variables where appropriate. +- Avoid global variables; use function arguments or class attributes. + +--- diff --git a/.github/instructions/languages/sam.instructions.md b/.github/instructions/languages/sam.instructions.md new file mode 100644 index 00000000..4bb4788f --- /dev/null +++ b/.github/instructions/languages/sam.instructions.md @@ -0,0 +1,201 @@ +--- +description: 'Guidelines for writing, reviewing, and maintaining SAM templates' +applyTo: 'SAMtemplates/**' +--- + +This file is mastered in https://github.com/NHSDigital/eps-copilot-instructions and is automatically synced to all EPS repositories. To suggest changes, please open an issue or pull request in the eps-copilot-instructions repository. + +## Scope +These instructions apply exclusively to files located under the `SAMtemplates` directory. Ensure that any SAM templates or related configurations outside this directory are not governed by these guidelines. + +## Project Context +This is a healthcare API service deployed using AWS SAM (Serverless Application Model) with a modular template structure. The service includes Lambda functions, API Gateway, Step Functions state machines, and associated AWS resources. + +## Template Structure and Conventions + +### File Organization +- `main_template.yaml` - Root template that orchestrates all components +- `functions/main.yaml` - Lambda functions and layers +- `apis/main.yaml` - API Gateway and domain configuration +- `state_machines/main.yaml` - Step Functions state machines +- `parameters/main.yaml` - SSM parameters and policies +- `*_resources.yaml` - Reusable resource templates for IAM roles, policies, and logging + +### Naming Conventions +- Stack resources: Use `!Sub ${StackName}-` pattern +- Functions: `${StackName}-` (e.g., `${StackName}-GetMyPrescriptions`) +- Parameters: Environment-specific with validation (dev, dev-pr, qa, int, prod, ref) +- IAM roles: Follow AWS service naming conventions with descriptive suffixes + +### Standard Parameters +Always include these common parameters in templates: +```yaml +Parameters: + StackName: + Type: String + Default: none + Env: + Type: String + Default: dev + AllowedValues: [dev, dev-pr, qa, int, prod, ref] + + LogRetentionInDays: + Type: Number + Default: 30 + AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653] + + EnableSplunk: + Type: String + Default: false + AllowedValues: [true, false] +``` + +### Lambda Function + +The runtime should match the nodejs version in .tool-versions file +The LambdaInsightsExtension version should match the latest available version available in eu-west-2 region + +#### Global Configuration +```yaml +Globals: + Function: + Timeout: 50 + MemorySize: 256 + Architectures: [x86_64] + Runtime: nodejs22.x + Environment: + Variables: + STACK_NAME: !Ref StackName + NODE_OPTIONS: "--enable-source-maps" + Layers: + - !Sub arn:aws:lambda:${AWS::Region}:580247275435:layer:LambdaInsightsExtension:52 +``` + +#### Lambda Function Template +```yaml +: + Type: AWS::Serverless::Function + Properties: + FunctionName: !Sub ${StackName}- + CodeUri: ../../packages + Handler: .handler + Role: !GetAtt Resources.Outputs.LambdaRoleArn + Environment: + Variables: + LOG_LEVEL: !Ref LogLevel + DEPLOYMENT_ENVIRONMENT: !Ref Env + Metadata: + BuildMethod: esbuild + guard: + SuppressedRules: + - LAMBDA_DLQ_CHECK + - LAMBDA_INSIDE_VPC +``` + +### API Gateway Patterns + +#### REST API Configuration +```yaml +RestApiGateway: + Type: AWS::ApiGateway::RestApi + Properties: + Name: !Sub ${StackName}-apigw + DisableExecuteApiEndpoint: !If [ShouldUseMutualTLS, true, !Ref AWS::NoValue] + EndpointConfiguration: + Types: [REGIONAL] + +RestApiDomain: + Type: AWS::ApiGateway::DomainName + Properties: + DomainName: !Join ['.', [!Ref StackName, !ImportValue eps-route53-resources:EPS-domain]] + RegionalCertificateArn: !Ref GenerateCertificate + EndpointConfiguration: + Types: [REGIONAL] + SecurityPolicy: TLS_1_2 +``` + +### State Machine Patterns +```yaml +: + Type: AWS::Serverless::StateMachine + Properties: + Name: !Sub ${StackName}- + Type: EXPRESS + Role: !GetAtt Resources.Outputs.StateMachineRoleArn + DefinitionUri: .asl.json + DefinitionSubstitutions: + Arn: !Sub ${Arn}:$LATEST +``` + +### Security and Compliance + +#### Mutual TLS Support +Use conditions for optional mTLS: +```yaml +Conditions: + ShouldUseMutualTLS: !Equals [true, !Ref EnableMutualTLS] + +# In resource properties: +MutualTlsAuthentication: + TruststoreUri: !If [ShouldUseMutualTLS, !Sub 's3://${TruststoreFile}', !Ref AWS::NoValue] +``` + +#### IAM Policies +- Use managed policies from separate resource templates +- Import cross-stack values: `!ImportValue account-resources:SpinePrivateKey` +- Follow principle of least privilege +- Include guard rules suppression only where necessary. By default these should not be added. If they are added an explanation should be included to say why we are overriding them + +### Environment Variables and Secrets +```yaml +Environment: + Variables: + STACK_NAME: !Ref StackName + DEPLOYMENT_ENVIRONMENT: !Ref Env + # Spine integration + TargetSpineServer: !Ref TargetSpineServer + SpinePrivateKeyARN: !ImportValue account-resources:SpinePrivateKey + SpinePublicCertificateARN: !ImportValue account-resources:SpinePublicCertificate + # Service search + TargetServiceSearchServer: !Ref TargetServiceSearchServer + ServiceSearchApiKeyARN: !ImportValue account-resources:ServiceSearchApiKey +``` + +### Logging Configuration +```yaml +# CloudWatch Log Groups +LogGroup: + Type: AWS::Logs::LogGroup + Properties: + LogGroupName: !Sub /aws/lambda/${StackName}- + RetentionInDays: !Ref LogRetentionInDays + KmsKeyId: !If [ShouldUseKMS, !Ref CloudWatchKMSKeyId, !Ref AWS::NoValue] + +# Splunk integration (conditional) +SubscriptionFilter: + Type: AWS::Logs::SubscriptionFilter + Properties: + LogGroupName: !Ref LogGroup + FilterPattern: "" + DestinationArn: !Ref SplunkDeliveryStreamArn + RoleArn: !Ref SplunkSubscriptionFilterRole +``` + +### Best Practices + +1. **Modular Design**: Split templates by service domain (functions, apis, state_machines) +2. **Parameter Validation**: Use AllowedValues for environment-specific parameters +3. **Cross-Stack References**: Use ImportValue for shared resources +4. **Conditional Resources**: Use conditions for environment-specific resources +5. **Resource Naming**: Consistent naming with stack prefix +6. **Documentation**: Include meaningful descriptions for all resources +7. **Guard Rules**: Suppress only when necessary and document reasons +8. **Build Methods**: Use esbuild for Node.js Lambda functions +9. **Version Pinning**: Pin Lambda layer versions and runtimes + +### Common Import Values +- `eps-route53-resources:EPS-domain` +- `eps-route53-resources:EPS-ZoneID` + + +When generating CloudFormation/SAM templates, follow these patterns and ensure compliance with NHS Digital standards and AWS security best practices. diff --git a/.github/instructions/languages/terraform.instructions.md b/.github/instructions/languages/terraform.instructions.md new file mode 100644 index 00000000..62830c86 --- /dev/null +++ b/.github/instructions/languages/terraform.instructions.md @@ -0,0 +1,147 @@ +--- +description: 'Comprehensive guidelines for writing, organizing, and maintaining Terraform code in this repository.' +applyTo: 'terraform/**/*.tf' +--- + +This file is mastered in https://github.com/NHSDigital/eps-copilot-instructions and is automatically synced to all EPS repositories. To suggest changes, please open an issue or pull request in the eps-copilot-instructions repository. + +# Terraform Development Guidelines + +This document provides best practices and conventions for writing, organizing, and maintaining Terraform code. It is intended for use by developers and GitHub Copilot to ensure consistency, reliability, and maintainability across all Terraform files in the project. + +## General Instructions + +- Use Terraform modules to promote code reuse and separation of concerns. +- Keep resource definitions declarative and avoid imperative logic. +- Store environment-specific configuration in separate files (e.g., `env/` folders). +- Use variables and outputs to parameterize and expose configuration. +- Document resources, modules, and variables with comments. +- Prefer explicit resource dependencies using `depends_on` when needed. +- Use remote state for shared resources and outputs. + +## Best Practices + +- Group related resources in logical subfolders (e.g., `archive/`, `backup-source/`). +- Use `locals` for computed values and to reduce repetition. +- Use data sources to reference existing infrastructure. +- Avoid hardcoding values; use variables and environment files. +- Use `terraform fmt` to enforce consistent formatting. +- Use `terraform validate` and `terraform plan` before applying changes. +- Use `Makefile` targets for common operations (init, plan, apply, destroy). +- Store secrets and sensitive values in secure locations (e.g., AWS SSM, environment variables), not in code. +- Use resource tags for traceability and cost management. +- Prefer resource names that include environment and purpose (e.g., `archive_prod_bucket`). + +## Code Standards + +### Naming Conventions + +- Use snake_case for resource, variable, and output names. +- Prefix resource names with their type and purpose (e.g., `s3_archive_bucket`). +- Use clear, descriptive names for modules and files. +- Use consistent naming for environments (e.g., `dev`, `prod`, `test`). + +### File Organization + +- Place each environment's configuration in its own file under `env/`. +- Use a `variables.tf` file for input variables. +- Use an `outputs.tf` file for outputs. +- Use a `locals.tf` file for local values. +- Use a `provider.tf` file for provider configuration. +- Use a `Makefile` for automation and common tasks. +- Organize resources by domain (e.g., `archive/`, `infra/`, `storage/`). + +## Common Patterns + +### Using Variables + +```hcl +variable "bucket_name" { + description = "Name of the S3 bucket" + type = string +} + +resource "aws_s3_bucket" "archive" { + bucket = var.bucket_name + ... +} +``` + +### Using Locals + +```hcl +locals { + tags = { + Environment = var.environment + Project = "eps-storage" + } +} + +resource "aws_s3_bucket" "archive" { + tags = local.tags + ... +} +``` + +### Good Example - Using Modules + +```hcl +module "archive" { + source = "../modules/aws-archive" + environment = var.environment + ... +} +``` + +### Bad Example - Hardcoding Values + +```hcl +resource "aws_s3_bucket" "archive" { + bucket = "my-hardcoded-bucket-name" + ... +} +``` + +## Security + +- Never commit secrets or credentials to version control. +- Use IAM roles and policies with least privilege. +- Enable encryption for all supported resources (e.g., S3, KMS, DynamoDB). +- Use secure remote state backends (e.g., S3 with encryption and locking). +- Validate input variables for expected values and types. + +## Performance + +- Use resource lifecycle rules to manage retention and cleanup. +- Use data sources to avoid duplicating resources. +- Minimize resource drift by keeping code and infrastructure in sync. +- Use `terraform plan` to preview changes and avoid unnecessary updates. + +## Testing + +- Use `terraform validate` to check syntax and configuration. +- Use `terraform plan` to preview changes before applying. +- Use `tfsec` for static security analysis (`tfsec.yml` config). +- Use automated CI/CD pipelines for deployment and testing. + +## Validation and Verification + +- Format code: `terraform fmt` (run in each Terraform folder) +- Validate code: `terraform validate` +- Security scan: `tfsec .` +- Plan changes: `terraform plan -var-file=env/dev.tfvars.json` +- Apply changes: `terraform apply -var-file=env/dev.tfvars.json` + +## Maintenance + +- Review and update modules and dependencies regularly. +- Remove unused resources and variables. +- Update environment files as infrastructure evolves. +- Keep documentation up to date. +- Refactor code to improve readability and maintainability. + +## Additional Resources + +- [Terraform Documentation](https://www.terraform.io/docs) +- [Terraform AWS Provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) +- [tfsec Security Scanner](https://tfsec.dev/) diff --git a/.github/instructions/languages/INSTRUCTIONS-TYPESCRIPT.md b/.github/instructions/languages/typescript.instructions.md similarity index 95% rename from .github/instructions/languages/INSTRUCTIONS-TYPESCRIPT.md rename to .github/instructions/languages/typescript.instructions.md index 87502466..4c15f421 100644 --- a/.github/instructions/languages/INSTRUCTIONS-TYPESCRIPT.md +++ b/.github/instructions/languages/typescript.instructions.md @@ -1,8 +1,10 @@ --- description: 'Guidelines for writing high-quality, maintainable TypeScript code with best practices for logging, error handling, code organization, naming, formatting, and style.' -applyTo: '**/*.ts, **/*.tsx' +applyTo: '**/*.{ts,tsx}' --- +This file is mastered in https://github.com/NHSDigital/eps-copilot-instructions and is automatically synced to all EPS repositories. To suggest changes, please open an issue or pull request in the eps-copilot-instructions repository. + # TypeScript Development Guidelines This document provides instructions for generating, reviewing, and maintaining TypeScript code. It is designed to guide Copilot and developers in producing domain-specific, robust, and maintainable code across a variety of TypeScript projects. diff --git a/.github/prompts/code_review.prompt.md b/.github/prompts/code_review.prompt.md new file mode 100644 index 00000000..d63bcf2e --- /dev/null +++ b/.github/prompts/code_review.prompt.md @@ -0,0 +1,61 @@ +--- +description: "Perform a comprehensive code review" +--- + +This file is mastered in https://github.com/NHSDigital/eps-copilot-instructions and is automatically synced to all EPS repositories. To suggest changes, please open an issue or pull request in the eps-copilot-instructions repository. + +## Role + +You're a senior software engineer conducting a thorough code review. Provide constructive, actionable feedback. + +## Review Areas + +Analyze the selected code for: + +1. **Security Issues** + - Input validation and sanitization + - Authentication and authorization + - Data exposure risks + - Injection vulnerabilities + +2. **Performance & Efficiency** + - Algorithm complexity + - Memory usage patterns + - Database query optimization + - Unnecessary computations + +3. **Code Quality** + - Readability and maintainability + - Proper naming conventions + - Function/class size and responsibility + - Code duplication + +4. **Architecture & Design** + - Design pattern usage + - Separation of concerns + - Dependency management + - Error handling strategy + +5. **Testing & Documentation** + - Test coverage and quality + - Documentation completeness + - Comment clarity and necessity + +## Output Format + +Provide feedback as: + +**🔴 Critical Issues** - Must fix before merge +**🟡 Suggestions** - Improvements to consider +**✅ Good Practices** - What's done well + +For each issue: + +- Specific line references +- Clear explanation of the problem +- Suggested solution with code example +- Rationale for the change + +Focus on: ${input:focus:Any specific areas to emphasize in the review?} + +Be constructive and educational in your feedback.