English

Poradnik · Bezpieczeństwo API · Logowanie i rejestracja

Bezpieczeństwo API w praktyce – OWASP API Security Top 10, BOLA, JWT, mass assignment, limity żądań i podpisy webhooków (NestJS, Express)

API pierogarni obsługuje aplikację mobilną, kiosk w lokalu i webhooki firmy kurierskiej. Przechodzimy przez OWASP API Security Top 10 (edycja 2023) z działającym kodem – autoryzacja obiektów i funkcji w NestJS, weryfikacja JWT z jose, ochrona przed mass assignment, limity żądań, podpisane webhooki z ochroną przed powtórzeniem, bezpieczne korzystanie z cudzych API i sekrety, które nie trafiają do logów.

Autor · · 17 min czytania

API pierogarni ma dziś trzech głównych klientów: aplikację mobilną, kiosk do zamawiania w lokalu i firmę kurierską, która wysyła webhooki o statusie dostaw. API nie ma interfejsu, który „ukrywa” przyciski – każdy endpoint jest dostępny dla każdego, kto potrafi wysłać żądanie HTTP. Dlatego OWASP prowadzi osobną listę ryzyk dla API. W tym poradniku przechodzimy przez nią z kodem, który uruchomiłem lokalnie – razem z prawdziwymi odpowiedziami serwera.

Wymagania wstępne: NestJS lub Express (poradnik NestJS, poradnik Express), podstawy JWT i OAuth (poradnik o logowaniu), TypeScript.

2023
aktualna edycja – OWASP API Security Top 10
API1
BOLA – autoryzacja na poziomie obiektu – miejsce 1.
15 min
maks. wiek access tokenu – w tym poradniku
5 min
okno podpisu webhooka – starsze żądanie = podejrzenie powtórki
IDRyzyko (2023)W skrócieGdzie w poradniku
API1Broken Object Level Authorizationcudze zamówienie po zmianie IDNestJS – BOLA
API2Broken Authenticationsłaba weryfikacja tokenów, brak limitów logowaniaJWT z jose
API3Broken Object Property Level Authorizationmass assignment i zbyt dużo pól w odpowiedziDTO, zod
API4Unrestricted Resource Consumptionbrak limitów żądań, rozmiaru, paginacjirate limiting
API5Broken Function Level Authorizationklient wywołuje endpoint dla obsługistrażnik ról
API6Unrestricted Access to Sensitive Business Flowsboty wykupujące limitowaną ofertęlimity biznesowe
API7Server Side Request ForgeryAPI pobiera adres podany przez klientaOWASP Top 10
API8Security MisconfigurationCORS, szczegółowe błędy, brak TLSnagłówki, CORS
API9Improper Inventory Managementzapomniane wersje i „cienie” APIOpenAPI, wersje
API10Unsafe Consumption of APIsślepe zaufanie do odpowiedzi partnerawebhooki, walidacja
Diagram: Droga żądania przez warstwy obrony API pierogarni

API1 i API5: autoryzacja obiektów i funkcji (NestJS)

BOLA to IDOR w świecie API: GET /orders/{id} zwraca zamówienie, nie sprawdzając, czy należy do pytającego. BFLA to to samo dla funkcji: klient wywołuje PATCH /orders/{id}/status, przeznaczone dla obsługi kuchni, bo endpoint sprawdzał tylko, czy ktoś jest zalogowany.

Moduł zamówień NestJS: właściciel, role, DTO i limity

src/orders.module.ts
import {
  Body, CanActivate, Controller, ExecutionContext, ForbiddenException, Get, Injectable, Module,
  NotFoundException, Param, ParseUUIDPipe, Patch, Req, SetMetadata,
} from '@nestjs/common';
import { APP_GUARD, Reflector } from '@nestjs/core';
import { Throttle, ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { IsIn, IsOptional, IsString, MaxLength } from 'class-validator';

interface User { id: string; role: 'customer' | 'staff' | 'admin' }
interface Order { id: string; customerId: string; status: string; total: number; note?: string }
type AuthedRequest = { user: User }; // set by the JWT guard (verifyAccessToken)

export const Roles = (...roles: User['role'][]) => SetMetadata('roles', roles);

/** API5 BFLA: endpoints marked @Roles(...) are closed to everyone else. */
@Injectable()
class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}
  canActivate(ctx: ExecutionContext): boolean {
    const roles = this.reflector.getAllAndOverride<User['role'][]>('roles', [ctx.getHandler(), ctx.getClass()]);
    if (!roles) return true;
    const { user } = ctx.switchToHttp().getRequest<AuthedRequest>();
    if (!roles.includes(user.role)) throw new ForbiddenException();
    return true;
  }
}

class UpdateNoteDto {
  @IsOptional() @IsString() @MaxLength(300) note?: string;
}
class UpdateStatusDto {
  @IsIn(['preparing', 'ready', 'collected']) status!: string;
}

