Doc03 — Application Security

Part A Strategic + Part B Structural (gaps in 09_GAP)

A. Document controlA. Kiểm soát tài liệu

Doc IDCPG-SEC-DOC03
VersionPhiên bản1.2
StatusTrạng tháiLiving document
OwnerPlatform / Security
AudienceĐối tượngSecurity, Engineering, Ops, Architecture
ClassificationPhân loạiInternal — Security / Engineering
Effective dateNgày hiệu lực01/12/2026
Related docs BR/NFR Catalog · 01_BR Index · 09_GAP Impl · 09_GAP Docs · System Architecture (SAD) · Monitoring Stack · SPEC Shared UI (2FA)

B. Version historyB. Lịch sử phiên bản

Version Date Author ChangesThay đổi
1.2 01/12/2026 Platform / Security Part B structural in suite; B-Gaps moved to 09_GAP; reserved Part B retired
1.1 12/07/2026 Platform / Security Part A in suite; Part B reserved standalone; flows as SVG

C. Table of contentsC. Mục lục

D. ContentD. Nội dung

Requirement mapping

Trace application-security requirements in the BR/NFR catalog and gap registers: Truy vết yêu cầu bảo mật ứng dụng trong catalog BR/NFR và sổ gap:

  • BR/NFR Catalog — Business Requirements (BR) and Non-Functional Requirements (NFR) Business Requirements (BR) và Non-Functional Requirements (NFR)
  • 01_BR Index
  • Module Map
  • 09_GAP — Gap Register — Docs vs implemented · Questions for FlyPay Docs vs triển khai · Câu hỏi cho FlyPay

Disclaimer

This document supports engineering design, security review, and audit preparation. It maps CPG application-layer controls to SOC 2 Trust Services Criteria (Type 2 readiness) and GDPR technical measures (application scope only).

It is not:

  • A SOC 2 Type 2 attestation report
  • A GDPR DPIA, Record of Processing Activities (RoPA), or legal compliance opinion
  • A certification that “CPG is GDPR / SOC 2 certified”

Do not interpret control mappings or “Implemented” labels as proof of Type 2 operating effectiveness over a review period, or as a complete GDPR compliance program. Type 2 readiness requires sustained evidence (access reviews, change tickets, log retention samples, incident records). Legal bases, DPIAs, DPAs, and transfer assessments are owned by Legal / Compliance.

Vendor certifications (for example, node providers claiming SOC 2) are not CPG’s own attestation.

ISO 27001 Annex A mapping is out of scope for Doc03 (see Doc01 / ISMS materials if produced separately).

Implementation status labels

Label Meaning
Implemented Enforced in service code or shared packages today, with cited evidence paths
Partial Present in some services, only at the edge/network, inconsistently applied, or incomplete vs Strategic Approach
Planned Required by Strategic Approach; not yet built (or only documented as design)
Out of scope Owned by infrastructure / operations / legal documents; referenced only for trust-boundary context
Document Relationship
Doc01 — Platform / Infrastructure Security (placeholder) Network, edge WAF, cluster IAM, DR — complements Doc03
Doc02 — Ledger FSD Money-movement data model, templates, idempotency; Scanner FSD remains separate (BR-03)
CRM FSD Auth Product requirements: login, 2FA, password reset
CRM FSD Audit Product requirements: admin audit trail
CRM FSD Compliance Product AML / risk cases (DSR handoff context)
Staging Infrastructure Deployment Plan §11 Edge WAF, Kong, Vault / Secret Manager
Branch protection Required CI security checks, environment approvals
pkg/auth README Shared JWT validation for consumer services
API contract / observability rule Error envelope, authz, no secret/PII logging
Compliance and regulatory alignment MiCA / FinCEN / FATF (adjacent; not SOC 2 / GDPR AppSec)
A4 Key management Custody / HSM / MPC design (out of Doc03 depth)
BR-01-02-03 LEDGER Ledger business requirements; Doc02 forward references
URG field catalog PII field_id masking catalog (GDPR Art. 25/32 technical enabler)

Document map

Part A — Strategic Approach Purpose / Scope / Audience Security Principles Threat Model / Boundaries Control Objectives SOC 2 / GDPR Framing Part B — Structural Implementation Reserved file (not in suite nav yet)
Document map — Part A in this page; Part B reserved for later publication.

Part A — Strategic Approach (Why / What)

A1. Purpose and scope

Purpose

Define how CPG application services are designed and protected, and how they communicate with each other at the application layer, so that:

  1. Engineers share a single trust model (identity planes, S2S contracts, data protection).
  2. Control objectives are explicit and mappable to SOC 2 Type 2 and GDPR (technical measures).
  3. Gaps between intended and actual controls are visible and actionable — fleet-wide (General) vs service-unique (Specific).

In scope

  • Authentication and authorization for CRM (admin) and merchant portal APIs
  • Inter-service HTTP contracts (JWT forwarding, internal secrets, ledger API keys, webhook HMAC)
  • Input validation, stable error responses, upload safety
  • Application-layer cryptography (passwords, field encryption, TOTP secrets)
  • Personal-data technical measures in APIs and logs (minimization, encryption, access control)
  • Request correlation and audit-relevant app behaviors
  • Secure SDLC gates that gate application code changes

