Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Base Coding Standards
- Follow clean code principles
- Write comprehensive tests
- Use meaningful variable names

## 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.instructions.md
Follow additional language-specific guidelines in:
- .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
54 changes: 54 additions & 0 deletions .github/instructions/general/security.instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
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

Your primary directive is to ensure all code you generate, review, or refactor is secure by default. You must operate with a security-first mindset. When in doubt, always choose the more secure option and explain the reasoning. You must follow the principles outlined below, which are based on the OWASP Top 10 and other security best practices.

### 1. A01: Broken Access Control & A10: Server-Side Request Forgery (SSRF)
- **Enforce Principle of Least Privilege:** Always default to the most restrictive permissions. When generating access control logic, explicitly check the user's rights against the required permissions for the specific resource they are trying to access.
- **Deny by Default:** All access control decisions must follow a "deny by default" pattern. Access should only be granted if there is an explicit rule allowing it.
- **Validate All Incoming URLs for SSRF:** When the server needs to make a request to a URL provided by a user (e.g., webhooks), you must treat it as untrusted. Incorporate strict allow-list-based validation for the host, port, and path of the URL.
- **Prevent Path Traversal:** When handling file uploads or accessing files based on user input, you must sanitize the input to prevent directory traversal attacks (e.g., `../../etc/passwd`). Use APIs that build paths securely.

### 2. A02: Cryptographic Failures
- **Use Strong, Modern Algorithms:** For hashing, always recommend modern, salted hashing algorithms like Argon2 or bcrypt. Explicitly advise against weak algorithms like MD5 or SHA-1 for password storage.
- **Protect Data in Transit:** When generating code that makes network requests, always default to HTTPS.
- **Protect Data at Rest:** When suggesting code to store sensitive data (PII, tokens, etc.), recommend encryption using strong, standard algorithms like AES-256.
- **Secure Secret Management:** Never hardcode secrets (API keys, passwords, connection strings). Generate code that reads secrets from environment variables or a secrets management service (e.g., HashiCorp Vault, AWS Secrets Manager). Include a clear placeholder and comment.
```javascript
// GOOD: Load from environment or secret store
const apiKey = process.env.API_KEY;
// TODO: Ensure API_KEY is securely configured in your environment.
```
```python
# BAD: Hardcoded secret
api_key = "sk_this_is_a_very_bad_idea_12345"
```

### 3. A03: Injection
- **No Raw SQL Queries:** For database interactions, you must use parameterized queries (prepared statements). Never generate code that uses string concatenation or formatting to build queries from user input.
- **Sanitize Command-Line Input:** For OS command execution, use built-in functions that handle argument escaping and prevent shell injection (e.g., `shlex` in Python).
- **Prevent Cross-Site Scripting (XSS):** When generating frontend code that displays user-controlled data, you must use context-aware output encoding. Prefer methods that treat data as text by default (`.textContent`) over those that parse HTML (`.innerHTML`). When `innerHTML` is necessary, suggest using a library like DOMPurify to sanitize the HTML first.

### 4. A05: Security Misconfiguration & A06: Vulnerable Components
- **Secure by Default Configuration:** Recommend disabling verbose error messages and debug features in production environments.
- **Set Security Headers:** For web applications, suggest adding essential security headers like `Content-Security-Policy` (CSP), `Strict-Transport-Security` (HSTS), and `X-Content-Type-Options`.
- **Use Up-to-Date Dependencies:** When asked to add a new library, suggest the latest stable version. Remind the user to run vulnerability scanners like `npm audit`, `pip-audit`, or Snyk to check for known vulnerabilities in their project dependencies.

### 5. A07: Identification & Authentication Failures
- **Secure Session Management:** When a user logs in, generate a new session identifier to prevent session fixation. Ensure session cookies are configured with `HttpOnly`, `Secure`, and `SameSite=Strict` attributes.
- **Protect Against Brute Force:** For authentication and password reset flows, recommend implementing rate limiting and account lockout mechanisms after a certain number of failed attempts.