@Injectable()
class OrdersService {
  private readonly orders = new Map<string, Order>([
    ['0b9c6a1e-2f4d-4c55-9a7e-3c1f8d2b6a10', { id: '0b9c6a1e-2f4d-4c55-9a7e-3c1f8d2b6a10', customerId: 'cus_42', status: 'new', total: 64.5 }],
    ['7d41e2c3-8a9b-4f0e-b6d5-1a2b3c4d5e6f', { id: '7d41e2c3-8a9b-4f0e-b6d5-1a2b3c4d5e6f', customerId: 'cus_77', status: 'new', total: 38 }],
  ]);
  /** API1 BOLA: the owner is part of the lookup, not an afterthought. */
  findForCustomer(id: string, customerId: string) {
    const order = this.orders.get(id);
    return order?.customerId === customerId ? order : undefined;
  }
  findAny(id: string) { return this.orders.get(id); }
}

@Controller('orders')
class OrdersController {
  constructor(private readonly orders: OrdersService) {}

  @Get(':id')
  get(@Param('id', ParseUUIDPipe) id: string, @Req() req: AuthedRequest) {
    const order = this.orders.findForCustomer(id, req.user.id);
    if (!order) throw new NotFoundException();
    return order;
  }

  // API3: the DTO has only "note" – "status" or "total" in the body is rejected by the ValidationPipe.
  @Patch(':id/note')
  updateNote(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateNoteDto, @Req() req: AuthedRequest) {
    const order = this.orders.findForCustomer(id, req.user.id);
    if (!order) throw new NotFoundException();
    order.note = dto.note;
    return order;
  }

  // API5 + API4: staff only, with a tighter rate limit than the global one.
  @Patch(':id/status')
  @Roles('staff', 'admin')
  @Throttle({ default: { limit: 30, ttl: 60_000 } })
  updateStatus(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateStatusDto) {
    const order = this.orders.findAny(id);
    if (!order) throw new NotFoundException();
    order.status = dto.status;
    return order;
  }
}

@Module({
  imports: [ThrottlerModule.forRoot([{ ttl: 60_000, limit: 100 }])], // API4: a global budget per client
  controllers: [OrdersController],
  providers: [
    OrdersService,
    { provide: APP_GUARD, useClass: ThrottlerGuard },
    { provide: APP_GUARD, useClass: RolesGuard },
  ],
})
export class OrdersModule {}
src/main.ts
import 'reflect-metadata';
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import type { NextFunction, Request, Response } from 'express';
import { OrdersModule } from './orders.module.js';

const app = await NestFactory.create(OrdersModule, { logger: ['error'] });
// API3: strip unknown properties AND fail loudly when someone sends them.
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
// Demo only – in the real app a JWT guard sets req.user from a verified token.
app.use((req: Request & { user?: unknown }, _res: Response, next: NextFunction) => {
  const [id, role] = String(req.headers['x-demo-user'] ?? 'cus_42:customer').split(':');
  req.user = { id, role };
  next();
});
await app.listen(3009);
Odpowiedzi serwera NestJS (uruchomione lokalnie, polecenia skrócone)
$ curl -s localhost:3009/orders/7d41e2c3-8a9b-4f0e-b6d5-1a2b3c4d5e6f   # cus_42 pyta o cudze zamówienie
{"message":"Not Found","statusCode":404}
$ curl -s -X PATCH localhost:3009/orders/0b9c6a1e-…/note -H 'Content-Type: application/json' \
    -d '{"note":"bez cebulki","status":"collected","total":0}'
{"message":["property status should not exist","property total should not exist"],"error":"Bad Request","statusCode":400}
$ curl -s -X PATCH localhost:3009/orders/0b9c6a1e-…/status -d '{"status":"collected"}'   # jako klient
{"message":"Forbidden","statusCode":403}
$ curl -s -X PATCH localhost:3009/orders/0b9c6a1e-…/status -H 'x-demo-user: emp_3:staff' -d '{"status":"ready"}'
{"id":"0b9c6a1e-2f4d-4c55-9a7e-3c1f8d2b6a10","customerId":"cus_42","status":"ready","total":64.5}
  • Właściciel w zapytaniu (findForCustomer(id, req.user.id)) – a nie „pobierz, a potem sprawdź”, o którym łatwo zapomnieć w nowym endpoincie.
  • 404 dla cudzych obiektów – nie zdradzasz, że zamówienie istnieje.
  • Role jako metadane + globalny strażnik (APP_GUARD) – nowy endpoint administracyjny bez @Roles to ryzyko, dlatego w większych projektach warto odwrócić logikę: domyślnie odmawiaj, a endpointy publiczne oznaczaj jawnie (@Public()).
  • Testy z dwoma kontami – najskuteczniejszy test BOLA to automatyczny test, w którym użytkownik B próbuje każdego endpointu z identyfikatorami użytkownika A.

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • API2: uwierzytelnianie i pułapki JWT
  • API3: mass assignment i nadmiar danych w odpowiedzi
  • API4 i API6: limity zasobów i wrażliwe przepływy
  • Webhooki: podpis, okno czasowe, idempotencja
  • API7, API8, API9, API10: SSRF, konfiguracja, inwentarz, cudze API
  • Sekrety i dane osobowe poza logami
  • Typowe błędy
  • Sprawdź się
  • Co dalej

Załóż darmowe konto · Zaloguj się