Out of scope (referenced only)

  • Physical security, HR controls, vendor risk programs
  • Full network / WAF / Cloudflare Zero Trust configuration (Doc01 / staging plan)
  • On-chain custody and MiCA / FinCEN / FATF matrices beyond cross-links
  • Full GDPR legal program (RoPA, DPIA text, DPA templates, transfer impact assessments)
  • ISO 27001 Annex A mapping
  • Formal auditor workpapers and evidence calendars

Audience

Platform engineers, service owners, security reviewers, and external auditors preparing a CPG TSC workbook and GDPR Art. 32 technical-measures register.

A2. Security principles (normative)

These principles are must requirements for CPG application design. Structural Implementation records how far each is met today.

ID Principle Intent
P1 Zero trust at app boundaries Authenticate and authorize every request at the service; do not rely on network location alone
P2 Least privilege URG/RBAC; per-service secrets; no undocumented god credentials
P3 Defense in depth Edge TLS + service middleware + service-layer re-checks of effective permissions
P4 Secure by default Missing critical secrets in non-dev environments must fail closed
P5 Explicit trust zones Documented S2S contracts per identity plane (admin JWT, merchant JWT, ledger key, webhook, internal)
P6 Safe observability Structured logs and errors without secrets, tokens, or raw PII
P7 Controlled change Application changes pass PR security gates and protected-branch policy
P8 Privacy by design / data minimization Collect and expose only personal data needed for the API purpose; mask/encrypt sensitive fields; no PII in logs by default (GDPR Art. 5, 25)

A3. Threat model (application layer)

