Skip to content

Commit 2b085e0

Browse files
Upgrade: [dependabot] - sync Copilot instructions (#492)
Syncing Copilot instructions from central repo. Ref: `main` Co-authored-by: eps-create-pull-request[bot] <270920461+eps-create-pull-request[bot]@users.noreply.github.com> Co-authored-by: anthony-nhs <121869075+anthony-nhs@users.noreply.github.com>
1 parent 4aa64c7 commit 2b085e0

File tree

9 files changed

+985
-0
lines changed

9 files changed

+985
-0
lines changed

.github/copilot-instructions.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Base Coding Standards
2+
- Follow clean code principles
3+
- Write comprehensive tests
4+
- Use meaningful variable names
5+
6+
## Project-Specific instructions
7+
Check the following files for any project-specific coding standards or guidelines:
8+
- .github/instructions/project/instructions.md
9+
- If no project-specific conventions are defined there, use the general and language-specific best practices referenced below.
10+
- 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.
11+
12+
## Language-Specific Instructions
13+
Always follow security best practices as outlined in:
14+
- .github/instructions/general/security.instructions.md
15+
Follow additional language-specific guidelines in:
16+
- .github/instructions/languages/cdk.instructions.md
17+
- .github/instructions/languages/cloudformation.instructions.md
18+
- .github/instructions/languages/python.instructions.md
19+
- .github/instructions/languages/terraform.instructions.md
20+
- .github/instructions/languages/sam.instructions.md
21+
- .github/instructions/languages/typescript.instructions.md
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
---
2+
applyTo: '**/*'
3+
description: "Comprehensive secure coding instructions for all languages and frameworks, based on OWASP Top 10 and industry best practices."
4+
---
5+
6+
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.
7+
8+
# Secure Coding and OWASP Guidelines
9+
10+
## Instructions
11+
12+
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.
13+
14+
### 1. A01: Broken Access Control & A10: Server-Side Request Forgery (SSRF)
15+
- **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.
16+
- **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.
17+
- **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.
18+
- **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.
19+
20+
### 2. A02: Cryptographic Failures
21+
- **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.
22+
- **Protect Data in Transit:** When generating code that makes network requests, always default to HTTPS.
23+
- **Protect Data at Rest:** When suggesting code to store sensitive data (PII, tokens, etc.), recommend encryption using strong, standard algorithms like AES-256.
24+
- **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.
25+
```javascript
26+
// GOOD: Load from environment or secret store
27+
const apiKey = process.env.API_KEY;
28+
// TODO: Ensure API_KEY is securely configured in your environment.
29+
```
30+
```python
31+
# BAD: Hardcoded secret
32+
api_key = "sk_this_is_a_very_bad_idea_12345"
33+
```
34+
35+
### 3. A03: Injection
36+
- **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.
37+
- **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).
38+
- **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.
39+
40+
### 4. A05: Security Misconfiguration & A06: Vulnerable Components
41+
- **Secure by Default Configuration:** Recommend disabling verbose error messages and debug features in production environments.
42+
- **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`.
43+
- **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.
44+
45+
### 5. A07: Identification & Authentication Failures
46+
- **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.
47+
- **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.
48+
49+
### 6. A08: Software and Data Integrity Failures
50+
- **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.
51+
52+
## General Guidelines
53+
- **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.").
54+
- **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.
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
---
2+
description: 'Guidelines for writing, reviewing, and maintaining AWS CDK (TypeScript) code in the cdk package'
3+
applyTo: 'packages/cdk/**/*.ts'
4+
---
5+
6+
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.
7+
8+
# AWS CDK TypeScript Development
9+
10+
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.
11+
12+
## General Instructions
13+
14+
- Use AWS CDK v2 constructs and idioms
15+
- Prefer high-level CDK constructs over raw CloudFormation resources
16+
- Organize code by logical infrastructure components (e.g., stacks, constructs, resources)
17+
- Document public APIs and exported constructs
18+
19+
## Best Practices
20+
21+
- Use environment variables and context for configuration, not hardcoded values
22+
- Use CDK Aspects for cross-cutting concerns (e.g., security, tagging)
23+
- Suppress warnings with `nagSuppressions.ts` only when justified and documented
24+
- Use `bin/` for entrypoint apps, `constructs/` for reusable components, and `stacks/` for stack definitions
25+
- Prefer `props` interfaces for construct configuration
26+
27+
## Code Standards
28+
29+
### Naming Conventions
30+
31+
- Classes: PascalCase (e.g., `LambdaFunction`)
32+
- Files: PascalCase for classes, kebab-case for utility files
33+
- Variables: camelCase
34+
- Stacks: Suffix with `Stack` (e.g., `CptsApiAppStack`)
35+
- Entry points: Suffix with `App` (e.g., `CptsApiApp.ts`)
36+
37+
### File Organization
38+
39+
- `bin/`: CDK app entry points
40+
- `constructs/`: Custom CDK constructs
41+
- `stacks/`: Stack definitions
42+
- `resources/`: Resource configuration and constants
43+
- `lib/`: Shared utilities and code
44+
45+
## Common Patterns
46+
47+
### Good Example - Defining a Construct
48+
49+
```typescript
50+
export class LambdaFunction extends Construct {
51+
constructor(scope: Construct, id: string, props: LambdaFunctionProps) {
52+
super(scope, id);
53+
// ...implementation...
54+
}
55+
}
56+
```
57+
58+
### Bad Example - Using Raw CloudFormation
59+
60+
```typescript
61+
const lambda = new cdk.CfnResource(this, 'Lambda', {
62+
type: 'AWS::Lambda::Function',
63+
// ...properties...
64+
});
65+
```
66+
67+
### Good Example - Stack Definition
68+
69+
```typescript
70+
export class CptsApiAppStack extends Stack {
71+
constructor(scope: Construct, id: string, props?: StackProps) {
72+
super(scope, id, props);
73+
// ...add constructs...
74+
}
75+
}
76+
```
77+
78+
## Security
79+
80+
- Use least privilege IAM policies for all resources
81+
- Avoid wildcard permissions in IAM statements
82+
- Store secrets in AWS Secrets Manager, not in code or environment variables
83+
- Enable encryption for all data storage resources
84+
85+
## Performance
86+
87+
- Use provisioned concurrency for Lambda functions when needed
88+
- Prefer VPC endpoints for private connectivity
89+
- Minimize resource creation in test environments
90+
91+
92+
## Validation and Verification
93+
94+
- Build: `make cdk-synth`
95+
- Lint: `npm run lint --workspace packages/cdk`
96+
97+
## Maintenance
98+
99+
- Update dependencies regularly
100+
- Remove deprecated constructs and suppressions
101+
- Document changes in `nagSuppressions.ts` with reasons
102+
103+
## Additional Resources
104+
105+
- [AWS CDK Documentation](https://docs.aws.amazon.com/cdk/latest/guide/home.html)
106+
- [CDK Best Practices](https://github.com/aws-samples/aws-cdk-best-practices)
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
---
2+
description: 'Guidelines for writing, reviewing, and maintaining cloudformation templates'
3+
applyTo: 'cloudformation/**'
4+
---
5+
6+
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.
7+
8+
## General
9+
- 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).
10+
- Always start with `AWSTemplateFormatVersion: "2010-09-09"`.
11+
- Keep descriptions concise (> operator used only for multi‑line).
12+
- Use logical region `eu-west-2` unless cross‑region behavior explicitly required.
13+
- 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)).
14+
15+
## Parameters
16+
- Reuse and align parameter naming with existing templates: `LogRetentionDays`, `Env`, `SplunkHECEndpoint`, `DeployDriftDetection`.
17+
- 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).
18+
- Use `CommaDelimitedList` for OIDC subject claim filters like in [cloudformation/ci_resources.yml](cloudformation/ci_resources.yml).
19+
20+
## Conditions
21+
- Follow pattern `ShouldDeployDriftDetection` (see [SAMtemplates/lambda_resources.yaml](SAMtemplates/lambda_resources.yaml)); avoid ad‑hoc condition names.
22+
- If creating a never-used placeholder stack use pattern from [cloudformation/empty_stack.yml](cloudformation/empty_stack.yml).
23+
24+
## IAM Policies
25+
- 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)).
26+
- Scope resources minimally; prefer specific ARNs (e.g. logs, KMS aliases) as in [cloudformation/account_resources.yml](cloudformation/account_resources.yml).
27+
- When granting CloudFormation execution access: separate IAM‑focused policy (`GrantCloudFormationExecutionAccessIAMPolicy`) from broad service policies.
28+
- Use exports for policy ARNs with naming `ci-resources:GrantCloudFormationExecutionAccessPolicyA` pattern.
29+
30+
## KMS
31+
- 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)).
32+
- Grant encrypt/decrypt explicitly for principals (e.g. API Gateway, Lambda) mirroring key policy blocks in [cloudformation/account_resources.yml](cloudformation/account_resources.yml).
33+
34+
## Secrets / Parameters
35+
- SecretsManager resources must depend on alias if needed (`DependsOn: SecretsKMSKeyKMSKeyAlias`) like in [cloudformation/account_resources_bootstrap.yml](cloudformation/account_resources_bootstrap.yml).
36+
- Export secret IDs (not ARNs unless specifically required) using colon-separated naming with stack name (pattern in outputs section of account templates).
37+
- Default placeholder value `ChangeMe` for bootstrap secrets.
38+
39+
## S3 Buckets
40+
- Apply `PublicAccessBlockConfiguration` and encryption blocks consistent with [cloudformation/account_resources.yml](cloudformation/account_resources.yml).
41+
- Suppress guard rules using `Metadata.guard.SuppressedRules` where legacy exceptions exist (e.g. replication / logging) matching existing patterns.
42+
43+
## Lambda / SAM
44+
- Shared lambda resources belong in SAM template ([SAMtemplates/lambda_resources.yaml](SAMtemplates/lambda_resources.yaml)); CloudFormation templates should not duplicate build-specific metadata.
45+
- Suppress cfn-guard rules where justified via `Metadata.guard.SuppressedRules` (e.g. `LAMBDA_INSIDE_VPC`, `LAMBDA_CONCURRENCY_CHECK`) only if precedent exists.
46+
47+
## Exports & Cross Stack
48+
- Output export naming pattern: `!Join [":", [!Ref "AWS::StackName", "ResourceLogicalName"]]`.
49+
- Reference exports via `!ImportValue stack-name:ExportName` (see Proxygen role usage in [SAMtemplates/lambda_resources.yaml](SAMtemplates/lambda_resources.yaml)).
50+
- Avoid changing existing export names (breaking downstream stacks and scripts).
51+
52+
## OIDC / Roles
53+
- Federated trust for GitHub actions must use conditions:
54+
- `token.actions.githubusercontent.com:aud: sts.amazonaws.com`
55+
- `ForAnyValue:StringLike token.actions.githubusercontent.com:sub: <ClaimFilters>`
56+
(pattern in roles inside [cloudformation/ci_resources.yml](cloudformation/ci_resources.yml)).
57+
- When adding a new OIDC role add matching parameter `<RoleName>ClaimFilters` and outputs `<RoleName>` and `<RoleName>Name`.
58+
59+
## Drift Detection
60+
- 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)).
61+
- Avoid duplicating rule identifiers; follow `${AWS::StackName}-CloudFormationDriftDetector-<Group>`.
62+
63+
## Route53
64+
- 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.
65+
66+
## Style / Lint / Guard
67+
- Keep resources grouped with `#region` / `#endregion` comments as in existing templates for readability.
68+
- Use `Metadata.cfn-lint.config.ignore_checks` only when upstream spec mismatch (example: W3037 in large policy templates).
69+
- Ensure new templates pass `make lint-cloudformation` and `make cfn-guard` (scripts: [scripts/run_cfn_guard.sh](scripts/run_cfn_guard.sh)).
70+
71+
## Naming Conventions
72+
- Logical IDs: PascalCase (`ArtifactsBucketKMSKey`, `CloudFormationDeployRole`).
73+
- Managed policy logical IDs end with `Policy` or `ManagedPolicy`.
74+
- KMS Key alias logical IDs end with `Alias` (e.g. `CloudwatchLogsKmsKeyAlias`).
75+
- Secrets logical IDs end with `Secret`.
76+
77+
## Security
78+
- Block public access for all buckets unless explicitly required.
79+
- Encrypt logs with KMS key; provide alias export (see `CloudwatchLogsKmsKeyAlias`).
80+
- Limit wildcard `Resource: "*"` where service requires (e.g. some IAM, CloudFormation actions). Prefer service/resource ARNs otherwise.
81+
82+
## When Adding New Resource Types
83+
- Update execution policies in [cloudformation/ci_resources.yml](cloudformation/ci_resources.yml) minimally; do not expand existing broad statements unnecessarily.
84+
- Run policy length check (`make test` invokes [scripts/check_policy_length.py](scripts/check_policy_length.py)) after modifications.
85+
86+
## Do Not
87+
- Do not hardcode account IDs; use `${AWS::AccountId}`.
88+
- Do not remove existing exports or rename keys.
89+
- Do not inline large policy statements in a single managed policy if size risk exists.
90+
91+
## Examples
92+
- IAM Role with OIDC trust: replicate structure from `CloudFormationDeployRole` in [cloudformation/ci_resources.yml](cloudformation/ci_resources.yml).
93+
- KMS key + alias + usage policy: follow `ArtifactsBucketKMSKey` block in [cloudformation/account_resources.yml](cloudformation/account_resources.yml).
94+
95+
## Testing
96+
- After changes: run `make lint-cloudformation` and `make cfn-guard`.
97+
- For SAM-related cross-stack exports ensure `sam build` (see [Makefile](Makefile)) passes.
98+
99+
## Automation Awareness
100+
- 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)).
101+
- Changes to tagging keys must be reflected in release / changeset scripts; avoid unless necessary.
102+
103+
## Preferred Patterns Summary
104+
- Exports: colon join
105+
- Tags: version, stack, repo, cfnDriftDetectionGroup
106+
- Conditions: prefixed with `Should`
107+
- Claim filter parameters: `<RoleName>ClaimFilters`
108+
- Secrets: depend on KMS alias, default `ChangeMe`
109+
110+
Use these rules to guide completions for any new or modified CloudFormation template in this repository.

0 commit comments

Comments
 (0)