From 4b3cb604a0c64d25a1a2c4d588bff5143dea369a Mon Sep 17 00:00:00 2001 From: Yousef Ahmed Maher <160799433+Yousefa7medmaher@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:30:17 +0200 Subject: [PATCH] feat: mask personal data in staff views and audit every reveal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Staff views mask phones (+20 10•• ••• 123) and emails (m•••@example.com) and withhold addresses (owner decision on admin#3). - POST /admin/users/:id/reveal {field, reason} and POST /admin/restaurants/:id/reveal {reason} (support.read) return one value and record pii.reveal: who saw which field of whom, never the value. - The owner's own restaurant view keeps its phone; exact search still matches the full value. Co-authored-by: Yousef Ahmed Maher --- .project-context/16-current-state.md | 1 + docs/openapi/admin.json | 167 ++++++++++++++++++ docs/roadmap/production.md | 2 + docs/services/restaurant-service.md | 1 + docs/services/user-service.md | 2 +- services/api-gateway/src/main.spec.ts | 2 + services/api-gateway/src/public-openapi.ts | 33 ++++ .../admin-restaurants.controller.ts | 12 +- .../admin-restaurants.service.spec.ts | 20 ++- .../src/services/admin-restaurants.service.ts | 27 ++- .../src/services/restaurants.service.ts | 5 +- .../admin-users.controller.spec.ts | 2 +- .../src/controllers/admin-users.controller.ts | 18 +- .../user-service/src/dto/admin-users.dto.ts | 16 +- .../src/services/admin-users.service.spec.ts | 42 ++++- .../src/services/admin-users.service.ts | 48 ++++- shared/src/index.ts | 1 + shared/src/utils/pii-mask.spec.ts | 26 +++ shared/src/utils/pii-mask.ts | 27 +++ 19 files changed, 433 insertions(+), 19 deletions(-) create mode 100644 shared/src/utils/pii-mask.spec.ts create mode 100644 shared/src/utils/pii-mask.ts diff --git a/.project-context/16-current-state.md b/.project-context/16-current-state.md index 68cf9273..400e3ace 100644 --- a/.project-context/16-current-state.md +++ b/.project-context/16-current-state.md @@ -12,6 +12,7 @@ Snapshot of `dev` after per-stage customer notifications (#129, 2026-10-06). Mer - Production 3, #214 (people): `/api/admin/users` in user-service: list (name prefix, role, status, verification, dates), exact phone/email search by POST, and detail. The account side comes from auth-service's internal SYSTEM route; `credentials.lastLoginAt` is set on sign-in. - Production 3, #214 (drivers): `/api/admin/drivers` in driver-service: the list (status, verification, licences expiring, plate prefix), the review queue (`onboarding.review`) and the driver page with the ledger balance and rating from delivery-service's internal route. Names come from user-service's names-only internal route. - Production 3, #214 (restaurants): `/api/admin/restaurants` in restaurant-service: the list (approval, status, name prefix, area), the review queue, the exact phone search (POST) and the restaurant page with owner, menu counts and today's orders (order-service internal route, Cairo day). The person page links drivers and owners to their records. +- Production 3, #317: staff views mask phone and email and withhold addresses (owner decision); `POST /api/admin/users/:id/reveal` and `/api/admin/restaurants/:id/reveal` return one value and record `pii.reveal`. - Production 3, #215: staff actions, all audited in the same transaction and each telling the person through the same `admin.actions` event (notification-service, `ACCOUNT_UPDATE`): driver and restaurant review, suspend and reactivate (`/api/admin/drivers|restaurants/:id/...`; a BUSY driver finishes the delivery first), and account suspend, reactivate and sign-out-everywhere (`/api/admin/auth/users/:id/...`). A suspended restaurant disappears from customers (owner decision). The old staff routes are deprecated for one release. - Production 3, #216: staff accounts by invitation (`/api/admin/auth/staff`, `staff.manage`): email invite with a single-use 48 h link, acceptance with a 12+ character password and exactly the invited permissions, permission changes (applied at the next refresh), disable/enable, role templates; nobody removes their own `staff.manage` and the last super admin stays. All audited. diff --git a/docs/openapi/admin.json b/docs/openapi/admin.json index f0cd26dc..e371aeb6 100644 --- a/docs/openapi/admin.json +++ b/docs/openapi/admin.json @@ -504,6 +504,94 @@ } } }, + "/api/admin/users/{id}/reveal": { + "post": { + "summary": "Reveal one of a person's masked values; audited as pii.reveal (staff with support.read)", + "description": "Requires staff permission: support.read.", + "tags": [ + "users" + ], + "operationId": "admin_users_post_api_admin_users_id_reveal", + "security": [ + { + "bearerAuth": [] + } + ], + "x-permissions": [ + "support.read" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The resource", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "400": { + "description": "Invalid parameters or body", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "401": { + "description": "Missing or invalid JWT, or a SYSTEM token on an admin route" + }, + "403": { + "description": "Staff token without the required permission" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "field", + "reason" + ], + "properties": { + "field": { + "type": "string", + "enum": [ + "phone", + "email", + "address" + ] + }, + "reason": { + "type": "string", + "minLength": 3, + "maxLength": 300, + "description": "Why, for the audit log." + } + } + } + } + } + }, + "x-audit-action": "pii.reveal" + } + }, "/api/admin/drivers": { "get": { "summary": "List drivers: status, verification, licences expiring, plate prefix (staff with support.read)", @@ -1713,6 +1801,85 @@ "x-audit-action": "restaurant.reactivate" } }, + "/api/admin/restaurants/{id}/reveal": { + "post": { + "summary": "Reveal a restaurant's masked contact phone; audited as pii.reveal (staff with support.read)", + "description": "Requires staff permission: support.read.", + "tags": [ + "restaurants" + ], + "operationId": "admin_restaurants_post_api_admin_restaurants_id_reveal", + "security": [ + { + "bearerAuth": [] + } + ], + "x-permissions": [ + "support.read" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "The resource", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + }, + "400": { + "description": "Invalid parameters or body", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + } + } + } + }, + "401": { + "description": "Missing or invalid JWT, or a SYSTEM token on an admin route" + }, + "403": { + "description": "Staff token without the required permission" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "reason" + ], + "properties": { + "reason": { + "type": "string", + "minLength": 3, + "maxLength": 300, + "description": "Why, for the audit log." + } + } + } + } + } + }, + "x-audit-action": "pii.reveal" + } + }, "/api/admin/auth/users/{id}/suspend": { "post": { "summary": "Suspend an account and end its sessions (staff with users.manage)", diff --git a/docs/roadmap/production.md b/docs/roadmap/production.md index 6baf1dea..82f1f382 100644 --- a/docs/roadmap/production.md +++ b/docs/roadmap/production.md @@ -92,6 +92,8 @@ done - **Partial refunds (#219):** not in M4. Staff refunds are full refunds only; partial refunds come with the real payment gateway in M6 (#224). - **Finance read APIs (#220):** order-service owns `/admin/finance/*` and gets payment and ledger aggregates from payment- and delivery-service over internal routes (ADR 001). No money math in the admin app. - **Suspended restaurants (#215):** disappear from customers at once (left out of the list, 404 by id); `BUSY` and `CLOSED` stay visible. `docs/business/restaurant-availability.md`. +- **Personal data for staff (#317):** masked by default; each reveal is its own call and is audited (`pii.reveal`). +- **Undo in the review queues (#318):** a second, audited action within 10 seconds, never a delete. - **Search by phone or email (#217, #214):** a `POST .../search` with the value in the body, never in the URL or a log; exact match after normalising (E.164 phone, lowercased email). **Still needed, before the milestone shown** diff --git a/docs/services/restaurant-service.md b/docs/services/restaurant-service.md index 9049dc04..a4349a0a 100644 --- a/docs/services/restaurant-service.md +++ b/docs/services/restaurant-service.md @@ -42,6 +42,7 @@ Published as `/api/admin/restaurants`: | `GET /admin/restaurants/:id` | `support.read` | The staff application view with its reviews, the row with the owner's name, the menu counts (`categories`, `availableItems`, from the public menu) and today's orders (order-service, Cairo day). | - Owners' names come from user-service's names-only internal route. A part whose service doesn't answer is null. +- The contact phone is masked in every staff view (#317); `POST /admin/restaurants/:id/reveal` `{reason}` (`support.read`) returns it and records `pii.reveal`. The owner's own view keeps it. - `GET /internal/restaurants/by-owner/:ownerId` (SYSTEM, user-service only) links an owner account to its restaurants on the staff person page. - Needs `USER_SERVICE_URL` and `ORDER_SERVICE_URL`. diff --git a/docs/services/user-service.md b/docs/services/user-service.md index fe288d15..4449153d 100644 --- a/docs/services/user-service.md +++ b/docs/services/user-service.md @@ -74,7 +74,7 @@ Profiles live here; the account side (role, status, email verified, suspension, - profile filters only, or none: user-service pages and auth-service adds the accounts; - both: the profile filters give an id set (at most 1000; more is a 400 asking staff to narrow it), and auth-service pages within it. -The staff view may carry phone, email and address (the admin app masks them by default) and never hashes, codes or tokens (snapshot-tested). +The staff view never carries hashes, codes or tokens (snapshot-tested). **Personal data is masked** (#317, owner decision): the phone as `+20 10•• ••• 123`, the email as `m•••@example.com`, and the address withheld (`hasAddress`). `POST /admin/users/:id/reveal` `{field: phone|email|address, reason}` (`support.read`) returns one value and records a `pii.reveal` audit event: who saw which field of whom, never the value. Search still matches the full value; its results come back masked. ## Dependencies - Calls `order-service` to fetch order history via `src/common/order-service.client.ts` diff --git a/services/api-gateway/src/main.spec.ts b/services/api-gateway/src/main.spec.ts index 87e6fec4..242f46b1 100644 --- a/services/api-gateway/src/main.spec.ts +++ b/services/api-gateway/src/main.spec.ts @@ -336,6 +336,8 @@ describe('admin OpenAPI contract (#212)', () => { 'POST /api/admin/restaurants/{id}/reactivate -> restaurant.reactivate', 'POST /api/admin/restaurants/{id}/review -> restaurant.approve', 'POST /api/admin/restaurants/{id}/suspend -> restaurant.suspend', + 'POST /api/admin/restaurants/{id}/reveal -> pii.reveal', + 'POST /api/admin/users/{id}/reveal -> pii.reveal', ].sort(), ); }); diff --git a/services/api-gateway/src/public-openapi.ts b/services/api-gateway/src/public-openapi.ts index 9050c8e3..72efe5f9 100644 --- a/services/api-gateway/src/public-openapi.ts +++ b/services/api-gateway/src/public-openapi.ts @@ -341,6 +341,23 @@ export const ADMIN_SERVICE_DEFINITIONS: readonly { statusCode: 200, response: 'object', }, + { + method: 'post', + path: '/{id}/reveal', + summary: "Reveal one of a person's masked values; audited as pii.reveal (staff with support.read)", + permissions: ['support.read'], + statusCode: 200, + response: 'object', + auditAction: 'pii.reveal', + requestBody: { + type: 'object', + required: ['field', 'reason'], + properties: { + field: { type: 'string', enum: ['phone', 'email', 'address'] }, + reason: { type: 'string', minLength: 3, maxLength: 300, description: 'Why, for the audit log.' }, + }, + }, + }, ], }, { @@ -535,6 +552,22 @@ export const ADMIN_SERVICE_DEFINITIONS: readonly { }, }, }, + { + method: 'post', + path: '/{id}/reveal', + summary: "Reveal a restaurant's masked contact phone; audited as pii.reveal (staff with support.read)", + permissions: ['support.read'], + statusCode: 200, + response: 'object', + auditAction: 'pii.reveal', + requestBody: { + type: 'object', + required: ['reason'], + properties: { + reason: { type: 'string', minLength: 3, maxLength: 300, description: 'Why, for the audit log.' }, + }, + }, + }, ], }, { diff --git a/services/restaurant-service/src/controllers/admin-restaurants.controller.ts b/services/restaurant-service/src/controllers/admin-restaurants.controller.ts index d9acd5fb..c646323d 100644 --- a/services/restaurant-service/src/controllers/admin-restaurants.controller.ts +++ b/services/restaurant-service/src/controllers/admin-restaurants.controller.ts @@ -1,8 +1,9 @@ import { Body, Controller, Get, HttpCode, HttpStatus, Param, ParseUUIDPipe, Post, Query, UseGuards } from '@nestjs/common'; import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; -import { JwtAuthGuard, PermissionsGuard, RateLimitGuard, RequirePermissions } from '@food-delivery/shared'; +import { CurrentUser, JwtAuthGuard, JwtPayload, PermissionsGuard, RateLimitGuard, RequirePermissions } from '@food-delivery/shared'; import { AdminRestaurantsService } from '../services/admin-restaurants.service'; import { AdminListRestaurantsQueryDto, AdminRestaurantQueueQueryDto, AdminSearchRestaurantsDto } from '../dto/admin-restaurants.dto'; +import { AdminRestaurantReasonDto } from '../dto/admin-restaurant-actions.dto'; /** #214: staff restaurant lists and the restaurant page, published as /api/admin/restaurants. */ @ApiTags('admin') @@ -36,6 +37,15 @@ export class AdminRestaurantsController { return this.restaurants.search(dto.phone); } + /** #317: the masked contact phone, shown to this staff member and recorded in the audit log. */ + @Post(':id/reveal') + @HttpCode(HttpStatus.OK) + @RequirePermissions('support.read') + @ApiOperation({ summary: "Reveal a restaurant's contact phone; audited (support.read)" }) + reveal(@Param('id', new ParseUUIDPipe()) id: string, @Body() dto: AdminRestaurantReasonDto, @CurrentUser() user: JwtPayload) { + return this.restaurants.revealContactPhone({ id: user.sub, email: user.email ?? null }, id, dto.reason); + } + @Get(':id') @RequirePermissions('support.read') @ApiOperation({ summary: "One restaurant: application, reviews, owner, menu counts and today's orders (support.read)" }) diff --git a/services/restaurant-service/src/services/admin-restaurants.service.spec.ts b/services/restaurant-service/src/services/admin-restaurants.service.spec.ts index a923b6fb..07058c1e 100644 --- a/services/restaurant-service/src/services/admin-restaurants.service.spec.ts +++ b/services/restaurant-service/src/services/admin-restaurants.service.spec.ts @@ -20,12 +20,14 @@ const restaurant = (id: string, ownerId: string) => ({ }); const setup = () => { - const restaurants = { findForAdmin: jest.fn(), findByContactPhone: jest.fn(), findById: jest.fn() }; + const manager = { query: jest.fn().mockResolvedValue([]) }; + const restaurants = { findForAdmin: jest.fn(), findByContactPhone: jest.fn(), findById: jest.fn(), transaction: jest.fn((work: (m: unknown) => unknown) => work(manager)), manager }; const restaurantsService = { getApplicationForStaff: jest.fn() }; const menu = { menuReadiness: jest.fn() }; const lookups = { names: jest.fn(), ordersToday: jest.fn() }; + const outbox = { kick: jest.fn() }; return { - service: new AdminRestaurantsService(restaurants as never, restaurantsService as never, menu as never, lookups as never), + service: new AdminRestaurantsService(restaurants as never, restaurantsService as never, menu as never, lookups as never, outbox as never), restaurants, restaurantsService, menu, @@ -73,4 +75,18 @@ describe('AdminRestaurantsService (#214)', () => { lookups.ordersToday.mockResolvedValueOnce(null); await expect(service.detail('r1')).resolves.toMatchObject({ menu: null, ordersToday: null }); }); + + it('masks the contact phone in staff rows, and reveals it with one audit event (#317)', async () => { + const { service, restaurants, lookups } = setup(); + restaurants.findByContactPhone.mockResolvedValue([restaurant('r1', 'o1')]); + lookups.names.mockResolvedValue(new Map()); + expect((await service.search('+201011111111')).items[0].contactPhone).toBe('+20 10•• ••• 111'); + + restaurants.findById.mockResolvedValue(restaurant('r1', 'o1')); + await expect(service.revealContactPhone({ id: 'staff-1' }, 'r1', 'Calling the owner')).resolves.toEqual({ field: 'contactPhone', value: '+201011111111' }); + const [, params] = restaurants.manager.query.mock.calls[0]; + expect(JSON.parse(params[2]).payload).toMatchObject({ action: 'pii.reveal', targetType: 'RESTAURANT', after: { field: 'contactPhone' } }); + expect(params[2]).not.toContain('1011111111'); + }); }); + diff --git a/services/restaurant-service/src/services/admin-restaurants.service.ts b/services/restaurant-service/src/services/admin-restaurants.service.ts index f4749066..85cdb0ed 100644 --- a/services/restaurant-service/src/services/admin-restaurants.service.ts +++ b/services/restaurant-service/src/services/admin-restaurants.service.ts @@ -1,5 +1,6 @@ import { Injectable } from '@nestjs/common'; -import { PaginatedResult } from '@food-delivery/shared'; +import { AdminAudit, AuditActor, maskPhone, NotFoundError, PaginatedResult } from '@food-delivery/shared'; +import { OutboxRelayService } from '../common/outbox.module'; import { RestaurantsRepository } from '../repositories/restaurants.repository'; import { Restaurant } from '../entities/restaurant.entity'; import { MenuReadiness, MenuServiceClient } from '../common/menu-service.client'; @@ -44,8 +45,29 @@ export class AdminRestaurantsService { private readonly restaurantsService: RestaurantsService, private readonly menu: MenuServiceClient, private readonly lookups: StaffLookupsClient, + private readonly outbox: OutboxRelayService, ) {} + /** #317: the contact phone of one restaurant, recorded as a `pii.reveal` audit event (never the value). */ + async revealContactPhone(actor: AuditActor, id: string, reason: string): Promise<{ field: 'contactPhone'; value: string | null }> { + const restaurant = await this.restaurants.findById(id); + if (!restaurant) throw new NotFoundError(`Restaurant ${id} not found`); + await this.restaurants.transaction((manager) => + AdminAudit.record(manager, { + actor, + permission: 'support.read', + action: 'pii.reveal', + targetType: 'RESTAURANT', + targetId: id, + reason, + after: { field: 'contactPhone' }, + service: 'restaurant-service', + }), + ); + this.outbox.kick(); + return { field: 'contactPhone', value: restaurant.contactPhone ?? null }; + } + async list(query: AdminListRestaurantsQueryDto): Promise> { const near = query.nearLat !== undefined && query.nearLng !== undefined && query.withinKm !== undefined @@ -98,7 +120,8 @@ const toRow = (restaurant: Restaurant, names: Map | null): Staff latitude: restaurant.latitude, longitude: restaurant.longitude, deliveryRadiusKm: restaurant.deliveryRadiusKm, - contactPhone: restaurant.contactPhone ?? null, + // #317 (owner decision): masked; POST /admin/restaurants/:id/reveal shows it, audited. + contactPhone: maskPhone(restaurant.contactPhone), submittedAt: restaurant.submittedAt, approvedAt: restaurant.approvedAt, createdAt: restaurant.createdAt, diff --git a/services/restaurant-service/src/services/restaurants.service.ts b/services/restaurant-service/src/services/restaurants.service.ts index 22929f9c..3106663e 100644 --- a/services/restaurant-service/src/services/restaurants.service.ts +++ b/services/restaurant-service/src/services/restaurants.service.ts @@ -1,13 +1,14 @@ import { EntityManager } from 'typeorm'; import { Inject, Injectable } from '@nestjs/common'; import { + CacheService, ForbiddenError, NotFoundError, PaginatedResult, RestaurantStatus, S3StorageService, UserRole, - CacheService, + maskPhone, } from '@food-delivery/shared'; import { APP_CONFIG, AppConfig } from '../config/app-config'; import { RestaurantsRepository } from '../repositories/restaurants.repository'; @@ -343,6 +344,8 @@ export class RestaurantsService { private toStaffApplication(restaurant: Restaurant, reviews: RestaurantReview[]): StaffRestaurantApplicationDto { return { ...this.toOwnerRestaurant(restaurant, reviews), + // #317: staff see the contact phone masked; the owner's own view keeps it. + contactPhone: maskPhone(restaurant.contactPhone), ownerId: restaurant.ownerId, reviews: reviews.map(({ id, decision, note, reviewerUserId, applicationSubmittedAt, reviewedAt }) => ({ id, diff --git a/services/user-service/src/controllers/admin-users.controller.spec.ts b/services/user-service/src/controllers/admin-users.controller.spec.ts index ed11ab58..d8fe4a7a 100644 --- a/services/user-service/src/controllers/admin-users.controller.spec.ts +++ b/services/user-service/src/controllers/admin-users.controller.spec.ts @@ -7,7 +7,7 @@ import { AdminListUsersQueryDto, AdminSearchUsersDto } from '../dto/admin-users. describe('AdminUsersController (#214)', () => { it('requires support.read on every route', () => { - for (const route of ['list', 'search', 'detail'] as const) { + for (const route of ['list', 'search', 'detail', 'reveal'] as const) { expect(new Reflector().get(PERMISSIONS_KEY, AdminUsersController.prototype[route])).toEqual(['support.read']); } }); diff --git a/services/user-service/src/controllers/admin-users.controller.ts b/services/user-service/src/controllers/admin-users.controller.ts index d86ef775..623f66d7 100644 --- a/services/user-service/src/controllers/admin-users.controller.ts +++ b/services/user-service/src/controllers/admin-users.controller.ts @@ -1,8 +1,8 @@ import { Body, Controller, Get, Headers, HttpCode, HttpStatus, Param, ParseUUIDPipe, Post, Query, UseGuards } from '@nestjs/common'; import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'; -import { JwtAuthGuard, PermissionsGuard, RateLimitGuard, RequirePermissions } from '@food-delivery/shared'; +import { CurrentUser, JwtAuthGuard, JwtPayload, PermissionsGuard, RateLimitGuard, RequirePermissions } from '@food-delivery/shared'; import { AdminUsersService } from '../services/admin-users.service'; -import { AdminListUsersQueryDto, AdminSearchUsersDto } from '../dto/admin-users.dto'; +import { AdminListUsersQueryDto, AdminRevealDto, AdminSearchUsersDto } from '../dto/admin-users.dto'; /** #214: the staff people directory, published as /api/admin/users. */ @ApiTags('admin') @@ -28,6 +28,20 @@ export class AdminUsersController { return this.users.search(dto, correlationId); } + /** #317: one masked value, shown to this staff member and recorded in the audit log. */ + @Post(':id/reveal') + @HttpCode(HttpStatus.OK) + @RequirePermissions('support.read') + @ApiOperation({ summary: "Reveal one of a person's masked values (phone, email or address); audited (support.read)" }) + reveal( + @Param('id', new ParseUUIDPipe()) id: string, + @Body() dto: AdminRevealDto, + @CurrentUser() user: JwtPayload, + @Headers('x-correlation-id') correlationId?: string, + ) { + return this.users.reveal({ id: user.sub, email: user.email ?? null }, id, dto.field, dto.reason, correlationId); + } + @Get(':id') @RequirePermissions('support.read') @ApiOperation({ summary: 'One person: profile and account (support.read)' }) diff --git a/services/user-service/src/dto/admin-users.dto.ts b/services/user-service/src/dto/admin-users.dto.ts index 2d0a259c..cfc66608 100644 --- a/services/user-service/src/dto/admin-users.dto.ts +++ b/services/user-service/src/dto/admin-users.dto.ts @@ -1,7 +1,7 @@ import { ApiPropertyOptional } from '@nestjs/swagger'; import { Transform, Type } from 'class-transformer'; import { IsEmail, IsIn, IsInt, IsISO8601, IsOptional, IsString, Max, MaxLength, Min, MinLength } from 'class-validator'; -import { EgyptianMobile } from '@food-delivery/shared'; +import { EgyptianMobile, REVEALABLE_FIELDS, RevealableField } from '@food-delivery/shared'; const toBoolean = ({ value }: { value: unknown }) => (value === 'true' || value === true ? true : value === 'false' || value === false ? false : value); @@ -82,3 +82,17 @@ export class AdminSearchUsersDto { @MaxLength(320) email?: string; } + +/** `POST /admin/users/:id/reveal` (#317): one field, and why, for the audit log. */ +export class AdminRevealDto { + @ApiPropertyOptional({ enum: REVEALABLE_FIELDS }) + @IsIn(REVEALABLE_FIELDS) + field!: RevealableField; + + @ApiPropertyOptional({ minLength: 3, maxLength: 300, description: 'Why, for the audit log, e.g. "Calling about order 4f2c".' }) + @IsString() + @Transform(({ value }) => (typeof value === 'string' ? value.trim() : value)) + @MinLength(3) + @MaxLength(300) + reason!: string; +} diff --git a/services/user-service/src/services/admin-users.service.spec.ts b/services/user-service/src/services/admin-users.service.spec.ts index 13265777..be51bcbc 100644 --- a/services/user-service/src/services/admin-users.service.spec.ts +++ b/services/user-service/src/services/admin-users.service.spec.ts @@ -36,7 +36,16 @@ const setup = () => { }; const accounts = { queryAccounts: jest.fn() }; const linked = { driverIdFor: jest.fn(), restaurantIdsFor: jest.fn() }; - return { service: new AdminUsersService(profiles as never, accounts as never, linked as never), profiles, accounts, linked }; + const manager = { query: jest.fn().mockResolvedValue([]) }; + const dataSource = { transaction: jest.fn((work: (m: unknown) => unknown) => work(manager)) }; + const outbox = { kick: jest.fn() }; + return { + service: new AdminUsersService(profiles as never, accounts as never, linked as never, dataSource as never, outbox as never), + profiles, + accounts, + linked, + manager, + }; }; const query = (extra: Partial = {}) => Object.assign(new AdminListUsersQueryDto(), extra); @@ -106,7 +115,7 @@ describe('AdminUsersService (#214)', () => { const { service, profiles, accounts } = setup(); profiles.findById.mockResolvedValueOnce(profile('a')); accounts.queryAccounts.mockResolvedValueOnce({ items: [account('a')], total: 1 }); - await expect(service.detail('a')).resolves.toMatchObject({ id: 'a', address: 'Zamalek', auditTrail: { targetType: 'USER', targetId: 'a' } }); + await expect(service.detail('a')).resolves.toMatchObject({ id: 'a', hasAddress: true, auditTrail: { targetType: 'USER', targetId: 'a' } }); profiles.findById.mockResolvedValueOnce(null); accounts.queryAccounts.mockResolvedValueOnce({ items: [], total: 0 }); @@ -120,13 +129,13 @@ describe('AdminUsersService (#214)', () => { const view = await service.detail('a'); expect(Object.keys(view).sort()).toMatchInlineSnapshot(` [ - "address", "auditTrail", "avatarUrl", "createdAt", "email", "emailVerified", "fullName", + "hasAddress", "id", "lastLoginAt", "linked", @@ -169,4 +178,31 @@ describe('AdminUsersService (#214)', () => { linked.restaurantIdsFor.mockResolvedValueOnce(undefined); await expect(service.detail('o')).resolves.toMatchObject({ linked: { restaurantIds: 'unavailable' } }); }); + + it('masks phone and email and withholds the address on every staff view (#317)', async () => { + const { service, profiles, accounts } = setup(); + profiles.findById.mockResolvedValue(profile('a', { phone: '+201012345123' })); + accounts.queryAccounts.mockResolvedValue({ items: [account('a', { email: 'mona.ali@example.com' })], total: 1 }); + const view = await service.detail('a'); + expect(view).toMatchObject({ phone: '+20 10•• ••• 123', email: 'm•••@example.com', hasAddress: true }); + expect(JSON.stringify(view)).not.toMatch(/Zamalek|012345|mona\.ali/); + }); + + it('reveals one value and records who saw which field, never the value (#317)', async () => { + const { service, profiles, manager } = setup(); + profiles.findById.mockResolvedValue(profile('a', { phone: '+201012345123' })); + await expect(service.reveal({ id: 'staff-1' }, 'a', 'phone', 'Calling about an order')).resolves.toEqual({ field: 'phone', value: '+201012345123' }); + const [, params] = manager.query.mock.calls[0]; + const event = JSON.parse(params[2]); + expect(event.payload).toMatchObject({ action: 'pii.reveal', permission: 'support.read', targetType: 'USER', targetId: 'a', after: { field: 'phone' } }); + expect(params[2]).not.toContain('012345'); + }); + + it('404s a reveal for an unknown person', async () => { + const { service, profiles, accounts } = setup(); + profiles.findById.mockResolvedValue(null); + accounts.queryAccounts.mockResolvedValue({ items: [], total: 0 }); + await expect(service.reveal({ id: 'staff-1' }, 'x', 'address', 'Check')).rejects.toThrow('User not found'); + }); }); + diff --git a/services/user-service/src/services/admin-users.service.ts b/services/user-service/src/services/admin-users.service.ts index 67b166a4..02301722 100644 --- a/services/user-service/src/services/admin-users.service.ts +++ b/services/user-service/src/services/admin-users.service.ts @@ -1,5 +1,8 @@ import { Injectable } from '@nestjs/common'; -import { BadRequestError, NotFoundError, PaginatedResult, UserRole } from '@food-delivery/shared'; +import { AdminAudit, AuditActor, BadRequestError, maskEmail, maskPhone, NotFoundError, PaginatedResult, RevealableField, UserRole } from '@food-delivery/shared'; +import { DataSource } from 'typeorm'; +import { InjectDataSource } from '@nestjs/typeorm'; +import { OutboxRelayService } from '../common/outbox.module'; import { ProfilesRepository } from '../repositories/profiles.repository'; import { UserProfile } from '../entities/user-profile.entity'; import { AccountQuery, AccountSummary, AuthServiceClient } from '../common/auth-service.client'; @@ -30,7 +33,8 @@ export interface StaffUserView { } export interface StaffUserDetail extends StaffUserView { - address: string | null; + /** #317: never the address itself; whether there is one to reveal. */ + hasAddress: boolean; /** Status changes are in the audit log: GET /api/admin/audit?targetType=USER&targetId=. */ auditTrail: { targetType: 'USER'; targetId: string }; /** @@ -51,8 +55,9 @@ const toView = (profile: UserProfile | undefined, account: AccountSummary | unde return { id, fullName: profile?.fullName ?? null, - email: account?.email ?? profile?.email ?? '', - phone: profile?.phone ?? null, + // #317 (owner decision): masked by default; POST /admin/users/:id/reveal shows one value, audited. + email: maskEmail(account?.email ?? profile?.email) ?? '', + phone: maskPhone(profile?.phone), phoneVerified: Boolean(profile?.phoneVerifiedAt), avatarUrl: profile?.avatarUrl ?? null, role: account?.role ?? null, @@ -71,8 +76,41 @@ export class AdminUsersService { private readonly profiles: ProfilesRepository, private readonly accounts: AuthServiceClient, private readonly linkedRecords: LinkedRecordsClient, + @InjectDataSource() private readonly dataSource: DataSource, + private readonly outbox: OutboxRelayService, ) {} + /** + * #317: one personal value of one person, for staff with support.read. Each reveal records a + * `pii.reveal` audit event (who saw which field of whom, never the value) before the value is returned. + */ + async reveal(actor: AuditActor, id: string, field: RevealableField, reason: string, correlationId?: string): Promise<{ field: RevealableField; value: string | null }> { + const profile = await this.profiles.findById(id); + let value: string | null; + if (field === 'email') { + value = (await this.accountsFor([id], correlationId)).get(id)?.email ?? profile?.email ?? null; + if (!profile && value === null) throw new NotFoundError('User not found'); + } else { + if (!profile) throw new NotFoundError('User not found'); + value = (field === 'phone' ? profile.phone : profile.address) ?? null; + } + await this.dataSource.transaction((manager) => + AdminAudit.record(manager, { + actor, + permission: 'support.read', + action: 'pii.reveal', + targetType: 'USER', + targetId: id, + reason, + after: { field }, + service: 'user-service', + correlationId, + }), + ); + this.outbox.kick(); + return { field, value }; + } + /** * One paginated list across two services without reading auth-service's database (ADR 002): * - account filters only: auth-service pages, user-service adds the profiles; @@ -132,7 +170,7 @@ export class AdminUsersService { } return { ...toView(profile ?? undefined, account), - address: profile?.address ?? null, + hasAddress: Boolean(profile?.address), auditTrail: { targetType: 'USER', targetId: id }, linked: { driverId, restaurantIds }, }; diff --git a/shared/src/index.ts b/shared/src/index.ts index acd7c8ae..ca30c282 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -5,6 +5,7 @@ export * from './logging/logger'; export * from './events/base-event'; export * from './utils/id'; export * from './utils/egyptian-mobile'; +export * from './utils/pii-mask'; export * from './utils/geo'; export * from './utils/typeorm-safety'; export * from './nest/auth/jwt-payload.interface'; diff --git a/shared/src/utils/pii-mask.spec.ts b/shared/src/utils/pii-mask.spec.ts new file mode 100644 index 00000000..69f46b15 --- /dev/null +++ b/shared/src/utils/pii-mask.spec.ts @@ -0,0 +1,26 @@ +import { maskEmail, maskPhone } from './pii-mask'; + +describe('PII masking (#317)', () => { + it('masks an Egyptian mobile to the country code, operator prefix and last three digits', () => { + expect(maskPhone('+201012345123')).toBe('+20 10•• ••• 123'); + expect(maskPhone('+201512345678')).toBe('+20 15•• ••• 678'); + }); + + it('masks other numbers to their last three digits, and nothing to null', () => { + expect(maskPhone('+4915112345678')).toBe('••••••••••678'); + expect(maskPhone('12')).toBe('•••'); + expect(maskPhone(null)).toBeNull(); + }); + + it('masks an email to its first character and domain', () => { + expect(maskEmail('mona.ali@example.com')).toBe('m•••@example.com'); + expect(maskEmail('a@b.co')).toBe('a•••@b.co'); + expect(maskEmail('not-an-email')).toBe('•••'); + expect(maskEmail(undefined)).toBeNull(); + }); + + it('never leaks more than the last three digits', () => { + const masked = maskPhone('+201098765432') as string; + expect(masked.replace(/\D/g, '')).toBe('2010432'); + }); +}); diff --git a/shared/src/utils/pii-mask.ts b/shared/src/utils/pii-mask.ts new file mode 100644 index 00000000..6b66e26c --- /dev/null +++ b/shared/src/utils/pii-mask.ts @@ -0,0 +1,27 @@ +/** + * #317 (owner decision on admin#3): staff see personal data masked by default; revealing a value is + * its own audited call. These helpers are the one masking format for every staff view. + */ +const DOT = '•'; + +/** `+201012345678` → `+20 10•• ••• 678`: the country code, the operator prefix and the last three digits. */ +export function maskPhone(phone: string | null | undefined): string | null { + if (!phone) return null; + const digits = phone.replace(/\D/g, ''); + if (phone.startsWith('+20') && digits.length === 12) { + return `+20 ${digits.slice(2, 4)}${DOT.repeat(2)} ${DOT.repeat(3)} ${digits.slice(-3)}`; + } + return digits.length > 3 ? `${DOT.repeat(Math.max(digits.length - 3, 3))}${digits.slice(-3)}` : DOT.repeat(3); +} + +/** `mona.ali@example.com` → `m•••@example.com`: the first character and the domain. */ +export function maskEmail(email: string | null | undefined): string | null { + if (!email) return null; + const at = email.lastIndexOf('@'); + if (at <= 0) return DOT.repeat(3); + return `${email[0]}${DOT.repeat(3)}${email.slice(at)}`; +} + +/** The personal fields a staff member can reveal one at a time (#317). */ +export const REVEALABLE_FIELDS = ['phone', 'email', 'address'] as const; +export type RevealableField = (typeof REVEALABLE_FIELDS)[number];