Threat Abuse scenario Primary mitigations (see Part B below) Residual risk if gap remains
T1 Stolen JWT Bearer token exfiltrated from browser or logs Short-lived access tokens; refresh revocation; HTTPS at edge; no token logging Long-lived or leaked shared HMAC secret widens blast radius
T2 Privilege escalation User calls admin APIs or elevates via stale JWT claims RBAC middleware; auth-service re-resolves effective permissions from DB Consumers that trust JWT claims alone
T3 Forged internal calls Attacker hits /internal/* without going through issuers Shared X-Internal-Secret; network policies Optional secret when unset (Specific gap)
T4 Webhook spoofing Fake KYC status updates HMAC-SHA256 verification with constant-time compare Misconfigured / empty webhook secret
T5 Malicious upload Executable or oversized payload via file API Category MIME/size checks; dangerous-type denylist Unauthenticated file routes (Specific gap)
T6 PII / secret leakage Tokens or PII in logs/errors Error envelope policy; Cursor/CI rules; field encryption No automatic log redaction helper (General gap)
T7 Replay / duplicate money movement Retried writes double-post ledger effects Ledger idempotency keys CRM writes largely lack app idempotency
T8 Vulnerable dependency Known CVE in Go module or image gosec, govulncheck, OSV, gitleaks, Trivy, semgrep in CI Exclusions for some packages

A4. Trust boundaries and identity planes

Client Edge (Cloudflare / Kong / TLS) auth-service merchant-auth Business APIs (merchant / ticket / common / account / notification) file-service ledger-service account / sync / transaction → Bearer LEDGER_API_KEY Sumsub webhook (HMAC) Data stores (Postgres / Redis / Object store) Planes: Admin JWT · Merchant JWT · X-Internal-Secret · Ledger API key · Webhook HMAC · Edge TLS
Trust boundaries — client → edge → issuers / APIs / ledger / data; Sumsub HMAC into merchant-service.

Identity planes

Plane Credential Issuers / consumers Purpose
Admin JWT HS256 Bearer auth-service → CRM APIs via pkg/auth Admin / CRM user sessions
Merchant JWT HS256 Bearer (+ merchant_uuid) merchant-auth-service → merchant-scoped APIs Merchant portal sessions
Internal S2S X-Internal-Secret Auth/ticket/merchant clients → notification-service /internal/* Trusted notification ingest
Ledger API key Authorization: Bearer <API_KEY> account-service, sync, transaction → ledger Programmable money movement
Webhook HMAC Sumsub digest headers Sumsub → merchant-service public webhook KYC status callbacks
Edge TLS TLS certificates Cloudflare / Kong / Istio Transport confidentiality (Out of scope for app code; trust boundary)

Applications typically listen on HTTP inside the cluster; TLS termination is expected at the edge. Application security must still assume that cluster-network reachability alone is insufficient (P1).

A5. Control objectives

Identity and access

Objective ID What good looks like
CO-ID-01 Every externally reachable business API requires authentication except explicitly documented public endpoints (health, documented webhooks)
CO-ID-02 Authorization enforces least privilege (flat permissions and/or URG grants); sensitive admin actions re-check effective rights from the source of truth
CO-ID-03 Sessions can be listed and revoked; refresh tokens are opaque and stored hashed
CO-ID-04 Strong authentication options exist for privileged users (e.g. TOTP 2FA); brute-force login is mitigated

Cryptography and secrets

Objective ID What good looks like
CO-CR-01 Secrets are injected from a secret manager (Vault / Secret Manager), not hardcoded
CO-CR-02 Passwords are stored with a modern one-way hash (bcrypt); TOTP and sensitive fields use authenticated encryption
CO-CR-03 Signing/validation keys are rotatable; non-dev fails closed if secrets are missing

Communication

Objective ID What good looks like
CO-CM-01 Each S2S pattern uses a documented credential plane (table in A4)
CO-CM-02 Retryable financial operations support idempotency
CO-CM-03 External webhooks verify integrity and authenticity before state change

Input / output

Objective ID What good looks like
CO-IO-01 Inbound payloads are validated; failures return stable VALIDATION_ERROR details
CO-IO-02 Errors use a stable envelope without stack traces, SQL, or secrets
CO-IO-03 Uploads are constrained by type, size, and dangerous content policies

Logging and monitoring

Objective ID What good looks like
CO-LG-01 Requests are correlatable via request / correlation IDs in errors and logs
CO-LG-02 Security-relevant actions leave an audit trail (auth sessions, ledger HTTP audit, CRM audit product)
CO-LG-03 Logs do not contain secrets, tokens, or unnecessary raw PII

Secure development

Objective ID What good looks like
CO-SD-01 PRs run SAST / vuln / dedicated secret scanners (gitleaks) before merge; deploys require Trivy image gates
CO-SD-02 Protected branches require security checks and appropriate approvals

Personal data / GDPR technical measures

Objective ID What good looks like
CO-PD-01 APIs expose only personal data needed for the stated purpose; sensitive attributes are masked or encrypted (Art. 5 minimization, Art. 25)
CO-PD-02 Personal data at rest in application stores uses appropriate encryption or access restriction (Art. 32)
CO-PD-03 Application logging and errors do not become an unintended PII disclosure channel (Art. 5, 32)
CO-PD-04 Processor integrations (e.g. KYC, email) are authenticated and scoped; transfer/DPA details live in vendor docs (Art. 28)
CO-PD-05 Data subject rights are supported by product/API capabilities or an explicit handoff to CRM Compliance (Art. 15–18, 20–21) — Planned where not built

A6. Compliance framing (SOC 2 Type 2 and GDPR)

How to read this mapping

  • SOC 2 Type 2 evaluates whether controls operated effectively over a period. Doc03 defines design and evidence sources (code paths, CI, Vault injection). Operating evidence is an organizational process.
  • GDPR in Doc03 covers application technical measures that support Art. 5, 25, 32 (and related articles). It does not replace legal bases, RoPA, DPIA, or DPA programs.

Primary Trust Services Criteria (application focus)

TSC Application relevance
CC6 Logical and physical access JWT, RBAC, S2S secrets, Vault injection, least privilege
CC7 System operations Logging, correlation IDs, audit trails, monitoring hooks, incident-relevant signals
CC8 Change management PR quality gate, branch protection, CODEOWNERS, GitOps deploys
C1 Confidentiality Field encryption, TLS at edge, secret handling, PII masking grants
PI1 Processing integrity Validation, idempotency (ledger), webhook authenticity
A1 Availability App timeouts/retries contribute; primary availability is infra/DR (Partial in Doc03)

Primary GDPR articles (application technical focus)

GDPR Application relevance
Art. 5 Integrity/confidentiality and data minimization via access control, encryption, log hygiene (technical enablers; accountability evidence is org-owned)
Art. 25 Privacy by design/default: URG field masking, least data in responses, secure defaults
Art. 32 Security of processing: encryption, access control, integrity of processing (validation/idempotency), ability to detect issues via logs
Art. 33–34 Breach detection support via correlation IDs and audit signals (IR process is org-owned)
Art. 15–18, 20–21 Data subject rights — product/API support or CRM Compliance handoff
Art. 28, 44–49 Processors/transfers where app integrates Sumsub, email, etc. — boundary only; legal detail elsewhere

Detailed control-to-evidence mapping is in B-Matrix (Part B below).

APPSEC — Step-up 2FA for Account sensitive mutations

ID: APPSEC-ACC-STEPUP-2FA
Related: Merchant Portal Accounts Round A (docs/html/02A_SPEC/Merchant_Portal/Account/CPG-SPEC-ACC-SHARED-UI.html), MP FSD Account v2.2, API_Account.

Login / session 2FA alone is not sufficient for Account custody mutations. The portal and APIs MUST require a fresh step-up 2FA (TOTP or approved challenge) immediately before:

  • Create Beneficiary Wallet, Hot Wallet, or Virtual Account
  • Approve or reject an Inactive Beneficiary Wallet (maker-checker)
  • Request Hot Wallet activation (Support ticket)
  • Change Virtual Account or Beneficiary Wallet status (where merchant-initiated)

Rules:

  • Failed or cancelled challenge → no state change and no side-effect API call.
  • Challenge binding SHOULD be scoped to the pending action (anti-replay).
  • Prefer server-side verification via merchant-auth; do not trust a client-only “verified” flag.
  • Audit successful and failed step-up attempts without logging OTP codes.

Control mapping: strengthens authentication for privileged money-path configuration (aligned with Doc03 authentication / APPSEC expectations for strong auth on sensitive operations).

Appendix A — Error code to HTTP status (application contract)

HTTP Stable error.code examples
400 VALIDATION_ERROR, BAD_REQUEST
401 UNAUTHORIZED
403 FORBIDDEN
404 NOT_FOUND
409 CONFLICT, ALREADY_EXISTS
429 RATE_LIMITED
500 INTERNAL_ERROR
503 SERVICE_UNAVAILABLE

Source: pkg/apierror and .cursor/rules/api-contract-observability.mdc.

Part B — Structural Implementation (How)

Gap register — fleet-wide and service-specific gaps with acceptance criteria are published under 09_GAP — Docs vs Implemented. Doc↔doc questions for FlyPay: 09_GAP Docs.

Part B — Structural Implementation B0 Inventory B-General (all services) B-Specific (deltas) B-Matrix Evidence B-Gaps Register
Part B structure — General controls feed Specific deltas, matrix, and gaps.

Part B has two layers:

  • B-General — controls every application service is expected to follow (Implemented baseline vs fleet-wide Gap).
  • B-Specific — only deltas unique to a named service (stronger controls or material gaps vs General).

Each claim: mechanisms → status → evidence → SOC 2 TSC + GDPR tags.

B0. Service inventory and trust zones

Architecture pattern

CPG backend is a Go monorepo (be/): independent modules under services/, shared libraries under pkg/. Typical service layout:

cmd/main.go → chi router + CORS → internal/api handlers → internal/* domain → env / Vault-injected config.

Handlers stay thin; business logic lives in internal/* (see .cursor/rules/go-service-best-practices.mdc).

Service inventory

Zone Service Role Default port (local)
Identity issuer auth-service Admin/CRM auth: login, JWT, 2FA, sessions, URG RBAC 8080
Identity issuer merchant-auth-service Merchant portal auth (parallel model) 8086
Business API merchant-service Merchants, KYC, Sumsub webhooks 8085
Business API ticket-service Support tickets; merchant-scoped actors 8089
Business API common-service Settings / payment service catalog 8084
Business API account-service Accounts / hot wallets; calls ledger —
Business API notification-service In-app/email + WS; internal ingest 8082
Business API file-service Uploads (MinIO/GCS) 8081
Money movement transaction Crypto tx API → ledger —
Money movement sync Chain sync → ledger / portal —
Money movement ledger / ledger-service Formance-based ledger —

Shared libraries (security-relevant)

Package Role
pkg/auth JWT parse/validate, permission middleware helpers
pkg/apierror Canonical JSON error envelope + request ID helpers
pkg/rbac Shared RBAC helpers (e.g. ticket categories)
pkg/ledgerclient HTTP client with Bearer ledger API key
pkg/logger Zap logging (no automatic PII redaction today)

Empty scaffolding (pkg/middleware, pkg/tracing, pkg/metrics, pkg/validator) indicates planned shared cross-cutting concerns not yet filled.

Compliance tags: CC6; Art. 32 (configuration / component inventory as security baseline).

B-General — Controls for all application services

Cross-cutting design that every CPG application service is expected to follow.

G1. Identity consumption

  • Consumers validate Bearer JWTs with the shared secret via pkg/auth (JWT_SECRET / JWT_SECRET_KEY).
  • Principle P1: do not rely on network-only trust for business APIs.

```53:61:pkg/auth/jwt.go func NewJWTConfig() *JWTConfig { secret := os.Getenv("JWT_SECRET") if secret == "" { secret = os.Getenv("JWT_SECRET_KEY") } if secret == "" { secret = "supersecretkey" // fallback for development only } return &JWTConfig{SecretKey: []byte(secret)} }


| Status | Notes |
|--------|-------|
| **Partial** | Pattern is standard for CRM/merchant consumers; **not** universal (see Specific: `file-service`). Dev hardcoded fallback is a fleet-wide **Gap** for staging/prod. |

**Tags:** CC6; Art. 32. **Evidence:** `pkg/auth/jwt.go`, `pkg/auth/README`.

### G2. Authorization pattern

- Authenticate near entrypoints; re-check ownership/permissions in service logic when needed (`.cursor/rules/api-contract-observability.mdc`).
- Flat permission helpers in `pkg/auth`; URG grants where applicable.

| Status | Notes |
|--------|-------|
| **Partial** | Strongest on auth-service (DB re-check). Consumer routes are inconsistent — some JWT-only without fine-grained flat checks. |

**Tags:** CC6; Art. 5, 32. **Evidence:** `pkg/auth/middleware_permission.go`; service `authz` helpers.

### G3. Error envelope

Canonical shape via `pkg/apierror`:

```json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request payload",
    "details": [{ "field": "email", "reason": "must be a valid email" }],
    "request_id": "req_123"
  }
}
Status Notes
Partial Adopted by auth, ticket, notification internals; common-service and some middleware still diverge (see Specific).

Tags: PI1, CC7; Art. 5, 32 (no secret/PII leakage in errors). Evidence: pkg/apierror/response.go.

G4. Secrets injection

  • Production: Vault CSI → Kubernetes Secret → env (JWT_SECRET, encryption keys, DB/Redis, etc.).
  • Cloud SQL passwords also via GCP Secret Manager.
  • Semgrep cpg.no-hardcoded-secrets in CI.
Status Notes
Implemented pattern; Gap on JWT/NewJWTConfig fallback Must fail closed in non-dev (P4).

Tags: CC6, C1; Art. 32. Evidence: infra/services/*/templates/spc.yaml, scripts/vault/bootstrap-k8s-roles.sh, be/.semgrep.yml.

