This is an automated email from the ASF dual-hosted git repository.

DImuthuUpe pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/airavata.git


The following commit(s) were added to refs/heads/master by this push:
     new f604269d6c Initial audit log support (#763)
f604269d6c is described below

commit f604269d6c656e99daa89c7a78f44b9361dcdbf8
Author: Dimuthu Wannipurage <[email protected]>
AuthorDate: Wed Nov 11 09:12:47 2026 -0500

    Initial audit log support (#763)
    
    * Added a simple domain model-based audit support
    
    * Added audit log dashboard with filters
---
 api/audit/controller/event.go                |  68 ++++++++
 api/audit/dto/event.go                       | 124 +++++++++++++
 api/audit/model/event.go                     |  73 ++++++++
 api/audit/repository/event.go                |  71 ++++++++
 api/audit/service/event.go                   |  75 ++++++++
 cmd/airavata-server/main.go                  |   5 +
 dashboard/src/app/audit/page.tsx             | 199 +++++++++++++++++++++
 dashboard/src/components/Icons.tsx           |   7 +
 dashboard/src/components/Shell.tsx           |   1 +
 dashboard/src/components/ui.tsx              |   4 +
 dashboard/src/lib/types.ts                   |  18 ++
 docs/audit.md                                |  75 ++++++++
 docs/openapi.yaml                            | 100 +++++++++++
 internal/app/app.go                          |   9 +
 internal/audit/audit.go                      | 191 ++++++++++++++++++++
 internal/db/migrate.go                       |   5 +
 internal/db/migrations/0014_audit_events.sql |  13 ++
 internal/server/audit_test.go                | 250 +++++++++++++++++++++++++++
 internal/server/server.go                    |   2 +
 internal/server/server_test.go               |   4 +
 website/sidebars.js                          |   2 +-
 21 files changed, 1295 insertions(+), 1 deletion(-)

diff --git a/api/audit/controller/event.go b/api/audit/controller/event.go
new file mode 100644
index 0000000000..691661540d
--- /dev/null
+++ b/api/audit/controller/event.go
@@ -0,0 +1,68 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+// Package controller serves /api/v1/audit-events.
+package controller
+
+import (
+       "net/http"
+
+       "github.com/apache/airavata/internal/httpx"
+
+       "github.com/apache/airavata/api/audit/dto"
+       "github.com/apache/airavata/api/audit/service"
+)
+
+// EventController serves the audit log.
+type EventController struct{ svc *service.EventService }
+
+// NewEventController returns a handler delegating to svc.
+func NewEventController(svc *service.EventService) *EventController {
+       return &EventController{svc: svc}
+}
+
+// Register mounts the audit routes.
+func (h *EventController) Register(mux *http.ServeMux) {
+       mux.HandleFunc("GET /api/v1/audit-events", h.list)
+       mux.HandleFunc("GET /api/v1/audit-events/entity-types", h.entityTypes)
+}
+
+func (h *EventController) list(w http.ResponseWriter, r *http.Request) {
+       q, err := dto.ParseEventQuery(r.URL.Query())
+       if err != nil {
+               httpx.WriteError(w, r, err)
+               return
+       }
+       out, err := h.svc.List(r.Context(), q)
+       if err != nil {
+               httpx.WriteError(w, r, err)
+               return
+       }
+       httpx.WriteJSON(w, http.StatusOK, out)
+}
+
+func (h *EventController) entityTypes(w http.ResponseWriter, r *http.Request) {
+       out, err := h.svc.EntityTypes(r.Context())
+       if err != nil {
+               httpx.WriteError(w, r, err)
+               return
+       }
+       httpx.WriteJSON(w, http.StatusOK, out)
+}
diff --git a/api/audit/dto/event.go b/api/audit/dto/event.go
new file mode 100644
index 0000000000..8320a1c959
--- /dev/null
+++ b/api/audit/dto/event.go
@@ -0,0 +1,124 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+// Package dto holds the audit log's request and response shapes.
+package dto
+
+import (
+       "net/url"
+       "strconv"
+
+       "github.com/apache/airavata/internal/httpx"
+
+       model "github.com/apache/airavata/api/audit/model"
+)
+
+// Page-size bounds for listing events.
+const (
+       DefaultLimit = 100
+       MaxLimit     = 500
+)
+
+// EventQuery selects events. Every filter is optional and they combine with 
AND.
+type EventQuery struct {
+       // UserID matches the actor exactly.
+       UserID string
+       // EntityType matches the record's table exactly, such as "processes".
+       EntityType string
+       // From is inclusive and To exclusive, both in milliseconds since the 
epoch; zero
+       // leaves that end open.
+       From, To int64
+       // Before returns only events with a smaller id than this, which is how 
a caller
+       // reads the next page. Zero starts from the newest.
+       Before int64
+       Limit  int
+}
+
+// ParseEventQuery reads and validates the query string of a list request.
+func ParseEventQuery(q url.Values) (*EventQuery, error) {
+       out := &EventQuery{
+               UserID:     q.Get("userId"),
+               EntityType: q.Get("entityType"),
+               Limit:      DefaultLimit,
+       }
+
+       var c httpx.Constraints
+       num := func(name string) int64 {
+               raw := q.Get(name)
+               if raw == "" {
+                       return 0
+               }
+               n, err := strconv.ParseInt(raw, 10, 64)
+               if err != nil || n < 0 {
+                       c.Add(name, name+" must be a non-negative integer")
+                       return 0
+               }
+               return n
+       }
+       out.From, out.To, out.Before = num("from"), num("to"), num("before")
+       if out.To != 0 && out.From >= out.To {
+               c.Add("to", "to must be after from")
+       }
+       if raw := q.Get("limit"); raw != "" {
+               n, err := strconv.Atoi(raw)
+               if err != nil || n < 1 || n > MaxLimit {
+                       c.Add("limit", "limit must be between 1 and 
"+strconv.Itoa(MaxLimit))
+               } else {
+                       out.Limit = n
+               }
+       }
+
+       if fields := c.Fields(); len(fields) > 0 {
+               return nil, &httpx.Error{Status: 400, Message: "Validation 
failed", Fields: fields}
+       }
+       return out, nil
+}
+
+// EventResponse is one audit event.
+type EventResponse struct {
+       ID            int64  `json:"id"`
+       OccurredAt    int64  `json:"occurredAt"`
+       Actor         string `json:"actor"`
+       Action        string `json:"action"`
+       EntityType    string `json:"entityType"`
+       EntityID      string `json:"entityId"`
+       ChangedFields string `json:"changedFields"`
+}
+
+// NewEventResponse maps an event to its response.
+func NewEventResponse(e *model.Event) EventResponse {
+       return EventResponse{
+               ID:            e.ID,
+               OccurredAt:    e.OccurredAt,
+               Actor:         e.Actor,
+               Action:        string(e.Action),
+               EntityType:    e.EntityType,
+               EntityID:      e.EntityID,
+               ChangedFields: e.ChangedFields,
+       }
+}
+
+// EventPage is one page of events, newest first.
+type EventPage struct {
+       Items []EventResponse `json:"items"`
+       // NextCursor is the "before" value that fetches the following page, or 
null when
+       // this was the last.
+       NextCursor *int64 `json:"nextCursor"`
+}
diff --git a/api/audit/model/event.go b/api/audit/model/event.go
new file mode 100644
index 0000000000..56ac4c2bdf
--- /dev/null
+++ b/api/audit/model/event.go
@@ -0,0 +1,73 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+// Package model holds the audit log's entity.
+package model
+
+// Action is what was done to a record.
+type Action string
+
+const (
+       ActionCreate Action = "CREATE"
+       ActionUpdate Action = "UPDATE"
+       ActionDelete Action = "DELETE"
+       // ActionUpsert is a write that inserts the record or, if it already 
exists,
+       // updates it; the database does not say which happened.
+       ActionUpsert Action = "UPSERT"
+)
+
+// SystemActor is recorded for a change made with no caller behind it, such as 
the
+// execution engine moving a process to its next status.
+const SystemActor = "system"
+
+// Event is one change to one record: who made it, what was done and to what.
+//
+// The table is append-only. Nothing in the server updates or deletes a row, 
and it
+// deliberately has no foreign keys: an audit trail must outlive the users and 
records
+// it describes, so Actor and EntityID are plain strings rather than 
references.
+//
+// An event names the record, never its contents. Values are left out on 
purpose: rows
+// carry token digests, SSH passwords and job secrets, and a log that copied 
them would
+// be a second place to protect them.
+type Event struct {
+       ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
+
+       // OccurredAt is when the change was made, in milliseconds since the 
epoch.
+       OccurredAt int64 `gorm:"column:occurred_at;not 
null;index:idx_audit_events_occurred_at;index:idx_audit_events_actor,priority:2;index:idx_audit_events_entity,priority:3"
 json:"occurredAt"`
+
+       // Actor is the principal's name — a users.user_id, "root", or 
"sa:<name>" — or
+       // SystemActor.
+       Actor string `gorm:"column:actor;type:varchar(255);not 
null;index:idx_audit_events_actor,priority:1" json:"actor"`
+
+       Action Action `gorm:"column:action;type:varchar(10);not null" 
json:"action"`
+
+       // EntityType is the table the record lives in, such as "processes", 
and EntityID its
+       // primary key; a composite key is joined with ":". EntityID is empty 
when the
+       // change addressed rows by a condition instead of by key.
+       EntityType string `gorm:"column:entity_type;type:varchar(64);not 
null;index:idx_audit_events_entity,priority:1" json:"entityType"`
+       EntityID   string `gorm:"column:entity_id;type:varchar(255);not 
null;default:'';index:idx_audit_events_entity,priority:2" json:"entityId"`
+
+       // ChangedFields lists the columns an update named, comma-separated, 
when the write
+       // named them. Empty for a create, a delete, and an update that saved 
the whole record.
+       ChangedFields string 
`gorm:"column:changed_fields;type:varchar(1024);not null;default:''" 
json:"changedFields"`
+}
+
+// TableName returns the table backing Event.
+func (Event) TableName() string { return "audit_events" }
diff --git a/api/audit/repository/event.go b/api/audit/repository/event.go
new file mode 100644
index 0000000000..40546eb5d8
--- /dev/null
+++ b/api/audit/repository/event.go
@@ -0,0 +1,71 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+// Package repository reads the audit log.
+package repository
+
+import (
+       "context"
+
+       "gorm.io/gorm"
+
+       "github.com/apache/airavata/api/audit/dto"
+       model "github.com/apache/airavata/api/audit/model"
+)
+
+// EventRepository reads audit events. There is deliberately no way to change 
or remove
+// one here: the writes come from the audit plugin, and the log is append-only.
+type EventRepository struct{ db *gorm.DB }
+
+// NewEventRepository returns a repository backed by db.
+func NewEventRepository(db *gorm.DB) *EventRepository { return 
&EventRepository{db: db} }
+
+// Find returns up to q.Limit+1 events matching q, newest first. The extra 
row, if
+// present, tells the caller there is another page without a second count 
query.
+func (r *EventRepository) Find(ctx context.Context, q *dto.EventQuery) 
([]model.Event, error) {
+       tx := r.db.WithContext(ctx).Model(&model.Event{})
+       if q.UserID != "" {
+               tx = tx.Where("actor = ?", q.UserID)
+       }
+       if q.EntityType != "" {
+               tx = tx.Where("entity_type = ?", q.EntityType)
+       }
+       if q.From != 0 {
+               tx = tx.Where("occurred_at >= ?", q.From)
+       }
+       if q.To != 0 {
+               tx = tx.Where("occurred_at < ?", q.To)
+       }
+       if q.Before != 0 {
+               tx = tx.Where("id < ?", q.Before)
+       }
+
+       var out []model.Event
+       err := tx.Order("id DESC").Limit(q.Limit + 1).Find(&out).Error
+       return out, err
+}
+
+// EntityTypes returns every entity type that has an event, alphabetically.
+func (r *EventRepository) EntityTypes(ctx context.Context) ([]string, error) {
+       var out []string
+       err := r.db.WithContext(ctx).Model(&model.Event{}).
+               Distinct().Order("entity_type").Pluck("entity_type", &out).Error
+       return out, err
+}
diff --git a/api/audit/service/event.go b/api/audit/service/event.go
new file mode 100644
index 0000000000..114665118e
--- /dev/null
+++ b/api/audit/service/event.go
@@ -0,0 +1,75 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+// Package service serves the audit log to administrators.
+package service
+
+import (
+       "context"
+
+       "github.com/apache/airavata/internal/auth"
+
+       "github.com/apache/airavata/api/audit/dto"
+       "github.com/apache/airavata/api/audit/repository"
+)
+
+// EventService reads the audit log. Every call needs ADMIN or SUPER_ADMIN: 
the log
+// names what every user did.
+type EventService struct{ events *repository.EventRepository }
+
+// NewEventService returns a service over events.
+func NewEventService(events *repository.EventRepository) *EventService {
+       return &EventService{events: events}
+}
+
+// List returns one page of events matching q, newest first.
+func (s *EventService) List(ctx context.Context, q *dto.EventQuery) 
(*dto.EventPage, error) {
+       if _, err := auth.RequireAdmin(ctx); err != nil {
+               return nil, err
+       }
+       found, err := s.events.Find(ctx, q)
+       if err != nil {
+               return nil, err
+       }
+
+       page := &dto.EventPage{Items: make([]dto.EventResponse, 0, len(found))}
+       if len(found) > q.Limit {
+               // The extra row only signals a next page; the cursor is the 
last row returned.
+               found = found[:q.Limit]
+               next := found[len(found)-1].ID
+               page.NextCursor = &next
+       }
+       for i := range found {
+               page.Items = append(page.Items, dto.NewEventResponse(&found[i]))
+       }
+       return page, nil
+}
+
+// EntityTypes lists the entity types the log holds events for.
+func (s *EventService) EntityTypes(ctx context.Context) ([]string, error) {
+       if _, err := auth.RequireAdmin(ctx); err != nil {
+               return nil, err
+       }
+       out, err := s.events.EntityTypes(ctx)
+       if out == nil {
+               out = []string{}
+       }
+       return out, err
+}
diff --git a/cmd/airavata-server/main.go b/cmd/airavata-server/main.go
index acb071da88..e070ec6798 100644
--- a/cmd/airavata-server/main.go
+++ b/cmd/airavata-server/main.go
@@ -35,6 +35,7 @@ import (
        iamrepo "github.com/apache/airavata/api/iam/repository"
        iamsvc "github.com/apache/airavata/api/iam/service"
        "github.com/apache/airavata/internal/app"
+       "github.com/apache/airavata/internal/audit"
        "github.com/apache/airavata/internal/auth"
        "github.com/apache/airavata/internal/config"
        "github.com/apache/airavata/internal/db"
@@ -129,6 +130,10 @@ func runServer() error {
        if err != nil {
                return err
        }
+       // Before anything writes, including the migration below and the root 
user.
+       if err := audit.Register(gdb); err != nil {
+               return fmt.Errorf("register audit log: %w", err)
+       }
        if cfg.AutoMigrate {
                if err := db.AutoMigrate(gdb); err != nil {
                        return fmt.Errorf("migrate schema: %w", err)
diff --git a/dashboard/src/app/audit/page.tsx b/dashboard/src/app/audit/page.tsx
new file mode 100644
index 0000000000..310409fd59
--- /dev/null
+++ b/dashboard/src/app/audit/page.tsx
@@ -0,0 +1,199 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Alert, Card, Field, formatTime, PageHead, StatusBadge, Table } from 
"@/components/ui";
+import { api, errorText } from "@/lib/api";
+import { useResource } from "@/lib/hooks";
+import { useSession } from "@/lib/session";
+import type { AuditEvent, AuditEventPage } from "@/lib/types";
+
+const PAGE_SIZE = 100;
+
+interface Filters {
+  userId: string;
+  entityType: string;
+  // Calendar days as the date inputs give them ("YYYY-MM-DD"), in the 
browser's time zone.
+  from: string;
+  to: string;
+}
+
+const NO_FILTERS: Filters = { userId: "", entityType: "", from: "", to: "" };
+
+// startOfDay is local midnight of a "YYYY-MM-DD" day, in milliseconds since 
the epoch.
+function startOfDay(day: string, plusDays = 0): number {
+  const [y, m, d] = day.split("-").map(Number);
+  return new Date(y, m - 1, d + plusDays).getTime();
+}
+
+// query builds the request string. The "to" day is inclusive for the person 
picking it,
+// so the server's exclusive bound is the start of the day after.
+function query(f: Filters, before?: number): string {
+  const p = new URLSearchParams({ limit: String(PAGE_SIZE) });
+  if (f.userId.trim()) p.set("userId", f.userId.trim());
+  if (f.entityType) p.set("entityType", f.entityType);
+  if (f.from) p.set("from", String(startOfDay(f.from)));
+  if (f.to) p.set("to", String(startOfDay(f.to, 1)));
+  if (before) p.set("before", String(before));
+  return p.toString();
+}
+
+export default function AuditPage() {
+  const { isAdmin } = useSession();
+  // What the form holds, versus what the table was last loaded with.
+  const [draft, setDraft] = useState<Filters>(NO_FILTERS);
+  const [applied, setApplied] = useState<Filters>(NO_FILTERS);
+
+  const types = useResource(
+    () => (isAdmin ? api.get<string[]>("/api/v1/audit-events/entity-types") : 
Promise.resolve([])),
+    [isAdmin],
+  );
+  const first = useResource(
+    () =>
+      isAdmin
+        ? api.get<AuditEventPage>(`/api/v1/audit-events?${query(applied)}`)
+        : Promise.resolve({ items: [], nextCursor: null }),
+    [isAdmin, applied],
+  );
+
+  // Older pages loaded with "Load more", appended below the first. A new 
first page
+  // (new filters, or a refresh) starts over.
+  const [older, setOlder] = useState<AuditEvent[]>([]);
+  const [cursor, setCursor] = useState<number | null>(null);
+  const [loadingMore, setLoadingMore] = useState(false);
+  const [moreError, setMoreError] = useState<string | null>(null);
+  useEffect(() => {
+    setOlder([]);
+    setCursor(first.data?.nextCursor ?? null);
+    setMoreError(null);
+  }, [first.data]);
+
+  const loadMore = async () => {
+    if (cursor === null) return;
+    setLoadingMore(true);
+    setMoreError(null);
+    try {
+      const page = await 
api.get<AuditEventPage>(`/api/v1/audit-events?${query(applied, cursor)}`);
+      setOlder((prev) => [...prev, ...page.items]);
+      setCursor(page.nextCursor);
+    } catch (e) {
+      setMoreError(errorText(e));
+    } finally {
+      setLoadingMore(false);
+    }
+  };
+
+  const set = <K extends keyof Filters>(k: K, v: Filters[K]) => setDraft((d) 
=> ({ ...d, [k]: v }));
+  const badRange = !!draft.from && !!draft.to && draft.from > draft.to;
+  const filtered = JSON.stringify(applied) !== JSON.stringify(NO_FILTERS);
+
+  if (!isAdmin) {
+    return (
+      <div className="stack">
+        <PageHead title="Audit log" />
+        <Alert kind="info">Only administrators can read the audit log.</Alert>
+      </div>
+    );
+  }
+
+  const rows = first.data ? [...first.data.items, ...older] : undefined;
+
+  return (
+    <div className="stack">
+      <PageHead
+        title="Audit log"
+        sub="Every change to a record: who made it, what they did and to which 
record. Newest first. Values are never recorded, and system is the actor for 
changes Airavata makes itself."
+      >
+        <button onClick={() => void first.reload()} disabled={first.loading}>
+          Refresh
+        </button>
+      </PageHead>
+
+      <Card>
+        <form
+          className="row"
+          style={{ alignItems: "flex-end" }}
+          onSubmit={(e) => {
+            e.preventDefault();
+            if (!badRange) setApplied(draft);
+          }}
+        >
+          <Field label="User id">
+            <input
+              style={{ minWidth: 240 }}
+              placeholder="cilogon:12345, root, sa:ci, system"
+              value={draft.userId}
+              onChange={(e) => set("userId", e.target.value)}
+            />
+          </Field>
+          <Field label="Record type">
+            <select value={draft.entityType} onChange={(e) => 
set("entityType", e.target.value)}>
+              <option value="">All</option>
+              {types.data?.map((t) => (
+                <option key={t} value={t}>
+                  {t}
+                </option>
+              ))}
+            </select>
+          </Field>
+          <Field label="From">
+            <input type="date" value={draft.from} max={draft.to || undefined} 
onChange={(e) => set("from", e.target.value)} />
+          </Field>
+          <Field label="To">
+            <input type="date" value={draft.to} min={draft.from || undefined} 
onChange={(e) => set("to", e.target.value)} />
+          </Field>
+          <button className="primary" type="submit" disabled={badRange}>
+            Apply
+          </button>
+          <button
+            type="button"
+            disabled={!filtered && JSON.stringify(draft) === 
JSON.stringify(NO_FILTERS)}
+            onClick={() => {
+              setDraft(NO_FILTERS);
+              setApplied(NO_FILTERS);
+            }}
+          >
+            Clear
+          </button>
+        </form>
+        {badRange && <p className="small muted">&ldquo;From&rdquo; must not be 
after &ldquo;To&rdquo;.</p>}
+      </Card>
+
+      <Alert>{first.error || types.error || moreError}</Alert>
+      <Card flush>
+        <Table
+          rows={rows}
+          rowKey={(e) => String(e.id)}
+          empty={filtered ? "No events match these filters." : "Nothing has 
been recorded yet."}
+          columns={[
+            {
+              header: "When",
+              cell: (e) => <span 
className="small">{formatTime(e.occurredAt)}</span>,
+            },
+            {
+              header: "User",
+              cell: (e) =>
+                e.actor === "system" ? <span className="muted">system</span> : 
<code className="small">{e.actor}</code>,
+            },
+            { header: "Action", cell: (e) => <StatusBadge status={e.action} /> 
},
+            { header: "Record type", cell: (e) => e.entityType },
+            {
+              header: "Record id",
+              cell: (e) => (e.entityId ? <code 
className="small">{e.entityId}</code> : <span className="muted">—</span>),
+            },
+            {
+              header: "Changed fields",
+              cell: (e) => (e.changedFields ? <code 
className="small">{e.changedFields}</code> : <span className="muted">—</span>),
+            },
+          ]}
+        />
+        {cursor !== null && (
+          <div className="row" style={{ justifyContent: "center", padding: 12 
}}>
+            <button onClick={() => void loadMore()} disabled={loadingMore}>
+              {loadingMore ? "Loading…" : "Load more"}
+            </button>
+          </div>
+        )}
+      </Card>
+    </div>
+  );
+}
diff --git a/dashboard/src/components/Icons.tsx 
b/dashboard/src/components/Icons.tsx
index 0cdc12ddeb..079ca05160 100644
--- a/dashboard/src/components/Icons.tsx
+++ b/dashboard/src/components/Icons.tsx
@@ -50,6 +50,7 @@ export type IconName =
   | "shield"
   | "user"
   | "bot"
+  | "history"
   | "logout"
   | "folder"
   | "close";
@@ -128,6 +129,12 @@ const PATHS: Record<IconName, React.ReactNode> = {
       <path d="M12 8V4M8 4h8M9 13v2M15 13v2M2 14h2M20 14h2" />
     </>
   ),
+  history: (
+    <>
+      <path d="M3 12a9 9 0 1 0 3-6.7L3 8" />
+      <path d="M3 3v5h5M12 7v5l3 2" />
+    </>
+  ),
   logout: <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 
12H9" />,
   folder: <path d="M3 6.5A1.5 1.5 0 0 1 4.5 5h4.6l2 2.5h8.4A1.5 1.5 0 0 1 21 
9v9.5a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 18.5z" />,
   close: <path d="M6 6l12 12M18 6 6 18" />,
diff --git a/dashboard/src/components/Shell.tsx 
b/dashboard/src/components/Shell.tsx
index bf0afe2452..39b939be04 100644
--- a/dashboard/src/components/Shell.tsx
+++ b/dashboard/src/components/Shell.tsx
@@ -12,6 +12,7 @@ import { InteractiveAuthDialog } from "./InteractiveAuth";
 const ADMIN_NAV: NavItem[] = [
   { href: "/users/", label: "Users", icon: "user" },
   { href: "/service-accounts/", label: "Service accounts", icon: "bot" },
+  { href: "/audit/", label: "Audit log", icon: "history" },
 ];
 
 const NAV: NavItem[] = [
diff --git a/dashboard/src/components/ui.tsx b/dashboard/src/components/ui.tsx
index a4f41311db..fd3ac9527b 100644
--- a/dashboard/src/components/ui.tsx
+++ b/dashboard/src/components/ui.tsx
@@ -238,6 +238,10 @@ const STATUS_TONE: Record<string, string> = {
   TIME_LIMIT: "danger",
   READ: "",
   WRITE: "info",
+  CREATE: "ok",
+  UPSERT: "info",
+  UPDATE: "info",
+  DELETE: "danger",
   ACTIVE: "ok",
   INACTIVE: "warn",
   SUSPENDED: "danger",
diff --git a/dashboard/src/lib/types.ts b/dashboard/src/lib/types.ts
index acf2339045..3f5fcbfa95 100644
--- a/dashboard/src/lib/types.ts
+++ b/dashboard/src/lib/types.ts
@@ -405,3 +405,21 @@ export interface Task {
   // Kind-specific fields; rendered generically.
   [key: string]: unknown;
 }
+
+// Audit log (admin only): GET /api/v1/audit-events
+export type AuditAction = "CREATE" | "UPDATE" | "DELETE" | "UPSERT";
+
+export interface AuditEvent {
+  id: number;
+  occurredAt: number;
+  actor: string; // a user id, "root", "sa:<name>", or "system"
+  action: AuditAction;
+  entityType: string; // the table, e.g. "processes"
+  entityId: string;
+  changedFields: string; // comma-separated; empty unless an update named its 
columns
+}
+
+export interface AuditEventPage {
+  items: AuditEvent[];
+  nextCursor: number | null;
+}
diff --git a/docs/audit.md b/docs/audit.md
new file mode 100644
index 0000000000..d35c72d573
--- /dev/null
+++ b/docs/audit.md
@@ -0,0 +1,75 @@
+# Audit log
+
+Airavata records every change made to a record: who made it, what they did, 
and to which record. Administrators read the log from the **Audit log** page of 
the dashboard or from the API.
+
+## What is recorded
+
+One event is written each time a record is created, updated or deleted, 
whatever caused it: a person using the dashboard, a script holding a token, or 
Airavata itself.
+
+| Field | Meaning |
+|---|---|
+| `occurredAt` | When it happened, in milliseconds since the epoch. |
+| `actor` | Who did it: a user id such as `cilogon:12345`, `root`, a service 
account `sa:<name>`, or `system`. |
+| `action` | `CREATE`, `UPDATE`, `DELETE`, or `UPSERT` for a write that 
inserts the record or updates it if it exists. |
+| `entityType` | The kind of record, such as `processes`, `groups` or 
`scp_data_storages`. |
+| `entityId` | The record's id. |
+| `changedFields` | For an update that named its columns, which ones. |
+
+`system` is the actor for changes with no person behind them, such as Airavata 
moving a process from one status to the next as its job progresses.
+
+The log records **that** a record changed, never the values. Records hold 
secrets such as SSH passwords and token digests, and the log would otherwise be 
a second place to protect them. To see what a record contains now, read it. A 
deleted record's last contents are not kept.
+
+Reading is not recorded, and neither is a request that fails or changes 
nothing.
+
+An event is written in the same transaction as the change it describes. A 
change that is rolled back leaves no event, and a change cannot commit without 
one. Events are never edited or removed by Airavata, and they outlive the users 
and records they refer to.
+
+When a record is deleted, anything the database removes along with it, such as 
a group's memberships, is not listed separately. Only the record you deleted 
has an event.
+
+## Reading the log
+
+Only `ADMIN` and `SUPER_ADMIN` can read it, because it names what every user 
did.
+
+```
+GET /api/v1/audit-events
+```
+
+Events come back newest first. Every filter is optional and they combine.
+
+| Parameter | Meaning |
+|---|---|
+| `userId` | Only events by this actor. |
+| `entityType` | Only events on this kind of record. |
+| `from` | Only events at or after this time (milliseconds since the epoch). |
+| `to` | Only events before this time. Must be after `from`. |
+| `limit` | Page size, 1 to 500. Defaults to 100. |
+| `before` | The previous response's `nextCursor`, to read the next page. |
+
+```bash
+# What did alice change on 11 November 2026 (UTC)?
+curl -s -H "Authorization: Bearer $TOKEN" \
+  
"localhost:9095/api/v1/audit-events?userId=cilogon:12345&entityType=processes&from=1794355200000&to=1794441600000"
+```
+
+```json
+{
+  "items": [
+    {
+      "id": 4182,
+      "occurredAt": 1794390211042,
+      "actor": "cilogon:12345",
+      "action": "CREATE",
+      "entityType": "processes",
+      "entityId": "7f87d3e9-f81c-4d44-bad0-0a8c3e8393e7",
+      "changedFields": ""
+    }
+  ],
+  "nextCursor": null
+}
+```
+
+When `nextCursor` is not null there are more events: pass it as `before` to 
get them. `GET /api/v1/audit-events/entity-types` lists the values `entityType` 
accepts.
+
+## In the dashboard
+
+Administrators see **Audit log** under the admin pages. Filter by user id, 
record type and date range, then page back through older events.
+The date range uses your browser's time zone.
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 40c7d7e49b..b969f1e9a0 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -77,6 +77,9 @@ tags:
     description: User accounts.
   - name: Groups
     description: Groups and their membership; the subject of a group share.
+  - name: Audit
+    description: >-
+      The record of who changed what. Admin only. See docs/audit.md.
   - name: Service Accounts
     description: >-
       Non-human users that authenticate with an Airavata-issued, expiring 
token.
@@ -443,6 +446,75 @@ paths:
         "502": { $ref: "#/components/responses/BadGateway" }
         "500": { $ref: "#/components/responses/InternalError" }
 
+  # ------------------------------------------------------------ Audit log
+
+  /api/v1/audit-events:
+    get:
+      tags: [Audit]
+      summary: List audit events
+      description: |
+        Requires `ADMIN` or `SUPER_ADMIN` authority. Returns the changes users 
and the
+        system have made to records, newest first. Every filter is optional 
and they
+        combine with AND. See docs/audit.md.
+
+        Page through the log by passing the previous response's `nextCursor` 
as `before`.
+      operationId: listAuditEvents
+      parameters:
+        - name: userId
+          in: query
+          description: Only events by this actor — a user id, `root`, 
`sa:<name>` or `system`.
+          schema: { type: string }
+        - name: entityType
+          in: query
+          description: Only events on this kind of record, such as 
`processes`. See `/api/v1/audit-events/entity-types`.
+          schema: { type: string }
+        - name: from
+          in: query
+          description: Only events at or after this time, in milliseconds 
since the epoch.
+          schema: { type: integer, format: int64, minimum: 0 }
+        - name: to
+          in: query
+          description: Only events before this time (exclusive), in 
milliseconds since the epoch. Must be after `from`.
+          schema: { type: integer, format: int64, minimum: 0 }
+        - name: before
+          in: query
+          description: Only events with an id below this one; the previous 
page's `nextCursor`.
+          schema: { type: integer, format: int64, minimum: 0 }
+        - name: limit
+          in: query
+          description: Page size.
+          schema: { type: integer, minimum: 1, maximum: 500, default: 100 }
+      responses:
+        "200":
+          description: One page of events.
+          content:
+            application/json:
+              schema: { $ref: "#/components/schemas/AuditEventPage" }
+        "400": { $ref: "#/components/responses/BadRequest" }
+        "401": { $ref: "#/components/responses/Unauthorized" }
+        "403": { $ref: "#/components/responses/Forbidden" }
+        "502": { $ref: "#/components/responses/BadGateway" }
+        "500": { $ref: "#/components/responses/InternalError" }
+
+  /api/v1/audit-events/entity-types:
+    get:
+      tags: [Audit]
+      summary: List audited entity types
+      description: Requires `ADMIN` or `SUPER_ADMIN` authority. The values 
`entityType` accepts, for the kinds of record the log holds events for.
+      operationId: listAuditEntityTypes
+      responses:
+        "200":
+          description: Entity types, alphabetically.
+          content:
+            application/json:
+              schema:
+                type: array
+                items: { type: string }
+        "401": { $ref: "#/components/responses/Unauthorized" }
+        "403": { $ref: "#/components/responses/Forbidden" }
+        "502": { $ref: "#/components/responses/BadGateway" }
+        "500": { $ref: "#/components/responses/InternalError" }
+
   # --------------------------------------------------------------- Groups
 
   /api/v1/groups:
@@ -3367,6 +3439,34 @@ components:
           maximum: 365
           description: How long the token lives from now. Defaults to 90.
 
+    AuditEvent:
+      type: object
+      description: >-
+        One change to one record. It names the record and what was done, never 
the values.
+      properties:
+        id: { type: integer, format: int64 }
+        occurredAt: { type: integer, format: int64, description: Milliseconds 
since the epoch. }
+        actor:
+          type: string
+          description: The user id, `root` or `sa:<name>` that made the 
change, or `system` when no caller was behind it.
+        action: { type: string, enum: [CREATE, UPDATE, DELETE, UPSERT] }
+        entityType: { type: string, description: "The kind of record, such as 
`processes`." }
+        entityId: { type: string, description: The record's id. A composite 
key is joined with `:`. Empty when the change addressed rows by a condition 
rather than by key. }
+        changedFields: { type: string, description: "Comma-separated columns 
an update set, when the write named them; otherwise empty." }
+      required: [id, occurredAt, actor, action, entityType, entityId, 
changedFields]
+
+    AuditEventPage:
+      type: object
+      properties:
+        items:
+          type: array
+          items: { $ref: "#/components/schemas/AuditEvent" }
+        nextCursor:
+          type: [integer, "null"]
+          format: int64
+          description: Pass as `before` to fetch the next page; null on the 
last page.
+      required: [items, nextCursor]
+
     ServiceAccountResponse:
       type: object
       description: The read model for a service account. It never carries the 
token.
diff --git a/internal/app/app.go b/internal/app/app.go
index 2411f99176..eda686d2c8 100644
--- a/internal/app/app.go
+++ b/internal/app/app.go
@@ -36,6 +36,8 @@ import (
 
        applicationrepo "github.com/apache/airavata/api/application/repository"
        applicationsvc "github.com/apache/airavata/api/application/service"
+       auditrepo "github.com/apache/airavata/api/audit/repository"
+       auditsvc "github.com/apache/airavata/api/audit/service"
        computerepo "github.com/apache/airavata/api/compute/repository"
        computesvc "github.com/apache/airavata/api/compute/service"
        credentialsrepo "github.com/apache/airavata/api/credentials/repository"
@@ -64,6 +66,9 @@ type Services struct {
        Config config.Config
        DB     *gorm.DB
 
+       // Audit log.
+       Audit *auditsvc.EventService
+
        // IAM.
        User        *iamsvc.UserService
        Group       *iamsvc.GroupService
@@ -116,6 +121,7 @@ type Services struct {
 }
 
 type Repositories struct {
+       AuditEvents             *auditrepo.EventRepository
        Users                   *iamrepo.UserRepository
        Groups                  *iamrepo.GroupRepository
        GroupMembers            *iamrepo.GroupMemberRepository
@@ -149,6 +155,7 @@ func NewRepositories(db *gorm.DB) *Repositories {
                Groups:                  iamrepo.NewGroupRepository(db),
                GroupMembers:            iamrepo.NewGroupMemberRepository(db),
                ServiceAccounts:         
iamrepo.NewServiceAccountRepository(db),
+               AuditEvents:             auditrepo.NewEventRepository(db),
                SSHCredentials:          
credentialsrepo.NewSSHCredentialRepository(db),
                SlurmClusters:           
computerepo.NewSlurmClusterRepository(db),
                ClusterPartitions:       
computerepo.NewClusterPartitionRepository(db),
@@ -236,6 +243,8 @@ func NewServices(cfg config.Config, db *gorm.DB, repos 
*Repositories, workflowBa
                Config: cfg,
                DB:     db,
 
+               Audit: auditsvc.NewEventService(repos.AuditEvents),
+
                User:        iamsvc.NewUserService(db, users),
                Group:       iamsvc.NewGroupService(db, groups, groupMembers, 
users, shares),
                GroupMember: iamsvc.NewGroupMemberService(db, groups, 
groupMembers, users),
diff --git a/internal/audit/audit.go b/internal/audit/audit.go
new file mode 100644
index 0000000000..87bd96f31f
--- /dev/null
+++ b/internal/audit/audit.go
@@ -0,0 +1,191 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+// Package audit records every change made to a persistent record.
+//
+// It hooks the data layer rather than the HTTP layer, so a change is recorded 
whichever
+// way it was made — an API call, the execution engine, a bootstrap step — and 
a request
+// that changes nothing leaves nothing behind.
+package audit
+
+import (
+       "fmt"
+       "reflect"
+       "sort"
+       "strings"
+       "time"
+       "unicode/utf8"
+
+       "gorm.io/gorm"
+       "gorm.io/gorm/clause"
+
+       "github.com/apache/airavata/api/audit/model"
+       "github.com/apache/airavata/internal/auth"
+)
+
+const pluginName = "airavata:audit"
+
+// Register makes gdb record an Event for every row its repositories create, 
update or
+// delete. Call it once per connection, before the first write.
+//
+// The Event is inserted on the same connection as the change, so inside a 
transaction
+// the two commit or roll back together: no change goes unrecorded, and none 
is recorded
+// that did not happen. The corollary is that a failure to write the Event 
fails the
+// change itself. An audit trail that can silently lose entries is not one.
+//
+// The caller is read from the context the repository was given. A repository 
call made
+// without one — the execution engine's, for instance — is recorded as 
SystemActor.
+//
+// Two things are not seen. Rows removed by a foreign key's ON DELETE CASCADE 
are removed
+// by the database, so only the record that was deleted is recorded. And a 
write made
+// through raw SQL bypasses the model entirely.
+func Register(gdb *gorm.DB) error {
+       return gdb.Use(plugin{})
+}
+
+type plugin struct{}
+
+func (plugin) Name() string { return pluginName }
+
+func (plugin) Initialize(gdb *gorm.DB) error {
+       cb := gdb.Callback()
+       if err := 
cb.Create().After("gorm:create").Register(pluginName+":create", 
record(model.ActionCreate)); err != nil {
+               return err
+       }
+       if err := 
cb.Update().After("gorm:update").Register(pluginName+":update", 
record(model.ActionUpdate)); err != nil {
+               return err
+       }
+       return cb.Delete().After("gorm:delete").Register(pluginName+":delete", 
record(model.ActionDelete))
+}
+
+func record(action model.Action) func(*gorm.DB) {
+       return func(tx *gorm.DB) {
+               stmt := tx.Statement
+               switch {
+               case tx.Error != nil, tx.DryRun, stmt.Schema == nil:
+                       return
+               case stmt.Schema.Table == (model.Event{}).TableName():
+                       // The log is not itself audited.
+                       return
+               case tx.RowsAffected == 0:
+                       // A write that changed nothing — an update that 
matched no row, an
+                       // insert that lost to ON CONFLICT DO NOTHING — is not 
a change.
+                       return
+               }
+
+               act := action
+               if _, ok := stmt.Clauses[clause.OnConflict{}.Name()]; ok && 
action == model.ActionCreate {
+                       act = model.ActionUpsert
+               }
+
+               actor := model.SystemActor
+               if p := auth.FromContext(stmt.Context); p != nil && p.Name != 
"" {
+                       actor = truncate(p.Name, 255)
+               }
+
+               now := time.Now().UnixMilli()
+               changed := changedFields(stmt)
+               ids := entityIDs(tx)
+
+               events := make([]model.Event, 0, len(ids))
+               for _, id := range ids {
+                       events = append(events, model.Event{
+                               OccurredAt:    now,
+                               Actor:         actor,
+                               Action:        act,
+                               EntityType:    truncate(stmt.Schema.Table, 64),
+                               EntityID:      truncate(id, 255),
+                               ChangedFields: changed,
+                       })
+               }
+               if len(events) == 0 {
+                       return
+               }
+
+               // A fresh statement on the same connection and context, so the 
insert joins the
+               // caller's transaction without inheriting its conditions.
+               if err := tx.Session(&gorm.Session{NewDB: 
true}).Create(&events).Error; err != nil {
+                       _ = tx.AddError(err)
+               }
+       }
+}
+
+// entityIDs returns the primary key of each row the statement wrote. A 
statement that
+// addressed rows by a condition and carries no key yields one empty id, so 
the change is
+// still recorded.
+func entityIDs(tx *gorm.DB) []string {
+       stmt := tx.Statement
+       rv := stmt.ReflectValue
+       if !rv.IsValid() {
+               return []string{""}
+       }
+
+       if rv.Kind() == reflect.Slice || rv.Kind() == reflect.Array {
+               out := make([]string, 0, rv.Len())
+               for i := 0; i < rv.Len(); i++ {
+                       out = append(out, keyOf(stmt, 
reflect.Indirect(rv.Index(i))))
+               }
+               return out
+       }
+       return []string{keyOf(stmt, rv)}
+}
+
+// keyOf joins a row's non-zero primary key columns with ":".
+func keyOf(stmt *gorm.Statement, row reflect.Value) string {
+       if !row.IsValid() || row.Kind() != reflect.Struct {
+               return ""
+       }
+       parts := make([]string, 0, len(stmt.Schema.PrimaryFields))
+       for _, f := range stmt.Schema.PrimaryFields {
+               v, zero := f.ValueOf(stmt.Context, row)
+               if zero {
+                       continue
+               }
+               parts = append(parts, fmt.Sprint(v))
+       }
+       return strings.Join(parts, ":")
+}
+
+// changedFields names the columns an update set, when the write said so: 
Updates with a
+// map, or a Select. Values are never read.
+func changedFields(stmt *gorm.Statement) string {
+       var cols []string
+       if m, ok := stmt.Dest.(map[string]any); ok {
+               for k := range m {
+                       cols = append(cols, k)
+               }
+               sort.Strings(cols)
+       } else {
+               cols = append(cols, stmt.Selects...)
+       }
+       return truncate(strings.Join(cols, ","), 1024)
+}
+
+// truncate cuts s to at most n bytes without splitting a character.
+func truncate(s string, n int) string {
+       if len(s) <= n {
+               return s
+       }
+       s = s[:n]
+       for !utf8.ValidString(s) {
+               s = s[:len(s)-1]
+       }
+       return s
+}
diff --git a/internal/db/migrate.go b/internal/db/migrate.go
index 4dae12b3b1..471762c919 100644
--- a/internal/db/migrate.go
+++ b/internal/db/migrate.go
@@ -25,6 +25,7 @@ import (
        "gorm.io/gorm"
 
        applicationmodel "github.com/apache/airavata/api/application/model"
+       auditmodel "github.com/apache/airavata/api/audit/model"
        computemodel "github.com/apache/airavata/api/compute/model"
        credentialsmodel "github.com/apache/airavata/api/credentials/model"
        datamodel "github.com/apache/airavata/api/data/model"
@@ -110,6 +111,10 @@ func Entities() []any {
 
                // The secrets a process's job is handed so its Linkspan can 
link back.
                &processmodel.ProcessLink{},
+
+               // The append-only record of what callers did. It references 
nothing, so it
+               // outlives the users and resources it describes.
+               &auditmodel.Event{},
        }
 }
 
diff --git a/internal/db/migrations/0014_audit_events.sql 
b/internal/db/migrations/0014_audit_events.sql
new file mode 100644
index 0000000000..1898b2ec0b
--- /dev/null
+++ b/internal/db/migrations/0014_audit_events.sql
@@ -0,0 +1,13 @@
+-- The audit log: one row per change to a record, recording who made it, what 
was done
+-- and to which record. Written by the audit plugin (internal/audit) in the 
same
+-- transaction as the change. Append-only, and deliberately free of foreign 
keys so the
+-- trail outlives the users and records it describes. The DDL is what 
AutoMigrate emits
+-- for audit/model.Event — see TestBaselineMigrationMatchesAutoMigrate.
+
+CREATE TABLE "audit_events" ("id" bigserial,"occurred_at" bigint NOT 
NULL,"actor" varchar(255) NOT NULL,"action" varchar(10) NOT NULL,"entity_type" 
varchar(64) NOT NULL,"entity_id" varchar(255) NOT NULL DEFAULT 
'',"changed_fields" varchar(1024) NOT NULL DEFAULT '',PRIMARY KEY ("id"));
+
+CREATE INDEX IF NOT EXISTS "idx_audit_events_entity" ON "audit_events" 
("entity_type","entity_id","occurred_at");
+
+CREATE INDEX IF NOT EXISTS "idx_audit_events_actor" ON "audit_events" 
("actor","occurred_at");
+
+CREATE INDEX IF NOT EXISTS "idx_audit_events_occurred_at" ON "audit_events" 
("occurred_at");
diff --git a/internal/server/audit_test.go b/internal/server/audit_test.go
new file mode 100644
index 0000000000..bebd6095ae
--- /dev/null
+++ b/internal/server/audit_test.go
@@ -0,0 +1,250 @@
+/**
+*
+* Licensed to the Apache Software Foundation (ASF) under one
+* or more contributor license agreements. See the NOTICE file
+* distributed with this work for additional information
+* regarding copyright ownership. The ASF licenses this file
+* to you under the Apache License, Version 2.0 (the
+* "License"); you may not use this file except in compliance
+* with the License. You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+ */
+
+package server_test
+
+import (
+       "context"
+       "encoding/json"
+       "errors"
+       "fmt"
+       "net/http"
+       "strings"
+       "testing"
+
+       auditmodel "github.com/apache/airavata/api/audit/model"
+       iammodel "github.com/apache/airavata/api/iam/model"
+       "github.com/apache/airavata/internal/auth"
+       "gorm.io/gorm"
+)
+
+func (h *harness) auditEvents(entityType string) []auditmodel.Event {
+       h.t.Helper()
+       var evs []auditmodel.Event
+       if err := h.db.Where("entity_type = ?", 
entityType).Order("id").Find(&evs).Error; err != nil {
+               h.t.Fatalf("read audit events: %v", err)
+       }
+       return evs
+}
+
+func TestAuditRecordsCreateUpdateDeleteWithActor(t *testing.T) {
+       h := newHarness(t)
+
+       groupID := h.seedGroup("g1", tokenAlice)
+       h.mustDo("PUT", "/api/v1/groups/"+groupID, tokenAlice, 
map[string]any{"groupName": "g2"}, http.StatusOK)
+       h.mustDo("DELETE", "/api/v1/groups/"+groupID, tokenAlice, nil, 
http.StatusNoContent)
+
+       var got []string
+       for _, e := range h.auditEvents("groups") {
+               if e.Actor != "alice" || e.EntityID != groupID || e.OccurredAt 
== 0 {
+                       t.Errorf("unexpected event: %+v", e)
+               }
+               got = append(got, string(e.Action))
+       }
+       want := []string{"CREATE", "UPDATE", "DELETE"}
+       if len(got) != len(want) {
+               t.Fatalf("group actions = %v, want %v", got, want)
+       }
+       for i := range want {
+               if got[i] != want[i] {
+                       t.Fatalf("group actions = %v, want %v", got, want)
+               }
+       }
+}
+
+func TestAuditIgnoresReadsAndRejectedRequests(t *testing.T) {
+       h := newHarness(t)
+       h.do("GET", "/api/v1/groups", tokenAlice, nil)
+       h.do("DELETE", "/api/v1/groups/does-not-exist", tokenAlice, nil)
+       h.do("POST", "/api/v1/groups", tokenAlice, map[string]any{"groupName": 
""})
+
+       var n int64
+       h.db.Model(&auditmodel.Event{}).Where("entity_type = ?", 
"groups").Count(&n)
+       if n != 0 {
+               t.Errorf("got %d group events, want none", n)
+       }
+}
+
+func TestAuditAttributesContextlessWritesToSystem(t *testing.T) {
+       h := newHarness(t)
+       if err := h.db.Create(&iammodel.User{ID: "sys-made", CreatedAt: 
1}).Error; err != nil {
+               t.Fatal(err)
+       }
+       evs := h.auditEvents("users")
+       last := evs[len(evs)-1]
+       if last.Actor != auditmodel.SystemActor || last.EntityID != "sys-made" 
|| last.Action != auditmodel.ActionCreate {
+               t.Errorf("unexpected event: %+v", last)
+       }
+
+       ctx := auth.WithPrincipal(context.Background(), &auth.Principal{Name: 
"carol"})
+       if err := h.db.WithContext(ctx).Model(&iammodel.User{ID: 
"sys-made"}).Update("created_at", 2).Error; err != nil {
+               t.Fatal(err)
+       }
+       evs = h.auditEvents("users")
+       last = evs[len(evs)-1]
+       if last.Actor != "carol" || last.Action != auditmodel.ActionUpdate || 
last.ChangedFields != "created_at" {
+               t.Errorf("unexpected update event: %+v", last)
+       }
+}
+
+func TestAuditRollsBackWithTheChange(t *testing.T) {
+       h := newHarness(t)
+       boom := errors.New("boom")
+       err := h.db.Transaction(func(tx *gorm.DB) error {
+               if err := tx.Create(&iammodel.User{ID: "rolled-back", 
CreatedAt: 1}).Error; err != nil {
+                       return err
+               }
+               return boom
+       })
+       if !errors.Is(err, boom) {
+               t.Fatalf("err = %v", err)
+       }
+       var n int64
+       h.db.Model(&auditmodel.Event{}).Where("entity_id = ?", 
"rolled-back").Count(&n)
+       if n != 0 {
+               t.Errorf("a rolled-back change left %d audit rows", n)
+       }
+}
+
+type auditPage struct {
+       Items []struct {
+               ID         int64  `json:"id"`
+               OccurredAt int64  `json:"occurredAt"`
+               Actor      string `json:"actor"`
+               Action     string `json:"action"`
+               EntityType string `json:"entityType"`
+               EntityID   string `json:"entityId"`
+       } `json:"items"`
+       NextCursor *int64 `json:"nextCursor"`
+}
+
+func (h *harness) auditPage(query string) auditPage {
+       h.t.Helper()
+       rec := h.do("GET", "/api/v1/audit-events"+query, tokenAdmin, nil)
+       if rec.Code != http.StatusOK {
+               h.t.Fatalf("GET audit-events%s: status = %d\nbody: %s", query, 
rec.Code, rec.Body.String())
+       }
+       var out auditPage
+       if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
+               h.t.Fatal(err)
+       }
+       return out
+}
+
+func TestAuditEndpointIsAdminOnly(t *testing.T) {
+       h := newHarness(t)
+       for _, path := range []string{"/api/v1/audit-events", 
"/api/v1/audit-events/entity-types"} {
+               if rec := h.do("GET", path, tokenAlice, nil); rec.Code != 
http.StatusForbidden {
+                       t.Errorf("%s as a user: status = %d, want 403", path, 
rec.Code)
+               }
+               if rec := h.do("GET", path, "", nil); rec.Code != 
http.StatusUnauthorized {
+                       t.Errorf("%s anonymous: status = %d, want 401", path, 
rec.Code)
+               }
+               if rec := h.do("GET", path, tokenAdmin, nil); rec.Code != 
http.StatusOK {
+                       t.Errorf("%s as an admin: status = %d, want 200", path, 
rec.Code)
+               }
+       }
+}
+
+func TestAuditEndpointFilters(t *testing.T) {
+       h := newHarness(t)
+       h.seedGroup("a-group", tokenAlice)
+       h.seedGroup("b-group", tokenBob)
+       h.seedGroup("b-group-2", tokenBob)
+
+       if got := h.auditPage("?userId=bob&entityType=groups").Items; len(got) 
!= 2 {
+               t.Errorf("bob's group events = %d, want 2", len(got))
+       }
+       for _, e := range h.auditPage("?userId=alice").Items {
+               if e.Actor != "alice" {
+                       t.Errorf("userId filter returned %+v", e)
+               }
+       }
+       // A second type, so the entity-type filter has something to exclude.
+       if n := len(h.auditPage("?entityType=users").Items); n == 0 {
+               t.Fatal("seeded users should have events")
+       }
+       for _, e := range h.auditPage("?entityType=users").Items {
+               if e.EntityType != "users" {
+                       t.Errorf("entityType filter returned %+v", e)
+               }
+       }
+
+       all := h.auditPage("")
+       if all.Items[0].ID < all.Items[len(all.Items)-1].ID {
+               t.Error("events should be newest first")
+       }
+
+       // Dates: from is inclusive, to exclusive.
+       t0 := all.Items[len(all.Items)-1].OccurredAt
+       t1 := all.Items[0].OccurredAt
+       if n := len(h.auditPage(fmt.Sprintf("?from=%d", t1+1)).Items); n != 0 {
+               t.Errorf("from after every event returned %d", n)
+       }
+       if n := len(h.auditPage(fmt.Sprintf("?to=%d", t0)).Items); n != 0 {
+               t.Errorf("to at the first event returned %d, want none 
(exclusive)", n)
+       }
+       if n := len(h.auditPage(fmt.Sprintf("?from=%d&to=%d", t0, 
t1+1)).Items); n != len(all.Items) {
+               t.Errorf("full range returned %d, want %d", n, len(all.Items))
+       }
+
+       types := h.do("GET", "/api/v1/audit-events/entity-types", tokenAdmin, 
nil).Body.String()
+       if !strings.Contains(types, `"groups"`) || !strings.Contains(types, 
`"users"`) {
+               t.Errorf("entity types = %s", types)
+       }
+}
+
+func TestAuditEndpointPagesWithCursor(t *testing.T) {
+       h := newHarness(t)
+       for i := 0; i < 5; i++ {
+               h.seedGroup(fmt.Sprintf("g%d", i), tokenAlice)
+       }
+
+       seen := map[int64]bool{}
+       query := "?entityType=groups&limit=2"
+       for pages := 0; ; pages++ {
+               if pages > 5 {
+                       t.Fatal("paging did not terminate")
+               }
+               p := h.auditPage(query)
+               for _, e := range p.Items {
+                       if seen[e.ID] {
+                               t.Fatalf("event %d returned twice", e.ID)
+                       }
+                       seen[e.ID] = true
+               }
+               if p.NextCursor == nil {
+                       break
+               }
+               query = fmt.Sprintf("?entityType=groups&limit=2&before=%d", 
*p.NextCursor)
+       }
+       if len(seen) != 5 {
+               t.Errorf("paged through %d events, want 5", len(seen))
+       }
+}
+
+func TestAuditEndpointRejectsBadQuery(t *testing.T) {
+       h := newHarness(t)
+       for _, q := range []string{"?limit=0", "?limit=100000", "?from=abc", 
"?from=10&to=5"} {
+               if rec := h.do("GET", "/api/v1/audit-events"+q, tokenAdmin, 
nil); rec.Code != http.StatusBadRequest {
+                       t.Errorf("%s: status = %d, want 400", q, rec.Code)
+               }
+       }
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index 5ca3d91516..14f48f6fce 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -31,6 +31,7 @@ import (
        "github.com/apache/airavata/internal/httpx"
 
        applicationctl "github.com/apache/airavata/api/application/controller"
+       auditctl "github.com/apache/airavata/api/audit/controller"
        computectl "github.com/apache/airavata/api/compute/controller"
        credentialsctl "github.com/apache/airavata/api/credentials/controller"
        datactl "github.com/apache/airavata/api/data/controller"
@@ -46,6 +47,7 @@ import (
 // over the same database.
 func New(cfg config.Config, svcs *app.Services, introspector 
auth.Introspector) http.Handler {
        mux := http.NewServeMux()
+       auditctl.NewEventController(svcs.Audit).Register(mux)
        iamctl.NewUserController(svcs.User).Register(mux)
        iamctl.NewGroupController(svcs.Group).Register(mux)
        iamctl.NewGroupMemberController(svcs.GroupMember).Register(mux)
diff --git a/internal/server/server_test.go b/internal/server/server_test.go
index 529ff267d6..0ca45c1142 100644
--- a/internal/server/server_test.go
+++ b/internal/server/server_test.go
@@ -36,6 +36,7 @@ import (
        "gorm.io/gorm/logger"
 
        "github.com/apache/airavata/internal/app"
+       "github.com/apache/airavata/internal/audit"
        "github.com/apache/airavata/internal/auth"
        "github.com/apache/airavata/internal/config"
        "github.com/apache/airavata/internal/db"
@@ -90,6 +91,9 @@ func newHarness(t *testing.T) *harness {
        if err := db.AutoMigrate(gdb); err != nil {
                t.Fatalf("automigrate: %v", err)
        }
+       if err := audit.Register(gdb); err != nil {
+               t.Fatalf("register audit: %v", err)
+       }
 
        // Every principal must have a users row: ownership resolution looks 
the caller up
        // by principal name, and an unregistered caller cannot own anything.
diff --git a/website/sidebars.js b/website/sidebars.js
index ed5db6d3e3..11a9898df2 100644
--- a/website/sidebars.js
+++ b/website/sidebars.js
@@ -14,7 +14,7 @@ const sidebars = {
       type: 'category',
       label: 'Security',
       collapsed: false,
-      items: ['auth', 'interactive-auth', 'sharing'],
+      items: ['auth', 'interactive-auth', 'sharing', 'audit'],
     },
     {
       type: 'category',

Reply via email to