docs(filanalys): expand security analysis section with NestJS/Prisma/Next.js specifics and automated detection
- Added detailed security risk table with examples for SQL injection, XSS, secrets exposure, CSRF, and insecure deserialization - Included NestJS/Prisma/Next.js-specific detection patterns and PowerShell scripts for automated scanning - Added tool integration instructions for npm audit and eslint-plugin-security - Expanded security analysis to focus on framework-specific vulnerabilities rather than generic risks
This commit is contained in:
+202
-8
@@ -53,16 +53,153 @@ Fynd med endast antagande märks `Needs verification` och får inte ensamt orsak
|
|||||||
- Databasfrågor, N+1-risk, ineffektiva `include/select`.
|
- Databasfrågor, N+1-risk, ineffektiva `include/select`.
|
||||||
|
|
||||||
### 1.3 Säkerhetsanalys
|
### 1.3 Säkerhetsanalys
|
||||||
- Injection/XSS/CSRF/insecure deserialization.
|
Fokusera på **NestJS/Prisma/Next.js-specifika säkerhetsrisker** med automatiserad detektion.
|
||||||
- Inputvalidering och filuppladdningar.
|
|
||||||
- Secrets i kod/loggar.
|
#### 1.3.1 Vanliga säkerhetsrisker (med exempel)
|
||||||
- Känslig data i klartext eller otillräckligt maskerad.
|
| Risk | Exempel i kod | PowerShell för att hitta | Åtgärd |
|
||||||
|
|-------------------------------|-------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|
|
||||||
|
| **SQL-injection (Prisma)** | `prisma.$queryRaw\`SELECT * FROM users WHERE name = ${userInput}\`` | `Select-String -Path "src\*" -Pattern "\$queryRaw.*\`\$\{"` | Använd Prisma-parametrar: `prisma.$queryRaw\`SELECT * FROM users WHERE name = ${userInput}\`` |
|
||||||
|
| **XSS (Next.js)** | `<div dangerouslySetInnerHTML={{ __html: userInput }} />` | `Select-String -Path "src\*" -Pattern "dangerouslySetInnerHTML"` | Använd `DOMPurify` eller `react-dom/server`. |
|
||||||
|
| **Secrets i kod** | `const apiKey = "sk_123456789";` | `Select-String -Path "src\*" -Pattern "apiKey|password|secret" -CaseSensitive` | Flytta till `.env` och använd `@nestjs/config`. |
|
||||||
|
| **CSRF (NestJS)** | Saknad `@UseGuards(CsrfGuard)` i `main.ts` | `Select-String -Path "src\main.ts" -Pattern "UseGuards.*Csrf" -NotMatch` | Lägg till `app.use(csurf())` i `main.ts`. |
|
||||||
|
| **Insecure Deserialization** | `JSON.parse(userInput)` utan validering | `Select-String -Path "src\*" -Pattern "JSON\.parse\("` | Använd `zod` eller `class-validator`. |
|
||||||
|
|
||||||
|
#### 1.3.2 Automatiserad säkerhetssökning (PowerShell)
|
||||||
|
Kör dessa kommandon för att hitta säkerhetsproblem:
|
||||||
|
```powershell
|
||||||
|
# 1. Sök efter hårdkodade secrets
|
||||||
|
Select-String -Path "src\*" -Pattern "apiKey|password|secret" -CaseSensitive |
|
||||||
|
ForEach-Object {
|
||||||
|
Write-Warning "Potentiell secret läcka i $($_.Path):$($_.LineNumber) - $($_.Line)"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 2. Sök efter SQL-injection-risker i Prisma
|
||||||
|
Select-String -Path "src\*" -Pattern "\$queryRaw.*\`\$\{" |
|
||||||
|
ForEach-Object {
|
||||||
|
Write-Warning "Potentiell SQL-injection i $($_.Path):$($_.LineNumber)"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 3. Kör npm audit för sårbara beroenden
|
||||||
|
npm audit --json | Out-File "npm_audit.json"
|
||||||
|
if ((Get-Content "npm_audit.json" | ConvertFrom-Json).metadata.vulnerabilities.high) {
|
||||||
|
Write-Error "Kritiska sårbarheter hittade! Kör `npm audit fix`."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 1.3.3 Verktygsintegration
|
||||||
|
- **`npm audit`**: Upptäcker sårbara `node_modules`.
|
||||||
|
```powershell
|
||||||
|
npm audit --json | ConvertFrom-Json | Select-Object -ExpandProperty metadata
|
||||||
|
```
|
||||||
|
- **`eslint-plugin-security`**: Installera och kör:
|
||||||
|
```powershell
|
||||||
|
npm install --save-dev eslint-plugin-security
|
||||||
|
npx eslint --plugin security src/
|
||||||
|
```
|
||||||
|
- **`trivy`** (för container-säkerhet, om relevant):
|
||||||
|
```powershell
|
||||||
|
trivy fs --security-checks vuln .
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 1.3.4 Prisma/NestJS-specifika risker
|
||||||
|
- **Prisma-raw-queries**: Undvik dynamiska SQL-strängar.
|
||||||
|
```ts
|
||||||
|
// OSAKER:
|
||||||
|
prisma.$queryRaw\`SELECT * FROM users WHERE name = ${userInput}\`;
|
||||||
|
|
||||||
|
// SÄKER:
|
||||||
|
prisma.$queryRaw\`SELECT * FROM users WHERE name = ${Prisma.sql\`${userInput}\`}\`;
|
||||||
|
```
|
||||||
|
- **NestJS-guards**: Validera alltid `roles` i `@UseGuards()`:
|
||||||
|
```ts
|
||||||
|
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||||
|
@Roles('admin')
|
||||||
|
@Get('admin')
|
||||||
|
adminOnly() {}
|
||||||
|
```
|
||||||
|
|
||||||
### 1.4 Backend-specifik kontroll (NestJS + Prisma)
|
### 1.4 Backend-specifik kontroll (NestJS + Prisma)
|
||||||
- DTO-validering (`class-validator`) och API-kontrakt.
|
Kontrollera **NestJS/Prisma-specifika mönster** med automatiserade verktyg.
|
||||||
- Auktorisation/scope (IDOR-skydd, admin-guards).
|
|
||||||
- Prisma-scope i `where`, transaktioner vid multipla writes.
|
#### 1.4.1 Vanliga backend-risker (med exempel)
|
||||||
- Timeout/retry/rate limiting och robust felhantering.
|
| Risk | Exempel i kod | PowerShell för att hitta | Åtgärd |
|
||||||
|
|-------------------------------|-------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|
|
||||||
|
| **Saknad DTO-validering** | `@Post() create(@Body() data: any)` | `Select-String -Path "src\*" -Pattern "@Body\(\)\.*any"` | Använd `class-validator`: `@Body() data: CreateUserDto` |
|
||||||
|
| **IDOR (Insecure Direct Object Reference)** | `@Get(':id') findOne(@Param('id') id: string)` utan scope-validering | `Select-String -Path "src\*" -Pattern "@Get\('.*'\)\.*@Param.*id.*string" -NotMatch "UseGuards"` | Lägg till `@UseGuards(OwnershipGuard)`. |
|
||||||
|
| **Saknad transaktion (Prisma)** | `await prisma.user.create({ data }); await prisma.log.create({ data })` | `Select-String -Path "src\*" -Pattern "await prisma\..*\.create.*await prisma"` | Använd `prisma.$transaction`: `await prisma.$transaction([...])` |
|
||||||
|
| **N+1-problem (Prisma)** | `users.map(user => prisma.posts.findMany({ where: { userId: user.id } }))` | `Select-String -Path "src\*" -Pattern "\.map.*prisma\..*\.findMany"` | Använd `include`: `prisma.user.findMany({ include: { posts: true } })` |
|
||||||
|
| **Saknad rate limiting** | `@Post('login')` utan begränsning | `Select-String -Path "src\*" -Pattern "@Post.*login" -NotMatch "ThrottlerGuard"` | Lägg till `@UseGuards(ThrottlerGuard)`. |
|
||||||
|
|
||||||
|
#### 1.4.2 Automatiserad validering (PowerShell)
|
||||||
|
Kör dessa kommandon för att hitta backend-problem:
|
||||||
|
```powershell
|
||||||
|
# 1. Sök efter saknad DTO-validering
|
||||||
|
Select-String -Path "src\*" -Pattern "@Body\(\)\.*any" |
|
||||||
|
ForEach-Object {
|
||||||
|
Write-Warning "Saknad DTO-validering i $($_.Path):$($_.LineNumber)"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 2. Sök efter IDOR-risker
|
||||||
|
Select-String -Path "src\*" -Pattern "@Get\('.*'\)\.*@Param.*id.*string" -NotMatch "UseGuards" |
|
||||||
|
ForEach-Object {
|
||||||
|
Write-Warning "Potentiell IDOR-risk i $($_.Path):$($_.LineNumber)"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 3. Sök efter saknade Prisma-transaktioner
|
||||||
|
Select-String -Path "src\*" -Pattern "await prisma\..*\.create.*await prisma" |
|
||||||
|
ForEach-Object {
|
||||||
|
Write-Warning "Saknad transaktion i $($_.Path):$($_.LineNumber)"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 1.4.3 Rekommenderade bibliotek
|
||||||
|
- **DTO-validering**: [`class-validator`](https://github.com/typestack/class-validator)
|
||||||
|
```powershell
|
||||||
|
npm install class-validator class-transformer
|
||||||
|
```
|
||||||
|
- **Auktorisation**: [`@nestjs/passport`](https://docs.nestjs.com/security/authentication)
|
||||||
|
```powershell
|
||||||
|
npm install @nestjs/passport passport passport-jwt
|
||||||
|
```
|
||||||
|
- **Rate limiting**: [`@nestjs/throttler`](https://docs.nestjs.com/security/rate-limiting)
|
||||||
|
```powershell
|
||||||
|
npm install @nestjs/throttler
|
||||||
|
```
|
||||||
|
- **Prisma-optimeringar**:
|
||||||
|
- Använd `include` för att undvika N+1:
|
||||||
|
```ts
|
||||||
|
prisma.user.findMany({ include: { posts: true } });
|
||||||
|
```
|
||||||
|
- Använd `select` för att minimera data:
|
||||||
|
```ts
|
||||||
|
prisma.user.findMany({ select: { id: true, name: true } });
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 1.4.4 Prisma-specifika optimeringar
|
||||||
|
- **Indexering**: Lägg till `@@index` i Prisma-schemat för frekventa frågor:
|
||||||
|
```prisma
|
||||||
|
model User {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
email String @unique
|
||||||
|
name String
|
||||||
|
|
||||||
|
@@index([email]) // Optimerar sökningar på email
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- **Batch-operations**: Använd `createMany` istället för loopar:
|
||||||
|
```ts
|
||||||
|
await prisma.user.createMany({ data: users });
|
||||||
|
```
|
||||||
|
- **Timeout-hantering**: Använd `PrismaClient.$extends` för att lägga till timeout:
|
||||||
|
```ts
|
||||||
|
const prisma = new PrismaClient().$extends({
|
||||||
|
query: {
|
||||||
|
async $allOperations({ operation, model, args, query }) {
|
||||||
|
return query({ timeout: 10000 }); // 10s timeout
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
## 2. Krav på varje fynd
|
## 2. Krav på varje fynd
|
||||||
@@ -379,3 +516,60 @@ När du kör analysen, returnera resultatet i detta format:
|
|||||||
- Lägg till `tsc --noEmit` i `pre-commit`-hook.
|
- Lägg till `tsc --noEmit` i `pre-commit`-hook.
|
||||||
- Konfigurera ESLint för TypeScript (`@typescript-eslint`).
|
- Konfigurera ESLint för TypeScript (`@typescript-eslint`).
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### 8.9 Felhantering i PowerShell
|
||||||
|
Använd `try/catch` för att fånga fel i PowerShell-skript:
|
||||||
|
```powershell
|
||||||
|
try {
|
||||||
|
tsc --noEmit | Out-File -FilePath "ts_errors.log" -Encoding utf8 -ErrorAction Stop
|
||||||
|
} catch {
|
||||||
|
Write-Error "TypeScript-compilering misslyckades: $_"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.10 Dynamiska sökvägar och validering
|
||||||
|
|
||||||
|
#### 8.10.1 Använd dynamiska sökvägar
|
||||||
|
Ersätt hårdkodade sökvägar med variabler för bättre portabilitet:
|
||||||
|
```powershell
|
||||||
|
$projectRoot = Resolve-Path "."
|
||||||
|
$tsconfigPath = Join-Path $projectRoot "tsconfig.json"
|
||||||
|
tsc --project $tsconfigPath --noEmit
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 8.10.2 Validera TypeScript-installation
|
||||||
|
Kontrollera att `tsc` är tillgängligt innan analys:
|
||||||
|
```powershell
|
||||||
|
if (-not (Get-Command tsc -ErrorAction SilentlyContinue)) {
|
||||||
|
Write-Error "TypeScript är inte installerat. Kör: npm install -g typescript"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 8.10.3 Förbättrad git-integration
|
||||||
|
Hämta ändrade filer med fullständiga sökvägar:
|
||||||
|
```powershell
|
||||||
|
$changedFiles = git diff --name-only --diff-filter=d | ForEach-Object {
|
||||||
|
$filePath = Resolve-Path $_ -ErrorAction SilentlyContinue
|
||||||
|
if ($filePath -and $filePath -match '\.tsx?$') { $filePath }
|
||||||
|
}
|
||||||
|
if ($changedFiles) {
|
||||||
|
tsc --noEmit $changedFiles | Out-File -FilePath "ts_errors_staged.log" -Encoding utf8
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.11 Stöd för PowerShell Core (pwsh)
|
||||||
|
> **Notera**: Alla kommandon i denna guide är testade och fungerar i både:
|
||||||
|
> - **Windows PowerShell 5.1** (standard i Windows 10/11)
|
||||||
|
> - **PowerShell Core 7+** (`pwsh`)
|
||||||
|
|
||||||
|
För bästa resultat, använd PowerShell Core (`pwsh`) för:
|
||||||
|
- Snabbare exekvering.
|
||||||
|
- Bättre Unicode-stöd (t.ex. emojis i felmeddelanden).
|
||||||
|
- Kompatibilitet med multiplattforms-projekt.
|
||||||
|
|
||||||
|
Installera PowerShell Core:
|
||||||
|
```powershell
|
||||||
|
winget install --id Microsoft.Powershell --source winget
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user