From 7aa5c4b9210f966dc131acd79a11b5effd84c064 Mon Sep 17 00:00:00 2001 From: ngqile Date: Mon, 30 Nov 2026 17:16:29 +0800 Subject: [PATCH] fix: audit target is the record acted on, never a typed username; guard retention Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- docs/deployment.md | 2 +- .../changes/add-admin-audit-log/design.md | 8 ++++-- .../specs/admin-audit-log/spec.md | 7 +++++- .../admin/AdminLoginSecurityController.java | 2 ++ .../api/useraccess/AppAccessAspect.java | 9 +++++-- .../mobile/api/useraccess/Audited.java | 3 +++ .../useraccess/AppAccessAspectAuditTest.java | 25 +++++++++++++++++++ .../log/configuration/PubSubConfig.java | 2 +- .../log/service/AuditEventLogPurge.java | 2 ++ .../log/service/AuditEventLogPurgeTest.java | 8 ++++++ 10 files changed, 61 insertions(+), 7 deletions(-) diff --git a/docs/deployment.md b/docs/deployment.md index 40bb31b..0f6bee1 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -105,7 +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. +- **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 diff --git a/openspec/changes/add-admin-audit-log/design.md b/openspec/changes/add-admin-audit-log/design.md index 3f19f21..49e5901 100644 --- a/openspec/changes/add-admin-audit-log/design.md +++ b/openspec/changes/add-admin-audit-log/design.md @@ -51,7 +51,7 @@ Full design with approaches and the user's approved calls: `docs/superpowers/spe 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 first `@PathVariable` value. + - **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`; @@ -92,5 +92,9 @@ Full design with approaches and the user's approved calls: `docs/superpowers/spe - **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 first path variable is a UUID or id. The concrete path is never stored, so no query string, and therefore no search text, ends up in the log. +- **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. diff --git a/openspec/changes/add-admin-audit-log/specs/admin-audit-log/spec.md b/openspec/changes/add-admin-audit-log/specs/admin-audit-log/spec.md index 8902e8c..28a6e2a 100644 --- a/openspec/changes/add-admin-audit-log/specs/admin-audit-log/spec.md +++ b/openspec/changes/add-admin-audit-log/specs/admin-audit-log/spec.md @@ -2,7 +2,7 @@ ### 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, and calls without a valid admin token SHALL NOT be 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 @@ -19,6 +19,11 @@ The system SHALL record an audit event for every state-changing admin API call m - **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). diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityController.java index 5afabbb..3d86cf3 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityController.java @@ -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 unlock(@PathVariable String username) { diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java index a33fe45..1649c65 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/AppAccessAspect.java @@ -181,9 +181,14 @@ public class AppAccessAspect { event.setHttpMethod(request.getMethod()); Object pattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); event.setPathTemplate(pattern == null ? null : pattern.toString()); - if (request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE) instanceof Map vars + // 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()) { - event.setTargetId(String.valueOf(vars.values().iterator().next())); + 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); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/Audited.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/Audited.java index 4893cca..88170aa 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/Audited.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/useraccess/Audited.java @@ -19,4 +19,7 @@ public @interface Audited { /** 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; } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAuditTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAuditTest.java index 92119ee..e4df88f 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAuditTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/useraccess/AppAccessAspectAuditTest.java @@ -93,6 +93,10 @@ class AppAccessAspectAuditTest { @Audited(skip = true) public void match() { } + + @Audited(target = false) + public void unlock() { + } } @BeforeEach @@ -180,6 +184,27 @@ class AppAccessAspectAuditTest { assertThat(e.getChanges()).isNull(); } + @Test + void target_isTheLastPathVariable() throws Throwable { + Map 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"); diff --git a/solvway-services-log/src/main/java/com/solvway/services/log/configuration/PubSubConfig.java b/solvway-services-log/src/main/java/com/solvway/services/log/configuration/PubSubConfig.java index 11bdb41..1ceae8a 100644 --- a/solvway-services-log/src/main/java/com/solvway/services/log/configuration/PubSubConfig.java +++ b/solvway-services-log/src/main/java/com/solvway/services/log/configuration/PubSubConfig.java @@ -94,7 +94,7 @@ public class PubSubConfig { Subscription request = Subscription.newBuilder() .setTopic(PROJECTS_PREFIX + projectId + TOPICS_PREFIX + auditEventTopic) .setName(PROJECTS_PREFIX + projectId + SUBSCRIPTIONS_PREFIX + auditEventSubscription) - .setRetainAckedMessages(true) + .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); diff --git a/solvway-services-log/src/main/java/com/solvway/services/log/service/AuditEventLogPurge.java b/solvway-services-log/src/main/java/com/solvway/services/log/service/AuditEventLogPurge.java index ab05c1d..0d52575 100644 --- a/solvway-services-log/src/main/java/com/solvway/services/log/service/AuditEventLogPurge.java +++ b/solvway-services-log/src/main/java/com/solvway/services/log/service/AuditEventLogPurge.java @@ -20,6 +20,8 @@ public class AuditEventLogPurge { 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; } diff --git a/solvway-services-log/src/test/java/com/solvway/services/log/service/AuditEventLogPurgeTest.java b/solvway-services-log/src/test/java/com/solvway/services/log/service/AuditEventLogPurgeTest.java index 67abf20..ee17d68 100644 --- a/solvway-services-log/src/test/java/com/solvway/services/log/service/AuditEventLogPurgeTest.java +++ b/solvway-services-log/src/test/java/com/solvway/services/log/service/AuditEventLogPurgeTest.java @@ -26,6 +26,14 @@ class AuditEventLogPurgeTest { 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}) {