G5. Logging and correlation

  • apierror reads X-Request-Id / X-Correlation-Id into error envelopes.
  • Policy: never log secrets, tokens, or raw PII.
Status Notes
Partial No shared middleware to generate/propagate IDs into all logs; pkg/logger has no automatic redaction helper.

Tags: CC7; Art. 5, 32, 33–34 (detection support). Evidence: pkg/apierror/response.go, .cursor/rules/api-contract-observability.mdc.

G6. CORS and edge assumptions

  • chi CORS + CORS_ALLOWED_ORIGINS per service.
  • TLS termination at Cloudflare / Kong / Istio (Out of scope for app code).
Status Notes
Partial Some defaults permissive (*). Edge rate limiting is target in staging plan; no shared app rate-limiter middleware (RATE_LIMITED code unused).

Tags: CC6; Art. 32. Evidence: service cmd/main.go CORS setup; staging plan §11.

G7. Secure SDLC

  • PR quality gate: gosec, govulncheck, OSV, gitleaks (secrets), semgrep.
  • Deploy gate: Trivy image scan fails on CRITICAL/HIGH (fixed) CVEs before push/promote.
  • Branch protection requires security checks; CODEOWNERS on sensitive paths.
Status Notes
Implemented for primary CRM modules; Partial gosec exclusions for ledger/sync/transaction/account-service; Sonar commented out.

