Merge pull request 'feat: admin audit log (recording, storage, Audit log screen)' (#21) from add-admin-audit-log into main
CI / build-and-publish (push) Failing after 0s
CI / build-and-publish (push) Failing after 0s
This commit was merged in pull request #21.
This commit is contained in:
commit
518901a6d8
63 files changed
+3361
-15
No files matched your search
@@ -82,6 +82,13 @@ After running `04`, `SELECT LENGTH(password) FROM \`service-system\`.\`user\` WH
|
||||
|
||||
`99-rollback.sql` in the same folder undoes the three and deletes the login history.
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/2026-11-30-add-admin-audit-log/sql/01-audit-event.sql` | Creates `service-log`.`audit_event` (the admin audit trail). DDL: run it with a user that may create tables, not the services' user. |
|
||||
| `openspec/changes/archive/2026-11-30-add-admin-audit-log/sql/02-audit-log-module.sql` | Adds the Audit log back-office module (`BO_AUDIT_LOG`). No role gets it; super admins grant it under Roles. |
|
||||
|
||||
`99-rollback.sql` in the same folder undoes the two and deletes the audit trail.
|
||||
|
||||
**Database user:**
|
||||
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas. EXECUTE is needed: service-member calls a stored function.
|
||||
- Every Java service reads the same variables (section 6): `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER`, `MYSQLPWD`.
|
||||
@@ -98,6 +105,7 @@ The services publish and subscribe through Google Pub/Sub. It is not replaced in
|
||||
- **Project:** use a Google Cloud project, and give its id as `GCP_PROJECT`.
|
||||
- **Service account:** create one with the Pub/Sub Publisher and Pub/Sub Subscriber roles, and download a JSON key. Mount the key into every Java image except `api-gateway` (section 7), and set `GCP_CREDENTIAL_FILE=file:/var/secrets/gcp/key.json`.
|
||||
- **Topics and subscriptions:** use `local/pubsub/topics.txt`. Each line is a topic name, optionally followed by a subscription name. Some topics appear on several lines with different subscriptions (e.g. `update-sync-topic`): create each topic once, then every subscription listed for it. Subscriptions use default settings.
|
||||
- **Audit log:** `audit-event-topic` with `audit-event-subscription` carries admin audit events from mobile-api to service-log. It is in `topics.txt`; service-log also creates both at startup if they are missing. Keep the subscription's default of not retaining acknowledged messages: the events carry admin usernames and IPs. `AUDIT_RETENTION_DAYS` (section 6) must be at least 1, or service-log does not start.
|
||||
|
||||
## 6. Environment variables
|
||||
|
||||
@@ -160,6 +168,12 @@ The keys:
|
||||
| `JWT_SECRET` | Secret | Same value as `JWT_TOKEN` |
|
||||
| `CUSTOMER_PORTAL_BASE_URL` | Plain | The customer portal is not deployed in phase 1. When unset, it falls back to a Tastefully address that only the member referral link uses, which Co-Lite does not use. Set it once a customer portal exists. |
|
||||
|
||||
**`service-log`:**
|
||||
|
||||
| Variable | Kind | Value |
|
||||
|---|---|---|
|
||||
| `AUDIT_RETENTION_DAYS` | Plain | Optional (default 730). Admin audit events older than this many days are deleted daily at 03:30. |
|
||||
|
||||
**`api-gateway`:** only `JWT_TOKEN` (same value as everywhere). No Pub/Sub, Redis or database settings, and no `key.json` mount. It reads its client keys from the mounted `appkeys.json` (section 7).
|
||||
|
||||
**`admin-portal`:**
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
# Admin Audit Log — Design
|
||||
|
||||
Date: 2026-11-30. Change id: `add-admin-audit-log`.
|
||||
|
||||
## Intent
|
||||
|
||||
Nothing in Co-Lite records who did what in the admin portal. When an admin edits a user, changes a role's grants, edits or exports leads, or opens a saved email (which can hold a temporary password), the only trace is a line in the application log. Sign-ins are the exception: the `login_audit` table covers them (`add-admin-login-security`).
|
||||
|
||||
The user wants an audit trail before go-live (2027-01-15) and a screen to read it. Scope was agreed on 2026-11-30, with lead edits recording field names only, not values.
|
||||
|
||||
Reference: babyboo's `add-portal-audit-log` (archive `2026-11-19`) and `audit-log-readable-actions` (`2026-11-20`). This design ports the admin half of that work, trimmed.
|
||||
|
||||
## Goals
|
||||
|
||||
- Record an audit event for every admin write through mobile-api, and for chosen sensitive reads.
|
||||
- Record refused attempts (a missing module grant, for example) when the token is valid, so the actor is known.
|
||||
- Store before/after values only for an allow-list of fields.
|
||||
- Provide an `/audit-log` screen in the admin portal with filters and a detail view, behind its own module.
|
||||
- Delete events after 2 years, automatically.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Member and public calls. The customer portal's public lead capture has no actor.
|
||||
- Sign-in, sign-out and own password change. `login_audit` already records these; the audit log neither duplicates nor links to them.
|
||||
- Page views and ordinary reads (the existing response-time log covers traffic).
|
||||
- Reviving or cleaning up the legacy `back_office_access_log`, `/log/save` and similar. They are unused; removing them belongs in a separate change.
|
||||
|
||||
## Anti-goals
|
||||
|
||||
- Any password, token, raw request body, or lead personal data (name, phone, email, notes) in an audit row.
|
||||
- An audit write that slows down or fails the admin's action.
|
||||
- Audit rows that anyone without `BO_AUDIT_LOG` can read.
|
||||
|
||||
## Approaches considered
|
||||
|
||||
- **A. Pub/Sub from mobile-api's `AppAccessAspect` to services-log (chosen).** The aspect already sees every admin call (the user, its `@AdminModule` code, the outcome) and already publishes a `ResponseTime` record per call to services-log over Pub/Sub. One more message type on the same path is the smallest change. It is asynchronous, and losing an event is acceptable.
|
||||
- **B. A synchronous REST call from mobile-api to services-log, like `login_audit`.** Simpler to test, but it adds a network hop to every admin write, and it needs its own error handling.
|
||||
- **C. Explicit calls inside each service method.** Easy to forget on new endpoints. Rejected: the aspect covers new endpoints by default.
|
||||
|
||||
## Design
|
||||
|
||||
### Event table `service-log`.`audit_event`
|
||||
|
||||
| Column | Meaning |
|
||||
|---|---|
|
||||
| `id` | PK |
|
||||
| `company_id` | the actor's company (nullable) |
|
||||
| `occurred_at` | server time of the call |
|
||||
| `actor` | admin username |
|
||||
| `module` | the handler's `@AdminModule` code (for example `BO_USERS`) |
|
||||
| `action` | readable action code (see below) |
|
||||
| `http_method`, `path_template` | for example `PUT /api/admin/users/{id}`: the template, never the concrete path or the query |
|
||||
| `target_id` | the record acted on: the first path variable, when there is one |
|
||||
| `outcome`, `http_status` | `SUCCESS` or `FAILURE`, plus the status code |
|
||||
| `client_ip` | forwarded browser IP (nullable) |
|
||||
| `changes` | JSON, nullable: `{field: {before, after}}` for allow-listed fields, or `{fields: [..]}` for lead edits |
|
||||
|
||||
Indexes: `occurred_at`, `(actor, occurred_at)`, `(module, action, occurred_at)`. The DDL and the module row go in the change's `sql/` folder and in `local/seed/03-colite.sql`.
|
||||
|
||||
### What is recorded
|
||||
|
||||
- **Every non-GET handler under `/api/admin/**`,** except:
|
||||
- `AdminAuthController`'s login, logout, refresh, forgot-password and change-password. Sign-in history covers these, or they have no actor.
|
||||
- `first-login` is recorded.
|
||||
- POSTs that only read, marked with `@Audited(skip = true)`. Today that is event-lead `match`.
|
||||
- **Sensitive GETs, marked with `@Audited`:**
|
||||
- the lead export;
|
||||
- the event-lead export;
|
||||
- the email detail (opening an email).
|
||||
- **Refusals:** a valid admin token refused by the access check (missing module, not super admin, pending first login) is recorded as `FAILURE` with the status. Calls without a valid token are not recorded, because there is no actor.
|
||||
|
||||
### Action codes
|
||||
|
||||
`@Audited(action = "...")` names an action explicitly. Without one, the code is derived from the handler: drop an `Admin` prefix and a `Controller` suffix, then convert both parts to UPPER_SNAKE. For example, `AdminUserController.update` becomes `USER_UPDATE`. Explicit names are used where the derived one would be unclear:
|
||||
- `USER_SET_TEMPORARY_PASSWORD`;
|
||||
- `USER_SEND_PASSWORD_RESET`;
|
||||
- `ROLE_SET_MODULES`;
|
||||
- `LEAD_EXPORT`;
|
||||
- `EVENT_LEAD_EXPORT`;
|
||||
- `EMAIL_VIEW`.
|
||||
|
||||
### Before/after (allow-listed)
|
||||
|
||||
The handler's service supplies the values through a small request-scoped holder (babyboo's `AuditChanges`). Nothing is diffed generically from request bodies.
|
||||
|
||||
- **Admin user update and create:** `roles` (role names) and `enabled`.
|
||||
- **Role module grants:** module codes added and removed.
|
||||
- **Lead edit and event-lead edit:** the names of the fields that changed, no values. This was the user's call.
|
||||
- **Login-security settings** (lockout and password rules): the changed setting names with before and after. These are not personal data.
|
||||
|
||||
### Write path
|
||||
|
||||
- After the handler returns or throws, `AppAccessAspect` builds an `AuditEvent` and publishes it to the new Pub/Sub topic `audit-event`. The `AuditEvent` message class lives in core-libs, shared by mobile-api and services-log.
|
||||
- services-log subscribes on `audit-event-log`, which it creates at startup like its existing subscriptions, and saves the event.
|
||||
- A publish failure is logged at WARN and swallowed. The existing response-time publishing is unchanged.
|
||||
|
||||
### Client IP
|
||||
|
||||
- The portal's server-side calls to mobile-api already send `X-Client-Ip` on every request (`app/lib/server/mobileApi.ts`, the last `x-forwarded-for` hop), so the portal needs no change.
|
||||
- mobile-api stores the value for reading only.
|
||||
|
||||
### Retention
|
||||
|
||||
A scheduled purge in services-log deletes events older than `audit.retention-days` (default 730) in batches, modelled on the existing response-time archive scheduler. The setting is an environment variable.
|
||||
|
||||
### Reading
|
||||
|
||||
- services-log gets `POST /log/audit/search`. It takes filters (actor, module, action, outcome, date range) and paging, returns newest first, and caps the page size at 100.
|
||||
- services-log also gets `GET /log/audit/{id}`.
|
||||
- Both are reached through the gateway with the admin's token, like the other services. Only mobile-api holds a gateway key (`docs/deployment.md` section 7).
|
||||
- mobile-api adds `GET /api/admin/audit-log` and `GET /api/admin/audit-log/{id}` under `@AdminModule("BO_AUDIT_LOG")`.
|
||||
|
||||
### Admin portal
|
||||
|
||||
- **`/audit-log`:** a paged list (newest first) with columns time, who, module, action, target, outcome and IP.
|
||||
- **Filters:** who, module (select), action, outcome and From/To date.
|
||||
- **Detail page:** the event, plus a before/after table, or a list of changed field names for lead edits.
|
||||
- **Copy and gating:** all copy goes through `t()`. The page is gated by `RequireModule` and `ROUTE_MODULES`.
|
||||
- **Module row:** `(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText')`. It has no role grants, so only super admins see it until it is granted.
|
||||
|
||||
## My calls (check these)
|
||||
|
||||
- Pub/Sub, asynchronous, best-effort. A lost event is acceptable, as in babyboo.
|
||||
- Reads go through the gateway with the admin's token. babyboo switched to in-cluster calls because other api-key holders existed; Co-Lite has only mobile-api.
|
||||
- `first-login` is recorded and the other auth endpoints are not.
|
||||
- The login-security settings record values, since they are not personal data. User changes record role names and the enabled flag only.
|
||||
- Retention is 730 days, set by environment variable rather than on a screen.
|
||||
- Legacy `/log/save` and the old access-log tables are left alone.
|
||||
|
||||
## Left to the builder
|
||||
|
||||
- The exact JSON shape of `changes`, as long as the detail view can render it.
|
||||
- Column widths, so the list fits at 1280 px without horizontal scrolling (babyboo hit this).
|
||||
@@ -1,5 +1,6 @@
|
||||
# topic [subscription] - one per line; created in the Pub/Sub emulator before services start
|
||||
activate-member-topic activate-member-subscription
|
||||
audit-event-topic audit-event-subscription
|
||||
backoffice-topic backoffice-subscription
|
||||
batch-transfer-member-topic batch-transfer-member-subscription
|
||||
camunda-new-registration-topic camunda-new-registration-subscription
|
||||
|
||||
@@ -151,3 +151,29 @@ WHERE `param` = 'ADMIN_LOGIN_BLOCK_PERIOD' AND `type` = 'ADMIN_LOGIN_BLOCK';
|
||||
-- add-admin-login-security/sql/03-login-security-module.sql
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(41000000, 'BO_LOGIN_SECURITY', 'Login security', 'BO', 'M', 40000000, '/login-security', 'Shield');
|
||||
|
||||
-- add-admin-audit-log/sql/02-audit-log-module.sql (still USE `service-system` from above)
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText');
|
||||
|
||||
-- add-admin-audit-log/sql/01-audit-event.sql
|
||||
USE `service-log`;
|
||||
CREATE TABLE IF NOT EXISTS `audit_event` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NULL,
|
||||
`occurred_at` datetime(6) NOT NULL,
|
||||
`actor` varchar(191) NOT NULL,
|
||||
`module` varchar(64) NULL,
|
||||
`action` varchar(128) NOT NULL,
|
||||
`http_method` varchar(16) NULL,
|
||||
`path_template` varchar(255) NULL,
|
||||
`target_id` varchar(128) NULL,
|
||||
`outcome` varchar(16) NOT NULL COMMENT 'SUCCESS | FAILURE',
|
||||
`http_status` int NULL,
|
||||
`client_ip` varchar(64) NULL,
|
||||
`changes` text NULL COMMENT 'JSON: allow-listed before/after, or changed field names',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_audit_event_occurred_at` (`occurred_at`),
|
||||
KEY `idx_audit_event_actor` (`actor`, `occurred_at`),
|
||||
KEY `idx_audit_event_module_action` (`module`, `action`, `occurred_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-30
|
||||
@@ -0,0 +1,100 @@
|
||||
# Design
|
||||
|
||||
Full design with approaches and the user's approved calls: `docs/superpowers/specs/2026-11-30-admin-audit-log-design.md`.
|
||||
|
||||
## Context
|
||||
|
||||
- **`AppAccessAspect`** (`solvway-mobile-api/.../useraccess/AppAccessAspect.java`) wraps every controller method. It already:
|
||||
- knows the admin from the JWT;
|
||||
- resolves `@AdminModule` from the method, falling back to the class;
|
||||
- refuses with 403 on a missing module, super admin required or pending reset;
|
||||
- publishes a `ResponseTime` record per call to services-log over Pub/Sub (`response-time-log-topic`).
|
||||
- **services-log** stores in MySQL schema `service-log` with JPA. It creates its topics and subscriptions at startup (`configuration/PubSubConfig.java`), listens in `pubsub/PubSubListener.java`, and archives response times on a schedule (`scheduler/ResponseTimeLogArchiveScheduler.java`).
|
||||
- **Local Pub/Sub:** the emulator creates the topics listed in `local/pubsub/topics.txt`.
|
||||
- **Client IP:** the portal already forwards `X-Client-Ip` on every call (`app/lib/server/mobileApi.ts`).
|
||||
- **babyboo reference:**
|
||||
- core-libs `model/AuditEvent.java`;
|
||||
- mobile-api `useraccess/Audited.java`, `useraccess/AuditChanges.java` and the audit part of `useraccess/AppAccessAspect.java`;
|
||||
- `service/AuditLogService.java` and `controller/AdminAuditLogController.java`;
|
||||
- services-log `controller/AuditEventController.java`, `model/AuditEventLog.java`, `repo/AuditEventLogRepository.java` and `service/AuditEventLogPurge.java`;
|
||||
- portal `app/audit-log/page.tsx` and `app/api/audit-log/**`.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- record admin writes, refusals and three sensitive reads;
|
||||
- record allow-listed changes;
|
||||
- delete events after 730 days;
|
||||
- an Audit log screen.
|
||||
|
||||
**Non-Goals:**
|
||||
- member and public calls;
|
||||
- page views;
|
||||
- sign-ins (covered by `login_audit`);
|
||||
- legacy `/log/save` cleanup.
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **`AuditEvent` in core-libs:** fields `companyId`, `occurredAt`, `actor`, `module`, `action`, `httpMethod`, `pathTemplate`, `targetId`, `outcome`, `httpStatus`, `clientIp` and `changes` (a JSON string). It is the shared contract, so it lands first.
|
||||
|
||||
2. **Table `service-log`.`audit_event`:**
|
||||
- Columns follow the event fields.
|
||||
- `changes` is TEXT.
|
||||
- Indexes: `occurred_at`, `(actor, occurred_at)` and `(module, action, occurred_at)`.
|
||||
|
||||
3. **What the aspect records:**
|
||||
- **Writes:** every handler under a class mapped to `/api/admin` whose HTTP method is not GET.
|
||||
- **Sensitive GETs:** handlers annotated `@Audited` (lead export, event-lead export, email detail).
|
||||
- **Skipped:** handlers annotated `@Audited(skip = true)` (event-lead `match`) and every `AdminAuthController` handler except `firstLogin`.
|
||||
- **Actor required:** only calls whose admin token resolved to a user are recorded. A refusal at the access check (403 from the module or super-admin check, or `PASSWORD_RESET_REQUIRED`) for such a user is recorded as `FAILURE`.
|
||||
|
||||
4. **Event fields, as the aspect builds them:**
|
||||
- **Action:** `@Audited(action)`; otherwise derived from the handler: drop an `Admin` prefix and a `Controller` suffix, then UPPER_SNAKE both parts and join them, so `AdminUserController.update` becomes `USER_UPDATE`.
|
||||
- **Path template:** the class `@RequestMapping` plus the method mapping, for example `/api/admin/users/{id}`.
|
||||
- **Target id:** the last path variable (the record acted on, e.g. the event lead in `/event-leads/{eventUuid}/leads/{eventLeadUuid}`). `@Audited(target = false)` records none: the unlock path carries a username as typed at a failed sign-in, which can be a mistyped password.
|
||||
- **Outcome:**
|
||||
- `SUCCESS` for a 2xx `ResponseEntity`, or when there is no `ResponseEntity`;
|
||||
- otherwise `FAILURE` with the status, taken from a non-2xx `ResponseEntity` or from a thrown `ResponseStatusException`;
|
||||
- any other exception is `FAILURE` with 500.
|
||||
- **Client IP:** the `X-Client-Ip` header.
|
||||
|
||||
5. **`AuditChanges`:** a request-scoped holder. Services call `AuditChanges.put(field, before, after)` or `AuditChanges.fields(names...)`, and the aspect serialises the result into `changes`. The allow-list is enforced where the values are supplied:
|
||||
- `AdminUserService` create and update: `roles` (role names) and `enabled`;
|
||||
- `AdminRoleService` set modules: `modules` with the codes added and removed;
|
||||
- `AdminLeadService` and `AdminEventLeadService` edits: changed field names only;
|
||||
- `AdminLoginSecurityService` config and password rules: the changed settings with before and after.
|
||||
|
||||
6. **Publishing:** to `audit-event-topic`, after the handler finishes, through the existing `PubSubUtil` and `PubSubTemplate` pattern used for `ResponseTime`. Any exception is logged at WARN and swallowed.
|
||||
|
||||
7. **services-log:**
|
||||
- Creates `audit-event-topic` and `audit-event-subscription` at startup, like the other topics.
|
||||
- The listener saves each `AuditEvent` as an `AuditEventLog`.
|
||||
- A scheduled purge (daily) deletes rows with `occurred_at` older than `audit.retention-days` (env `AUDIT_RETENTION_DAYS`, default 730), in batches.
|
||||
- **`POST /log/audit/search`:** body `{actor, module, action, outcome, from, to, page, size}`. `actor` and `action` match exactly; `from` and `to` are `yyyy-MM-dd` and inclusive. It returns newest first, caps the size at 100, and answers `{content, totalElements, number, size}`.
|
||||
- **`GET /log/audit/{id}`.**
|
||||
- Both need the admin's token at the gateway, like the other `/log/**` routes.
|
||||
|
||||
8. **mobile-api read API:** `AdminAuditLogController` (`@AdminModule("BO_AUDIT_LOG")`):
|
||||
- `GET /api/admin/audit-log?actor&module&action&outcome&from&to&page&size`;
|
||||
- `GET /api/admin/audit-log/{id}` (404 when missing).
|
||||
- The reads themselves are not audited (GET without `@Audited`).
|
||||
|
||||
9. **Portal `/audit-log`:**
|
||||
- **List:** time, who, module (label from the module's i18n key), action, target, outcome with status, and IP.
|
||||
- **Filters:** who, module select, action, outcome, and From/To `DatePicker`.
|
||||
- **Detail `/audit-log/[id]`:** the event fields, then a changes table (field, before, after), or a list of changed fields when only names were recorded.
|
||||
- **Gating:** `RequireModule` and `ROUTE_MODULES`.
|
||||
- **Proxy:** `app/api/audit-log/[[...path]]/route.ts`, GET only.
|
||||
|
||||
10. **Module row:** `(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText')`, with no role grants.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **Lost events:** Pub/Sub publishing is best-effort, so a broker outage loses events. This is accepted, as in babyboo; the application log still carries the existing `... by ...` lines.
|
||||
- **Role names and settings stored as values:** these are not personal data. Lead personal data is never stored; lead edits keep field names only.
|
||||
- **Path variables as targets:** the last path variable is a UUID or id, except the unlock username, which is not recorded. The concrete path is never stored, so no query string, and therefore no search text, ends up in the log.
|
||||
- **Requests refused before the handler:** malformed JSON or a binding error is answered before `AppAccessAspect` runs, so such calls are not recorded.
|
||||
- **Extra reads for before-values:** a lead edit and a login-security settings save read the current values once before saving, only for the audit. The read is best-effort and cannot fail the save; it adds one internal call.
|
||||
- **One company:** reads do not filter by `company_id`. Add the filter when Co-Lite becomes multi-company.
|
||||
- **Retention:** `AUDIT_RETENTION_DAYS` below 1 stops service-log at startup rather than deleting the whole trail.
|
||||
- **Volume:** one row per admin write. With one company and a handful of admins, 730 days is small.
|
||||
@@ -0,0 +1,60 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
Nothing in Co-Lite records who did what in the admin portal. When an admin edits a user, changes a role's grants, edits or exports leads, or opens a saved email (which can hold a temporary password), the only trace is a line in the application log. Sign-ins are the exception: `login_audit` covers them. Go-live is 2027-01-15, and the company needs an audit trail and a screen to read it.
|
||||
|
||||
babyboo built the same thing (`add-portal-audit-log`, archive 2026-11-19, plus `audit-log-readable-actions`, 2026-11-20). This change ports the admin half of that work, trimmed.
|
||||
|
||||
Design: `docs/superpowers/specs/2026-11-30-admin-audit-log-design.md`.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **Recording:**
|
||||
- mobile-api's `AppAccessAspect` publishes an audit event for every admin write under `/api/admin/**`, every refusal of a valid admin token, and three sensitive reads: the lead export, the event-lead export and opening an email.
|
||||
- Sign-in, sign-out, refresh, forgot-password and own password change are not recorded, because `login_audit` covers them or there is no actor.
|
||||
- **Each event:**
|
||||
- who and when; the module and a readable action code;
|
||||
- the method and the path template; the target id;
|
||||
- the outcome and status, and the browser IP.
|
||||
- Before/after values only for an allow-list:
|
||||
- a user's role names and enabled flag;
|
||||
- role module grants;
|
||||
- login-security settings;
|
||||
- for lead edits and event-lead edits, the names of the changed fields only, never the values.
|
||||
- **Transport:** a new Pub/Sub topic `audit-event-topic`. services-log subscribes on `audit-event-subscription` and saves to a new `service-log`.`audit_event` table. Publishing is best-effort: a failure never blocks the admin's action.
|
||||
- **Retention:** services-log deletes events older than `AUDIT_RETENTION_DAYS` (default 730) on a schedule.
|
||||
- **Reading:** services-log gets search and detail endpoints. mobile-api gets `GET /api/admin/audit-log` and `GET /api/admin/audit-log/{id}` under the new module `BO_AUDIT_LOG`.
|
||||
- **Portal:** a new `/audit-log` page with a list, filters and a detail view that shows the changes.
|
||||
- **Not in this change:**
|
||||
- member and public calls;
|
||||
- page views;
|
||||
- removing the unused legacy `/log/save` and `back_office_access_log`.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
- `admin-audit-log`: recording admin actions, refusals and sensitive reads; the allow-listed changes; retention; and the Audit log screen.
|
||||
|
||||
### Modified Capabilities
|
||||
None.
|
||||
|
||||
## Impact
|
||||
|
||||
- **`solvway-core-libs`:** a new `AuditEvent` message class shared by mobile-api and services-log.
|
||||
- **`solvway-services-log`:**
|
||||
- `AuditEventLog` entity and repository;
|
||||
- the topic and subscription setup and the listener;
|
||||
- the purge;
|
||||
- `/log/audit/search` and `/log/audit/{id}`.
|
||||
- **`solvway-mobile-api`:**
|
||||
- the `Audited` annotation and the `AuditChanges` request holder;
|
||||
- publishing in `AppAccessAspect`;
|
||||
- annotations on the sensitive reads and the read-only POST;
|
||||
- changes supplied by the user, role, lead, event-lead and login-security services;
|
||||
- `AdminAuditLogController`.
|
||||
- **`solvway-admin-portal`:** the `/audit-log` pages, a proxy, a service and i18n keys. Client IP is already forwarded on every call.
|
||||
- **Pub/Sub:** a new topic and subscription. They go in `local/pubsub/topics.txt` and `docs/deployment.md` section 5.
|
||||
- **Database:** `sql/01-audit-event.sql` (DDL in `service-log`) and `sql/02-audit-log-module.sql`, mirrored in `local/seed/03-colite.sql`, plus a rollback script.
|
||||
- **Privacy:** no passwords, tokens, request bodies or lead personal data are stored. User role names and login-security settings are stored as values.
|
||||
- No new dependency.
|
||||
@@ -0,0 +1,105 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Admin writes are recorded
|
||||
|
||||
The system SHALL record an audit event for every state-changing admin API call made with a valid admin token, successful or not, holding the time, admin username, module, readable action code, HTTP method, path template (never the concrete path or query), target id, outcome with HTTP status, and client IP. Sign-in, sign-out, token refresh, forgot-password, own password change from the user menu, and calls without a valid admin token SHALL NOT be recorded.
|
||||
|
||||
#### Scenario: A user edit is recorded
|
||||
|
||||
- **WHEN** admin `admin` updates user 4
|
||||
- **THEN** an audit event is saved with actor `admin`, module `BO_USERS`, action `USER_UPDATE`, path template `PUT /api/admin/users/{id}`, target `4`, outcome `SUCCESS`, and the client IP
|
||||
|
||||
#### Scenario: A failed write is recorded
|
||||
|
||||
- **WHEN** an admin's role update is refused with status 400
|
||||
- **THEN** an audit event is saved with outcome `FAILURE` and status 400
|
||||
|
||||
#### Scenario: Sign-in is not recorded
|
||||
|
||||
- **WHEN** an admin signs in or signs out
|
||||
- **THEN** no audit event is saved
|
||||
|
||||
#### Scenario: First-login password change is recorded
|
||||
|
||||
- **WHEN** a new admin sets their password at first login
|
||||
- **THEN** an audit event with action `AUTH_FIRST_LOGIN` is saved
|
||||
|
||||
### Requirement: Refused access is recorded
|
||||
|
||||
The system SHALL record an audit event with outcome `FAILURE` when a valid admin token is refused by the access check (missing module, super admin required, or pending first-login change).
|
||||
|
||||
#### Scenario: Missing module
|
||||
|
||||
- **GIVEN** admin `noevents` has no `BO_EVENTS`
|
||||
- **WHEN** `noevents` tries to create an event
|
||||
- **THEN** the request is refused with 403
|
||||
- **AND** an audit event with actor `noevents`, module `BO_EVENTS` and outcome `FAILURE` is saved
|
||||
|
||||
### Requirement: Sensitive reads are recorded
|
||||
|
||||
The system SHALL record an audit event when an admin exports leads, exports event leads, or opens a saved email. Read-only POST calls marked as such SHALL NOT be recorded.
|
||||
|
||||
#### Scenario: Opening an email
|
||||
|
||||
- **WHEN** an admin opens email 12
|
||||
- **THEN** an audit event with action `EMAIL_VIEW` and target `12` is saved
|
||||
|
||||
#### Scenario: Lead export
|
||||
|
||||
- **WHEN** an admin downloads the lead export
|
||||
- **THEN** an audit event with action `LEAD_EXPORT` is saved
|
||||
|
||||
### Requirement: Allow-listed changes
|
||||
|
||||
The system SHALL attach before and after values only for these fields: a user's role names and enabled flag, a role's granted module codes, and the login-security lockout settings and password rules. For lead and event-lead edits the system SHALL record only the names of the fields that changed, never their values. No audit event SHALL contain a password, token, raw request body, or lead name, phone, email or notes.
|
||||
|
||||
#### Scenario: Role change on a user
|
||||
|
||||
- **WHEN** an admin changes user 4's roles from `Sales` to `Sales, Manager`
|
||||
- **THEN** the event's changes show roles before `Sales` and after `Sales, Manager`
|
||||
|
||||
#### Scenario: Lead edit records field names only
|
||||
|
||||
- **WHEN** an admin changes a lead's phone and notes
|
||||
- **THEN** the event's changes list the fields `phone` and `notes`
|
||||
- **AND** neither the old nor the new phone or notes appear in the event
|
||||
|
||||
### Requirement: Recording never blocks the action
|
||||
|
||||
Recording SHALL be best-effort. A failure to publish or save an audit event MUST NOT change the response of the admin call.
|
||||
|
||||
#### Scenario: Publish failure
|
||||
|
||||
- **GIVEN** the audit event cannot be published
|
||||
- **WHEN** an admin updates a user
|
||||
- **THEN** the update succeeds as usual
|
||||
- **AND** the failure is logged
|
||||
|
||||
### Requirement: Retention
|
||||
|
||||
The system SHALL delete audit events older than the configured retention period, 730 days by default, on a schedule.
|
||||
|
||||
#### Scenario: Old events are purged
|
||||
|
||||
- **WHEN** the purge runs with a retention of 730 days
|
||||
- **THEN** events older than 730 days are deleted
|
||||
- **AND** newer events are kept
|
||||
|
||||
### Requirement: Audit log screen
|
||||
|
||||
The system SHALL let an admin with `BO_AUDIT_LOG` list audit events newest first, paged, filtered by actor, module, action, outcome and date range, and open one event to see its details and changes. An admin without `BO_AUDIT_LOG` SHALL be refused.
|
||||
|
||||
#### Scenario: Filter by actor
|
||||
|
||||
- **WHEN** an admin with `BO_AUDIT_LOG` filters the audit log by actor `admin`
|
||||
- **THEN** only events by `admin` are listed, newest first
|
||||
|
||||
#### Scenario: Event detail
|
||||
|
||||
- **WHEN** an admin opens an event for a role grant change
|
||||
- **THEN** the detail shows the event's fields and the modules added and removed
|
||||
|
||||
#### Scenario: Without the module
|
||||
|
||||
- **WHEN** an admin without `BO_AUDIT_LOG` calls the audit log API or opens `/audit-log`
|
||||
- **THEN** the API answers 403 and the page shows Not authorised
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Co-Lite change add-admin-audit-log: the admin audit trail.
|
||||
-- Target: `service-log`.`audit_event`. Additive only. Run once, after the release package.
|
||||
-- DDL: run with a user that may create tables, not the services' user.
|
||||
-- Written by services-log from the audit-event-topic Pub/Sub messages that mobile-api publishes.
|
||||
USE `service-log`;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `audit_event` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint NULL,
|
||||
`occurred_at` datetime(6) NOT NULL,
|
||||
`actor` varchar(191) NOT NULL,
|
||||
`module` varchar(64) NULL,
|
||||
`action` varchar(128) NOT NULL,
|
||||
`http_method` varchar(16) NULL,
|
||||
`path_template` varchar(255) NULL,
|
||||
`target_id` varchar(128) NULL,
|
||||
`outcome` varchar(16) NOT NULL COMMENT 'SUCCESS | FAILURE',
|
||||
`http_status` int NULL,
|
||||
`client_ip` varchar(64) NULL,
|
||||
`changes` text NULL COMMENT 'JSON: allow-listed before/after, or changed field names',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_audit_event_occurred_at` (`occurred_at`),
|
||||
KEY `idx_audit_event_actor` (`actor`, `occurred_at`),
|
||||
KEY `idx_audit_event_module_action` (`module`, `action`, `occurred_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Co-Lite change add-admin-audit-log: the Audit log back-office module (area BO).
|
||||
-- Target: `service-system`.`module`. Additive only. Run once, after the release package.
|
||||
-- No role grant: super admins see every module; they grant BO_AUDIT_LOG to other roles under Roles.
|
||||
USE `service-system`;
|
||||
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(41100000, 'BO_AUDIT_LOG', 'Audit log', 'BO', 'M', 40000000, '/audit-log', 'ScrollText');
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Co-Lite change add-admin-audit-log: rollback of 01-02. Destroys the audit trail.
|
||||
USE `service-system`;
|
||||
DELETE FROM `modules_roles` WHERE `module_id` = 41100000;
|
||||
DELETE FROM `module` WHERE `id` = 41100000;
|
||||
|
||||
USE `service-log`;
|
||||
DROP TABLE IF EXISTS `audit_event`;
|
||||
@@ -0,0 +1,96 @@
|
||||
# Tasks
|
||||
|
||||
Design: `design.md`. All tasks run serially: each builds on the one before.
|
||||
|
||||
## 1. Data and contract
|
||||
|
||||
- [x] 1.1 SQL and Pub/Sub topic.
|
||||
- Files:
|
||||
- `sql/01-audit-event.sql`: `CREATE TABLE IF NOT EXISTS service-log.audit_event` (design decision 2).
|
||||
- `sql/02-audit-log-module.sql`: the module row (design decision 10).
|
||||
- `sql/99-rollback.sql`.
|
||||
- Mirror 01 and 02 in `local/seed/03-colite.sql`, and add `audit-event-topic audit-event-subscription` to `local/pubsub/topics.txt`.
|
||||
- Apply them to the local database and emulator. This is local only.
|
||||
- Scope: `local/**`, `openspec/changes/add-admin-audit-log/sql/**`
|
||||
- Verify: `select` shows the table and the module row.
|
||||
- [x] 1.2 core-libs `AuditEvent` (design decision 1).
|
||||
- Tests first: JSON round trip through the same `PubSubUtil` used for `ResponseTime`.
|
||||
- Scope: `solvway-core-libs/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-core-libs verify`
|
||||
|
||||
## 2. services-log
|
||||
|
||||
- [x] 2.1 Storage, listener, purge and read endpoints (design decision 7).
|
||||
- Tests first:
|
||||
- the listener saves an event with every field;
|
||||
- search filters by actor, module, action, outcome and dates, returns newest first, caps the size at 100, and rejects a bad date with 400;
|
||||
- detail answers 404 for an unknown id;
|
||||
- the purge deletes only rows older than the retention and reads the env setting.
|
||||
- Scope: `solvway-services-log/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-services-log -am verify`
|
||||
|
||||
## 3. mobile-api
|
||||
|
||||
- [x] 3.1 Recording in `AppAccessAspect`, with `Audited` and `AuditChanges` (design decisions 3, 4 and 6).
|
||||
- Add annotations on the lead export, the event-lead export, the email detail (sensitive) and event-lead `match` (skip).
|
||||
- Tests first:
|
||||
- a write records every field: actor, module, action, method, template, target, outcome and IP;
|
||||
- the derived and the explicit action codes;
|
||||
- a non-2xx response and a thrown status exception record `FAILURE` with the status;
|
||||
- a 403 refusal for a valid user is recorded;
|
||||
- plain GETs, skipped POSTs and the auth endpoints (except first-login) are not recorded;
|
||||
- a call without a user is not recorded;
|
||||
- a publish failure does not change the response;
|
||||
- `AuditChanges` content lands in `changes` and is cleared between requests.
|
||||
- Scope: `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- [x] 3.2 Allow-listed changes from the services (design decision 5).
|
||||
- Tests first, one per service:
|
||||
- user role names and enabled flag before and after;
|
||||
- role modules added and removed;
|
||||
- lead and event-lead edits record field names only, and no value appears anywhere in `changes`;
|
||||
- login-security config and rules before and after.
|
||||
- Scope: `solvway-mobile-api/src/main/java/**/service/**` plus their tests
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- [x] 3.3 `AdminAuditLogController` and the read service (design decision 8).
|
||||
- Tests first:
|
||||
- the class-level module;
|
||||
- parameter mapping;
|
||||
- a 404 for an unknown id;
|
||||
- only the given filters are forwarded.
|
||||
- Scope: `solvway-mobile-api/src/**` (new audit-log files, constants, tests)
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- Live check through the stack:
|
||||
- edit a user and see the event with its changes;
|
||||
- `noevents` creating an event is recorded as `FAILURE`;
|
||||
- opening an email is recorded.
|
||||
|
||||
## 4. Portal
|
||||
|
||||
- [x] 4.1 `/audit-log` list and `/audit-log/[id]` detail, with a proxy, a service and i18n keys (design decision 9).
|
||||
- Tests first:
|
||||
- rows and filters go into the query;
|
||||
- the detail shows a before/after table and a field-name list;
|
||||
- `RequireModule` gates the page;
|
||||
- the proxy is GET only and refuses dot segments.
|
||||
- Scope: `solvway-admin-portal/app/audit-log/**`, `solvway-admin-portal/app/api/audit-log/**`, `solvway-admin-portal/app/lib/**`
|
||||
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`
|
||||
|
||||
## 5. Check and docs
|
||||
|
||||
- [x] 5.1 Browser check and handover.
|
||||
- Playwright on the local stack:
|
||||
- as admin, change a user's roles, change a role's grants, edit a lead, open an email and export leads, then see each in Audit log with its changes;
|
||||
- as `noevents`, try a forbidden action and see it as `FAILURE`;
|
||||
- `noevents` has no Audit log menu entry and sees Not authorized at `/audit-log`;
|
||||
- the list fits at 1280 px, and the pages work at 360 px.
|
||||
- Docs, in `docs/deployment.md`:
|
||||
- section 3: the new SQL;
|
||||
- section 5: the new topic and subscription;
|
||||
- section 6: `AUDIT_RETENTION_DAYS`.
|
||||
- Scope: `docs/deployment.md`
|
||||
- Verify: screenshots, and the steps above observed.
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
- Whole-branch review, push, PR to main and merge, then archive on its own branch.
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import * as route from "./route";
|
||||
|
||||
const { GET } = route;
|
||||
const req = (url: string) => new Request(url) as unknown as Parameters<typeof GET>[0];
|
||||
const ctx = (path?: string[]) => ({ params: Promise.resolve({ path }) });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
||||
});
|
||||
|
||||
describe("/api/audit-log/[[...path]]", () => {
|
||||
it("is GET only", () => {
|
||||
expect(Object.keys(route).filter((k) => /^(GET|POST|PUT|PATCH|DELETE)$/.test(k))).toEqual(["GET"]);
|
||||
});
|
||||
|
||||
it("returns 401 without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
expect((await GET(req("http://localhost/api/audit-log"), ctx())).status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses dot segments", async () => {
|
||||
expect((await GET(req("http://localhost/api/audit-log/.."), ctx([".."]))).status).toBe(400);
|
||||
expect((await GET(req("http://localhost/api/audit-log/."), ctx(["."]))).status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forwards the query to the list", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { content: [] } });
|
||||
const res = await GET(req("http://localhost/api/audit-log?actor=a&page=0&size=20"), ctx());
|
||||
expect(res.status).toBe(200);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/audit-log?actor=a&page=0&size=20", { token: "jwt" });
|
||||
});
|
||||
|
||||
it("forwards one event by encoded id", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: "a/b" } });
|
||||
await GET(req("http://localhost/api/audit-log/a%2Fb"), ctx(["a/b"]));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/audit-log/a%2Fb", { token: "jwt" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
// Read-only proxy for /api/admin/audit-log[/<id>]; mobile-api owns the BO_AUDIT_LOG guard. Audit events are never writable from the portal, so GET is the only method.
|
||||
type Ctx = { params: Promise<{ path?: string[] }> };
|
||||
|
||||
export async function GET(req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { path = [] } = await params;
|
||||
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
|
||||
const target = `/api/admin/audit-log${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`;
|
||||
const result = await callMobileApi<unknown>(target, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ getAuditEvent: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/auditLog", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/auditLog")>()),
|
||||
getAuditEvent: mocks.getAuditEvent,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", () => ({ useParams: () => ({ id: "e2" }) }));
|
||||
|
||||
import AuditEventPage from "./page";
|
||||
|
||||
const EVENT = {
|
||||
id: 2, companyId: 1, occurredAt: "2026-11-30T15:52:00.5", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE",
|
||||
httpMethod: "PUT", pathTemplate: "/api/admin/users/{id}", targetId: "42", outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.5", changes: null as string | null,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.getAuditEvent.mockReset();
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("AuditEventPage", () => {
|
||||
it("gates on BO_AUDIT_LOG", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<AuditEventPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
expect(mocks.getAuditEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows a before/after table for put-style changes", async () => {
|
||||
const changes = JSON.stringify({
|
||||
roles: { before: ["A"], after: ["A", "B"] },
|
||||
enabled: { before: false, after: true },
|
||||
lockout: { before: { status: "Y", value: 5 }, after: null },
|
||||
});
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes });
|
||||
render(<AuditEventPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
expect(within(table).getAllByRole("columnheader").map((h) => h.textContent)).toEqual(["Field", "Before", "After"]);
|
||||
const rows = within(table).getAllByRole("row").slice(1);
|
||||
expect(rows[0]).toHaveTextContent("rolesAA, B");
|
||||
expect(rows[1]).toHaveTextContent("enabledfalsetrue");
|
||||
expect(rows[2]).toHaveTextContent("lockoutstatus: Y, value: 5—");
|
||||
expect(screen.getByText("sales1")).toBeInTheDocument();
|
||||
expect(screen.getByText("/api/admin/users/{id}", { exact: false })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders module grants with a dash before and joined codes after", async () => {
|
||||
const changes = JSON.stringify({
|
||||
modulesAdded: { before: null, after: ["BO_USERS", "BO_LEADS"] },
|
||||
modulesRemoved: { before: null, after: ["BO_EVENTS"] },
|
||||
});
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes });
|
||||
render(<AuditEventPage />);
|
||||
const rows = within(await screen.findByRole("table")).getAllByRole("row").slice(1);
|
||||
expect(rows[0]).toHaveTextContent("modulesAdded—BO_USERS, BO_LEADS");
|
||||
expect(rows[1]).toHaveTextContent("modulesRemoved—BO_EVENTS");
|
||||
});
|
||||
|
||||
it("lists field names only for {fields: [...]}", async () => {
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes: JSON.stringify({ fields: ["phone", "notes"] }) });
|
||||
render(<AuditEventPage />);
|
||||
expect(await screen.findByText("phone")).toBeInTheDocument();
|
||||
expect(screen.getByText("notes")).toBeInTheDocument();
|
||||
expect(screen.getByText("Values are not recorded for these fields.")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("table")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows unparsable changes as plain text", async () => {
|
||||
mocks.getAuditEvent.mockResolvedValue({ ...EVENT, changes: "not json {" });
|
||||
render(<AuditEventPage />);
|
||||
expect(await screen.findByText("not json {")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a message when the event is not found", async () => {
|
||||
mocks.getAuditEvent.mockRejectedValue(new ApiError("NOT_FOUND", 404));
|
||||
render(<AuditEventPage />);
|
||||
expect(await screen.findByText("Audit event not found")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Back to audit log" })).toHaveAttribute("href", "/audit-log");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { useParams } from "next/navigation";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { Skeleton } from "@/app/components/ui/skeleton";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { formatEmailDate } from "@/app/lib/services/adminEmails";
|
||||
import { getAuditEvent, type AuditEvent } from "@/app/lib/services/auditLog";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
type Parsed = { kind: "fields"; fields: string[] } | { kind: "diff"; rows: [string, unknown, unknown][] } | { kind: "text"; text: string };
|
||||
|
||||
function parseChanges(raw: string): Parsed {
|
||||
try {
|
||||
const obj: unknown = JSON.parse(raw);
|
||||
if (obj && typeof obj === "object" && !Array.isArray(obj)) {
|
||||
const rec = obj as Record<string, unknown>;
|
||||
if (Array.isArray(rec.fields)) return { kind: "fields", fields: rec.fields.map(String) };
|
||||
const rows = Object.entries(rec).map(([k, v]): [string, unknown, unknown] => {
|
||||
const c = (v ?? {}) as { before?: unknown; after?: unknown };
|
||||
return [k, c.before, c.after];
|
||||
});
|
||||
return { kind: "diff", rows };
|
||||
}
|
||||
} catch { /* shown as plain text below */ }
|
||||
return { kind: "text", text: raw };
|
||||
}
|
||||
|
||||
const show = (v: unknown): string => {
|
||||
if (v === null || v === undefined) return "—";
|
||||
if (Array.isArray(v)) return v.map(show).join(", ");
|
||||
if (typeof v === "object") return Object.entries(v).map(([k, x]) => `${k}: ${show(x)}`).join(", ");
|
||||
return String(v);
|
||||
};
|
||||
|
||||
function Changes({ raw }: { raw: string | null }) {
|
||||
const t = useT();
|
||||
const parsed = useMemo(() => (raw ? parseChanges(raw) : null), [raw]);
|
||||
if (!parsed) return <p className="text-sm text-muted-foreground">{t("AuditNoChanges")}</p>;
|
||||
if (parsed.kind === "text") return <pre className="overflow-x-auto whitespace-pre-wrap break-all text-sm">{parsed.text}</pre>;
|
||||
if (parsed.kind === "fields") {
|
||||
return (
|
||||
<div className="space-y-2 text-sm">
|
||||
<ul className="list-disc pl-5">{parsed.fields.map((f) => <li key={f}>{f}</li>)}</ul>
|
||||
<p className="text-muted-foreground">{t("AuditFieldsOnly")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t("AuditField")}</TableHead>
|
||||
<TableHead>{t("AuditBefore")}</TableHead>
|
||||
<TableHead>{t("AuditAfter")}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{parsed.rows.map(([field, before, after]) => (
|
||||
<TableRow key={field}>
|
||||
<TableCell className="font-medium">{field}</TableCell>
|
||||
<TableCell className="break-words whitespace-normal">{show(before)}</TableCell>
|
||||
<TableCell className="break-words whitespace-normal">{show(after)}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
}
|
||||
|
||||
function AuditEventContent() {
|
||||
const t = useT();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [event, setEvent] = useState<AuditEvent | null>(null);
|
||||
const [error, setError] = useState<"notFound" | "failed" | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- clears the previous event/error before the id-triggered fetch below.
|
||||
setEvent(null);
|
||||
setError(null);
|
||||
getAuditEvent(id)
|
||||
.then((e) => { if (!cancelled) setEvent(e); })
|
||||
.catch((err: unknown) => { if (!cancelled) setError(err instanceof ApiError && err.status === 404 ? "notFound" : "failed"); });
|
||||
return () => { cancelled = true; };
|
||||
}, [id]);
|
||||
|
||||
const back = <Link href="/audit-log" className="mt-4 inline-block text-primary underline-offset-4 hover:underline">{t("AuditBack")}</Link>;
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_AUDIT_LOG")} />
|
||||
{error === "notFound" ? <EmptyState title={t("AuditNotFound")} /> : <ErrorState message={t("AuditLoadFailed")} className="mb-4" />}
|
||||
{back}
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (!event) {
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_AUDIT_LOG")} />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PageHeader title={event.action} />
|
||||
<dl className="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1 text-sm">
|
||||
<dt className="text-muted-foreground">{t("LsTime")}</dt>
|
||||
<dd>{formatEmailDate(event.occurredAt)}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditWho")}</dt>
|
||||
<dd className="break-all">{event.actor}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditModule")}</dt>
|
||||
<dd>{event.module ? t(event.module) : "—"}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditAction")}</dt>
|
||||
<dd>{event.action}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditRequest")}</dt>
|
||||
<dd className="break-all">{event.httpMethod} {event.pathTemplate}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditTarget")}</dt>
|
||||
<dd className="break-all">{event.targetId ?? "—"}</dd>
|
||||
<dt className="text-muted-foreground">{t("AuditOutcome")}</dt>
|
||||
<dd><Badge variant={event.outcome === "SUCCESS" ? "positive" : "negative"}>{event.outcome} {event.httpStatus}</Badge></dd>
|
||||
<dt className="text-muted-foreground">{t("LsIp")}</dt>
|
||||
<dd>{event.clientIp ?? "—"}</dd>
|
||||
</dl>
|
||||
<section className="space-y-2">
|
||||
<h2 className="text-base font-semibold">{t("AuditChanges")}</h2>
|
||||
<Changes raw={event.changes} />
|
||||
</section>
|
||||
{back}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AuditEventPage() {
|
||||
return (
|
||||
<RequireModule pathname="/audit-log">
|
||||
<AuditEventContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ searchAuditLog: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/auditLog", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/auditLog")>()),
|
||||
searchAuditLog: mocks.searchAuditLog,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import AuditLogPage from "./page";
|
||||
|
||||
const EVENTS = [
|
||||
{ id: 2, companyId: 1, occurredAt: "2026-11-30T15:52:00.5", actor: "sales1", module: "BO_USERS", action: "USER_UPDATE", httpMethod: "PUT", pathTemplate: "/api/admin/users/{id}", targetId: "42", outcome: "FAILURE", httpStatus: 403, clientIp: "10.0.0.5", changes: null },
|
||||
{ id: 1, companyId: 1, occurredAt: "2026-11-29T09:05:00", actor: "admin", module: null, action: "LEAD_EXPORT", httpMethod: "GET", pathTemplate: "/api/admin/leads/export", targetId: null, outcome: "SUCCESS", httpStatus: 200, clientIp: "10.0.0.6", changes: null },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/audit-log");
|
||||
mocks.searchAuditLog.mockReset().mockResolvedValue({ items: EVENTS, total: 2 });
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
|
||||
});
|
||||
|
||||
describe("AuditLogPage", () => {
|
||||
it("renders NotAuthorized without BO_AUDIT_LOG", () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
|
||||
render(<AuditLogPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
expect(mocks.searchAuditLog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lists rows with module label, outcome badge with status, and a link to the detail", async () => {
|
||||
render(<AuditLogPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
const rows = within(table).getAllByRole("row").slice(1);
|
||||
expect(rows[0]).toHaveTextContent("30/11/2026 15:52");
|
||||
expect(rows[0]).toHaveTextContent("sales1");
|
||||
expect(rows[0]).toHaveTextContent("Users");
|
||||
expect(rows[0]).toHaveTextContent("USER_UPDATE");
|
||||
expect(rows[0]).toHaveTextContent("FAILURE 403");
|
||||
expect(rows[0]).toHaveTextContent("10.0.0.5");
|
||||
expect(within(rows[0]).getByRole("link", { name: "USER_UPDATE" })).toHaveAttribute("href", "/audit-log/2");
|
||||
expect(rows[1]).toHaveTextContent("SUCCESS 200");
|
||||
});
|
||||
|
||||
it("labels lead modules and offers them in the module filter, without BO_AUDIT_LOG", async () => {
|
||||
mocks.searchAuditLog.mockResolvedValue({ items: [{ ...EVENTS[1], module: "BO_LEADS_EXPORT" }], total: 1 });
|
||||
render(<AuditLogPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
expect(within(table).getAllByRole("row")[1]).toHaveTextContent("Lead export");
|
||||
await userEvent.click(screen.getByRole("combobox", { name: "Module" }));
|
||||
expect(await screen.findByRole("option", { name: "Lead editing" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("option", { name: "Lead export" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("option", { name: "Audit log" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows a dash for a null module", async () => {
|
||||
render(<AuditLogPage />);
|
||||
const table = await screen.findByRole("table");
|
||||
expect(within(table).getAllByRole("row")[2]).toHaveTextContent("admin—LEAD_EXPORT");
|
||||
});
|
||||
|
||||
it("puts the filters in the query", async () => {
|
||||
memoryRouter.reset("/audit-log", "outcome=FAILURE&from=2026-11-01&module=BO_USERS");
|
||||
render(<AuditLogPage />);
|
||||
await screen.findByRole("table");
|
||||
expect(mocks.searchAuditLog).toHaveBeenCalledWith(expect.objectContaining({ outcome: "FAILURE", from: "2026-11-01", module: "BO_USERS", page: 1, pageSize: 20 }));
|
||||
await userEvent.type(screen.getByRole("searchbox", { name: "Who" }), "sales");
|
||||
await waitFor(() => expect(mocks.searchAuditLog).toHaveBeenLastCalledWith(expect.objectContaining({ actor: "sales", outcome: "FAILURE" })));
|
||||
});
|
||||
|
||||
it("shows an empty state and an error state", async () => {
|
||||
mocks.searchAuditLog.mockResolvedValue({ items: [], total: 0 });
|
||||
const { unmount } = render(<AuditLogPage />);
|
||||
expect(await screen.findByText("No audit events found")).toBeInTheDocument();
|
||||
unmount();
|
||||
mocks.searchAuditLog.mockRejectedValue(new Error("x"));
|
||||
render(<AuditLogPage />);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the audit log");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { FilterField, FilterPanel, FilterSearch, FilterSelect } from "@/app/components/ui/filter-panel";
|
||||
import { DataTable } from "@/app/components/ui/data-table";
|
||||
import { DatePicker } from "@/app/components/ui/date-picker";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useListFilters } from "@/app/lib/hooks/useListFilters";
|
||||
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
||||
import { ROUTE_MODULES } from "@/app/lib/routeModules";
|
||||
import { formatEmailDate as formatDate } from "@/app/lib/services/adminEmails";
|
||||
import { searchAuditLog, type AuditEvent } from "@/app/lib/services/auditLog";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
const DEFAULTS = { actor: "", module: "", action: "", outcome: "", from: "", to: "" };
|
||||
// The backend stores the handler's @AdminModule code, so the filter lists those: the route modules plus the lead edit/export codes. Audit-log reads are never recorded.
|
||||
const MODULES = [...Object.values(ROUTE_MODULES).filter((m) => m !== "BO_AUDIT_LOG"), "BO_LEADS_EDIT", "BO_LEADS_EXPORT"];
|
||||
|
||||
function AuditLogContent() {
|
||||
const t = useT();
|
||||
const { tableRef, pageSize } = useFitPageSize();
|
||||
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
||||
const [data, setData] = useState<{ items: AuditEvent[]; total: number }>({ items: [], total: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (pageSize == null) return;
|
||||
let cancelled = false;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the filter/page/reloadKey-triggered fetch below, which is the actual synchronization.
|
||||
setLoading(true);
|
||||
setFailed(false);
|
||||
searchAuditLog({ ...filters, page, pageSize })
|
||||
.then((result) => { if (!cancelled) setData(result); })
|
||||
.catch(() => { if (!cancelled) setFailed(true); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
return () => { cancelled = true; };
|
||||
}, [filters, page, reloadKey, pageSize]);
|
||||
|
||||
const moduleOptions = useMemo(() => MODULES.map((m) => ({ value: m, label: t(m) })), [t]);
|
||||
const outcomeOptions = useMemo(() => [{ value: "SUCCESS", label: t("AuditSuccess") }, { value: "FAILURE", label: t("AuditFailure") }], [t]);
|
||||
const cut = (text: string | null | undefined, max = "max-w-40") => <span className={`block truncate ${max}`} title={text ?? undefined}>{text}</span>;
|
||||
const columns = useMemo<ColumnDef<AuditEvent, unknown>[]>(
|
||||
() => [
|
||||
{ id: "time", header: t("LsTime"), enableSorting: false, cell: ({ row }) => <span className="whitespace-nowrap">{formatDate(row.original.occurredAt)}</span> },
|
||||
{ id: "actor", header: t("AuditWho"), enableSorting: false, cell: ({ row }) => cut(row.original.actor, "max-w-32") },
|
||||
{ id: "module", header: t("AuditModule"), enableSorting: false, cell: ({ row }) => (row.original.module ? t(row.original.module) : "—") },
|
||||
{
|
||||
id: "action",
|
||||
header: t("AuditAction"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<Link href={`/audit-log/${row.original.id}`} title={row.original.action} className="block max-w-48 truncate font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
|
||||
{row.original.action}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
{ id: "target", header: t("AuditTarget"), enableSorting: false, cell: ({ row }) => cut(row.original.targetId, "max-w-28") },
|
||||
{
|
||||
id: "outcome",
|
||||
header: t("AuditOutcome"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.outcome === "SUCCESS" ? "positive" : "negative"}>{row.original.outcome} {row.original.httpStatus}</Badge>
|
||||
),
|
||||
},
|
||||
{ accessorKey: "clientIp", header: t("LsIp"), enableSorting: false },
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_AUDIT_LOG")} />
|
||||
{failed && <ErrorState message={t("AuditLoadFailed")} onRetry={refetch} className="mb-4" />}
|
||||
<FilterPanel activeCount={activeCount} onClear={clear}>
|
||||
<FilterField label={t("AuditWho")}>
|
||||
<FilterSearch className="w-full" aria-label={t("AuditWho")} value={filters.actor} onChange={(actor) => set({ actor })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("AuditModule")}>
|
||||
<FilterSelect className="w-full" aria-label={t("AuditModule")} allLabel={t("AuditAllModules")} options={moduleOptions} value={filters.module} onChange={(module) => set({ module })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("AuditAction")}>
|
||||
<FilterSearch className="w-full" aria-label={t("AuditAction")} value={filters.action} onChange={(action) => set({ action })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("AuditOutcome")}>
|
||||
<FilterSelect className="w-full" aria-label={t("AuditOutcome")} allLabel={t("AuditAllOutcomes")} options={outcomeOptions} value={filters.outcome} onChange={(outcome) => set({ outcome })} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LsFrom")}>
|
||||
<DatePicker aria-label={t("LsFrom")} value={filters.from} onChange={(from) => set({ from })} max={filters.to || undefined} />
|
||||
</FilterField>
|
||||
<FilterField label={t("LsTo")}>
|
||||
<DatePicker aria-label={t("LsTo")} value={filters.to} onChange={(to) => set({ to })} min={filters.from || undefined} />
|
||||
</FilterField>
|
||||
</FilterPanel>
|
||||
<DataTable
|
||||
label={t("BO_AUDIT_LOG")}
|
||||
columns={columns}
|
||||
data={data.items}
|
||||
total={data.total}
|
||||
page={page}
|
||||
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
||||
tableRef={tableRef}
|
||||
onPageChange={setPage}
|
||||
isLoading={loading}
|
||||
rowKey={(r) => String(r.id)}
|
||||
empty={<EmptyState title={activeCount > 0 ? t("AuditNoMatch") : t("AuditNoEvents")} />}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AuditLogPage() {
|
||||
return (
|
||||
<RequireModule pathname="/audit-log">
|
||||
<AuditLogContent />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -373,6 +373,30 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
LsRulesSaved: "Password rules saved.",
|
||||
LsSettingsLoadFailed: "Failed to load the settings",
|
||||
LsSaveFailed: "Failed to save",
|
||||
BO_AUDIT_LOG: "Audit log",
|
||||
BO_LEADS_EDIT: "Lead editing",
|
||||
BO_LEADS_EXPORT: "Lead export",
|
||||
AuditWho: "Who",
|
||||
AuditModule: "Module",
|
||||
AuditAction: "Action",
|
||||
AuditTarget: "Target",
|
||||
AuditOutcome: "Outcome",
|
||||
AuditAllModules: "All modules",
|
||||
AuditAllOutcomes: "All outcomes",
|
||||
AuditSuccess: "Success",
|
||||
AuditFailure: "Failure",
|
||||
AuditNoEvents: "No audit events found",
|
||||
AuditNoMatch: "No audit events match your filters",
|
||||
AuditLoadFailed: "Failed to load the audit log",
|
||||
AuditNotFound: "Audit event not found",
|
||||
AuditBack: "Back to audit log",
|
||||
AuditRequest: "Request",
|
||||
AuditChanges: "Changes",
|
||||
AuditNoChanges: "No changes recorded.",
|
||||
AuditField: "Field",
|
||||
AuditBefore: "Before",
|
||||
AuditAfter: "After",
|
||||
AuditFieldsOnly: "Values are not recorded for these fields.",
|
||||
PwdRule_INPUT_LENGTH_MIN: "Minimum length",
|
||||
PwdRule_INPUT_LENGTH_MAX: "Maximum length",
|
||||
PwdRule_ALPHABET_LENGTH_MIN: "Minimum letters",
|
||||
|
||||
@@ -14,7 +14,7 @@ describe("routeModules", () => {
|
||||
it("leaves other routes ungated", () => {
|
||||
expect(requiredModuleFor("/")).toBeUndefined();
|
||||
expect(requiredModulesFor("/members")).toBeUndefined();
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/emails", "/event-leads", "/events", "/interests", "/leads", "/login-security", "/roles", "/users"]);
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/audit-log", "/emails", "/event-leads", "/events", "/interests", "/leads", "/login-security", "/roles", "/users"]);
|
||||
expect(requiredModuleFor("/emails")).toBe("BO_EMAILS");
|
||||
expect(requiredModuleFor("/leads")).toBe("BO_LEADS");
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ export const ROUTE_MODULES: Record<string, string> = {
|
||||
"/leads": "BO_LEADS",
|
||||
"/emails": "BO_EMAILS",
|
||||
"/login-security": "BO_LOGIN_SECURITY",
|
||||
"/audit-log": "BO_AUDIT_LOG",
|
||||
};
|
||||
|
||||
export function requiredModuleFor(pathname: string): string | undefined {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", () => mocks);
|
||||
|
||||
import { getAuditEvent, searchAuditLog } from "./auditLog";
|
||||
|
||||
beforeEach(() => mocks.apiGet.mockReset());
|
||||
|
||||
describe("auditLog service", () => {
|
||||
it("searchAuditLog sends only non-empty filters with a 0-based page", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ content: [{ id: "e1" }], totalElements: 9 });
|
||||
const out = await searchAuditLog({ actor: "admin", module: "", action: "USER_UPDATE", outcome: "FAILURE", from: "2026-11-01", to: "", page: 2, pageSize: 10 });
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/audit-log?actor=admin&action=USER_UPDATE&outcome=FAILURE&from=2026-11-01&page=1&size=10");
|
||||
expect(out).toEqual({ items: [{ id: "e1" }], total: 9 });
|
||||
});
|
||||
|
||||
it("searchAuditLog tolerates an empty body", async () => {
|
||||
mocks.apiGet.mockResolvedValue(null);
|
||||
expect(await searchAuditLog({ page: 1, pageSize: 10 })).toEqual({ items: [], total: 0 });
|
||||
});
|
||||
|
||||
it("getAuditEvent GETs one event by encoded id", async () => {
|
||||
mocks.apiGet.mockResolvedValue({ id: "a/b" });
|
||||
await getAuditEvent("a/b");
|
||||
expect(mocks.apiGet).toHaveBeenCalledWith("/api/audit-log/a%2Fb");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { apiGet } from "@/app/lib/clientApi";
|
||||
|
||||
export interface AuditEvent {
|
||||
id: number;
|
||||
companyId: number;
|
||||
/** Server-local ISO datetime, e.g. "2026-11-30T15:52:00.5". */
|
||||
occurredAt: string;
|
||||
actor: string;
|
||||
module: string | null;
|
||||
action: string;
|
||||
httpMethod: string;
|
||||
pathTemplate: string;
|
||||
targetId: string | null;
|
||||
outcome: "SUCCESS" | "FAILURE";
|
||||
httpStatus: number;
|
||||
clientIp: string | null;
|
||||
/** JSON string: {"<field>": {before, after}} or {"fields": [...]}; null when nothing was recorded. */
|
||||
changes: string | null;
|
||||
}
|
||||
|
||||
export interface AuditLogParams {
|
||||
actor?: string;
|
||||
module?: string;
|
||||
action?: string;
|
||||
outcome?: string;
|
||||
/** "yyyy-MM-dd". */
|
||||
from?: string;
|
||||
to?: string;
|
||||
/** 1-based. */
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
const BASE = "/api/audit-log";
|
||||
|
||||
export async function searchAuditLog(params: AuditLogParams): Promise<{ items: AuditEvent[]; total: number }> {
|
||||
const qs = new URLSearchParams();
|
||||
for (const key of ["actor", "module", "action", "outcome", "from", "to"] as const) if (params[key]) qs.set(key, params[key]);
|
||||
qs.set("page", String(Math.max(0, params.page - 1)));
|
||||
qs.set("size", String(params.pageSize));
|
||||
const raw = await apiGet<{ content?: AuditEvent[]; totalElements?: number } | null>(`${BASE}?${qs}`);
|
||||
const items = Array.isArray(raw?.content) ? raw.content : [];
|
||||
return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length };
|
||||
}
|
||||
|
||||
export const getAuditEvent = (id: string) => apiGet<AuditEvent>(`${BASE}/${encodeURIComponent(id)}`);
|
||||
@@ -125,6 +125,11 @@
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.jknack</groupId>
|
||||
<artifactId>handlebars</artifactId>
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.solvway.core.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** One admin audit event: published by mobile-api on audit-event-topic, stored by services-log. */
|
||||
@Setter
|
||||
@Getter
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class AuditEvent {
|
||||
public static final String OUTCOME_SUCCESS = "SUCCESS";
|
||||
public static final String OUTCOME_FAILURE = "FAILURE";
|
||||
|
||||
private Long companyId;
|
||||
private LocalDateTime occurredAt;
|
||||
private String actor;
|
||||
private String module;
|
||||
private String action;
|
||||
private String httpMethod;
|
||||
private String pathTemplate;
|
||||
private String targetId;
|
||||
private String outcome;
|
||||
private Integer httpStatus;
|
||||
private String clientIp;
|
||||
/** JSON: {field: {before, after}} for allow-listed fields, or {fields: [..]} for lead edits. */
|
||||
private String changes;
|
||||
}
|
||||
@@ -47,6 +47,9 @@ pubsub:
|
||||
activate-member:
|
||||
subscription: activate-member-subscription
|
||||
topic: activate-member-topic
|
||||
audit-event:
|
||||
subscription: audit-event-subscription
|
||||
topic: audit-event-topic
|
||||
backoffice-message-source-refresh:
|
||||
subscription: backoffice-message-source-refresh-subscription
|
||||
topic: backoffice-message-source-refresh-topic
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.solvway.core.model;
|
||||
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class AuditEventTest {
|
||||
|
||||
private final PubSubUtil util = new PubSubUtil();
|
||||
|
||||
@Test
|
||||
void roundTripsEveryFieldThroughPubSubUtil() {
|
||||
AuditEvent e = new AuditEvent();
|
||||
e.setCompanyId(7L);
|
||||
e.setOccurredAt(LocalDateTime.of(2026, 11, 30, 15, 4, 5, 123_000_000));
|
||||
e.setActor("admin");
|
||||
e.setModule("BO_USERS");
|
||||
e.setAction("USER_UPDATE");
|
||||
e.setHttpMethod("PUT");
|
||||
e.setPathTemplate("/api/admin/users/{id}");
|
||||
e.setTargetId("42");
|
||||
e.setOutcome(AuditEvent.OUTCOME_SUCCESS);
|
||||
e.setHttpStatus(200);
|
||||
e.setClientIp("203.0.113.9");
|
||||
e.setChanges("{\"enabled\":{\"before\":true,\"after\":false}}");
|
||||
|
||||
String json = util.convertToString(e);
|
||||
assertThat(json).contains("\"occurredAt\":\"2026-11-30T15:04:05.123\"");
|
||||
|
||||
AuditEvent back = util.convertToOriginalObject(json.getBytes(StandardCharsets.UTF_8), AuditEvent.class);
|
||||
assertThat(back).usingRecursiveComparison().isEqualTo(e);
|
||||
assertThat(AuditEvent.OUTCOME_FAILURE).isEqualTo("FAILURE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ignoresUnknownFieldsSoTheContractCanGrow() {
|
||||
String json = "{\"actor\":\"admin\",\"action\":\"USER_UPDATE\",\"outcome\":\"SUCCESS\",\"addedLater\":1}";
|
||||
AuditEvent back = util.convertToOriginalObject(json.getBytes(StandardCharsets.UTF_8), AuditEvent.class);
|
||||
assertThat(back).isNotNull();
|
||||
assertThat(back.getActor()).isEqualTo("admin");
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,9 @@ public class PubSubConfig {
|
||||
@Value("${pubsub.response-time-log.topic}")
|
||||
public String responseTimeLogTopic;
|
||||
|
||||
@Value("${pubsub.audit-event.topic}")
|
||||
public String auditEventTopic;
|
||||
|
||||
@Value("${pubsub.email.save-request.topic}")
|
||||
public String emailSaveRequestTopic;
|
||||
|
||||
@@ -35,6 +38,7 @@ public class PubSubConfig {
|
||||
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
executor.submit(() -> pubSubUtil.createTopicIfNotExists(pubSubAdmin, responseTimeLogTopic));
|
||||
executor.submit(() -> pubSubUtil.createTopicIfNotExists(pubSubAdmin, emailSaveRequestTopic));
|
||||
executor.submit(() -> pubSubUtil.createTopicIfNotExists(pubSubAdmin, auditEventTopic));
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.solvway.mobile.api.constant.api;
|
||||
|
||||
public class RestApiLogServiceConstants {
|
||||
|
||||
private RestApiLogServiceConstants() {}
|
||||
|
||||
public static final String API_REST_LOG_AUDIT_SEARCH = "/log/audit/search";
|
||||
public static final String API_REST_LOG_AUDIT_DETAIL = "/log/audit/{id}";
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminAuditLogService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** Audit log screen: search and detail of admin audit events. Reads are not audited. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/audit-log")
|
||||
@RequiredArgsConstructor
|
||||
@AdminModule("BO_AUDIT_LOG")
|
||||
public class AdminAuditLogController {
|
||||
|
||||
private final AdminAuditLogService auditLog;
|
||||
|
||||
@AppAuth
|
||||
@GetMapping
|
||||
public ResponseEntity<Map<String, Object>> list(
|
||||
@RequestParam(required = false) String actor,
|
||||
@RequestParam(required = false) String module,
|
||||
@RequestParam(required = false) String action,
|
||||
@RequestParam(required = false) String outcome,
|
||||
@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(auditLog.search(actor, module, action, outcome, from, to, page, size));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<Map<String, Object>> detail(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(auditLog.get(id));
|
||||
}
|
||||
}
|
||||
+2
@@ -3,6 +3,7 @@ package com.solvway.mobile.api.controller.admin;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminEmailService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -34,6 +35,7 @@ public class AdminEmailController {
|
||||
return ResponseEntity.ok(adminEmailService.list(recipient, subject, from, to, page, size));
|
||||
}
|
||||
|
||||
@Audited(action = "EMAIL_VIEW")
|
||||
@AppAuth
|
||||
@GetMapping("/emails/{id}")
|
||||
public ResponseEntity<Map<String, Object>> detail(@PathVariable Long id) {
|
||||
|
||||
+2
@@ -6,6 +6,7 @@ import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.service.AdminEventLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -48,6 +49,7 @@ public class AdminEventLeadController {
|
||||
return ResponseEntity.ok(adminEventLeadService.salespersonOptions(eventUuid));
|
||||
}
|
||||
|
||||
@Audited(skip = true)
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENT_LEADS")
|
||||
@PostMapping("/{eventUuid}/match")
|
||||
|
||||
+2
@@ -3,6 +3,7 @@ package com.solvway.mobile.api.controller.admin;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminEventLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -20,6 +21,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class AdminEventLeadExportController {
|
||||
private final AdminEventLeadService adminEventLeadService;
|
||||
|
||||
@Audited(action = "EVENT_LEAD_EXPORT")
|
||||
@AppAuth
|
||||
@AdminModule(value = "BO_LEADS_EXPORT", also = "BO_EVENT_LEADS")
|
||||
@GetMapping("/{eventUuid}/export")
|
||||
|
||||
+2
@@ -4,6 +4,7 @@ import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.service.AdminLeadService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -34,6 +35,7 @@ public class AdminLeadController {
|
||||
return ResponseEntity.ok(adminLeadService.list(q, page, size));
|
||||
}
|
||||
|
||||
@Audited(action = "LEAD_EXPORT")
|
||||
@AppAuth
|
||||
@AdminModule(value = "BO_LEADS_EXPORT", also = "BO_LEADS")
|
||||
@GetMapping("/export")
|
||||
|
||||
+2
@@ -3,6 +3,7 @@ package com.solvway.mobile.api.controller.admin;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminLoginSecurityService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -44,6 +45,7 @@ public class AdminLoginSecurityController {
|
||||
return ResponseEntity.ok(loginSecurity.locked());
|
||||
}
|
||||
|
||||
@Audited(target = false) // the username is whatever was typed at sign-in, possibly a password
|
||||
@AppAuth
|
||||
@PostMapping("/locked/{username}/unlock")
|
||||
public ResponseEntity<Void> unlock(@PathVariable String username) {
|
||||
|
||||
+2
@@ -7,6 +7,7 @@ import com.solvway.mobile.api.dto.admin.AdminRoleRequest;
|
||||
import com.solvway.mobile.api.service.AdminAclService;
|
||||
import com.solvway.mobile.api.service.AdminRoleService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -52,6 +53,7 @@ public class AdminRoleController {
|
||||
public ResponseEntity<List<AdminModuleGrant>> getModules(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(adminAclService.getGrantTree(id));
|
||||
}
|
||||
@Audited(action = "ROLE_SET_MODULES")
|
||||
@AppAuth
|
||||
@AdminModule("BO_ROLES")
|
||||
@PutMapping("/roles/{id}/modules")
|
||||
|
||||
+3
@@ -4,6 +4,7 @@ import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
|
||||
import com.solvway.mobile.api.service.AdminUserService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -49,12 +50,14 @@ public class AdminUserController {
|
||||
return ResponseEntity.ok(adminUserService.update(id, request));
|
||||
}
|
||||
|
||||
@Audited(action = "USER_SEND_PASSWORD_RESET")
|
||||
@AppAuth
|
||||
@PostMapping("/users/{id}/resetPassword")
|
||||
public ResponseEntity<Map<String, Object>> resetPassword(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(Map.of("updated", adminUserService.resetPassword(id)));
|
||||
}
|
||||
|
||||
@Audited(action = "USER_SET_TEMPORARY_PASSWORD")
|
||||
@AppAuth
|
||||
@PostMapping("/users/{id}/password")
|
||||
public ResponseEntity<Void> setPassword(@PathVariable Long id, @RequestBody Map<String, String> body) {
|
||||
|
||||
+10
-1
@@ -5,6 +5,7 @@ import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminModuleGrant;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
@@ -52,8 +53,12 @@ public class AdminAclService {
|
||||
List<Map<String, Object>> modules = modules();
|
||||
Set<Long> known = new HashSet<>();
|
||||
Set<Long> current = new HashSet<>();
|
||||
Map<Long, String> codes = new java.util.HashMap<>();
|
||||
for (Map<String, Object> m : modules) {
|
||||
if (isGrantable(m)) known.add(AdminRoleService.idOf(m));
|
||||
if (isGrantable(m)) {
|
||||
known.add(AdminRoleService.idOf(m));
|
||||
codes.put(AdminRoleService.idOf(m), String.valueOf(m.get("name")));
|
||||
}
|
||||
if (isGrantable(m) && grantedTo(m, roleId)) current.add(AdminRoleService.idOf(m));
|
||||
}
|
||||
Set<Long> wanted = new HashSet<>(moduleIds);
|
||||
@@ -62,6 +67,10 @@ public class AdminAclService {
|
||||
// ponytail: not atomic, adds run before deletes and a failure midway leaves a partial grant; a repeated PUT converges. Upgrade: one services-system endpoint that replaces grants in a transaction.
|
||||
for (Long id : wanted) if (!current.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_ADD_MODULE_ROLE, id, roleId);
|
||||
for (Long id : current) if (!wanted.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_DELETE_MODULE_ROLE, id, roleId);
|
||||
List<String> added = wanted.stream().filter(id -> !current.contains(id)).map(codes::get).sorted().toList();
|
||||
List<String> removed = current.stream().filter(id -> !wanted.contains(id)).map(codes::get).sorted().toList();
|
||||
if (!added.isEmpty()) AuditChanges.put("modulesAdded", null, added);
|
||||
if (!removed.isEmpty()) AuditChanges.put("modulesRemoved", null, removed);
|
||||
return getGrantTree(roleId);
|
||||
}
|
||||
|
||||
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.mobile.api.constant.api.RestApiLogServiceConstants;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** Reads the audit trail from services-log for the Audit log screen, turning its 400/404 into coded admin errors. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminAuditLogService {
|
||||
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public Map<String, Object> search(String actor, String module, String action, String outcome, String from, String to, int page, int size) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
put(body, "actor", actor);
|
||||
put(body, "module", module);
|
||||
put(body, "action", action);
|
||||
put(body, "outcome", outcome);
|
||||
put(body, "from", from);
|
||||
put(body, "to", to);
|
||||
body.put("page", page);
|
||||
body.put("size", size);
|
||||
try {
|
||||
return restTemplateUtil.postForEntity(url(RestApiLogServiceConstants.API_REST_LOG_AUDIT_SEARCH), MAP, body).getBody();
|
||||
} catch (HttpClientErrorException.BadRequest e) {
|
||||
throw new CodedResponseStatusException(HttpStatus.BAD_REQUEST, reason(e), "INVALID_FILTER");
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> get(Long id) {
|
||||
try {
|
||||
return restTemplateUtil.getForEntity(url(RestApiLogServiceConstants.API_REST_LOG_AUDIT_DETAIL), MAP, id).getBody();
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Audit event not found", "NOT_FOUND");
|
||||
}
|
||||
}
|
||||
|
||||
private static void put(Map<String, Object> body, String key, String value) {
|
||||
if (StringUtils.hasText(value)) body.put(key, value.trim());
|
||||
}
|
||||
|
||||
private static String reason(HttpClientErrorException e) {
|
||||
try {
|
||||
JsonNode detail = JSON.readTree(e.getResponseBodyAsString()).get("detail");
|
||||
if (detail != null && detail.isTextual() && StringUtils.hasText(detail.asText())) return detail.asText();
|
||||
} catch (Exception ignored) {
|
||||
// empty or unparsable body: fall through to the generic reason
|
||||
}
|
||||
return "Invalid request";
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return restTemplateUtil.getURLforApiService(api);
|
||||
}
|
||||
}
|
||||
+13
-2
@@ -10,6 +10,7 @@ import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -23,6 +24,7 @@ import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
@@ -260,8 +262,17 @@ public class AdminEventLeadService {
|
||||
body.put("nextFollowUpDate", followUp == null ? null : followUp.toString());
|
||||
body.put("notes", trimmed(r.notes()));
|
||||
body.put("doneBy", caller.getUsername());
|
||||
return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody(),
|
||||
known, new HashMap<>());
|
||||
Map<String, Object> saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody();
|
||||
// field names only: follow-up values are personal data
|
||||
List<String> changed = new ArrayList<>();
|
||||
if (!Objects.equals(r.salespersonId(), currentSalesperson)) changed.add("salespersonId");
|
||||
if (!Objects.equals(temperature, current.get("temperature"))) changed.add("temperature");
|
||||
if (!Objects.equals(status, current.get("status"))) changed.add("status");
|
||||
if (!new HashSet<>(interestIds).equals(new HashSet<>(longs(current.get("interestIds"))))) changed.add("interestIds");
|
||||
if (!Objects.equals(body.get("nextFollowUpDate"), current.get("nextFollowUpDate") == null ? null : current.get("nextFollowUpDate").toString())) changed.add("nextFollowUpDate");
|
||||
if (!Objects.equals(body.get("notes"), current.get("notes"))) changed.add("notes");
|
||||
if (!changed.isEmpty()) AuditChanges.fields(changed.toArray(String[]::new));
|
||||
return view(saved, known, new HashMap<>());
|
||||
}
|
||||
|
||||
// --- rules ---
|
||||
|
||||
+23
-1
@@ -6,6 +6,7 @@ import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
@@ -19,6 +20,7 @@ import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.email;
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.error;
|
||||
@@ -118,11 +120,31 @@ public class AdminLeadService {
|
||||
body.put("jobTitle", jobTitle);
|
||||
body.put("notes", notes);
|
||||
body.put("doneBy", caller.getUsername());
|
||||
Map<String, Object> before = storedOrNull(caller.getCompanyId(), id);
|
||||
Map<String, Object> saved;
|
||||
try {
|
||||
return detail(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_UPDATE), MAP, body).getBody());
|
||||
saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_UPDATE), MAP, body).getBody();
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw notFound();
|
||||
}
|
||||
// field names only: lead values are personal data. No readable before-state means nothing is recorded.
|
||||
if (before != null) {
|
||||
List<String> changed = new ArrayList<>();
|
||||
for (String f : List.of("name", "mobileE164", "email", "companyName", "jobTitle", "notes")) {
|
||||
if (!Objects.equals(before.get(f), body.get(f))) changed.add("mobileE164".equals(f) ? "phone" : f);
|
||||
}
|
||||
if (!changed.isEmpty()) AuditChanges.fields(changed.toArray(String[]::new));
|
||||
}
|
||||
return detail(saved);
|
||||
}
|
||||
|
||||
/** Best-effort read of the lead before it is changed, for the audit trail only. */
|
||||
private Map<String, Object> storedOrNull(Long companyId, long id) {
|
||||
try {
|
||||
return restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_DETAIL), MAP, companyId, id).getBody();
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Digits to match against the stored E.164 mobile, or null when the term is not a phone-like number. */
|
||||
|
||||
+36
@@ -6,6 +6,7 @@ import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -15,9 +16,11 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Passes the Login security screen's calls to services-system, turning its 400s into coded admin errors. */
|
||||
@@ -59,7 +62,13 @@ public class AdminLoginSecurityService {
|
||||
}
|
||||
|
||||
public Map<String, Object> saveConfig(Map<String, Object> config) {
|
||||
Map<String, Object> before = readOrNull(this::config);
|
||||
Map<String, Object> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_CONFIG, MAP, config);
|
||||
if (before != null && saved != null) {
|
||||
for (String key : List.of("enabled", "maxAttempts", "period", "unit")) {
|
||||
if (!Objects.equals(before.get(key), saved.get(key))) AuditChanges.put(key, before.get(key), saved.get(key));
|
||||
}
|
||||
}
|
||||
log.info("lockout settings changed by {}", callerName());
|
||||
return saved;
|
||||
}
|
||||
@@ -69,11 +78,38 @@ public class AdminLoginSecurityService {
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> savePasswordRules(List<Map<String, Object>> rules) {
|
||||
List<Map<String, Object>> before = readOrNull(this::passwordRules);
|
||||
List<Map<String, Object>> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_PASSWORD_RULES, LIST, rules);
|
||||
if (before != null && saved != null) {
|
||||
Map<Object, Map<String, Object>> old = new HashMap<>();
|
||||
before.forEach(b -> old.put(b.get("param"), b));
|
||||
for (Map<String, Object> now : saved) {
|
||||
Map<String, Object> was = old.get(now.get("param"));
|
||||
if (was != null && !(Objects.equals(was.get("status"), now.get("status")) && Objects.equals(was.get("value"), now.get("value")))) {
|
||||
AuditChanges.put(String.valueOf(now.get("param")), ruleState(was), ruleState(now));
|
||||
}
|
||||
}
|
||||
}
|
||||
log.info("password rules changed by {}", callerName());
|
||||
return saved;
|
||||
}
|
||||
|
||||
private static Map<String, Object> ruleState(Map<String, Object> rule) {
|
||||
Map<String, Object> state = new HashMap<>();
|
||||
state.put("status", rule.get("status"));
|
||||
state.put("value", rule.get("value"));
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Best-effort read of the settings before they change, for the audit trail only. */
|
||||
private static <T> T readOrNull(Supplier<T> read) {
|
||||
try {
|
||||
return read.get();
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T post(String api, ParameterizedTypeReference<T> type, Object body) {
|
||||
return upstream(() -> restTemplateUtil.postForEntity(url(api), type, body).getBody());
|
||||
}
|
||||
|
||||
+16
-1
@@ -6,6 +6,7 @@ import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminRoleRef;
|
||||
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -115,6 +116,8 @@ public class AdminUserService {
|
||||
if (adminAuthenticationService.setAdminPassword(((Number) saved.get("id")).longValue(), r.password()) == 0) {
|
||||
throw error(HttpStatus.INTERNAL_SERVER_ERROR, "User created but the password was not stored; set a temporary password", "SAVE_FAILED");
|
||||
}
|
||||
AuditChanges.put("roles", null, sortedRoleNames(user.get("roles")));
|
||||
AuditChanges.put("enabled", null, true);
|
||||
return clean(saved);
|
||||
}
|
||||
|
||||
@@ -132,6 +135,8 @@ public class AdminUserService {
|
||||
if (r.roles() != null && r.roles().isEmpty()) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "At least one role is required", "REQUIRED_FIELD");
|
||||
}
|
||||
List<String> rolesBefore = sortedRoleNames(user.get("roles"));
|
||||
Object enabledBefore = user.get("enabled");
|
||||
if (StringUtils.hasText(r.name())) user.put("name", r.name());
|
||||
if (r.surname() != null) user.put("surname", r.surname());
|
||||
if (StringUtils.hasText(r.email())) user.put("email", r.email());
|
||||
@@ -141,7 +146,12 @@ public class AdminUserService {
|
||||
user.put("status", r.enabled() ? "Y" : "N");
|
||||
}
|
||||
user.put("doneBy", caller.getUsername());
|
||||
return clean(save(user));
|
||||
Map<String, Object> saved = save(user);
|
||||
// names and ids only: never the user's name, surname or email
|
||||
List<String> rolesAfter = sortedRoleNames(user.get("roles"));
|
||||
if (r.roles() != null && !rolesBefore.equals(rolesAfter)) AuditChanges.put("roles", rolesBefore, rolesAfter);
|
||||
if (r.enabled() != null && !r.enabled().equals(enabledBefore)) AuditChanges.put("enabled", enabledBefore, r.enabled());
|
||||
return clean(saved);
|
||||
}
|
||||
|
||||
public int resetPassword(Long id) {
|
||||
@@ -301,6 +311,11 @@ public class AdminUserService {
|
||||
return Comparator.comparing(m -> String.valueOf(m.get(key)).toLowerCase());
|
||||
}
|
||||
|
||||
private static List<String> sortedRoleNames(Object roles) {
|
||||
if (!(roles instanceof List<?> l)) return List.of();
|
||||
return l.stream().map(r -> r instanceof Map<?, ?> rm ? String.valueOf(rm.get("name")) : String.valueOf(r)).sorted().toList();
|
||||
}
|
||||
|
||||
private static String roleNames(Map<String, Object> m) {
|
||||
Object roles = m.get("roles");
|
||||
if (!(roles instanceof List<?> l)) return "";
|
||||
|
||||
+130
-9
@@ -1,10 +1,12 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.GeneralEnum.CmsPlatform;
|
||||
import com.solvway.core.enums.GeneralEnum.FlagYesNo;
|
||||
import com.solvway.core.enums.JwtEnum.JwtCustomClaim;
|
||||
import com.solvway.core.model.AuditEvent;
|
||||
import com.solvway.core.model.Role;
|
||||
import com.solvway.core.model.ResponseTime;
|
||||
import com.solvway.core.model.User;
|
||||
@@ -15,6 +17,7 @@ import com.solvway.core.utils.SnowflakeIdWorker;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.mobile.api.config.AuthAppKeyConfig;
|
||||
import com.solvway.mobile.api.config.PubSubConfig;
|
||||
import com.solvway.mobile.api.controller.admin.AdminAuthController;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.UserService;
|
||||
@@ -29,6 +32,7 @@ import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
@@ -40,6 +44,7 @@ import org.springframework.web.servlet.HandlerMapping;
|
||||
import java.lang.reflect.Method;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -102,29 +107,144 @@ public class AppAccessAspect {
|
||||
maskKey(apiKey), authAppKey.getList().size());
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid header 'api-key'");
|
||||
}
|
||||
User[] admin = new User[1];
|
||||
Object result = null;
|
||||
Throwable thrown = null;
|
||||
try {
|
||||
if(!shouldSkipAuth(joinPoint)){
|
||||
String jwt = validateJwt();
|
||||
requireAdminAccess(joinPoint, jwt);
|
||||
requireAdminAccess(joinPoint, jwt, admin);
|
||||
requireVerifiedPhoneForCp(joinPoint, apiKey);
|
||||
}
|
||||
return joinPoint.proceed();
|
||||
result = joinPoint.proceed();
|
||||
return result;
|
||||
} catch (ResponseStatusException ex) {
|
||||
thrown = ex;
|
||||
log.warn("[AppAccessAspect] REJECT: {} for method={}", ex.getReason(), methodSig);
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
thrown = ex;
|
||||
log.error(StackTraceUtil.getStackTraceAsJsonString(ex));
|
||||
throw ex;
|
||||
} catch (Error err) {
|
||||
thrown = err;
|
||||
throw err;
|
||||
} finally {
|
||||
long executionTime = System.currentTimeMillis() - start;
|
||||
long uuid = SnowflakeIdWorker.getUUID();
|
||||
String username = getUsernameFromJwt();
|
||||
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
|
||||
ResponseTime logBean = buildResponseTimeLog(uuid, apiKey, username, executionTime, methodSignature);
|
||||
publishLogSafely(logBean);
|
||||
try {
|
||||
long executionTime = System.currentTimeMillis() - start;
|
||||
long uuid = SnowflakeIdWorker.getUUID();
|
||||
String username = getUsernameFromJwt();
|
||||
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
|
||||
ResponseTime logBean = buildResponseTimeLog(uuid, apiKey, username, executionTime, methodSignature);
|
||||
publishLogSafely(logBean);
|
||||
publishAudit(joinPoint, admin[0], result, thrown);
|
||||
} finally {
|
||||
AuditChanges.clear(); // pooled threads: never leave one request's changes for the next
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort audit event for an admin call (add-admin-audit-log). Never throws: a failure is logged at WARN
|
||||
* with the exception class only and the response is unaffected.
|
||||
*/
|
||||
private void publishAudit(ProceedingJoinPoint joinPoint, User admin, Object result, Throwable thrown) {
|
||||
try {
|
||||
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
|
||||
if (!isAdminPath() || !isAudited(method, requestOrNull().getMethod())) {
|
||||
return;
|
||||
}
|
||||
int status = auditStatus(result, thrown);
|
||||
String actor = admin != null ? admin.getUsername() : null;
|
||||
if (actor == null && admin == null && status == HttpStatus.FORBIDDEN.value()) {
|
||||
// Refused before the user was loaded (PASSWORD_RESET_REQUIRED): the actor is the admin token's user.
|
||||
String jwt = HttpReqRespUtils.getJwtToken();
|
||||
if ("A".equals(userTypeClaim(jwt))) {
|
||||
actor = authenticationService.getUsernameFromToken(jwt);
|
||||
}
|
||||
}
|
||||
if (actor == null) {
|
||||
return;
|
||||
}
|
||||
HttpServletRequest request = requestOrNull();
|
||||
AuditEvent event = new AuditEvent();
|
||||
event.setCompanyId(admin != null ? admin.getCompanyId() : null);
|
||||
event.setOccurredAt(LocalDateTime.now());
|
||||
event.setActor(actor);
|
||||
AdminModule onMethod = method.getAnnotation(AdminModule.class);
|
||||
AdminModule declared = onMethod != null ? onMethod : method.getDeclaringClass().getAnnotation(AdminModule.class);
|
||||
event.setModule(declared == null || Arrays.asList(declared.value()).contains(AdminModule.ANY_ADMIN)
|
||||
? null : String.join(",", declared.value()));
|
||||
Audited audited = method.getAnnotation(Audited.class);
|
||||
event.setAction(audited != null && StringUtils.hasText(audited.action()) ? audited.action()
|
||||
: defaultAuditAction(method.getDeclaringClass().getSimpleName(), method.getName()));
|
||||
event.setHttpMethod(request.getMethod());
|
||||
Object pattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
event.setPathTemplate(pattern == null ? null : pattern.toString());
|
||||
// The last path variable is the record acted on (/events/{eventUuid}/leads/{eventLeadUuid}); Spring
|
||||
// fills the map in template order.
|
||||
if ((audited == null || audited.target())
|
||||
&& request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE) instanceof Map<?, ?> vars
|
||||
&& !vars.isEmpty()) {
|
||||
Object last = null;
|
||||
for (Object v : vars.values()) last = v;
|
||||
event.setTargetId(String.valueOf(last));
|
||||
}
|
||||
event.setHttpStatus(status);
|
||||
event.setOutcome(status >= 200 && status < 300 ? AuditEvent.OUTCOME_SUCCESS : AuditEvent.OUTCOME_FAILURE);
|
||||
String ip = request.getHeader("X-Client-Ip");
|
||||
event.setClientIp(ip == null || ip.length() <= 64 ? ip : ip.substring(0, 64));
|
||||
Map<String, Object> changes = AuditChanges.current();
|
||||
if (changes != null && !changes.isEmpty()) {
|
||||
event.setChanges(AUDIT_JSON.writeValueAsString(changes));
|
||||
}
|
||||
pubSubUtil.publishMessage(pubSubTemplate, pubSubConfig.auditEventTopic, event);
|
||||
} catch (Exception ex) {
|
||||
log.warn("[AppAccessAspect] audit event dropped: {}", ex.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
private static final ObjectMapper AUDIT_JSON = new ObjectMapper();
|
||||
|
||||
private static HttpServletRequest requestOrNull() {
|
||||
return RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs
|
||||
? attrs.getRequest() : null;
|
||||
}
|
||||
|
||||
/** Writes, and GETs marked {@code @Audited}, unless skipped; login, logout and the like are never recorded. */
|
||||
private static boolean isAudited(Method method, String httpMethod) {
|
||||
Audited audited = method.getAnnotation(Audited.class);
|
||||
if (audited != null && audited.skip()) {
|
||||
return false;
|
||||
}
|
||||
if (method.getDeclaringClass() == AdminAuthController.class && !"firstLogin".equals(method.getName())) {
|
||||
return false;
|
||||
}
|
||||
return !"GET".equalsIgnoreCase(httpMethod) || audited != null;
|
||||
}
|
||||
|
||||
/** {@code AdminUserController.update} becomes {@code USER_UPDATE}. */
|
||||
static String defaultAuditAction(String simpleClassName, String methodName) {
|
||||
String type = simpleClassName.replaceFirst("^Admin(?=.)", "").replaceFirst("(?<=.)Controller$", "");
|
||||
return upperSnake(type) + "_" + upperSnake(methodName);
|
||||
}
|
||||
|
||||
private static String upperSnake(String camel) {
|
||||
return camel.replaceAll("([a-z0-9])([A-Z])", "$1_$2")
|
||||
.replaceAll("([A-Z]+)([A-Z][a-z])", "$1_$2")
|
||||
.toUpperCase(java.util.Locale.ROOT);
|
||||
}
|
||||
|
||||
private static int auditStatus(Object result, Throwable thrown) {
|
||||
if (thrown instanceof ResponseStatusException rse) {
|
||||
return rse.getStatusCode().value();
|
||||
}
|
||||
if (thrown != null) {
|
||||
return HttpStatus.INTERNAL_SERVER_ERROR.value();
|
||||
}
|
||||
return result instanceof ResponseEntity<?> entity ? entity.getStatusCode().value() : HttpStatus.OK.value();
|
||||
}
|
||||
|
||||
private String getUsernameFromJwt() {
|
||||
String username = "APP_PUBLIC";
|
||||
String jwt = HttpReqRespUtils.getJwtToken();
|
||||
@@ -235,7 +355,7 @@ public class AppAccessAspect {
|
||||
private static final long INJECTED_ROLE_ADMIN_ID = 2L;
|
||||
|
||||
/** Admin paths: admin token, live and enabled session, and a granted BO module. Fails closed. */
|
||||
private void requireAdminAccess(ProceedingJoinPoint joinPoint, String jwt) {
|
||||
private void requireAdminAccess(ProceedingJoinPoint joinPoint, String jwt, User[] adminOut) {
|
||||
if (!isAdminPath()) {
|
||||
return;
|
||||
}
|
||||
@@ -247,6 +367,7 @@ public class AppAccessAspect {
|
||||
AdminModule declared = onMethod != null ? onMethod : method.getDeclaringClass().getAnnotation(AdminModule.class);
|
||||
// allowPendingReset is honoured on the method only, so it never opens a whole controller.
|
||||
User admin = adminSessionGuard.check(jwt, onMethod != null && onMethod.allowPendingReset());
|
||||
adminOut[0] = admin;
|
||||
if (declared != null && Arrays.asList(declared.value()).contains(AdminModule.ANY_ADMIN)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* What an audited handler changed, collected for the current request thread and attached to its audit event by
|
||||
* {@link AppAccessAspect}, which always clears it afterwards. Callers pass allow-listed fields only: never
|
||||
* passwords, tokens or identity numbers.
|
||||
*/
|
||||
public final class AuditChanges {
|
||||
|
||||
private static final ThreadLocal<Map<String, Object>> CURRENT = new ThreadLocal<>();
|
||||
|
||||
private AuditChanges() {
|
||||
}
|
||||
|
||||
/** One allow-listed field's value before and after the change. */
|
||||
public static void put(String field, Object before, Object after) {
|
||||
Map<String, Object> changes = CURRENT.get();
|
||||
if (changes == null) {
|
||||
changes = new LinkedHashMap<>();
|
||||
CURRENT.set(changes);
|
||||
}
|
||||
Map<String, Object> change = new LinkedHashMap<>();
|
||||
change.put("before", before);
|
||||
change.put("after", after);
|
||||
changes.put(field, change);
|
||||
}
|
||||
|
||||
/** Names of the fields that changed, without values. */
|
||||
public static void fields(String... names) {
|
||||
Map<String, Object> changes = CURRENT.get();
|
||||
if (changes == null) {
|
||||
changes = new LinkedHashMap<>();
|
||||
CURRENT.set(changes);
|
||||
}
|
||||
changes.put("fields", List.of(names));
|
||||
}
|
||||
|
||||
public static Map<String, Object> current() {
|
||||
return CURRENT.get();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
CURRENT.remove();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Audit marking for an {@code /api/admin/**} handler, read by {@link AppAccessAspect}. Every non-GET handler is
|
||||
* audited by default; this annotation names the action, makes a sensitive GET audited, or {@code skip = true}
|
||||
* excludes a read-only POST.
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface Audited {
|
||||
|
||||
/** Stable action key; empty means derived from the controller and method name. */
|
||||
String action() default "";
|
||||
|
||||
/** Never audit this handler (read-only POST). */
|
||||
boolean skip() default false;
|
||||
|
||||
/** False when the path variable is free text a person typed (e.g. a username from a failed sign-in): no target is recorded. */
|
||||
boolean target() default true;
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.mobile.api.service.AdminAuditLogService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminAuditLogControllerTest {
|
||||
|
||||
@Mock private AdminAuditLogService audit;
|
||||
@InjectMocks private AdminAuditLogController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void classLevelModule_notOverriddenOrAudited() {
|
||||
assertThat(AdminAuditLogController.class.getAnnotation(AdminModule.class).value()).containsExactly("BO_AUDIT_LOG");
|
||||
for (Method m : AdminAuditLogController.class.getDeclaredMethods()) {
|
||||
assertThat(m.getAnnotation(AdminModule.class)).isNull();
|
||||
assertThat(m.getAnnotation(Audited.class)).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_passesEveryParam() throws Exception {
|
||||
when(audit.search("boss", "LEADS", "UPDATE", "SUCCESS", "2026-11-01", "2026-11-30", 1, 5))
|
||||
.thenReturn(Map.of("content", List.of(Map.of("id", 7))));
|
||||
mvc.perform(get("/api/admin/audit-log").param("actor", "boss").param("module", "LEADS").param("action", "UPDATE")
|
||||
.param("outcome", "SUCCESS").param("from", "2026-11-01").param("to", "2026-11-30")
|
||||
.param("page", "1").param("size", "5"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.content[0].id").value(7));
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_defaultsToFirstPageOfTwenty() throws Exception {
|
||||
when(audit.search(null, null, null, null, null, null, 0, 20)).thenReturn(Map.of());
|
||||
mvc.perform(get("/api/admin/audit-log")).andExpect(status().isOk());
|
||||
verify(audit).search(null, null, null, null, null, null, 0, 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void detail_returnsEvent() throws Exception {
|
||||
when(audit.get(9L)).thenReturn(Map.of("id", 9));
|
||||
mvc.perform(get("/api/admin/audit-log/9")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(9));
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.Role;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminAclServiceAuditChangesTest {
|
||||
|
||||
private static final long ROOT = 40000000L, USERS = 40700000L, ROLES = 40800000L, LEADS = 40900000L;
|
||||
|
||||
private AdminAclService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
AdminRoleService roles = mock(AdminRoleService.class);
|
||||
service = new AdminAclService(rest, auth, roles);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(roles.find(4L)).thenReturn(Map.of("id", 4L, "name", "ROLE_SALES"));
|
||||
// role 4 holds BO_USERS and BO_ROLES
|
||||
when(rest.getForEntity(eq("/module/findAllByArea/{area}"), any(ParameterizedTypeReference.class), eq("BO"))).thenReturn(ResponseEntity.ok(List.of(
|
||||
module(ROOT, "BO_ROOT", "R"),
|
||||
module(USERS, "BO_USERS", "M", 4),
|
||||
module(ROLES, "BO_ROLES", "M", 4),
|
||||
module(LEADS, "BO_LEADS", "M"))));
|
||||
User u = new User();
|
||||
u.setId(50L);
|
||||
Role r = new Role();
|
||||
r.setId(1L);
|
||||
u.setRoles(List.of(r));
|
||||
when(auth.loadUserByToken("tok")).thenReturn(u);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private static Map<String, Object> module(long id, String name, String type, long... roleIds) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("name", name);
|
||||
m.put("type", type);
|
||||
m.put("parent", "R".equals(type) ? null : ROOT);
|
||||
m.put("roles", java.util.Arrays.stream(roleIds).mapToObj(x -> (Object) Map.of("id", x, "name", "R" + x)).toList());
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateGrants_recordsAddedAndRemovedModuleCodes() {
|
||||
service.updateGrants(4L, List.of(USERS, LEADS));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("modulesAdded", "modulesRemoved");
|
||||
assertThat((Map<String, Object>) AuditChanges.current().get("modulesAdded")).containsEntry("after", List.of("BO_LEADS")).containsEntry("before", null);
|
||||
assertThat((Map<String, Object>) AuditChanges.current().get("modulesRemoved")).containsEntry("after", List.of("BO_ROLES")).containsEntry("before", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateGrants_recordsOnlyTheNonEmptySide() {
|
||||
service.updateGrants(4L, List.of(USERS, ROLES, LEADS));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("modulesAdded");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateGrants_sameSetRecordsNothing() {
|
||||
service.updateGrants(4L, List.of(USERS, ROLES));
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminAuditLogServiceTest {
|
||||
|
||||
private static final String SEARCH = "/log/audit/search";
|
||||
private static final String DETAIL = "/log/audit/{id}";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuditLogService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
service = new AdminAuditLogService(rest);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
}
|
||||
|
||||
private static HttpClientErrorException clientError(HttpStatus status, String body) {
|
||||
return HttpClientErrorException.create(status, status.getReasonPhrase(), new HttpHeaders(), body.getBytes(StandardCharsets.UTF_8), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void search_forwardsOnlyGivenFiltersWithPaging() {
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("content", List.of())));
|
||||
service.search(" boss ", null, "", " ", "2026-11-01", null, 0, 20);
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) body.getValue()).containsOnlyKeys("actor", "from", "page", "size")
|
||||
.containsEntry("actor", "boss").containsEntry("from", "2026-11-01").containsEntry("page", 0).containsEntry("size", 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void search_upstreamBadRequest_becomesInvalidFilterWithDetail() {
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(clientError(HttpStatus.BAD_REQUEST, "{\"detail\":\"from must be yyyy-MM-dd\"}"));
|
||||
assertThatThrownBy(() -> service.search(null, null, null, null, "nope", null, 0, 20))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertThat(e.getCode()).isEqualTo("INVALID_FILTER");
|
||||
assertThat(e.getReason()).isEqualTo("from must be yyyy-MM-dd");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void search_upstreamBadRequestWithoutBody_usesGenericReason() {
|
||||
when(rest.postForEntity(eq(SEARCH), any(ParameterizedTypeReference.class), any())).thenThrow(clientError(HttpStatus.BAD_REQUEST, ""));
|
||||
assertThatThrownBy(() -> service.search(null, null, null, null, "nope", null, 0, 20))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("Invalid request"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returnsEvent() {
|
||||
when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok(Map.of("id", 9)));
|
||||
assertThat(service.get(9L)).containsEntry("id", 9);
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_upstreamNotFound_becomesNotFound() {
|
||||
when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(99L))).thenThrow(clientError(HttpStatus.NOT_FOUND, ""));
|
||||
assertThatThrownBy(() -> service.get(99L))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
assertThat(e.getCode()).isEqualTo("NOT_FOUND");
|
||||
assertThat(e.getReason()).isEqualTo("Audit event not found");
|
||||
});
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminEventLeadServiceAuditChangesTest {
|
||||
|
||||
private static final long EV = 3312726793093644288L;
|
||||
private static final long EL = 3312853897594494976L;
|
||||
private static final long COMPANY = 5L;
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminEventLeadService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminEventLeadService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
User caller = new User();
|
||||
caller.setId(21L);
|
||||
caller.setUsername("sales1");
|
||||
caller.setCompanyId(COMPANY);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
Event e = new Event();
|
||||
e.setUuid(EV);
|
||||
e.setName("Fair");
|
||||
e.setEnabled(GeneralEnum.FlagYesNo.Y);
|
||||
when(rest.getForEntity(eq("/counter/event/findByUuid/{uuid}"), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e));
|
||||
when(rest.getForEntity(eq("/counter/interest/findByCompany/{companyId}"), any(ParameterizedTypeReference.class), eq(COMPANY)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(
|
||||
Map.of("id", 3L, "companyId", COMPANY, "name", "Cookware", "active", true, "sortOrder", 0),
|
||||
Map.of("id", 4L, "companyId", COMPANY, "name", "Kitchen", "active", true, "sortOrder", 0))));
|
||||
Map<String, Object> d = new LinkedHashMap<>();
|
||||
d.put("eventLeadUuid", EL);
|
||||
d.put("eventUuid", EV);
|
||||
d.put("name", "Aisyah");
|
||||
d.put("salespersonUserId", 21L);
|
||||
d.put("temperature", "WARM");
|
||||
d.put("status", "OPEN");
|
||||
d.put("interestIds", List.of(3L));
|
||||
d.put("nextFollowUpDate", "2027-01-20");
|
||||
d.put("notes", "old note");
|
||||
when(rest.getForEntity(eq("/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}"), any(ParameterizedTypeReference.class), eq(COMPANY), eq(EL)))
|
||||
.thenReturn(ResponseEntity.ok(d));
|
||||
when(rest.postForEntity(eq("/counter/eventLead/update"), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> ResponseEntity.ok(new HashMap<String, Object>(Map.of("eventLeadUuid", EL, "eventUuid", EV))));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private void update(AdminEventLeadUpdateRequest r) {
|
||||
service.update(String.valueOf(EV), String.valueOf(EL), r);
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_recordsChangedFieldNamesAndNoValues() throws Exception {
|
||||
update(new AdminEventLeadUpdateRequest(21L, "HOT", "OPEN", List.of(3L, 4L), "2027-01-20", "private call note"));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("fields");
|
||||
assertThat((List<String>) AuditChanges.current().get("fields")).containsExactlyInAnyOrder("temperature", "interestIds", "notes");
|
||||
String json = new ObjectMapper().writeValueAsString(AuditChanges.current());
|
||||
assertThat(json).doesNotContain("private call note", "old note", "HOT", "2027-01-20");
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_nothingChangedRecordsNothing() {
|
||||
update(new AdminEventLeadUpdateRequest(21L, "WARM", "OPEN", List.of(3L), "2027-01-20", "old note"));
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminLeadServiceAuditChangesTest {
|
||||
|
||||
private static final String DETAIL = "/counter/lead/detail/{companyId}/{leadUuid}";
|
||||
private static final String UPDATE = "/counter/lead/update";
|
||||
private static final long LEAD = 3312853897040846848L;
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminLeadService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminLeadService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
User caller = new User();
|
||||
caller.setId(21L);
|
||||
caller.setUsername("sales1");
|
||||
caller.setCompanyId(5L);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private void stored() {
|
||||
Map<String, Object> d = new HashMap<>();
|
||||
d.put("leadUuid", LEAD);
|
||||
d.put("name", "Old Name");
|
||||
d.put("mobileE164", "+60123456701");
|
||||
d.put("email", "old@example.test");
|
||||
d.put("companyName", "Acme");
|
||||
when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(5L), eq(LEAD))).thenReturn(ResponseEntity.ok(d));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_recordsChangedFieldNamesAndNoValues() throws Exception {
|
||||
stored();
|
||||
|
||||
service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("Brand New Name", "012-345 6701", "fresh@example.test", "Acme", null, "secret note"));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("fields");
|
||||
assertThat((List<String>) AuditChanges.current().get("fields")).containsExactlyInAnyOrder("name", "email", "notes");
|
||||
String json = new ObjectMapper().writeValueAsString(AuditChanges.current());
|
||||
assertThat(json).doesNotContain("Brand New Name", "fresh@example.test", "secret note", "Old Name", "0123456701");
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_nothingChangedRecordsNothing() {
|
||||
stored();
|
||||
|
||||
service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("Old Name", "012-345 6701", "old@example.test", "Acme", null, null));
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_unreadableBeforeStateRecordsNothing() {
|
||||
service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("Brand New Name", "012-345 6701", null, null, null, null));
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_phoneAndNotesRecordedByNameWithoutEitherNumber() throws Exception {
|
||||
stored();
|
||||
|
||||
service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("Old Name", "019-876 5432", "old@example.test", "Acme", null, "fresh private note"));
|
||||
|
||||
assertThat((List<String>) AuditChanges.current().get("fields")).containsExactly("phone", "notes");
|
||||
String json = new ObjectMapper().writeValueAsString(AuditChanges.current());
|
||||
assertThat(json).doesNotContain("+60123456701", "123456701", "+60198765432", "198765432", "fresh private note");
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_refusedByValidationRecordsNothing() {
|
||||
stored();
|
||||
|
||||
assertThatThrownBy(() -> service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest(" ", "012-345 6701", null, null, null, null)))
|
||||
.isInstanceOf(RuntimeException.class);
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_saveAnswering404RecordsNothing() {
|
||||
stored();
|
||||
when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "gone", HttpHeaders.EMPTY, new byte[0], null));
|
||||
|
||||
assertThatThrownBy(() -> service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("Brand New Name", "012-345 6701", "old@example.test", "Acme", null, null)))
|
||||
.isInstanceOf(RuntimeException.class);
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminLoginSecurityServiceAuditChangesTest {
|
||||
|
||||
private static final String CONFIG = "/loginSecurity/config";
|
||||
private static final String RULES = "/loginSecurity/passwordRules";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminLoginSecurityService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminLoginSecurityService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
User caller = new User();
|
||||
caller.setUsername("boss");
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private static Map<String, Object> change(Object before, Object after) {
|
||||
Map<String, Object> m = new java.util.HashMap<>();
|
||||
m.put("before", before);
|
||||
m.put("after", after);
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveConfig_recordsChangedSettingsOnly() {
|
||||
Map<String, Object> before = Map.of("enabled", true, "maxAttempts", 5, "period", 15, "unit", "MINUTES");
|
||||
Map<String, Object> after = Map.of("enabled", true, "maxAttempts", 3, "period", 30, "unit", "MINUTES");
|
||||
when(rest.getForEntity(eq(CONFIG), any(ParameterizedTypeReference.class))).thenReturn(ResponseEntity.ok(before));
|
||||
when(rest.postForEntity(eq(CONFIG), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(after));
|
||||
|
||||
service.saveConfig(after);
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("maxAttempts", "period")
|
||||
.containsEntry("maxAttempts", change(5, 3)).containsEntry("period", change(15, 30));
|
||||
}
|
||||
|
||||
@Test
|
||||
void savePasswordRules_recordsChangedRulesOnly() {
|
||||
List<Map<String, Object>> before = List.of(
|
||||
Map.of("id", 1, "param", "MIN_LENGTH", "status", true, "value", "8"),
|
||||
Map.of("id", 2, "param", "UPPERCASE", "status", true, "value", "1"));
|
||||
List<Map<String, Object>> after = List.of(
|
||||
Map.of("id", 1, "param", "MIN_LENGTH", "status", true, "value", "12"),
|
||||
Map.of("id", 2, "param", "UPPERCASE", "status", true, "value", "1"));
|
||||
when(rest.getForEntity(eq(RULES), any(ParameterizedTypeReference.class))).thenReturn(ResponseEntity.ok(before));
|
||||
when(rest.postForEntity(eq(RULES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(after));
|
||||
|
||||
service.savePasswordRules(after);
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("MIN_LENGTH")
|
||||
.containsEntry("MIN_LENGTH", change(Map.of("status", true, "value", "8"), Map.of("status", true, "value", "12")));
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.LocationHierarchy;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminRoleRef;
|
||||
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminUserServiceAuditChangesTest {
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminUserService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminUserService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
User caller = new User();
|
||||
caller.setId(1L);
|
||||
caller.setUsername("boss");
|
||||
caller.setCompanyId(7L);
|
||||
LocationHierarchy branch = new LocationHierarchy();
|
||||
branch.setId(3L);
|
||||
caller.setBranch(branch);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
when(auth.passesAdminPasswordRules(anyString())).thenReturn(true);
|
||||
when(auth.setAdminPassword(any(), anyString())).thenReturn(1);
|
||||
when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(role(4, "ROLE_SALES"), role(5, "ROLE_OPS"), role(6, "ROLE_ACCOUNTS"))));
|
||||
when(rest.getForEntity(eq("/user/findByUsername/{username}"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build());
|
||||
when(rest.getForEntity(eq("/user/findByEmail/{email}"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build());
|
||||
when(rest.getForEntity(eq("/user/findByEmailAndIdNot/{email}/{id}"), any(ParameterizedTypeReference.class), any(), any())).thenReturn(ResponseEntity.ok().build());
|
||||
when(rest.postForEntity(eq("/user/save"), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> {
|
||||
Map<String, Object> saved = new HashMap<>((Map<String, Object>) i.getArgument(2));
|
||||
saved.put("id", 9L);
|
||||
return ResponseEntity.ok(saved);
|
||||
});
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private static Map<String, Object> role(long id, String name) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("name", name);
|
||||
return m;
|
||||
}
|
||||
|
||||
private void stored(boolean enabled, Map<String, Object>... roles) {
|
||||
Map<String, Object> u = new HashMap<>();
|
||||
u.put("id", 9L);
|
||||
u.put("name", "Sam");
|
||||
u.put("username", "sam");
|
||||
u.put("email", "sam@x.com");
|
||||
u.put("enabled", enabled);
|
||||
u.put("type", "A");
|
||||
u.put("roles", List.of(roles));
|
||||
when(rest.getForEntity(eq("/user/findById/{id}"), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok(u));
|
||||
}
|
||||
|
||||
private static Map<String, Object> change(Object before, Object after) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("before", before);
|
||||
m.put("after", after);
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_recordsRoleNamesAndEnabledBeforeAndAfter() {
|
||||
stored(true, role(5, "ROLE_OPS"), role(4, "ROLE_SALES"));
|
||||
|
||||
service.update(9L, new AdminUserRequest("Sam", null, null, null, false, List.of(new AdminRoleRef(6L, null), new AdminRoleRef(4L, null))));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("roles", "enabled")
|
||||
.containsEntry("roles", change(List.of("ROLE_OPS", "ROLE_SALES"), List.of("ROLE_ACCOUNTS", "ROLE_SALES")))
|
||||
.containsEntry("enabled", change(true, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_recordsNothingForUnchangedOrAbsentFields() {
|
||||
stored(true, role(4, "ROLE_SALES"));
|
||||
|
||||
service.update(9L, new AdminUserRequest("Renamed", "Surname", null, "new@x.com", true, List.of(new AdminRoleRef(4L, null))));
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_recordsNothingWhenRefused() {
|
||||
stored(true, role(4, "ROLE_SALES"));
|
||||
|
||||
assertThatThrownBy(() -> service.update(9L, new AdminUserRequest(null, null, null, null, null, List.of()))).isInstanceOf(RuntimeException.class);
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_recordsRolesAndEnabled() {
|
||||
service.create(new AdminUserRequest("Sam", null, "sam", "sam@x.com", null,
|
||||
List.of(new AdminRoleRef(5L, null), new AdminRoleRef(4L, null)), "Good#Pass1", "Good#Pass1"));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("roles", "enabled")
|
||||
.containsEntry("roles", change(null, List.of("ROLE_OPS", "ROLE_SALES")))
|
||||
.containsEntry("enabled", change(null, true));
|
||||
}
|
||||
}
|
||||
+407
@@ -0,0 +1,407 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.enums.JwtEnum.JwtCustomClaim;
|
||||
import com.solvway.core.model.AuditEvent;
|
||||
import com.solvway.core.model.Role;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.JwtTokenUtil;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.mobile.api.config.AuthAppKeyConfig;
|
||||
import com.solvway.mobile.api.config.PubSubConfig;
|
||||
import com.solvway.mobile.api.controller.admin.AdminAuthController;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.UserService;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** add-admin-audit-log: what AppAccessAspect records for /api/admin/** calls. */
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class AppAccessAspectAuditTest {
|
||||
|
||||
private static final String API_KEY = "valid-api-key";
|
||||
private static final String TOK = "admin-tok";
|
||||
private static final String TOPIC = "audit-event-topic";
|
||||
|
||||
@Mock private PubSubTemplate pubSubTemplate;
|
||||
@Mock private PubSubUtil pubSubUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private JwtTokenUtil jwtTokenUtil;
|
||||
@Mock private ProceedingJoinPoint joinPoint;
|
||||
@Mock private MethodSignature methodSignature;
|
||||
@Mock private AdminSessionGuard guard;
|
||||
@Mock private RestTemplateCustomUtil rest;
|
||||
|
||||
private AppAccessAspect aspect;
|
||||
private MockHttpServletRequest req;
|
||||
|
||||
@AdminModule("BO_USERS")
|
||||
static class AdminUserController {
|
||||
@AdminModule("BO_ROLES")
|
||||
public void update() {
|
||||
}
|
||||
|
||||
public void classModule() {
|
||||
}
|
||||
|
||||
@Audited(action = "USER_SET_TEMPORARY_PASSWORD")
|
||||
public void setPassword() {
|
||||
}
|
||||
|
||||
@Audited(action = "LEAD_EXPORT")
|
||||
public void export() {
|
||||
}
|
||||
|
||||
@Audited(skip = true)
|
||||
public void match() {
|
||||
}
|
||||
|
||||
@Audited(target = false)
|
||||
public void unlock() {
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuthAppKeyConfig cfg = new AuthAppKeyConfig();
|
||||
cfg.setList(List.of(API_KEY));
|
||||
PubSubConfig pubSubConfig = mock(PubSubConfig.class);
|
||||
pubSubConfig.auditEventTopic = TOPIC;
|
||||
aspect = new AppAccessAspect(mock(MemberService.class), mock(UserService.class), pubSubConfig,
|
||||
pubSubTemplate, pubSubUtil, cfg, authenticationService, jwtTokenUtil, guard, rest);
|
||||
req = new MockHttpServletRequest("PUT", "/api/admin/users/42");
|
||||
req.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/api/admin/users/{id}");
|
||||
Map<String, String> vars = new LinkedHashMap<>();
|
||||
vars.put("id", "42");
|
||||
req.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, vars);
|
||||
req.addHeader("X-Client-Ip", "203.0.113.7");
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void clear() {
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private void handler(Class<?> type, String name) {
|
||||
Method m = Arrays.stream(type.getMethods()).filter(x -> x.getName().equals(name)).findFirst().orElseThrow();
|
||||
when(joinPoint.getSignature()).thenReturn(methodSignature);
|
||||
when(methodSignature.getMethod()).thenReturn(m);
|
||||
when(methodSignature.toShortString()).thenReturn(type.getSimpleName() + "." + name + "()");
|
||||
}
|
||||
|
||||
private User admin(Long... roleIds) {
|
||||
User u = new User();
|
||||
u.setEnabled(true);
|
||||
u.setUsername("alice");
|
||||
u.setCompanyId(7L);
|
||||
for (Long id : roleIds) {
|
||||
Role r = new Role();
|
||||
r.setId(id);
|
||||
u.getRoles().add(r);
|
||||
}
|
||||
when(guard.check(eq(TOK), any(Boolean.class))).thenReturn(u);
|
||||
return u;
|
||||
}
|
||||
|
||||
private Object call() throws Throwable {
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
h.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(API_KEY);
|
||||
h.when(HttpReqRespUtils::getJwtToken).thenReturn(TOK);
|
||||
when(jwtTokenUtil.isTokenExpired(TOK)).thenReturn(false);
|
||||
when(jwtTokenUtil.getCustomClaimFromToken(TOK, JwtCustomClaim.USERTYPE)).thenReturn("A");
|
||||
return aspect.appAccessAuthCheck(joinPoint);
|
||||
}
|
||||
}
|
||||
|
||||
private AuditEvent published() {
|
||||
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
|
||||
verify(pubSubUtil).publishMessage(eq(pubSubTemplate), eq(TOPIC), captor.capture());
|
||||
return (AuditEvent) captor.getValue();
|
||||
}
|
||||
|
||||
private void notPublished() {
|
||||
verify(pubSubUtil, never()).publishMessage(any(PubSubTemplate.class), eq(TOPIC), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void write_recordsEveryField() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
admin(1L);
|
||||
when(joinPoint.proceed()).thenReturn(ResponseEntity.ok("x"));
|
||||
call();
|
||||
AuditEvent e = published();
|
||||
assertThat(e.getActor()).isEqualTo("alice");
|
||||
assertThat(e.getCompanyId()).isEqualTo(7L);
|
||||
assertThat(e.getModule()).isEqualTo("BO_ROLES");
|
||||
assertThat(e.getAction()).isEqualTo("USER_UPDATE");
|
||||
assertThat(e.getHttpMethod()).isEqualTo("PUT");
|
||||
assertThat(e.getPathTemplate()).isEqualTo("/api/admin/users/{id}");
|
||||
assertThat(e.getTargetId()).isEqualTo("42");
|
||||
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_SUCCESS);
|
||||
assertThat(e.getHttpStatus()).isEqualTo(200);
|
||||
assertThat(e.getClientIp()).isEqualTo("203.0.113.7");
|
||||
assertThat(e.getOccurredAt()).isNotNull();
|
||||
assertThat(e.getChanges()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void target_isTheLastPathVariable() throws Throwable {
|
||||
Map<String, String> vars = new LinkedHashMap<>();
|
||||
vars.put("eventUuid", "E1");
|
||||
vars.put("eventLeadUuid", "L9");
|
||||
req.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, vars);
|
||||
handler(AdminUserController.class, "update");
|
||||
admin(1L);
|
||||
call();
|
||||
assertThat(published().getTargetId()).isEqualTo("L9");
|
||||
}
|
||||
|
||||
@Test
|
||||
void target_isNotRecordedWhenTheHandlerOptsOut() throws Throwable {
|
||||
req.setMethod("POST");
|
||||
handler(AdminUserController.class, "unlock");
|
||||
admin(1L);
|
||||
call();
|
||||
assertThat(published().getTargetId()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void module_fallsBackToClassLevel() throws Throwable {
|
||||
handler(AdminUserController.class, "classModule");
|
||||
admin(1L);
|
||||
call();
|
||||
assertThat(published().getModule()).isEqualTo("BO_USERS");
|
||||
}
|
||||
|
||||
@Test
|
||||
void actionCodes_derivedAndExplicit() throws Throwable {
|
||||
assertThat(AppAccessAspect.defaultAuditAction("AdminUserController", "update")).isEqualTo("USER_UPDATE");
|
||||
assertThat(AppAccessAspect.defaultAuditAction("AdminEventLeadController", "putModules"))
|
||||
.isEqualTo("EVENT_LEAD_PUT_MODULES");
|
||||
assertThat(AppAccessAspect.defaultAuditAction("LeadThing", "exportPDF")).isEqualTo("LEAD_THING_EXPORT_PDF");
|
||||
|
||||
req.setMethod("GET");
|
||||
handler(AdminUserController.class, "export");
|
||||
admin(1L);
|
||||
call();
|
||||
assertThat(published().getAction()).isEqualTo("LEAD_EXPORT");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonSuccessResponseEntity_recordsFailureWithStatus() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
admin(1L);
|
||||
when(joinPoint.proceed()).thenReturn(ResponseEntity.status(HttpStatus.CONFLICT).build());
|
||||
call();
|
||||
AuditEvent e = published();
|
||||
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_FAILURE);
|
||||
assertThat(e.getHttpStatus()).isEqualTo(409);
|
||||
}
|
||||
|
||||
@Test
|
||||
void redirectResponseEntity_isNotASuccess() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
admin(1L);
|
||||
when(joinPoint.proceed()).thenReturn(ResponseEntity.status(HttpStatus.FOUND).build());
|
||||
call();
|
||||
AuditEvent e = published();
|
||||
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_FAILURE);
|
||||
assertThat(e.getHttpStatus()).isEqualTo(302);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anyAdminHandler_recordsNoModule() throws Throwable {
|
||||
req.setMethod("POST");
|
||||
handler(AdminAuthController.class, "firstLogin");
|
||||
admin(1L);
|
||||
call();
|
||||
assertThat(published().getModule()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditChanges_areClearedEvenWhenTheLogStepThrows() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
admin(1L);
|
||||
when(joinPoint.proceed()).thenAnswer(i -> {
|
||||
AuditChanges.fields("phone");
|
||||
return ResponseEntity.ok("x");
|
||||
});
|
||||
try (MockedStatic<com.solvway.core.utils.SnowflakeIdWorker> ids = mockStatic(com.solvway.core.utils.SnowflakeIdWorker.class)) {
|
||||
ids.when(com.solvway.core.utils.SnowflakeIdWorker::getUUID).thenThrow(new RuntimeException("clock moved backwards"));
|
||||
assertThatThrownBy(this::call).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void thrownResponseStatusException_recordsFailureWithStatus() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
admin(1L);
|
||||
when(joinPoint.proceed()).thenThrow(new ResponseStatusException(HttpStatus.BAD_REQUEST, "bad"));
|
||||
assertThatThrownBy(this::call).isInstanceOf(ResponseStatusException.class);
|
||||
AuditEvent e = published();
|
||||
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_FAILURE);
|
||||
assertThat(e.getHttpStatus()).isEqualTo(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherException_recordsFailure500() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
admin(1L);
|
||||
when(joinPoint.proceed()).thenThrow(new IllegalStateException("boom"));
|
||||
assertThatThrownBy(this::call).isInstanceOf(IllegalStateException.class);
|
||||
AuditEvent e = published();
|
||||
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_FAILURE);
|
||||
assertThat(e.getHttpStatus()).isEqualTo(500);
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleNotGranted_isRecordedAsFailure403() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
admin(5L); // not super admin, no grants
|
||||
when(rest.getURLforApiService(any())).thenReturn("http://system/x");
|
||||
assertThatThrownBy(this::call).isInstanceOf(ResponseStatusException.class);
|
||||
verify(joinPoint, never()).proceed();
|
||||
AuditEvent e = published();
|
||||
assertThat(e.getActor()).isEqualTo("alice");
|
||||
assertThat(e.getCompanyId()).isEqualTo(7L);
|
||||
assertThat(e.getOutcome()).isEqualTo(AuditEvent.OUTCOME_FAILURE);
|
||||
assertThat(e.getHttpStatus()).isEqualTo(403);
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordResetRequired_actorFromToken_isRecordedAsFailure403() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
when(guard.check(eq(TOK), any(Boolean.class)))
|
||||
.thenThrow(new ResponseStatusException(HttpStatus.FORBIDDEN, "PASSWORD_RESET_REQUIRED"));
|
||||
when(authenticationService.getUsernameFromToken(TOK)).thenReturn("alice");
|
||||
assertThatThrownBy(this::call).isInstanceOf(ResponseStatusException.class);
|
||||
AuditEvent e = published();
|
||||
assertThat(e.getActor()).isEqualTo("alice");
|
||||
assertThat(e.getHttpStatus()).isEqualTo(403);
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainGet_isNotRecorded() throws Throwable {
|
||||
req.setMethod("GET");
|
||||
handler(AdminUserController.class, "update");
|
||||
admin(1L);
|
||||
call();
|
||||
notPublished();
|
||||
}
|
||||
|
||||
@Test
|
||||
void skippedPost_isNotRecorded() throws Throwable {
|
||||
req.setMethod("POST");
|
||||
handler(AdminUserController.class, "match");
|
||||
admin(1L);
|
||||
call();
|
||||
notPublished();
|
||||
}
|
||||
|
||||
@Test
|
||||
void authControllerEndpoints_notRecorded_exceptFirstLogin() throws Throwable {
|
||||
req.setMethod("POST");
|
||||
admin(1L);
|
||||
for (String name : List.of("changePassword", "logout", "refresh")) {
|
||||
handler(AdminAuthController.class, name);
|
||||
call();
|
||||
}
|
||||
notPublished();
|
||||
|
||||
handler(AdminAuthController.class, "firstLogin");
|
||||
call();
|
||||
assertThat(published().getAction()).isEqualTo("AUTH_FIRST_LOGIN");
|
||||
}
|
||||
|
||||
@Test
|
||||
void noValidToken_isNotRecorded() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
h.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(API_KEY);
|
||||
h.when(HttpReqRespUtils::getJwtToken).thenReturn("");
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint)).isInstanceOf(ResponseStatusException.class);
|
||||
}
|
||||
notPublished();
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidAdminSession_401_isNotRecorded() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
when(guard.check(eq(TOK), any(Boolean.class)))
|
||||
.thenThrow(new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Token"));
|
||||
assertThatThrownBy(this::call).isInstanceOf(ResponseStatusException.class);
|
||||
notPublished();
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishFailure_doesNotChangeTheResponse() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
admin(1L);
|
||||
ResponseEntity<String> ok = ResponseEntity.ok("x");
|
||||
when(joinPoint.proceed()).thenReturn(ok);
|
||||
doThrow(new IllegalStateException("pubsub down")).when(pubSubUtil)
|
||||
.publishMessage(any(PubSubTemplate.class), eq(TOPIC), any());
|
||||
assertThat(call()).isSameAs(ok);
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditChanges_landInChangesJson_andAreClearedAfterwards() throws Throwable {
|
||||
handler(AdminUserController.class, "update");
|
||||
admin(1L);
|
||||
when(joinPoint.proceed()).thenAnswer(inv -> {
|
||||
AuditChanges.put("enabled", true, false);
|
||||
AuditChanges.fields("name");
|
||||
return ResponseEntity.ok("x");
|
||||
});
|
||||
call();
|
||||
AuditEvent e = published();
|
||||
assertThat(e.getChanges()).contains("\"enabled\":{\"before\":true,\"after\":false}")
|
||||
.contains("\"fields\":[\"name\"]");
|
||||
|
||||
org.mockito.Mockito.clearInvocations(pubSubUtil);
|
||||
org.mockito.Mockito.doReturn(ResponseEntity.ok("y")).when(joinPoint).proceed(); // when(..) would re-run the answer above
|
||||
call();
|
||||
assertThat(published().getChanges()).isNull();
|
||||
}
|
||||
}
|
||||
+30
@@ -38,6 +38,11 @@ public class PubSubConfig {
|
||||
|
||||
@Value("${pubsub.response-time-log.subscription}")
|
||||
public String responseTimeLogSubscription;
|
||||
@Value("${pubsub.audit-event.topic}")
|
||||
public String auditEventTopic;
|
||||
|
||||
@Value("${pubsub.audit-event.subscription}")
|
||||
public String auditEventSubscription;
|
||||
@Value("${pubsub.error-log.topic}")
|
||||
public String errorLogTopic;
|
||||
|
||||
@@ -56,6 +61,9 @@ public class PubSubConfig {
|
||||
if (pubSubAdmin.getTopic(responseTimeLogTopic) == null) {
|
||||
pubSubAdmin.createTopic(responseTimeLogTopic);
|
||||
}
|
||||
if (pubSubAdmin.getTopic(auditEventTopic) == null) {
|
||||
pubSubAdmin.createTopic(auditEventTopic);
|
||||
}
|
||||
if (pubSubAdmin.getTopic(errorLogTopic) == null) {
|
||||
pubSubAdmin.createTopic(errorLogTopic);
|
||||
}
|
||||
@@ -82,6 +90,15 @@ public class PubSubConfig {
|
||||
.build();
|
||||
subscriptionAdminClient.createSubscription(request);
|
||||
}
|
||||
if (pubSubAdmin.getSubscription(auditEventSubscription) == null) {
|
||||
Subscription request = Subscription.newBuilder()
|
||||
.setTopic(PROJECTS_PREFIX + projectId + TOPICS_PREFIX + auditEventTopic)
|
||||
.setName(PROJECTS_PREFIX + projectId + SUBSCRIPTIONS_PREFIX + auditEventSubscription)
|
||||
.setRetainAckedMessages(false) // audit payloads carry actors and IPs: keep them only in audit_event
|
||||
.setExpirationPolicy(ExpirationPolicy.newBuilder().setTtl(com.google.protobuf.Duration.newBuilder().setSeconds(31536000)).build())
|
||||
.build();
|
||||
subscriptionAdminClient.createSubscription(request);
|
||||
}
|
||||
if (pubSubAdmin.getSubscription(errorLogSubscription) == null) {
|
||||
Subscription request = Subscription.newBuilder()
|
||||
.setTopic(PROJECTS_PREFIX + projectId + TOPICS_PREFIX + errorLogTopic)
|
||||
@@ -111,6 +128,15 @@ public class PubSubConfig {
|
||||
adapter.setAckMode(AckMode.MANUAL);
|
||||
return adapter;
|
||||
}
|
||||
@Bean
|
||||
public PubSubInboundChannelAdapter auditEventSubscriptionChannelAdapter(
|
||||
@Qualifier("auditEventSubscriptionChannel") MessageChannel inputChannel, PubSubTemplate pubSubTemplate) {
|
||||
PubSubInboundChannelAdapter adapter = new PubSubInboundChannelAdapter(pubSubTemplate, auditEventSubscription);
|
||||
adapter.setOutputChannel(inputChannel);
|
||||
adapter.setAckMode(AckMode.MANUAL);
|
||||
return adapter;
|
||||
}
|
||||
|
||||
// @Bean
|
||||
// public PubSubInboundChannelAdapter errorLogSubscriptionChannelAdapter(
|
||||
// @Qualifier("errorLogSubscriptionChannel") MessageChannel inputChannel, PubSubTemplate pubSubTemplate) {
|
||||
@@ -129,6 +155,10 @@ public class PubSubConfig {
|
||||
public MessageChannel reponseTimeLogSubscriptionChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
@Bean
|
||||
public MessageChannel auditEventSubscriptionChannel() {
|
||||
return new DirectChannel();
|
||||
}
|
||||
// @Bean
|
||||
// public MessageChannel errorLogSubscriptionChannel() {
|
||||
// return new DirectChannel();
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.solvway.services.log.controller;
|
||||
|
||||
import com.solvway.services.log.model.AuditEventLog;
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/log/audit")
|
||||
public class AuditEventController {
|
||||
|
||||
public record SearchRequest(String actor, String module, String action, String outcome,
|
||||
String from, String to, Integer page, Integer size) {
|
||||
}
|
||||
|
||||
private final AuditEventLogRepository repository;
|
||||
|
||||
public AuditEventController(AuditEventLogRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@PostMapping("/search")
|
||||
public Map<String, Object> search(@RequestBody SearchRequest r) {
|
||||
int p = r.page() == null || r.page() < 0 ? 0 : r.page();
|
||||
int s = r.size() == null || r.size() < 1 ? 20 : Math.min(r.size(), 100);
|
||||
LocalDateTime from = day(r.from(), 0);
|
||||
LocalDateTime to = day(r.to(), 1);
|
||||
Page<AuditEventLog> page = repository.search(blankToNull(r.actor()), blankToNull(r.module()),
|
||||
blankToNull(r.action()), blankToNull(r.outcome()), from, to,
|
||||
PageRequest.of(p, s, Sort.by(Sort.Direction.DESC, "occurredAt", "id")));
|
||||
return Map.of("content", page.getContent(), "totalElements", page.getTotalElements(), "number", p, "size", s);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public AuditEventLog get(@PathVariable Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "No audit event " + id));
|
||||
}
|
||||
|
||||
private static String blankToNull(String v) {
|
||||
return v == null || v.isBlank() ? null : v;
|
||||
}
|
||||
|
||||
/** yyyy-MM-dd to that day's start plus plusDays; blank is null; malformed is 400. */
|
||||
private static LocalDateTime day(String v, int plusDays) {
|
||||
if (v == null || v.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(v.trim()).plusDays(plusDays).atStartOfDay();
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Dates must be yyyy-MM-dd");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.solvway.services.log.model;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** Maps `service-log`.`audit_event` as created by the OpenSpec change SQL; the app never runs DDL. */
|
||||
@Entity
|
||||
@Table(name = "audit_event")
|
||||
@Getter
|
||||
@Setter
|
||||
public class AuditEventLog {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
private Long companyId;
|
||||
private LocalDateTime occurredAt;
|
||||
private String actor;
|
||||
private String module;
|
||||
private String action;
|
||||
private String httpMethod;
|
||||
private String pathTemplate;
|
||||
private String targetId;
|
||||
private String outcome;
|
||||
private Integer httpStatus;
|
||||
private String clientIp;
|
||||
private String changes;
|
||||
}
|
||||
+42
@@ -4,7 +4,10 @@ import com.google.cloud.spring.pubsub.support.BasicAcknowledgeablePubsubMessage;
|
||||
import com.google.cloud.spring.pubsub.support.GcpPubSubHeaders;
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.core.model.AuditEvent;
|
||||
import com.solvway.services.log.model.AuditEventLog;
|
||||
import com.solvway.services.log.model.BackOfficeAccessLog;
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import com.solvway.services.log.model.ResponseTime;
|
||||
import com.solvway.services.log.repo.BackOfficeAccessLogRepository;
|
||||
import com.solvway.services.log.service.ResponseTimeService;
|
||||
@@ -70,6 +73,45 @@ public class PubSubListener {
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ServiceActivator(inputChannel = "auditEventSubscriptionChannel")
|
||||
public MessageHandler auditEventMessageReceiver(AuditEventLogRepository repository) {
|
||||
return message -> {
|
||||
try {
|
||||
pubSubUtil.checkMessageId(redisUtil.getRedisTemplate(), message.getHeaders());
|
||||
AuditEvent e = pubSubUtil.convertToOriginalObject(message.getPayload(), AuditEvent.class);
|
||||
AuditEventLog row = new AuditEventLog();
|
||||
row.setCompanyId(e.getCompanyId());
|
||||
row.setOccurredAt(e.getOccurredAt());
|
||||
row.setActor(clip(e.getActor(), 191));
|
||||
row.setModule(clip(e.getModule(), 64));
|
||||
row.setAction(clip(e.getAction(), 128));
|
||||
row.setHttpMethod(clip(e.getHttpMethod(), 16));
|
||||
row.setPathTemplate(clip(e.getPathTemplate(), 255));
|
||||
row.setTargetId(clip(e.getTargetId(), 128));
|
||||
row.setOutcome(clip(e.getOutcome(), 16));
|
||||
row.setHttpStatus(e.getHttpStatus());
|
||||
row.setClientIp(clip(e.getClientIp(), 64));
|
||||
row.setChanges(e.getChanges());
|
||||
repository.save(row);
|
||||
} catch (Exception ex) {
|
||||
// Class only: the payload carries actors and IPs.
|
||||
log.error("Audit event not stored: {}", ex.getClass().getName());
|
||||
} finally {
|
||||
BasicAcknowledgeablePubsubMessage originalMessage = message.getHeaders()
|
||||
.get(GcpPubSubHeaders.ORIGINAL_MESSAGE, BasicAcknowledgeablePubsubMessage.class);
|
||||
if (originalMessage != null) {
|
||||
originalMessage.ack();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Column widths of audit_event: over-long text is cut so the insert cannot fail. */
|
||||
private static String clip(String v, int max) {
|
||||
return v == null || v.length() <= max ? v : v.substring(0, max);
|
||||
}
|
||||
|
||||
private void updateAppSession(ResponseTime bean) {
|
||||
try {
|
||||
if (bean.getSourcePlatform().equals(GeneralEnum.CmsPlatform.APP)
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.solvway.services.log.repo;
|
||||
|
||||
import com.solvway.services.log.model.AuditEventLog;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public interface AuditEventLogRepository extends JpaRepository<AuditEventLog, Long> {
|
||||
|
||||
/** A null filter is ignored; {@code to} is exclusive. */
|
||||
@Query("select e from AuditEventLog e where (:actor is null or e.actor = :actor)"
|
||||
+ " and (:module is null or e.module = :module) and (:action is null or e.action = :action)"
|
||||
+ " and (:outcome is null or e.outcome = :outcome)"
|
||||
+ " and (:from is null or e.occurredAt >= :from)"
|
||||
+ " and (:to is null or e.occurredAt < :to)")
|
||||
Page<AuditEventLog> search(@Param("actor") String actor, @Param("module") String module,
|
||||
@Param("action") String action, @Param("outcome") String outcome,
|
||||
@Param("from") LocalDateTime from, @Param("to") LocalDateTime to, Pageable pageable);
|
||||
|
||||
/** Deletes up to {@code limit} old rows; each call is its own transaction. */
|
||||
@Transactional
|
||||
@Modifying
|
||||
@Query(value = "DELETE FROM audit_event WHERE occurred_at < :cutoff LIMIT :limit", nativeQuery = true)
|
||||
int deleteBatchOlderThan(@Param("cutoff") LocalDateTime cutoff, @Param("limit") int limit);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.solvway.services.log.service;
|
||||
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Component
|
||||
public class AuditEventLogPurge {
|
||||
private static final Logger log = LoggerFactory.getLogger(AuditEventLogPurge.class);
|
||||
private static final int BATCH = 5000;
|
||||
|
||||
private final AuditEventLogRepository repository;
|
||||
private final int retentionDays;
|
||||
|
||||
public AuditEventLogPurge(AuditEventLogRepository repository,
|
||||
@Value("${audit.retention-days:${AUDIT_RETENTION_DAYS:730}}") int retentionDays) {
|
||||
this.repository = repository;
|
||||
// 0 or less would delete the whole trail at the next run: refuse to start instead.
|
||||
if (retentionDays < 1) throw new IllegalArgumentException("audit.retention-days must be at least 1");
|
||||
this.retentionDays = retentionDays;
|
||||
}
|
||||
|
||||
@Scheduled(cron = "0 30 3 * * *")
|
||||
public void purge() {
|
||||
LocalDateTime cutoff = LocalDateTime.now().minusDays(retentionDays);
|
||||
long total = 0;
|
||||
int n;
|
||||
do {
|
||||
n = repository.deleteBatchOlderThan(cutoff, BATCH);
|
||||
total += n;
|
||||
} while (n > 0);
|
||||
log.info("Audit purge deleted {} rows older than {}", total, cutoff);
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package com.solvway.services.log.controller;
|
||||
|
||||
import com.solvway.services.log.model.AuditEventLog;
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AuditEventControllerTest {
|
||||
|
||||
private final AuditEventLogRepository repository = mock(AuditEventLogRepository.class);
|
||||
private final AuditEventController controller = new AuditEventController(repository);
|
||||
|
||||
private ArgumentCaptor<Pageable> pageable = ArgumentCaptor.forClass(Pageable.class);
|
||||
private ArgumentCaptor<LocalDateTime> from = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||
private ArgumentCaptor<LocalDateTime> to = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||
|
||||
private Map<String, Object> search(AuditEventController.SearchRequest r) {
|
||||
AuditEventLog row = new AuditEventLog();
|
||||
Page<AuditEventLog> page = new PageImpl<>(List.of(row));
|
||||
when(repository.search(any(), any(), any(), any(), any(), any(), any())).thenReturn(page);
|
||||
return controller.search(r);
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesExactFiltersAndInclusiveDateRange() {
|
||||
Map<String, Object> res = search(new AuditEventController.SearchRequest(
|
||||
"a@x.com", "LEADS", "lead.update", "FAILURE", "2026-11-01", "2026-11-30", 2, 50));
|
||||
|
||||
verify(repository).search(org.mockito.ArgumentMatchers.eq("a@x.com"), org.mockito.ArgumentMatchers.eq("LEADS"),
|
||||
org.mockito.ArgumentMatchers.eq("lead.update"), org.mockito.ArgumentMatchers.eq("FAILURE"),
|
||||
from.capture(), to.capture(), pageable.capture());
|
||||
assertThat(from.getValue()).isEqualTo(LocalDateTime.of(2026, 11, 1, 0, 0));
|
||||
assertThat(to.getValue()).isEqualTo(LocalDateTime.of(2026, 12, 1, 0, 0));
|
||||
assertThat(pageable.getValue().getPageNumber()).isEqualTo(2);
|
||||
assertThat(pageable.getValue().getPageSize()).isEqualTo(50);
|
||||
assertThat(pageable.getValue().getSort())
|
||||
.isEqualTo(Sort.by(Sort.Direction.DESC, "occurredAt").and(Sort.by(Sort.Direction.DESC, "id")));
|
||||
assertThat(res).containsEntry("totalElements", 1L).containsEntry("number", 2).containsEntry("size", 50);
|
||||
assertThat((List<?>) res.get("content")).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankFiltersAreIgnoredAndPagingDefaults() {
|
||||
search(new AuditEventController.SearchRequest(" ", "", null, "", "", null, -3, 0));
|
||||
|
||||
verify(repository).search(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), pageable.capture());
|
||||
assertThat(pageable.getValue().getPageNumber()).isZero();
|
||||
assertThat(pageable.getValue().getPageSize()).isEqualTo(20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sizeIsCappedAtOneHundred() {
|
||||
search(new AuditEventController.SearchRequest(null, null, null, null, null, null, null, 5000));
|
||||
|
||||
verify(repository).search(any(), any(), any(), any(), any(), any(), pageable.capture());
|
||||
assertThat(pageable.getValue().getPageSize()).isEqualTo(100);
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedDateAnswers400() {
|
||||
assertThatThrownBy(() -> controller.search(
|
||||
new AuditEventController.SearchRequest(null, null, null, null, "30/11/2026", null, 0, 20)))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailUnknownIdAnswers404() {
|
||||
when(repository.findById(9L)).thenReturn(Optional.empty());
|
||||
|
||||
assertThatThrownBy(() -> controller.get(9L))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailReturnsTheRow() {
|
||||
AuditEventLog row = new AuditEventLog();
|
||||
when(repository.findById(1L)).thenReturn(Optional.of(row));
|
||||
|
||||
assertThat(controller.get(1L)).isSameAs(row);
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package com.solvway.services.log.pubsub;
|
||||
|
||||
import com.google.cloud.spring.pubsub.support.BasicAcknowledgeablePubsubMessage;
|
||||
import com.google.cloud.spring.pubsub.support.GcpPubSubHeaders;
|
||||
import com.solvway.core.model.AuditEvent;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.services.log.model.AuditEventLog;
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import com.solvway.services.log.util.RedisUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.MessageHandler;
|
||||
import org.springframework.messaging.support.MessageBuilder;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AuditEventListenerTest {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private final RedisUtil<String> redisUtil = mock(RedisUtil.class);
|
||||
private final PubSubUtil pubSubUtil = mock(PubSubUtil.class);
|
||||
private final AuditEventLogRepository repository = mock(AuditEventLogRepository.class);
|
||||
private final BasicAcknowledgeablePubsubMessage original = mock(BasicAcknowledgeablePubsubMessage.class);
|
||||
private final MessageHandler handler =
|
||||
new PubSubListener(redisUtil, pubSubUtil).auditEventMessageReceiver(repository);
|
||||
|
||||
private Message<byte[]> message() {
|
||||
return MessageBuilder.withPayload(new byte[0]).setHeader(GcpPubSubHeaders.ORIGINAL_MESSAGE, original).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void savesEveryFieldAndAcks() {
|
||||
AuditEvent e = new AuditEvent();
|
||||
e.setCompanyId(7L);
|
||||
e.setOccurredAt(LocalDateTime.of(2026, 11, 30, 10, 0));
|
||||
e.setActor("admin@x.com");
|
||||
e.setModule("LEADS");
|
||||
e.setAction("lead.update");
|
||||
e.setHttpMethod("PUT");
|
||||
e.setPathTemplate("/api/admin/leads/{id}");
|
||||
e.setTargetId("42");
|
||||
e.setOutcome(AuditEvent.OUTCOME_SUCCESS);
|
||||
e.setHttpStatus(200);
|
||||
e.setClientIp("10.0.0.1");
|
||||
e.setChanges("{\"fields\":[\"name\"]}");
|
||||
when(pubSubUtil.convertToOriginalObject(any(), any())).thenReturn(e);
|
||||
|
||||
handler.handleMessage(message());
|
||||
|
||||
ArgumentCaptor<AuditEventLog> c = ArgumentCaptor.forClass(AuditEventLog.class);
|
||||
verify(repository).save(c.capture());
|
||||
AuditEventLog r = c.getValue();
|
||||
assertThat(r.getCompanyId()).isEqualTo(7L);
|
||||
assertThat(r.getOccurredAt()).isEqualTo(e.getOccurredAt());
|
||||
assertThat(r.getActor()).isEqualTo("admin@x.com");
|
||||
assertThat(r.getModule()).isEqualTo("LEADS");
|
||||
assertThat(r.getAction()).isEqualTo("lead.update");
|
||||
assertThat(r.getHttpMethod()).isEqualTo("PUT");
|
||||
assertThat(r.getPathTemplate()).isEqualTo("/api/admin/leads/{id}");
|
||||
assertThat(r.getTargetId()).isEqualTo("42");
|
||||
assertThat(r.getOutcome()).isEqualTo("SUCCESS");
|
||||
assertThat(r.getHttpStatus()).isEqualTo(200);
|
||||
assertThat(r.getClientIp()).isEqualTo("10.0.0.1");
|
||||
assertThat(r.getChanges()).isEqualTo("{\"fields\":[\"name\"]}");
|
||||
verify(original).ack();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cutsOversizeStringsToColumnWidth() {
|
||||
AuditEvent e = new AuditEvent();
|
||||
e.setActor("a".repeat(300));
|
||||
e.setAction("b".repeat(300));
|
||||
e.setPathTemplate("p".repeat(300));
|
||||
e.setClientIp("i".repeat(100));
|
||||
when(pubSubUtil.convertToOriginalObject(any(), any())).thenReturn(e);
|
||||
|
||||
handler.handleMessage(message());
|
||||
|
||||
ArgumentCaptor<AuditEventLog> c = ArgumentCaptor.forClass(AuditEventLog.class);
|
||||
verify(repository).save(c.capture());
|
||||
assertThat(c.getValue().getActor()).hasSize(191);
|
||||
assertThat(c.getValue().getAction()).hasSize(128);
|
||||
assertThat(c.getValue().getPathTemplate()).hasSize(255);
|
||||
assertThat(c.getValue().getClientIp()).hasSize(64);
|
||||
}
|
||||
|
||||
@Test
|
||||
void acksEvenWhenSaveFails() {
|
||||
when(pubSubUtil.convertToOriginalObject(any(), any())).thenReturn(new AuditEvent());
|
||||
when(repository.save(any())).thenThrow(new IllegalStateException("db down"));
|
||||
|
||||
handler.handleMessage(message());
|
||||
|
||||
verify(original).ack();
|
||||
verify(original, never()).nack();
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.solvway.services.log.service;
|
||||
|
||||
import com.solvway.services.log.repo.AuditEventLogRepository;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AuditEventLogPurgeTest {
|
||||
|
||||
private final AuditEventLogRepository repository = mock(AuditEventLogRepository.class);
|
||||
|
||||
private LocalDateTime purgeCutoff(int retentionDays) {
|
||||
when(repository.deleteBatchOlderThan(any(), org.mockito.ArgumentMatchers.anyInt())).thenReturn(0);
|
||||
new AuditEventLogPurge(repository, retentionDays).purge();
|
||||
ArgumentCaptor<LocalDateTime> c = ArgumentCaptor.forClass(LocalDateTime.class);
|
||||
verify(repository).deleteBatchOlderThan(c.capture(), org.mockito.ArgumentMatchers.anyInt());
|
||||
return c.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsARetentionBelowOneDay() {
|
||||
for (int days : new int[] {0, -1}) {
|
||||
org.assertj.core.api.Assertions.assertThatThrownBy(() -> new AuditEventLogPurge(repository, days))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void cutoffIsNowMinusConfiguredRetention() {
|
||||
for (int days : new int[] {730, 30}) {
|
||||
org.mockito.Mockito.reset(repository);
|
||||
LocalDateTime expected = LocalDateTime.now().minusDays(days);
|
||||
assertThat(Duration.between(purgeCutoff(days), expected).abs()).isLessThan(Duration.ofSeconds(5));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletesInBatchesUntilNoRowsLeft() {
|
||||
when(repository.deleteBatchOlderThan(any(), org.mockito.ArgumentMatchers.anyInt()))
|
||||
.thenReturn(5000, 5000, 120, 0);
|
||||
|
||||
new AuditEventLogPurge(repository, 730).purge();
|
||||
|
||||
verify(repository, times(4)).deleteBatchOlderThan(any(), org.mockito.ArgumentMatchers.anyInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void retentionComesFromTheAuditRetentionDaysProperty() throws Exception {
|
||||
var ctor = AuditEventLogPurge.class.getDeclaredConstructors()[0];
|
||||
var value = ctor.getParameters()[1].getAnnotation(org.springframework.beans.factory.annotation.Value.class);
|
||||
assertThat(value.value()).isEqualTo("${audit.retention-days:${AUDIT_RETENTION_DAYS:730}}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user