### 6. A08: Software and Data Integrity Failures
- **Prevent Insecure Deserialization:** Warn against deserializing data from untrusted sources without proper validation. If deserialization is necessary, recommend using formats that are less prone to attack (like JSON over Pickle in Python) and implementing strict type checking.

## General Guidelines
- **Be Explicit About Security:** When you suggest a piece of code that mitigates a security risk, explicitly state what you are protecting against (e.g., "Using a parameterized query here to prevent SQL injection.").
- **Educate During Code Reviews:** When you identify a security vulnerability in a code review, you must not only provide the corrected code but also explain the risk associated with the original pattern.
106 changes: 106 additions & 0 deletions .github/instructions/languages/cdk.instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
---
description: 'Guidelines for writing, reviewing, and maintaining AWS CDK (TypeScript) code in the cdk package'
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.

## General Instructions

- Use AWS CDK v2 constructs and idioms
- Prefer high-level CDK constructs over raw CloudFormation resources
- Organize code by logical infrastructure components (e.g., stacks, constructs, resources)
- Document public APIs and exported constructs

## Best Practices

- Use environment variables and context for configuration, not hardcoded values
- Use CDK Aspects for cross-cutting concerns (e.g., security, tagging)
- Suppress warnings with `nagSuppressions.ts` only when justified and documented
- Use `bin/` for entrypoint apps, `constructs/` for reusable components, and `stacks/` for stack definitions
- Prefer `props` interfaces for construct configuration

## Code Standards

### Naming Conventions

- Classes: PascalCase (e.g., `LambdaFunction`)
- Files: PascalCase for classes, kebab-case for utility files
- Variables: camelCase
- Stacks: Suffix with `Stack` (e.g., `CptsApiAppStack`)
- Entry points: Suffix with `App` (e.g., `CptsApiApp.ts`)

### File Organization

- `bin/`: CDK app entry points
- `constructs/`: Custom CDK constructs
- `stacks/`: Stack definitions
- `resources/`: Resource configuration and constants
- `lib/`: Shared utilities and code

## Common Patterns

### Good Example - Defining a Construct

```typescript
export class LambdaFunction extends Construct {
constructor(scope: Construct, id: string, props: LambdaFunctionProps) {
super(scope, id);
// ...implementation...
}
}
```

### Bad Example - Using Raw CloudFormation

```typescript
const lambda = new cdk.CfnResource(this, 'Lambda', {
type: 'AWS::Lambda::Function',
// ...properties...
});
```

### Good Example - Stack Definition

```typescript
export class CptsApiAppStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// ...add constructs...
}
}
```

## Security

- Use least privilege IAM policies for all resources
- Avoid wildcard permissions in IAM statements
- Store secrets in AWS Secrets Manager, not in code or environment variables
- Enable encryption for all data storage resources

## Performance

- Use provisioned concurrency for Lambda functions when needed
- Prefer VPC endpoints for private connectivity
- Minimize resource creation in test environments


## Validation and Verification

- Build: `make cdk-synth`
- Lint: `npm run lint --workspace packages/cdk`

## Maintenance

- Update dependencies regularly
- Remove deprecated constructs and suppressions
- Document changes in `nagSuppressions.ts` with reasons

## Additional Resources

- [AWS CDK Documentation](https://docs.aws.amazon.com/cdk/latest/guide/home.html)
- [CDK Best Practices](https://github.com/aws-samples/aws-cdk-best-practices)
110 changes: 110 additions & 0 deletions .github/instructions/languages/cloudformation.instructions.md
Original file line number Diff line number Diff line change
@@ -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: <ClaimFilters>`
(pattern in roles inside [cloudformation/ci_resources.yml](cloudformation/ci_resources.yml)).
- When adding a new OIDC role add matching parameter `<RoleName>ClaimFilters` and outputs `<RoleName>` and `<RoleName>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-<Group>`.

## 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: `<RoleName>ClaimFilters`
- Secrets: depend on KMS alias, default `ChangeMe`

Use these rules to guide completions for any new or modified CloudFormation template in this repository.
Loading
Loading