Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
5 changes: 3 additions & 2 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"USER_GID": "${localEnv:GROUP_ID:}"
}
},
"postAttachCommand": "git-secrets --register-aws; git-secrets --add-provider -- cat /usr/share/secrets-scanner/nhsd-rules-deny.txt",
"postCreateCommand": "bash -lc 'if ! git config --get-all secrets.patterns | grep -Fq AKIA; then git-secrets --register-aws; fi; if ! git config --get-all secrets.providers | grep -Fxq \"cat /usr/share/secrets-scanner/nhsd-rules-deny.txt\"; then git-secrets --add-provider -- cat /usr/share/secrets-scanner/nhsd-rules-deny.txt; fi'",
"mounts": [
"source=${env:HOME}${env:USERPROFILE}/.aws,target=/home/vscode/.aws,type=bind",
"source=${env:HOME}${env:USERPROFILE}/.ssh,target=/home/vscode/.ssh,type=bind",
Expand All @@ -34,7 +34,8 @@
"timonwong.shellcheck",
"github.vscode-github-actions",
"dbaeumer.vscode-eslint",
"vitest.explorer"
"vitest.explorer",
"sonarsource.sonarlint-vscode"
],
"settings": {
"cSpell.words": [
Expand Down
20 changes: 20 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Base Coding Standards
- Follow clean code principles
- Write comprehensive tests
- Use meaningful variable names
- Use British English spelling

## Language-Specific Instructions
Always follow security best practices as outlined in:
- .github/instructions/general/SECURITY.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
51 changes: 51 additions & 0 deletions .github/instructions/general/SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
applyTo: '*'
description: "Comprehensive secure coding instructions for all languages and frameworks, based on OWASP Top 10 and industry best practices."
---
# 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.
104 changes: 104 additions & 0 deletions .github/instructions/languages/INSTRUCTIONS-CDK.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
---
description: 'Guidelines for writing, reviewing, and maintaining AWS CDK (TypeScript) code in the cdk package'
applyTo: 'packages/cdk/**/*.ts'
---

# 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 packges/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)
190 changes: 190 additions & 0 deletions .github/instructions/languages/INSTRUCTIONS-TYPESCRIPT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
---
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'
---

# 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.

## General Instructions

- Use modern TypeScript features and syntax.
- Prefer explicit types and interfaces for clarity and safety.
- Organize code into logical modules and folders.
- Write code that is easy to read, test, and maintain.

## Best Practices

- Use `const` and `let` appropriately; avoid `var`.
- Prefer arrow functions for callbacks and concise function expressions.
- Use destructuring for objects and arrays to improve readability.
- Avoid magic numbers and hardcoded values; use named constants.
- Keep functions pure and side-effect free when possible.

## Code Standards

### Naming Conventions

- Use `camelCase` for variables, functions, and object properties.
- Use `PascalCase` for types, interfaces, classes, and enums.
- Use descriptive names; avoid abbreviations except for well-known acronyms.
- Prefix boolean variables with `is`, `has`, or `should` (e.g., `isActive`).

### File Organization

- Group related code in folders (e.g., `src/`, `tests/`, `lib/`).
- Place one class, interface, or component per file when possible.
- Name files using `kebab-case` (e.g., `user-service.ts`).
- Keep test files close to the code they test (e.g., `src/foo.ts` and `tests/foo.test.ts`).

### Formatting and Style

- Use 2 spaces for indentation.
- Limit lines to 120 characters.
- Use single quotes for strings.
- Never use semicolons for line termination.
- Avoid trailing commas in multiline objects and arrays.
- Avoid spaces at start and end of single line braces.
- Use ESLint and Prettier for consistent formatting.

## Architecture/Structure

- Separate business logic from API handlers and utility functions.
- Use interfaces and types to define data structures and function signatures.
- Organize code by feature or domain when scaling projects.
- Use dependency injection for testability and flexibility.

## Common Patterns

### Logging

- Use a centralized logging utility or library.
- Log errors, warnings, and important events with context.
- Avoid logging sensitive information.
- Example:

```typescript
import {logger} from './utils/logger';

logger.info('Fetching user data', {userId});
logger.error('Failed to fetch user', {error});
```

### Error Handling

- Use `try/catch` for asynchronous code and error-prone operations.
- Throw custom error types for domain-specific errors.
- Always handle errors gracefully and provide meaningful messages.
- Example:

```typescript
try {
const result = await fetchData();
} catch (error) {
logger.error('Data fetch failed', {error});
throw new DataFetchError('Unable to fetch data');
}
```

### Type Safety

- Prefer interfaces and types. You MUST NOT use `any`.
- Use type guards and assertions when necessary.
- Example:

```typescript
interface User {
id: string;
name: string;
}

function isUser(obj: object): obj is User {
return typeof obj.id === 'string' && typeof obj.name === 'string';
}
```

## Security

- Validate and sanitize all external input.
- Avoid exposing sensitive data in logs or error messages.
- Use environment variables for secrets and configuration.
- Keep dependencies up to date and audit regularly.

## Performance

- Minimize synchronous blocking operations.
- Use async/await for asynchronous code.
- Avoid unnecessary computations inside render or handler functions.

## Testing

- Write unit tests for all business logic.
- Use the existing framework for testing and vitest for new packages.
- Mock external dependencies in tests.
- Example test file structure:

```
src/
handler.ts
tests/
handler.test.ts
```

## JSDoc

- Write concise JSDoc for exported interfaces, types, functions, classes, and exported constants.
- Prefer short phrase-style summaries; avoid long narrative prose.
- Avoid stating information that is obvious from function signatures.
- Consider @param and @returns for every exported function, then include them only when they add meaning not obvious from the signature.
- Skip @param when it only repeats parameter name/type; keep it when documenting constraints, defaults, units, side effects, or domain context.
- It is acceptable to use only @returns in a JSDoc block when that tag carries all useful context.
- Omit a free-text summary line when it only restates the @returns content.
- Provide @example on constructors of exported types/classes and on non-trivial exported types.
- Use @default only when the property is optional in the type and is defaulted in implementation.
- Keep JSDoc defaults aligned with both type signatures and runtime behaviour.
- For construct props interfaces, include a top-level summary and property docs only when intent is non-obvious.

## Examples and Code Snippets

### Good Example

```typescript
interface Prescription {
id: string;
medication: string;
issuedDate: Date;
}

function getPrescription(id: string): Prescription | null {
// Implementation
}
```

### Bad Example

```typescript
function getPrescription(id) {
// No type safety, unclear return type
}
```

## Validation and Verification

- Build: `npm run build`
- Lint: `npm run lint`
- Format: `npm run format`
- Test: `npm test`

## Maintenance

- Review and update instructions as dependencies or frameworks change.
- Update examples to reflect current best practices.
- Remove deprecated patterns and add new ones as needed.
- Ensure glob patterns match the intended files.

## Additional Resources

- [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/)
- [ESLint TypeScript Plugin](https://typescript-eslint.io/)
- [Prettier Documentation](https://prettier.io/docs/en/options.html)
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
echo "commit_id=${{ github.sha }}" >> "$GITHUB_OUTPUT"
echo "sha_short=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"
get_config_values:
uses: NHSDigital/eps-common-workflows/.github/workflows/get-repo-config.yml@97059401fbec4c0914532277dfe8ce95dd3213fd
uses: NHSDigital/eps-common-workflows/.github/workflows/get-repo-config.yml@b0172dbdb3af4ae232873106553c316d79d784fc
with:
verify_published_from_main_image: true
quality_checks:
Expand Down
Loading
Loading