feat: admin audit log (recording, storage, Audit log screen) #21
No files matched your search
+1
-1
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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).
|
||||
|
||||
+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) {
|
||||
|
||||
+7
-2
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
+25
@@ -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<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");
|
||||
|
||||
+1
-1
@@ -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);
|
||||
|
||||
+2
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+8
@@ -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}) {
|
||||
|
||||
Reference in new issue
Block a user