openapi: 3.0.3 info: title: Anti-fraud Service API version: 1.3.0 description: | # Anti-fraud Service REST API for detecting fraudulent transactions using configurable DSL rules. ## User Roles - **ADMIN** — full access: user management, rules, view all transactions and statistics - **USER** — limited access: own profile only, own transactions, create transactions for self ## Authentication (JWT) Bearer token is used in the `Authorization: Bearer ` header. **JWT Parameters:** - Algorithm: HS256 - Lifetime: 1 hour (3600 seconds) - Secret: from `RANDOM_SECRET` environment variable (128 characters) **Token Payload:** ```json { "sub": "", "role": "USER|ADMIN", "iat": 1234567890, "exp": 1234571490 } ``` ## DSL for Fraud Rules Rules are described using a simple expression language. **Grammar (EBNF):** ``` expression = term { "OR" term } term = factor { "AND" factor } factor = "NOT" factor | comparison | "(" expression ")" comparison = field operator value field = "amount" | "currency" | "merchantId" | "ipAddress" | "deviceId" | "user.age" | "user.region" operator = ">" | ">=" | "<" | "<=" | "=" | "!=" value = number | string string = "'" { character } "'" number = digit { digit } [ "." digit { digit } ] ``` **Important Parsing Rules:** - Operators AND, OR, NOT are case-INsensitive (and = AND = And) - Whitespace is ignored (amount>10000 = amount > 10000) - Strings are compared case-SENSITIVELY ('RUB' != 'rub') - Operator precedence: NOT > AND > OR - If user.age or user.region field is null — the rule does NOT trigger (returns false) **Examples:** - `amount > 10000` - `amount > 5000 AND currency = 'RUB'` - `user.age < 21 AND amount > 10000` - `(amount > 10000 OR user.region = 'HIGH_RISK') AND NOT (currency = 'USD')` ## HTTP Response Codes | Code | When Returned | |-----|-------------------| | 200 | Successful GET/PUT | | 201 | Successful POST (resource creation), including DECLINED transactions | | 204 | Successful DELETE | | 400 | Invalid JSON, unsupported Content-Type | | 401 | Missing/invalid/expired token | | 403 | Insufficient permissions (role or access to another's resource) | | 404 | Resource not found | | 409 | Conflict (email taken, rule name taken) | | 422 | Field validation error | | 423 | User deactivated | ## Data Storage - DECLINED transactions are saved to the database along with rule check results - GET /transactions/{id} returns stored ruleResults (does not recalculate) - DELETE /users/{id} sets isActive=false (does not physically delete) - DELETE /fraud-rules/{id} sets enabled=false (does not physically delete) servers: - url: /api/v1 tags: - name: Auth description: Registration and authorization - name: Users description: User and profile management - name: Transactions description: Transactions (purchases), anti-fraud execution - name: FraudRules description: Fraud rule management - name: Statistics description: Statistics/analytics (metrics and breakdowns) security: - BearerAuth: [] paths: /ping: get: tags: [Auth] summary: Health check description: | Service health check. Returns 200 OK if the service is ready to process requests. security: [] responses: '200': description: Service is running content: application/json: schema: type: object properties: status: type: string example: "ok" /auth/register: post: tags: [Auth] summary: Register new user description: | Scenarios: - 201: user created, USER role by default, returns accessToken and profile. - 409: email already in use. - 422: validation failed (email, password, age, etc.). security: [] requestBody: required: true content: application/json: schema: { $ref: '#/components/schemas/RegisterRequest' } examples: ok: summary: Successful registration value: email: user@example.com password: "Qwerty_123" fullName: "Ivan Ivanov" region: "RU-MOW" gender: MALE age: 25 maritalStatus: SINGLE responses: '201': description: | User successfully registered. Note: accessToken is used in Authorization: Bearer . content: application/json: schema: { $ref: '#/components/schemas/AuthResponse' } examples: created: summary: Token + profile value: accessToken: "eyJhbGciOi..." user: id: "550e8400-e29b-41d4-a716-446655440000" email: "user@example.com" fullName: "Ivan Ivanov" region: "RU-MOW" gender: "MALE" age: 25 maritalStatus: "SINGLE" role: "USER" isActive: true createdAt: "2025-12-15T10:00:00Z" updatedAt: "2025-12-15T10:00:00Z" '400': $ref: '#/components/responses/BadRequest' '409': description: Email already taken content: application/json: schema: { $ref: '#/components/schemas/ApiError' } examples: conflict: value: code: EMAIL_ALREADY_EXISTS message: "User with this email already exists" traceId: "[UUID13]" timestamp: "2025-12-15T10:00:00Z" path: "/api/v1/auth/register" details: field: "email" value: "user@example.com" '422': $ref: '#/components/responses/ValidationFailed' /auth/login: post: tags: [Auth] summary: User authorization description: | Scenarios: - 200: correct credentials => accessToken. - 401: incorrect email/password (do not reveal which one is wrong). - 423: user deactivated (isActive=false). - 422: email/password format is invalid. security: [] requestBody: required: true content: application/json: schema: { $ref: '#/components/schemas/LoginRequest' } examples: ok: value: email: "user@example.com" password: "Qwerty_123" responses: '200': description: Successful authorization content: application/json: schema: { $ref: '#/components/schemas/AuthResponse' } '400': $ref: '#/components/responses/BadRequest' '401': $ref: '#/components/responses/Unauthorized' '423': $ref: '#/components/responses/Locked' '422': $ref: '#/components/responses/ValidationFailed' /users: get: tags: [Users] summary: List of users description: | ADMIN only. Scenarios: - 200: page of users - 422: invalid page/size x-roles: [ADMIN] parameters: - $ref: '#/components/parameters/Page' - $ref: '#/components/parameters/Size' responses: '200': description: List of users content: application/json: schema: { $ref: '#/components/schemas/PagedUsers' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '422': $ref: '#/components/responses/ValidationFailed' post: tags: [Users] summary: Create user by admin description: | ADMIN only. No tokens in response (creation "from admin panel"). Scenarios: - 201: created - 409: email taken - 422: field validation failed (password/role/age, etc.) x-roles: [ADMIN] requestBody: required: true content: application/json: schema: { $ref: '#/components/schemas/UserCreateRequest' } responses: '201': description: User created content: application/json: schema: { $ref: '#/components/schemas/User' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '409': $ref: '#/components/responses/Conflict' '422': $ref: '#/components/responses/ValidationFailed' /users/me: get: tags: [Users] summary: Get current user profile description: | Returns the profile of the user identified by the JWT token. Convenient way to get your own profile without knowing your ID. Available for any role (ADMIN, USER). x-roles: [ADMIN, USER] responses: '200': description: Current user profile content: application/json: schema: { $ref: '#/components/schemas/User' } '401': $ref: '#/components/responses/Unauthorized' put: tags: [Users] summary: Update current user profile description: | Full update of the current user profile. All fields must be provided. To clear a field, pass null. **Required fields:** fullName, age, region, gender, maritalStatus **Fields that can be null:** age, region, gender, maritalStatus **Fields that CANNOT be null:** fullName **Restrictions for USER:** - Cannot change role — returns 403 - Cannot change isActive — returns 403 ADMIN can change any fields of their profile, including role and isActive. x-roles: [ADMIN, USER] requestBody: required: true content: application/json: schema: { $ref: '#/components/schemas/UserUpdateRequest' } examples: fullUpdate: summary: Full update with null value: fullName: "Ivan Ivanov" age: 30 region: "RU-SPB" gender: null maritalStatus: "MARRIED" responses: '200': description: Updated profile content: application/json: schema: { $ref: '#/components/schemas/User' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '422': $ref: '#/components/responses/ValidationFailed' /users/{id}: parameters: - $ref: '#/components/parameters/UserId' get: tags: [Users] summary: Get user profile description: | Access: - ADMIN: any user - USER: own profile only (id == sub/id in token) Scenarios: - 200: found - 403: USER attempting to read another's profile - 404: not found x-roles: [ADMIN, USER] responses: '200': description: User profile content: application/json: schema: { $ref: '#/components/schemas/User' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '404': $ref: '#/components/responses/NotFound' put: tags: [Users] summary: Full update of user profile description: | Full profile update. All fields must be provided. To clear a field, pass null. **Required fields:** fullName, age, region, gender, maritalStatus **Fields that can be null:** age, region, gender, maritalStatus **Fields that CANNOT be null:** fullName **Access rights:** - ADMIN: can update any profile, including role and isActive - USER: own profile only (id in URL == id in token) **Restrictions for USER:** - Attempt to change role => 403 FORBIDDEN - Attempt to change isActive => 403 FORBIDDEN - Attempt to update another's profile => 403 FORBIDDEN **Validation:** - fullName: 2-200 characters (required, cannot be null) - age: 18-120 or null - region: up to 32 characters or null - email cannot be changed (ignored if provided) x-roles: [ADMIN, USER] requestBody: required: true content: application/json: schema: { $ref: '#/components/schemas/UserUpdateRequest' } examples: fullUpdate: summary: Full update with null value: fullName: "New Name" age: 25 region: null gender: "MALE" maritalStatus: null responses: '200': description: Updated profile content: application/json: schema: { $ref: '#/components/schemas/User' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '404': $ref: '#/components/responses/NotFound' '422': $ref: '#/components/responses/ValidationFailed' delete: tags: [Users] summary: Deactivate user description: | **Important:** This is a soft-delete. The user is NOT physically deleted from the database, but marked as inactive (isActive = false). Only ADMIN can deactivate users. **Idempotency:** - Repeated call for already deactivated user => 204 (not an error) - Non-existent user => 404 **Consequences of deactivation:** - POST /auth/login => 423 USER_INACTIVE - POST /transactions with deactivated userId => 403 FORBIDDEN - All existing user tokens continue to work until expiration (1 hour) **Recovery:** - ADMIN can reactivate via PUT /users/{id} with isActive=true x-roles: [ADMIN] responses: '204': description: User deactivated '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '404': $ref: '#/components/responses/NotFound' /transactions: post: tags: [Transactions] summary: Create transaction and perform anti-fraud check description: | Creates a transaction (purchase) and checks it against all active anti-fraud rules. **Important:** Anti-fraud rejection is NOT an error, but a business decision. Therefore, 201 is returned for both APPROVED and DECLINED transactions. **Access rights:** - USER: can create transactions only for themselves (userId in body == id in token) - ADMIN: can create transactions for any user **Anti-fraud check algorithm:** 1. Get user profile (userId) from DB 2. Load all active rules (enabled=true), sorted by priority ASC, then by id ASC 3. For each rule: parse dslExpression and evaluate the result 4. If at least one rule matched=true => status=DECLINED, isFraud=true 5. Otherwise => status=APPROVED, isFraud=false 6. Save transaction along with results of all rules (ruleResults) **Response codes:** - 201: transaction created (APPROVED or DECLINED) - 403: USER attempting to create transaction for another user - 404: user with specified userId not found - 422: invalid fields (amount <= 0, invalid currency, etc.) x-roles: [ADMIN, USER] requestBody: required: true content: application/json: schema: { $ref: '#/components/schemas/TransactionCreateRequest' } examples: ok: value: userId: "[UUID14]" amount: 1999.99 currency: "RUB" merchantId: "shop-123" merchantCategoryCode: "5411" timestamp: "2025-12-15T10:01:00Z" ipAddress: "192.168.0.1" deviceId: "device-abc" channel: "WEB" location: country: "RU" city: "Moscow" latitude: 55.7558 longitude: 37.6173 responses: '201': description: | Transaction created. Variants: - status=APPROVED: transaction allowed - status=DECLINED: rejected by anti-fraud (ruleResults shows which rules triggered) content: application/json: schema: { $ref: '#/components/schemas/TransactionDecision' } examples: approved: summary: Approved value: transaction: id: "[UUID15]" userId: "[UUID16]" amount: 1999.99 currency: "RUB" status: "APPROVED" merchantId: "shop-123" merchantCategoryCode: "5411" timestamp: "2025-12-15T10:01:00Z" ipAddress: "192.168.0.1" deviceId: "device-abc" channel: "WEB" location: { country: "RU", city: "Moscow", latitude: 55.7558, longitude: 37.6173 } isFraud: false metadata: { cartSize: 3 } createdAt: "2025-12-15T10:01:01Z" ruleResults: - ruleId: "[UUID17]" ruleName: "High amount check" priority: 10 enabled: true matched: false description: "amount <= 10000, rule did not trigger" declined: summary: Declined by anti-fraud value: transaction: id: "550e8400-e29b-41d4-a716-446655440005" userId: "550e8400-e29b-41d4-a716-446655440002" amount: 15000 currency: "RUB" status: "DECLINED" merchantId: "shop-999" merchantCategoryCode: "7995" timestamp: "2025-12-15T10:05:00Z" ipAddress: "10.0.0.7" deviceId: "device-xyz" channel: "MOBILE" location: { country: "RU", city: "Moscow" } isFraud: true metadata: {} createdAt: "2025-12-15T10:05:01Z" ruleResults: - ruleId: "550e8400-e29b-41d4-a716-446655440004" ruleName: "High amount check" priority: 10 enabled: true matched: true description: "amount > 10000, rule triggered" '400': $ref: '#/components/responses/BadRequest' '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '422': $ref: '#/components/responses/ValidationFailed' '404': description: User with specified userId not found content: application/json: schema: { $ref: '#/components/schemas/ApiError' } examples: userNotFound: value: code: USER_NOT_FOUND message: "User not found" traceId: "[UUID67]" timestamp: "2025-12-15T10:00:00Z" path: "/api/v1/transactions" details: { userId: "[UUID68]" } get: tags: [Transactions] summary: List of transactions description: | Access: - ADMIN: all transactions - USER: own only Filters: - userId (ADMIN only) - status, isFraud - from/to (RFC3339) - page/size x-roles: [ADMIN, USER] parameters: - in: query name: userId schema: { type: string, format: uuid } description: Filter by user (ADMIN only) - in: query name: status schema: { $ref: '#/components/schemas/TransactionStatus' } - in: query name: isFraud schema: { type: boolean } - $ref: '#/components/parameters/From' - $ref: '#/components/parameters/To' - $ref: '#/components/parameters/Page' - $ref: '#/components/parameters/Size' responses: '200': description: List of transactions content: application/json: schema: { $ref: '#/components/schemas/PagedTransactions' } '401': $ref: '#/components/responses/Unauthorized' '422': $ref: '#/components/responses/ValidationFailed' /transactions/{id}: parameters: - $ref: '#/components/parameters/TransactionId' get: tags: [Transactions] summary: Get transaction description: | - ADMIN: any transaction - USER: own only x-roles: [ADMIN, USER] responses: '200': description: Transaction + rule results content: application/json: schema: { $ref: '#/components/schemas/TransactionDecision' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '404': $ref: '#/components/responses/NotFound' /transactions/batch: post: tags: [Transactions] summary: Create batch of transactions description: | Batch supports partial success. Scenarios: - 201: all elements processed successfully (each element can be APPROVED or DECLINED) - 207: partial success (some elements not created due to 422/403/409, etc.) Index (0-based) is used for matching. x-roles: [ADMIN, USER] requestBody: required: true content: application/json: schema: { $ref: '#/components/schemas/TransactionBatchCreateRequest' } responses: '201': description: All batch elements processed (no transport errors per element) content: application/json: schema: { $ref: '#/components/schemas/TransactionBatchResult' } '207': description: Partial success (per-element errors/validations) content: application/json: schema: { $ref: '#/components/schemas/TransactionBatchResult' } '401': $ref: '#/components/responses/Unauthorized' '422': $ref: '#/components/responses/ValidationFailed' /fraud-rules: get: tags: [FraudRules] summary: List of fraud rules description: | ADMIN only. Scenarios: - 200: list of rules x-roles: [ADMIN] responses: '200': description: List of rules content: application/json: schema: type: array items: { $ref: '#/components/schemas/FraudRule' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' post: tags: [FraudRules] summary: Create fraud rule description: | ADMIN only. Validation: - name: 3..120 characters - dslExpression: required, must parse according to DSL specification - priority: >=1 (lower = higher priority) Scenarios: - 201: created - 422: invalid fields or DSL syntactically incorrect - 409: rule with this name already exists (if name uniqueness is enabled) x-roles: [ADMIN] requestBody: required: true content: application/json: schema: { $ref: '#/components/schemas/FraudRuleCreateRequest' } examples: ok: value: name: "High amount for young users" description: "Block transactions > 10000 from users under 21" dslExpression: "amount > 10000 AND user.age < 21" enabled: true priority: 5 responses: '201': description: Rule created content: application/json: schema: { $ref: '#/components/schemas/FraudRule' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '409': $ref: '#/components/responses/Conflict' '422': $ref: '#/components/responses/ValidationFailed' /fraud-rules/validate: post: tags: [FraudRules] summary: Validate DSL expression (without saving rule) description: | ADMIN only. Useful for UI "check rule". Scenarios: - 200: valid (isValid=true) - 200: invalid (isValid=false, errors filled) x-roles: [ADMIN] requestBody: required: true content: application/json: schema: { $ref: '#/components/schemas/DslValidateRequest' } examples: valid: value: dslExpression: "amount > 10000 AND user.age < 21" invalid: value: dslExpression: "amount > AND user.age < 21" responses: '200': description: DSL validation result content: application/json: schema: { $ref: '#/components/schemas/DslValidateResponse' } examples: valid: value: isValid: true normalizedExpression: "amount > 10000 AND user.age < 21" errors: [] invalid: value: isValid: false normalizedExpression: null errors: - code: DSL_PARSE_ERROR message: "Expected a number after '>'" position: 9 near: "> AND" '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' /fraud-rules/{id}: parameters: - $ref: '#/components/parameters/FraudRuleId' get: tags: [FraudRules] summary: Get fraud rule by ID description: | Returns full information about the anti-fraud rule. Only ADMIN has access to this endpoint. **Response fields:** - id: unique rule identifier - name: rule name - description: description for documentation - dslExpression: DSL expression - enabled: whether the rule is active (applied when checking transactions) - priority: priority (lower = higher, checked earlier) - createdAt, updatedAt: timestamps x-roles: [ADMIN] responses: '200': description: Fraud rule content: application/json: schema: { $ref: '#/components/schemas/FraudRule' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '404': $ref: '#/components/responses/NotFound' put: tags: [FraudRules] summary: Update fraud rule description: | ADMIN only. Full update. 422 returned for invalid DSL/fields. x-roles: [ADMIN] requestBody: required: true content: application/json: schema: { $ref: '#/components/schemas/FraudRuleUpdateRequest' } responses: '200': description: Updated rule content: application/json: schema: { $ref: '#/components/schemas/FraudRule' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '404': $ref: '#/components/responses/NotFound' '422': $ref: '#/components/responses/ValidationFailed' delete: tags: [FraudRules] summary: Deactivate fraud rule description: | **Important:** This is a soft-delete. The rule is NOT physically deleted from the database, but marked as inactive (enabled = false). Only ADMIN can deactivate rules. **Idempotency:** - Repeated call for already deactivated rule => 204 (not an error) - Non-existent rule => 404 **Consequences of deactivation:** - Rule is no longer applied when checking transactions - Rule remains in database and accessible via GET /fraud-rules/{id} - Rule statistics are preserved **Recovery:** - ADMIN can reactivate via PUT /fraud-rules/{id} with enabled=true x-roles: [ADMIN] responses: '204': description: Rule deactivated '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '404': $ref: '#/components/responses/NotFound' # -------------------- Statistics -------------------- /stats/overview: get: tags: [Statistics] summary: Key metrics overview (dashboard) description: | Returns aggregated metrics for the specified period for the dashboard. Only ADMIN has access to this endpoint. **Period restrictions:** - from < to (otherwise 422) - Maximum period: 90 days (otherwise 422) - If from/to not specified — last 30 days **Metrics:** - volume: total number of transactions - gmv: Gross Merchandise Value (sum of all transactions) - approvalRate: share of APPROVED transactions (0..1) - declineRate: share of DECLINED transactions (0..1) - topRiskMerchants: top 10 merchants by declineRate x-roles: [ADMIN] parameters: - $ref: '#/components/parameters/From' - $ref: '#/components/parameters/To' - $ref: '#/components/parameters/Timezone' responses: '200': description: Statistics overview content: application/json: schema: { $ref: '#/components/schemas/StatsOverview' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '422': $ref: '#/components/responses/ValidationFailed' /stats/transactions/timeseries: get: tags: [Statistics] summary: Transaction time series description: | Returns time series of transaction metrics for building charts. Only ADMIN has access to this endpoint. **Period restrictions:** - from < to (otherwise 422) - Maximum period: 90 days (otherwise 422) - If from/to not specified — last 7 days **Grouping (groupBy):** - hour: points by hours (max period 7 days) - day: points by days (max period 90 days) - week: points by weeks (max period 1 year) **Metrics in each point:** - txCount: number of transactions - gmv: sum of transactions - approvalRate, declineRate: shares by status x-roles: [ADMIN] parameters: - $ref: '#/components/parameters/From' - $ref: '#/components/parameters/To' - $ref: '#/components/parameters/GroupBy' - $ref: '#/components/parameters/Timezone' - in: query name: channel schema: { $ref: '#/components/schemas/TransactionChannel' } description: Optional filter by channel responses: '200': description: Time series content: application/json: schema: { $ref: '#/components/schemas/TransactionsTimeSeries' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' /stats/rules/matches: get: tags: [Statistics] summary: Rule trigger statistics description: | Returns statistics on anti-fraud rule triggers for the period. Only ADMIN has access to this endpoint. **Period restrictions:** - from < to (otherwise 422) - Maximum period: 90 days (otherwise 422) - If from/to not specified — last 30 days **Metrics for each rule:** - matches: how many times the rule triggered (matched=true) - uniqueUsers: how many unique users affected - uniqueMerchants: how many unique merchants affected - shareOfDeclines: share of DECLINED transactions where this rule was among matched Results sorted by matches DESC. x-roles: [ADMIN] parameters: - $ref: '#/components/parameters/From' - $ref: '#/components/parameters/To' - in: query name: top schema: { type: integer, minimum: 1, maximum: 100, default: 20 } description: Top-N rules by matches responses: '200': description: Rule statistics content: application/json: schema: { $ref: '#/components/schemas/RuleMatchStats' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' /stats/merchants/risk: get: tags: [Statistics] summary: Merchant risk metrics description: | ADMIN only. Metrics by merchantId/merchantCategoryCode: - txCount, gmv - declineRate - fraudRate x-roles: [ADMIN] parameters: - $ref: '#/components/parameters/From' - $ref: '#/components/parameters/To' - in: query name: merchantCategoryCode schema: { type: string, pattern: '^\d{4}$' } - in: query name: top schema: { type: integer, minimum: 1, maximum: 200, default: 50 } responses: '200': description: Merchant risk stats content: application/json: schema: { $ref: '#/components/schemas/MerchantRiskStats' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' /stats/users/{id}/risk-profile: get: tags: [Statistics] summary: User risk profile (including for USER — own only) description: | Access: - ADMIN: any user - USER: own only (id == id in token) Metrics: - txCount_24h / gmv_24h - distinctDevices_24h / distinctIps_24h / distinctCities_24h - declineRate_30d - lastSeenAt x-roles: [ADMIN, USER] parameters: - $ref: '#/components/parameters/UserId' responses: '200': description: Risk profile content: application/json: schema: { $ref: '#/components/schemas/UserRiskProfile' } '401': $ref: '#/components/responses/Unauthorized' '403': $ref: '#/components/responses/Forbidden' '404': $ref: '#/components/responses/NotFound' components: securitySchemes: BearerAuth: type: http scheme: bearer bearerFormat: JWT parameters: UserId: in: path name: id required: true schema: { type: string, format: uuid } description: User identifier (UUID) TransactionId: in: path name: id required: true schema: { type: string, format: uuid } description: Transaction identifier (UUID) FraudRuleId: in: path name: id required: true schema: { type: string, format: uuid } description: Rule identifier (UUID) Page: in: query name: page schema: { type: integer, minimum: 0, default: 0 } Size: in: query name: size schema: { type: integer, minimum: 1, maximum: 100, default: 20 } From: in: query name: from schema: { type: string, format: date-time } description: | Period start (RFC3339, inclusive). **Validation:** - Must be less than `to` (otherwise 422) - Difference between from and to no more than 90 days (otherwise 422) **Defaults:** - /stats/overview: now - 30 days - /stats/transactions/timeseries: now - 7 days - /stats/rules/matches: now - 30 days - /stats/merchants/risk: now - 30 days To: in: query name: to schema: { type: string, format: date-time } description: | Period end (RFC3339, exclusive). **Validation:** - Must be greater than `from` (otherwise 422) - Difference between from and to no more than 90 days (otherwise 422) **Default:** current time (now) Timezone: in: query name: timezone schema: { type: string, example: "Europe/Moscow", default: "UTC" } description: Timezone for aggregations/groupings GroupBy: in: query name: groupBy schema: type: string enum: [hour, day, week] default: day responses: BadRequest: description: | Bad request at transport/format level: - invalid JSON - unsupported Content-Type - payload too large content: application/json: schema: { $ref: '#/components/schemas/ApiError' } examples: badJson: value: code: BAD_REQUEST message: "Invalid JSON" traceId: "[UUID21]" timestamp: "2025-12-15T10:00:00Z" path: "/api/v1/transactions" details: { hint: "Check commas/quotes" } ValidationFailed: description: | Data validation error (request semantics). Returned when JSON is correct but fields fail validation. content: application/json: schema: { $ref: '#/components/schemas/ValidationError' } examples: invalidAmount: value: code: VALIDATION_FAILED message: "Some fields failed validation" traceId: "[UUID22]" timestamp: "2025-12-15T10:00:00Z" path: "/api/v1/transactions" fieldErrors: - field: "amount" issue: "must be >= 0.01" rejectedValue: -10 Unauthorized: description: Authentication required (token missing/invalid/expired) content: application/json: schema: { $ref: '#/components/schemas/ApiError' } examples: noToken: value: code: UNAUTHORIZED message: "Token missing or invalid" traceId: "[UUID23]" timestamp: "2025-12-15T10:00:00Z" path: "/api/v1/users" Forbidden: description: Access denied (insufficient permissions or attempt to access another's resource) content: application/json: schema: { $ref: '#/components/schemas/ApiError' } examples: notAdmin: value: code: FORBIDDEN message: "Insufficient permissions to perform operation" traceId: "[UUID24]" timestamp: "2025-12-15T10:00:00Z" path: "/api/v1/fraud-rules" NotFound: description: Resource not found content: application/json: schema: { $ref: '#/components/schemas/ApiError' } examples: userNotFound: value: code: NOT_FOUND message: "User not found" traceId: "550e8400-e29b-41d4-a716-446655440014" timestamp: "2025-12-15T10:00:00Z" path: "/api/v1/users/550e8400-e29b-41d4-a716-446655440099" Conflict: description: Conflict (email taken, rule name taken) content: application/json: schema: { $ref: '#/components/schemas/ApiError' } examples: email: value: code: EMAIL_ALREADY_EXISTS message: "User with this email already exists" traceId: "[UUID27]" timestamp: "2025-12-15T10:00:00Z" path: "/api/v1/users" Locked: description: Resource locked (e.g., user deactivated) content: application/json: schema: { $ref: '#/components/schemas/ApiError' } examples: inactive: value: code: USER_INACTIVE message: "User deactivated" timestamp: "2025-12-15T10:00:00Z" path: "/api/v1/auth/login" schemas: # ---------- Common ---------- ErrorCode: type: string description: | Error code (machine-readable). Used for programmatic error handling on the client. enum: - BAD_REQUEST - VALIDATION_FAILED - UNAUTHORIZED - FORBIDDEN - NOT_FOUND - USER_NOT_FOUND - EMAIL_ALREADY_EXISTS - USER_INACTIVE - DSL_PARSE_ERROR - DSL_INVALID_FIELD - DSL_INVALID_OPERATOR - RULE_NAME_ALREADY_EXISTS - INTERNAL_SERVER_ERROR ApiError: type: object required: [code, message, traceId, timestamp, path] description: | Standard API error format. All errors (except 2xx) return this format. properties: code: $ref: '#/components/schemas/ErrorCode' message: type: string description: Human-readable message (for display to user) example: Bad request traceId: type: string format: uuid description: | Unique request identifier for tracing. Used for searching in logs during debugging. example: "[UUID73]" timestamp: type: string format: date-time description: Error occurrence time (ISO 8601, UTC) path: type: string description: Request path where error occurred example: "/api/v1/transactions" details: type: object additionalProperties: true description: Additional error details ValidationError: type: object required: [code, message, traceId, timestamp, path, fieldErrors] properties: code: type: string example: VALIDATION_FAILED message: type: string traceId: type: string format: uuid timestamp: type: string format: date-time path: type: string fieldErrors: type: array items: $ref: '#/components/schemas/FieldError' FieldError: type: object required: [field, issue] properties: field: type: string description: Field name with error (can be nested, e.g. "location.latitude") example: "amount" issue: type: string description: Problem description example: "must be >= 0.01" rejectedValue: description: Value that failed validation nullable: true UserRole: type: string enum: [ADMIN, USER] description: User role in the system Gender: type: string enum: [MALE, FEMALE] MaritalStatus: type: string enum: [SINGLE, MARRIED, DIVORCED, WIDOWED] TransactionStatus: type: string enum: [APPROVED, DECLINED] description: | Transaction status: - APPROVED: transaction approved - DECLINED: transaction declined by anti-fraud TransactionChannel: type: string enum: [WEB, MOBILE, POS, OTHER] description: Transaction channel CurrencyCode: type: string pattern: '^[A-Z]{3}$' description: ISO 4217 currency code example: "RUB" MccCode: type: string pattern: '^\d{4}$' description: Merchant Category Code (4 digits) example: "5411" # ---------- Auth ---------- RegisterRequest: type: object required: [email, password, fullName] properties: email: type: string format: email maxLength: 254 description: User email (unique) password: type: string format: password minLength: 8 maxLength: 72 pattern: '^(?=.*[A-Za-z])(?=.*\d).+$' writeOnly: true description: | Password. Requirements: - Minimum 8 characters - Minimum 1 letter (A-Z or a-z) - Minimum 1 digit (0-9) fullName: type: string minLength: 2 maxLength: 200 description: User full name example: Ivan Ivanov region: type: string maxLength: 32 description: User region (region code or arbitrary string) example: RU-MOW gender: $ref: '#/components/schemas/Gender' age: type: integer minimum: 18 maximum: 120 description: Age (minimum 18 years) example: 25 maritalStatus: $ref: '#/components/schemas/MaritalStatus' LoginRequest: type: object required: [email, password] properties: email: type: string format: email maxLength: 254 password: type: string format: password minLength: 8 maxLength: 72 writeOnly: true AuthResponse: type: object required: [accessToken, expiresIn, user] description: | Response on successful authentication. Contains JWT token, its lifetime, and user profile. properties: accessToken: type: string description: | JWT token for request authorization. Pass in header: Authorization: Bearer example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." expiresIn: type: integer minimum: 1 description: | Token lifetime in seconds. After expiration, token becomes invalid and a new one must be obtained via /auth/login. example: 3600 user: $ref: '#/components/schemas/User' # ---------- Users ---------- User: type: object required: [id, email, fullName, role, isActive, createdAt, updatedAt] properties: id: type: string format: uuid email: type: string format: email maxLength: 254 fullName: type: string minLength: 2 maxLength: 200 region: type: string maxLength: 32 description: Residence region gender: $ref: '#/components/schemas/Gender' age: type: integer minimum: 18 maximum: 120 maritalStatus: $ref: '#/components/schemas/MaritalStatus' role: $ref: '#/components/schemas/UserRole' isActive: type: boolean default: true description: Whether user is active (deactivated users cannot log in) createdAt: type: string format: date-time updatedAt: type: string format: date-time UserCreateRequest: type: object required: [email, password, fullName, role] properties: email: type: string format: email maxLength: 254 password: type: string format: password minLength: 8 maxLength: 72 pattern: '^(?=.*[A-Za-z])(?=.*\d).+$' writeOnly: true fullName: type: string minLength: 2 maxLength: 200 region: type: string maxLength: 32 gender: $ref: '#/components/schemas/Gender' age: type: integer minimum: 18 maximum: 120 maritalStatus: $ref: '#/components/schemas/MaritalStatus' role: $ref: '#/components/schemas/UserRole' UserUpdateRequest: type: object required: [fullName, age, region, gender, maritalStatus] description: | Full profile update. All fields must be provided. To clear an optional field, pass null. USER can update only their own profile and cannot change role/isActive. ADMIN can update any profile, including role/isActive. properties: fullName: type: string minLength: 2 maxLength: 200 region: type: string maxLength: 32 nullable: true gender: allOf: - $ref: '#/components/schemas/Gender' nullable: true age: type: integer minimum: 18 maximum: 120 nullable: true maritalStatus: allOf: - $ref: '#/components/schemas/MaritalStatus' nullable: true role: $ref: '#/components/schemas/UserRole' description: Only ADMIN can change role. USER will get 403 on attempt. isActive: type: boolean description: Only ADMIN can change isActive. PagedUsers: type: object required: [items, total, page, size] properties: items: type: array items: { $ref: '#/components/schemas/User' } total: type: integer minimum: 0 description: Total number of records page: type: integer minimum: 0 description: Current page (0-based) size: type: integer minimum: 1 description: Page size # ---------- Transactions ---------- TransactionLocation: type: object description: | Geographic location of the transaction. **Validation rules:** - country and city are independent fields, can be passed separately - latitude and longitude are dependent fields: either both or neither - If passing only latitude without longitude (or vice versa) => 422 VALIDATION_FAILED properties: country: type: string minLength: 2 maxLength: 2 pattern: '^[A-Z]{2}$' description: ISO 3166-1 alpha-2 country code (uppercase letters) example: RU city: type: string maxLength: 128 description: City name example: Moscow latitude: type: number format: double minimum: -90 maximum: 90 description: Latitude (requires longitude) example: 55.7558 longitude: type: number format: double minimum: -180 maximum: 180 description: Longitude (requires latitude) example: 37.6173 Transaction: type: object required: [id, userId, amount, currency, status, timestamp, isFraud, createdAt] properties: id: type: string format: uuid userId: type: string format: uuid amount: type: number format: double minimum: 0.01 maximum: 999999999.99 description: Transaction amount example: 1999.99 currency: $ref: '#/components/schemas/CurrencyCode' status: $ref: '#/components/schemas/TransactionStatus' merchantId: type: string maxLength: 64 description: Merchant identifier example: shop-123 merchantCategoryCode: $ref: '#/components/schemas/MccCode' timestamp: type: string format: date-time description: Operation time (specified by client) ipAddress: type: string maxLength: 64 description: Client IP address example: 192.168.0.1 deviceId: type: string maxLength: 128 description: Device identifier example: device-abc channel: $ref: '#/components/schemas/TransactionChannel' location: $ref: '#/components/schemas/TransactionLocation' isFraud: type: boolean description: Flag indicating transaction is marked as fraud (at least one rule triggered) metadata: type: object additionalProperties: true description: Arbitrary additional data createdAt: type: string format: date-time description: Record creation time in the system TransactionCreateRequest: type: object required: [userId, amount, currency, timestamp] properties: userId: type: string format: uuid description: | ID of user for whom transaction is created. USER can create only for themselves (userId == id from token). ADMIN can create for any user. amount: type: number format: double minimum: 0.01 maximum: 999999999.99 currency: $ref: '#/components/schemas/CurrencyCode' merchantId: type: string maxLength: 64 merchantCategoryCode: $ref: '#/components/schemas/MccCode' timestamp: type: string format: date-time description: | Operation time. Must not be too far in the future (> now + 5 minutes => 422). ipAddress: type: string maxLength: 64 deviceId: type: string maxLength: 128 channel: $ref: '#/components/schemas/TransactionChannel' location: $ref: '#/components/schemas/TransactionLocation' metadata: type: object additionalProperties: true TransactionBatchCreateRequest: type: object required: [items] properties: items: type: array minItems: 1 maxItems: 500 description: Array of transactions for batch creation items: { $ref: '#/components/schemas/TransactionCreateRequest' } FraudRuleEvaluationResult: type: object required: [ruleId, ruleName, priority, enabled, matched] description: Result of checking one transaction against one fraud rule. properties: ruleId: type: string format: uuid ruleName: type: string priority: type: integer minimum: 1 enabled: type: boolean matched: type: boolean description: true if rule triggered (condition met) description: type: string description: Human-readable description of check result TransactionDecision: type: object required: [transaction, ruleResults] description: Transaction creation result with results of all rule checks properties: transaction: $ref: '#/components/schemas/Transaction' ruleResults: type: array description: | Results of applying all enabled rules at the time of check. All rules are returned (both triggered and not triggered). items: $ref: '#/components/schemas/FraudRuleEvaluationResult' PagedTransactions: type: object required: [items, total, page, size] properties: items: type: array items: $ref: '#/components/schemas/Transaction' total: { type: integer, minimum: 0 } page: { type: integer, minimum: 0 } size: { type: integer, minimum: 1 } TransactionBatchResultItem: type: object required: [index] description: Processing result of one batch element properties: index: type: integer minimum: 0 description: Element index in original array (0-based) decision: $ref: '#/components/schemas/TransactionDecision' description: Result if transaction successfully processed error: $ref: '#/components/schemas/ApiError' description: Error if element not processed (validation/access/conflict) TransactionBatchResult: type: object required: [items] properties: items: type: array items: { $ref: '#/components/schemas/TransactionBatchResultItem' } # ---------- Fraud Rules ---------- FraudRule: type: object required: [id, name, dslExpression, enabled, priority, createdAt, updatedAt] properties: id: type: string format: uuid name: type: string minLength: 3 maxLength: 120 description: Unique rule name description: type: string maxLength: 500 description: Rule description (for documentation) dslExpression: type: string minLength: 3 maxLength: 2000 description: | DSL expression of the rule. Supported syntax: Transaction fields: amount, currency, merchantId, ipAddress, deviceId User fields: user.age, user.region Comparison operators: >, >=, <, <=, =, != Logical operators: AND, OR, NOT Parentheses for grouping: () Examples: - amount > 10000 - amount > 5000 AND currency = 'RUB' - user.age < 21 AND amount > 10000 - (amount > 10000 OR user.region = 'HIGH_RISK') AND NOT (currency = 'USD') enabled: type: boolean default: true description: Whether rule is active (inactive rules are not applied) priority: type: integer minimum: 1 description: Priority (lower number = higher priority, checked earlier) createdAt: type: string format: date-time updatedAt: type: string format: date-time FraudRuleCreateRequest: type: object required: [name, dslExpression] properties: name: type: string minLength: 3 maxLength: 120 description: type: string maxLength: 500 dslExpression: type: string minLength: 3 maxLength: 2000 enabled: type: boolean default: true priority: type: integer minimum: 1 default: 100 FraudRuleUpdateRequest: type: object required: [name, dslExpression, enabled, priority] description: Full rule update (all required fields must be specified) properties: name: type: string minLength: 3 maxLength: 120 description: type: string maxLength: 500 dslExpression: type: string minLength: 3 maxLength: 2000 enabled: type: boolean priority: type: integer minimum: 1 DslValidateRequest: type: object required: [dslExpression] properties: dslExpression: type: string minLength: 3 maxLength: 2000 DslValidateResponse: type: object required: [isValid, errors] properties: isValid: type: boolean normalizedExpression: type: string nullable: true description: Normalized expression (if valid) errors: type: array items: $ref: '#/components/schemas/DslError' DslError: type: object required: [code, message] properties: code: type: string example: DSL_PARSE_ERROR message: type: string position: type: integer nullable: true description: Error position in expression (0-based) near: type: string nullable: true description: Expression fragment near the error # ---------- Statistics ---------- StatsOverview: type: object required: [from, to, volume, gmv, approvalRate, declineRate, topRiskMerchants] description: | Aggregated metrics for the specified period. Used for administrator dashboard. properties: from: type: string format: date-time description: Period start (inclusive) to: type: string format: date-time description: Period end (exclusive) volume: type: integer minimum: 0 description: Total number of transactions for the period gmv: type: number format: double minimum: 0 description: | Gross Merchandise Value — sum of amount of all transactions. Includes both APPROVED and DECLINED transactions. approvalRate: type: number format: double minimum: 0 maximum: 1 description: | Share of APPROVED transactions (0..1). approvalRate + declineRate = 1 declineRate: type: number format: double minimum: 0 maximum: 1 description: | Share of DECLINED transactions (0..1). Equivalent to share of transactions with isFraud=true. topRiskMerchants: type: array description: Top 10 merchants with highest declineRate items: { $ref: '#/components/schemas/MerchantRiskRow' } MerchantRiskRow: type: object required: [merchantId, txCount, declineRate] properties: merchantId: type: string merchantCategoryCode: $ref: '#/components/schemas/MccCode' txCount: type: integer minimum: 0 description: Number of transactions gmv: type: number format: double minimum: 0 declineRate: type: number format: double minimum: 0 maximum: 1 description: Share of declined transactions TransactionsTimeSeries: type: object required: [points] properties: points: type: array items: $ref: '#/components/schemas/TransactionsTimePoint' TransactionsTimePoint: type: object required: [bucketStart, txCount, gmv, approvalRate, declineRate] description: One point in time series properties: bucketStart: type: string format: date-time description: Time interval (bucket) start txCount: type: integer minimum: 0 description: Number of transactions in interval gmv: type: number format: double minimum: 0 description: Sum of transactions in interval approvalRate: type: number format: double minimum: 0 maximum: 1 description: Share of APPROVED transactions (0..1) declineRate: type: number format: double minimum: 0 maximum: 1 description: Share of DECLINED transactions (0..1) RuleMatchStats: type: object required: [items] properties: items: type: array items: { $ref: '#/components/schemas/RuleMatchRow' } RuleMatchRow: type: object required: [ruleId, ruleName, matches, uniqueUsers, shareOfDeclines] properties: ruleId: type: string format: uuid ruleName: type: string matches: type: integer minimum: 0 description: Number of rule triggers uniqueUsers: type: integer minimum: 0 description: Unique users affected by rule uniqueMerchants: type: integer minimum: 0 description: Unique merchants affected by rule shareOfDeclines: type: number format: double minimum: 0 maximum: 1 description: Share of DECLINED transactions where this rule was among matched MerchantRiskStats: type: object required: [items] properties: items: type: array items: { $ref: '#/components/schemas/MerchantRiskRow' } UserRiskProfile: type: object required: [userId, txCount_24h, gmv_24h, distinctDevices_24h, distinctIps_24h, distinctCities_24h, declineRate_30d] properties: userId: type: string format: uuid txCount_24h: type: integer minimum: 0 description: Number of transactions in last 24 hours gmv_24h: type: number format: double minimum: 0 description: Sum of transactions in last 24 hours distinctDevices_24h: type: integer minimum: 0 description: Unique devices in last 24 hours distinctIps_24h: type: integer minimum: 0 description: Unique IP addresses in last 24 hours distinctCities_24h: type: integer minimum: 0 description: Unique cities in last 24 hours declineRate_30d: type: number format: double minimum: 0 maximum: 1 description: Share of declined transactions in last 30 days lastSeenAt: type: string format: date-time nullable: true description: Last activity time