Tags: CC8. Evidence: .github/workflows/pr-quality-gate.yml, BRANCH_PROTECTION, .github/CODEOWNERS.

G8. Inter-service contract discipline

  • Primary protocol: HTTP JSON (no gRPC in primary CPG services).
  • Every call must use a documented identity plane (A4).
Browser Edge (TLS) auth / merchant-auth Business APIs notification /internal ledger-service merchant webhook Bearer JWT X-Internal-Secret LEDGER_API_KEY Sumsub HMAC-SHA256
Inter-service contracts — each hop uses a documented identity plane (A4 / G8).
Status Notes
Implemented as pattern; Gaps in Specific Fail-open internal secret; unauthenticated file routes. Mesh mTLS Planned.

Tags: CC6, PI1; Art. 32. Evidence: pkg/ledgerclient/client.go; notification/file Specific sections.

G9. Personal data handling (GDPR technical)

  • Minimize PII in logs/responses; encrypt sensitive fields where stored; URG field_id masking catalog.
  • Data subject rights APIs largely product / Planned (handoff to CRM Compliance FSD).
Status Notes
Partial Field encryption in merchant / merchant-auth / ticket only; no universal redaction; DSR not fully built at API layer.

Tags: C1; Art. 5, 25, 32; Art. 15–18/20–21 Planned. Evidence: */internal/security/field_cipher.go, API_Setting_URG.

General gap summary (fleet-wide)

Full gap register (acceptance criteria, owners, remediation order) lives in 09_GAP — Docs vs Implemented:

Gap ID Priority Topic
GAP-G01 High JWT HS256 shared secret + fallback; no JWKS/rotation
GAP-G02 Medium Error envelope not universal
GAP-G03 Medium No shared request-ID / log redaction middleware
GAP-G04 Medium No app-layer rate limiting; permissive CORS
GAP-G05 Medium CRM write idempotency largely missing
GAP-G06 Medium Mesh mTLS / Kong config not in tree
GAP-G07 Medium DB/Redis transit encryption weak
GAP-G08 Medium Inconsistent permission enforcement

Specific service gaps: GAP-S01…S05. Doc↔doc / FlyPay questions: 09_GAP Docs gaps.

B-Specific — Per application service (deltas only)

Subsections appear only where a service adds unique controls or material gaps vs General. Do not restate G1–G9.

S1. auth-service

Delta Status Evidence
JWT issuer (admin plane): HS256 access tokens with user_id, email, sid, permissions, grants Implemented services/auth-service/internal/auth/jwt.go
Opaque refresh in Redis; SHA-256 hashed session audit; list/revoke Implemented internal/auth/token_store.go
TOTP 2FA; secrets encrypted with TOTP_ENCRYPTION_KEY Implemented internal/auth/totp.go
Login lockout after failed attempts Implemented internal/api/login_failed_attempts.go
URG RBAC with DB re-check of effective permissions (EffectiveFlat / urgAll / urgAny) Implemented internal/middleware/rbac.go, internal/api/user_handler.go
Security-action short-lived tokens; phishing-code UX Implemented internal/auth/security_action.go, phishing handler
Password strength + bcrypt Implemented internal/auth/password.go

