This is an automated email from the ASF dual-hosted git repository.
DImuthuUpe pushed a commit to branch simple-audit
in repository https://gitbox.apache.org/repos/asf/airavata.git
The following commit(s) were added to refs/heads/simple-audit by this push:
new 7048bb4e89 Added audit log dashboard with filters
7048bb4e89 is described below
commit 7048bb4e890d5259f29161e005de0eb618e5090b
Author: DImuthuUpe <[email protected]>
AuthorDate: Wed Nov 11 09:10:03 2026 -0500
Added audit log dashboard with filters
---
api/audit/controller/event.go | 68 +++++++++++++
api/audit/dto/event.go | 124 +++++++++++++++++++++++
api/audit/repository/event.go | 71 +++++++++++++
api/audit/service/event.go | 75 ++++++++++++++
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/server/audit_test.go | 129 ++++++++++++++++++++++++
internal/server/server.go | 2 +
website/sidebars.js | 2 +-
15 files changed, 883 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/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/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">“From” must not be
after “To”.</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/server/audit_test.go b/internal/server/audit_test.go
index 9bb76d23a4..bebd6095ae 100644
--- a/internal/server/audit_test.go
+++ b/internal/server/audit_test.go
@@ -22,8 +22,11 @@ package server_test
import (
"context"
+ "encoding/json"
"errors"
+ "fmt"
"net/http"
+ "strings"
"testing"
auditmodel "github.com/apache/airavata/api/audit/model"
@@ -119,3 +122,129 @@ func TestAuditRollsBackWithTheChange(t *testing.T) {
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/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',