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

commit 71094341180ae7ed2592d658c8e4a5d59beb84ce
Author: DImuthuUpe <[email protected]>
AuthorDate: Wed Nov 11 07:41:46 2026 -0500

    Added a simple domain model-based audit support
---
 api/audit/model/event.go                     |  73 ++++++++++
 cmd/airavata-server/main.go                  |   5 +
 internal/audit/audit.go                      | 191 +++++++++++++++++++++++++++
 internal/db/migrate.go                       |   5 +
 internal/db/migrations/0014_audit_events.sql |  13 ++
 internal/server/audit_test.go                | 121 +++++++++++++++++
 internal/server/server_test.go               |   4 +
 7 files changed, 412 insertions(+)

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/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/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..9bb76d23a4
--- /dev/null
+++ b/internal/server/audit_test.go
@@ -0,0 +1,121 @@
+/**
+*
+* 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"
+       "errors"
+       "net/http"
+       "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)
+       }
+}
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.

Reply via email to