Tags: CC6, C1; Art. 5, 32. Product intent: CRM FSD Auth.

S2. merchant-auth-service

Delta Status Evidence
Parallel JWT issuer with merchant_uuid claim Implemented services/merchant-auth-service/internal/auth/jwt.go
Merchant portal session / authz routes Implemented merchant-auth API under /api/v1/authz/...
AES-GCM field cipher for sensitive merchant-auth data Implemented internal/security/field_cipher.go

Tags: CC6, C1; Art. 25, 32.

S3. merchant-service

Delta Status Evidence
Sumsub KYC webhook HMAC-SHA256 (hmac.Equal) Implemented internal/api/kyc_webhook_handler.go, test/api/sumsub_webhook_test.go
Public webhook route documented exception to JWT Implemented (intentional) internal/api/server.go /api/v1/public/kyc/sumsub/webhook
Merchant AES-GCM field encryption (enc:v1:) Implemented internal/security/field_cipher.go
Sumsub as processor integration boundary Partial (tech auth only) Config webhook secret; DPA/transfers Out of scope

Tags: PI1, CC6, C1; Art. 28, 32. KYC personal data → Art. 5/32.

S4. ticket-service

Delta Status Evidence
Merchant vs admin actor from merchant_uuid Implemented handler actorFromRequest
Ticket category RBAC scoping Implemented pkg/rbac/ticket_categories.go
Field encryption for merchant contact fields Implemented internal/security/field_cipher.go

Tags: CC6, C1; Art. 25, 32.

S5. common-service

Delta Status Evidence
Flat + grant authorization helpers Implemented internal/api/authz.go
Gap: writeErr returns non-canonical {message, error} Partial / GAP-S03 common-service error helpers

Tags: CC6; Art. 32 (safe errors — Partial).

S6. notification-service

Delta Status Evidence
Internal ingest POST /internal/notifications Implemented path internal/api/internal_handler.go
X-Internal-Secret only when INTERNAL_SECRET set Partial / GAP-S02 same file — fail-open if unset
Redis pub/sub notifications:user:* for WS fan-out Implemented internal handler / event path

```22:36:services/notification-service/internal/api/internal_handler.go // Protects with optional X-Internal-Secret header when INTERNAL_SECRET is set. ... if internalSecret != "" { secret := strings.TrimSpace(r.Header.Get("X-Internal-Secret")) if secret != internalSecret { apierror.WriteFromRequest(w, r, http.StatusUnauthorized, ...) return } }


**Tags:** CC6; Art. 32.

### S7. file-service

| Delta | Status | Evidence |
|-------|--------|----------|
| Upload category MIME/size + dangerous-type checks | **Implemented** | `internal/api/file_handler.go` |
| Routes registered **without JWT** | **Gap** GAP-S01 | `RegisterRoutes` upload/get/list/delete |

```135:141:services/file-service/internal/api/file_handler.go
func (h *FileHandler) RegisterRoutes(r chi.Router) {
    r.Post("/api/v1/files/upload", h.Upload)
    r.Get("/api/v1/files/{id}", h.Get)
    r.Get("/api/v1/files", h.List)
    r.Delete("/api/v1/files/{id}", h.Delete)
}

Tags: PI1, CC6, C1; Art. 32 — validation Implemented, authentication not.

S8. account-service / transaction / sync

Delta Status Evidence
Ledger client Bearer API key Implemented pkg/ledgerclient/client.go; LEDGER_API_KEY env
Sync portal client Bearer service token Implemented services/sync/internal/client/portal_client.go
Outbound timeouts on money-path clients Partial / varies service clients
gosec CI exclusions for these packages Partial residual pr-quality-gate.yml

Tags: CC6, PI1; Art. 32.

S9. ledger / ledger-service

Delta Status Evidence
Strong idempotency (IdempotencyKey / hash) Implemented ledger-service log/idempotency; e2e api_idempotency*
HTTP audit middleware / audit-events Implemented ledger-service/internal/api/ httpaudit
OAuth / API key client model Implemented ledger auth clients
gosec exclusions (residual SDLC risk) Partial CI workflow

Tags: PI1, CC7, CC8; Art. 32 (integrity of processing).

B-Matrix — Control evidence matrix

Control ID Scope Objective SOC 2 TSC GDPR Mechanism Status Evidence (paths) Owner
APPSEC-ID-01 General Authenticate external APIs CC6 Art. 32 HS256 JWT via pkg/auth Partial pkg/auth/jwt.go; exception: file-service Platform / service owners
APPSEC-ID-02 Specific:auth / merchant-auth Dual identity planes CC6 Art. 32 Separate admin vs merchant issuers Implemented services/auth-service, merchant-auth-service Identity
APPSEC-ID-03 Specific:auth Session revoke / refresh hygiene CC6 Art. 32 Opaque refresh; hashed rows; revoke APIs Implemented auth-service/internal/auth/token_store.go Identity
APPSEC-ID-04 Specific:auth MFA for privileged access CC6 Art. 32 TOTP 2FA; encrypted secrets Implemented auth-service/internal/auth/totp.go Identity
APPSEC-ID-05 Specific:auth Brute-force login mitigation CC6 Art. 32 Failed attempt counter; lock inactive Implemented auth-service/internal/api/login_failed_attempts.go Identity
APPSEC-ID-06 General Least-privilege RBAC CC6 Art. 5, 32 URG + flat; DB re-check on admin Partial auth-service rbac; pkg/auth/middleware_permission.go Identity / API owners
APPSEC-ID-07 General Field-level grants / masking C1 Art. 25, 32 URG field_id catalog Partial API_Setting_URG Identity / CRM
APPSEC-ID-08 Specific:notification Internal S2S authentication CC6 Art. 32 X-Internal-Secret Partial notification-service/.../internal_handler.go Platform
APPSEC-ID-09 Specific:account/sync/transaction Ledger client authentication CC6 Art. 32 Bearer API key in pkg/ledgerclient Implemented pkg/ledgerclient/client.go Ledger / money movement
APPSEC-ID-10 Specific:merchant Webhook authenticity PI1, CC6 Art. 28, 32 Sumsub HMAC-SHA256 Implemented merchant KYC webhook + tests Merchant
APPSEC-ID-11 Specific:auth Password hashing C1, CC6 Art. 32 bcrypt Implemented auth-service/internal/auth/password.go Identity
APPSEC-ID-12 Specific:merchant, merchant-auth, ticket Field encryption at rest C1 Art. 5, 32 AES-256-GCM enc:v1: Implemented (those services) */internal/security/field_cipher.go Data / service owners
APPSEC-ID-13 General Secret injection CC6, C1 Art. 32 Vault CSI → env; Secret Manager Implemented SPC templates; vault bootstrap Platform
APPSEC-ID-14 General No hardcoded secrets in code CC8, C1 Art. 32 Gitleaks + Semgrep + CI Partial .gitleaks.toml; .semgrep.yml; JWT fallback in pkg/auth Platform
APPSEC-ID-15 General Stable error contract PI1, CC7 Art. 5, 32 pkg/apierror envelope Partial pkg/apierror; common-service exception API owners
APPSEC-ID-16 General Input validation PI1 Art. 32 Handler validators Implemented service handlers API owners
APPSEC-ID-17 Specific:file Upload safety PI1, C1 Art. 32 MIME/size/dangerous-type Partial validation yes; auth no File
APPSEC-ID-18 General Request correlation CC7 Art. 33–34, 32 Request ID in errors Partial pkg/apierror; no generate middleware Platform
APPSEC-ID-19 Specific:ledger + General Security audit logging CC7 Art. 5, 32 Sessions; ledger httpaudit; CRM Audit FSD Partial ledger audit; auth token store; FSD Audit Platform / CRM
APPSEC-ID-20 General No secret/PII in logs C1, CC7 Art. 5, 32 Policy in Cursor rules Partial observability rule; no logger redactor Platform
APPSEC-ID-21 Specific:ledger Ledger idempotency PI1 Art. 32 Idempotency keys Implemented ledger-service; e2e tests Ledger
APPSEC-ID-22 General CRM write idempotency PI1 Art. 32 Idempotency-Key on mutations Planned Cursor rule; most CRM writes lack keys API owners
APPSEC-ID-23 General App-layer rate limiting CC6, A1 Art. 32 Middleware + Kong limits Planned / Partial RATE_LIMITED unused; staging §11 Platform / Edge
APPSEC-ID-24 General CORS lockdown CC6 Art. 32 Explicit allowlists Partial service cmd/main.go Service owners
APPSEC-ID-25 General SAST / vuln / secret / image scanning CC8 — (SDLC) gosec, govulncheck, OSV, gitleaks, Trivy, semgrep Partial pr-quality-gate.yml, reusable-build-push.yml; gosec exclusions Platform
APPSEC-ID-26 General Protected change management CC8 — (SDLC) Branch protection, CODEOWNERS Implemented BRANCH_PROTECTION Platform
APPSEC-ID-27 General JWT key rotation / asymmetric CC6 Art. 32 JWKS / RS256 Planned — Identity
APPSEC-ID-28 General Fail-closed missing secrets CC6 Art. 25, 32 Refuse start if secrets missing in non-dev Planned contrast JWT fallback + optional INTERNAL_SECRET Platform
APPSEC-ID-29 General (edge) Edge TLS / WAF CC6, C1 Art. 32 Cloudflare WAF; Kong/Istio TLS Out of scope (app) Staging plan §11 Platform / Infra
APPSEC-ID-30 General (edge) Service mesh mTLS CC6 Art. 32 Istio STRICT mTLS + AuthZ Planned Not evidenced Platform / Infra
APPSEC-ID-31 General Data minimization in APIs C1 Art. 5, 25 Purpose-bound fields; URG masking Partial URG catalog; FE + grants CRM / API
APPSEC-ID-32 General Data subject rights support — Art. 15–18, 20–21 Product/API or Compliance handoff Planned CRM Compliance FSD CRM / Legal
APPSEC-ID-33 Specific:merchant Processor integration auth CC6 Art. 28 Sumsub HMAC; scoped secrets Implemented (tech) webhook handler Merchant / Legal

Appendix B — Maintaining this document

See source Doc03 markdown in the repository for maintenance rules. Gap lifecycle is tracked in 09_GAP.

Mapped Requirements

BR/NFR/REQ items from the master catalog mapped to this document. IDs link to anchors in 01_BR; local id anchors still accept deep-links from the catalog.Các BR/NFR/REQ từ catalog master được ánh xạ tới tài liệu này. ID liên kết tới anchor trong 01_BR; id cục bộ vẫn nhận deep-link từ catalog.

  • BR-OVW-SEC-001 BR — Security & Risk Mitigation: Ensure Maximum Security for both Merchant and Gateway Provider through the ZERO principleSecurity & Risk Mitigation: Đảm bảo Maximum Security cho cả Merchant và Gateway Provider thông qua nguyên tắc ZERO
  • BR-CORE-QUAL-001 BR — Primary DB for Transactions: Requires an RDBMS that ensures ACID compliance for financial records.Primary DB cho Transactions: Yêu cầu một RDBMS đảm bảo ACID compliance cho financial records.
  • BR-CORE-QUAL-002 BR — Host public-facing, elastic, and outbound-heavy services.Host các service public-facing, elastic, và outbound-heavy.
  • BR-CORE-SEC-001 BR — Host core business logic and sensitive data (complying with data residency and security control).Host các core business logic và sensitive data (tuân thủ data residency và security control).
  • BR-CORE-SEC-002 BR — Personal Identifiable Information (PII, such as admin name, email, KYC...) must be stored in a separate database/schema (PII Vault) withThông tin nhận dạng cá nhân (PII, như tên admin, email, KYC...) phải lưu trong database/schema riêng (PII Vault) với
  • NFR-Sec1 NFR — TLS 1.3 everywhere; HSTS on public endpoints.TLS 1.3 everywhere; HSTS trên public endpoints.
  • NFR-Sec2 NFR — Encryption at rest: DB, object storage, backups (AES-256).
  • NFR-Sec3 NFR — Secret management qua Vault / KMS / HSM.
  • NFR-Sec4 NFR — RBAC with least privilege; admin actions 2FA; sensitive actions step-up OTP.RBAC với least privilege; admin actions 2FA; sensitive actions step-up OTP .
  • NFR-Sec5 NFR — WAF + DDoS protection; rate limiting (per IP , per merchant).
  • NFR-Sec6 NFR — All code handed over by partners must fully meet security standards and software development processesTất cả code bàn giao bởi đối tác phải đáp ứng đầy đủ các tiêu chuẩn bảo mật và quy trình phát triển phần mềm
  • NFR-SC1 NFR — Smart Contract Governance: All Smart Contracts (fee-splitting) must be immutable OR follow the proxy patternSmart Contract Governance: Tất cả Smart Contract (fee-splitting) phải immutable HOẶC tuân theo proxy pattern
  • NFR-SC2 NFR — Admin Control: All privileged functions (pause/setFee/upgrade) must be owned by Gnosis Safe (multi-sig), strictly prohibited for EOA admin control.Admin Control: Mọi function privileged (pause/setFee/upgrade) phải owned bởi Gnosis Safe (multi-sig), nghiêm cấm EOA admin control.
  • NFR-SC3 NFR — Slither + Echidna fuzzing before deployment; external audit for production.Slither + Echidna fuzzing trước deployment; external audit cho production.
  • NFR-Sec8 NFR — WaaS Integration Security: API key calling WaaS provider (Web3Auth, ...) must be stored in Secret Manager and onlyWaaS Integration Security: API key call WaaS provider (Web3Auth, ...) phải lưu trong Secret Manager và chỉ
  • NFR-M1 NFR — Code quality gates (lint, unit, integration, contract tests) are mandatory to merge code.Code quality gates (lint, unit, integration, contract tests) bắt buộc để merge code.
  • NFR-M2 NFR — Minimum unit test coverage: Core ≥ 80%, smart contract (critical) ≥ 90%.Coverage unit test tối thiểu: Core ≥ 80%, smart contract (critical) ≥ 90%.
  • NFR-Dev1 NFR — Use immutable images for deployment.Dùng immutable images cho deployment.
  • NFR-Dev2 NFR — CI/CD deploys through staged approvals; the production environment requires a minimum of 2 people to review contractsCI/CD triển khai qua staged approvals; môi trường production yêu cầu review tối thiểu 2 người đối với contracts
  • NFR-Dev3 NFR — Do not store secrets in the repo; only use short-lived tokens.Không lưu secrets trong repo; chỉ sử dụng short-lived tokens.
  • NFR-Dev5 NFR — The CI/CD pipeline must support deploying artifacts to both Public Cloud (K8s cluster) and On-premise (K8s cluster) environments.CI/CD pipeline phải hỗ trợ deploy artifact đến cả Public Cloud (K8s cluster) và On-premise (K8s cluster) sử dụng
  • REQ-DATA-3 REQ — Data Segregation (PII Vault)

E. ReferencesE. Tham chiếu