Changeset 0.28.0.4 (#176)

This commit is contained in:
2026-03-12 12:12:17 +00:00
parent f5171d3bd3
commit 52bd36ba48
16 changed files with 520 additions and 292 deletions

View File

@@ -1,7 +1,6 @@
package handlers
import (
"context"
"encoding/json"
"fmt"
"log"
@@ -17,6 +16,7 @@ import (
"git.gobha.me/xcaliber/chat-switchboard/database"
"git.gobha.me/xcaliber/chat-switchboard/models"
"git.gobha.me/xcaliber/chat-switchboard/providers"
"git.gobha.me/xcaliber/chat-switchboard/storage"
"git.gobha.me/xcaliber/chat-switchboard/store"
"git.gobha.me/xcaliber/chat-switchboard/tools/search"
)
@@ -25,10 +25,11 @@ type AdminHandler struct {
stores store.Stores
vault *crypto.KeyResolver
uekCache *crypto.UEKCache
objStore storage.ObjectStore
}
func NewAdminHandler(s store.Stores, vault *crypto.KeyResolver, uekCache *crypto.UEKCache) *AdminHandler {
return &AdminHandler{stores: s, vault: vault, uekCache: uekCache}
func NewAdminHandler(s store.Stores, vault *crypto.KeyResolver, uekCache *crypto.UEKCache, objStore storage.ObjectStore) *AdminHandler {
return &AdminHandler{stores: s, vault: vault, uekCache: uekCache, objStore: objStore}
}
// ── User Management ─────────────────────────
@@ -87,6 +88,10 @@ func (h *AdminHandler) CreateUser(c *gin.Context) {
}
if err := h.stores.Users.Create(c.Request.Context(), user); err != nil {
if database.IsUniqueViolation(err) {
c.JSON(http.StatusConflict, gin.H{"error": "username or email already exists"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create user"})
return
}
@@ -105,6 +110,25 @@ func (h *AdminHandler) UpdateUserRole(c *gin.Context) {
return
}
// Guard: prevent demoting the last admin
if req.Role != models.UserRoleAdmin {
user, err := h.stores.Users.GetByID(c.Request.Context(), id)
if err != nil || user == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
return
}
if user.Role == models.UserRoleAdmin {
var adminCount int
database.DB.QueryRowContext(c.Request.Context(),
database.Q(`SELECT COUNT(*) FROM users WHERE role = $1`),
models.UserRoleAdmin).Scan(&adminCount)
if adminCount <= 1 {
c.JSON(http.StatusConflict, gin.H{"error": "cannot demote the last admin"})
return
}
}
}
if err := h.stores.Users.Update(c.Request.Context(), id, map[string]interface{}{"role": req.Role}); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update role"})
return
@@ -215,6 +239,27 @@ func (h *AdminHandler) ResetVault(c *gin.Context) {
func (h *AdminHandler) DeleteUser(c *gin.Context) {
id := c.Param("id")
// Guard: prevent deleting the last admin
user, err := h.stores.Users.GetByID(c.Request.Context(), id)
if err != nil || user == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
return
}
if user.Role == models.UserRoleAdmin {
var adminCount int
database.DB.QueryRowContext(c.Request.Context(),
database.Q(`SELECT COUNT(*) FROM users WHERE role = $1`),
models.UserRoleAdmin).Scan(&adminCount)
if adminCount <= 1 {
c.JSON(http.StatusConflict, gin.H{"error": "cannot delete the last admin"})
return
}
}
// Destroy vault and personal BYOK keys before deleting the user row
h.destroyVault(c, id)
if err := h.stores.Users.Delete(c.Request.Context(), id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete user"})
return
@@ -238,6 +283,17 @@ func (h *AdminHandler) ListGlobalSettings(c *gin.Context) {
func (h *AdminHandler) GetGlobalSetting(c *gin.Context) {
key := c.Param("key")
// If the key is a known policy, read from the policies table first
if _, ok := models.PolicyDefaults[key]; ok {
val, err := h.stores.Policies.Get(c.Request.Context(), key)
if err == nil {
c.JSON(http.StatusOK, gin.H{"key": key, "value": val})
return
}
// Fall through to global_config if not found in policies
}
val, err := h.stores.GlobalConfig.Get(c.Request.Context(), key)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "setting not found"})
@@ -639,8 +695,7 @@ func (h *AdminHandler) fetchModelsForProvider(c *gin.Context, cfg *models.Provid
func (h *AdminHandler) UpdateModelConfig(c *gin.Context) {
id := c.Param("id")
var req struct {
Visibility *string `json:"visibility"`
DisplayName *string `json:"display_name"`
Visibility *string `json:"visibility"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
@@ -712,67 +767,28 @@ func (h *AdminHandler) GetStats(c *gin.Context) {
// NOTE: ListAuditLog and ListAuditActions are in audit.go
func (h *AdminHandler) auditLog(c *gin.Context, action, resourceType, resourceID string, metadata interface{}) {
userID, _ := c.Get("user_id")
uid, _ := userID.(string)
var meta models.JSONMap
// Convert interface{} metadata to map[string]interface{} for the shared helper
var meta map[string]interface{}
if metadata != nil {
b, _ := json.Marshal(metadata)
json.Unmarshal(b, &meta)
}
entry := &models.AuditEntry{
ActorID: &uid,
Action: action,
ResourceType: resourceType,
ResourceID: resourceID,
Metadata: meta,
IPAddress: c.ClientIP(),
UserAgent: c.GetHeader("User-Agent"),
}
if err := h.stores.Audit.Log(context.Background(), entry); err != nil {
log.Printf("audit log error: %v", err)
}
AuditLog(h.stores.Audit, c, action, resourceType, resourceID, meta)
}
// ── Archived Channels (v0.23.2) ──────────────
func (h *AdminHandler) ListArchivedChannels(c *gin.Context) {
rows, err := database.DB.QueryContext(c.Request.Context(), database.Q(`
SELECT c.id, c.title, c.type, c.user_id,
COALESCE(u.username, '') AS owner_name,
c.updated_at,
(SELECT COUNT(*) FROM messages WHERE channel_id = c.id) AS message_count
FROM channels c
LEFT JOIN users u ON u.id = c.user_id
WHERE c.is_archived = true
ORDER BY c.updated_at DESC
LIMIT 100
`))
page, perPage, offset := parsePagination(c)
channels, total, err := h.stores.Channels.ListArchived(c.Request.Context(), store.ListOptions{
Limit: perPage,
Offset: offset,
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
return
}
defer rows.Close()
type archivedChannel struct {
ID string `json:"id"`
Title string `json:"title"`
Type string `json:"type"`
OwnerName string `json:"owner_name"`
UpdatedAt string `json:"updated_at"`
MessageCount int `json:"message_count"`
}
channels := []archivedChannel{}
for rows.Next() {
var ch archivedChannel
var userID string
if rows.Scan(&ch.ID, &ch.Title, &ch.Type, &userID, &ch.OwnerName, &ch.UpdatedAt, &ch.MessageCount) == nil {
channels = append(channels, ch)
}
}
// Retention config
retentionMode := "flexible"
@@ -784,6 +800,9 @@ func (h *AdminHandler) ListArchivedChannels(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"channels": channels,
"total": total,
"page": page,
"per_page": perPage,
"retention_mode": retentionMode,
})
}
@@ -791,32 +810,27 @@ func (h *AdminHandler) ListArchivedChannels(c *gin.Context) {
func (h *AdminHandler) PurgeChannel(c *gin.Context) {
channelID := c.Param("id")
// Verify the channel is actually archived
var isArchived bool
err := database.DB.QueryRowContext(c.Request.Context(), database.Q(`
SELECT is_archived FROM channels WHERE id = $1
`), channelID).Scan(&isArchived)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
return
// Clean up file storage blobs before CASCADE deletes the DB references
if h.objStore != nil {
prefix := fmt.Sprintf("files/%s", channelID)
if err := h.objStore.DeletePrefix(c.Request.Context(), prefix); err != nil {
log.Printf("⚠️ storage cleanup for purged channel %s failed: %v", channelID, err)
}
}
if !isArchived {
c.JSON(http.StatusConflict, gin.H{"error": "channel must be archived before purging"})
if err := h.stores.Channels.Purge(c.Request.Context(), channelID); err != nil {
msg := err.Error()
switch {
case msg == "channel not found":
c.JSON(http.StatusNotFound, gin.H{"error": msg})
case msg == "channel must be archived before purging":
c.JSON(http.StatusConflict, gin.H{"error": msg})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": "purge failed"})
}
return
}
// Hard delete (CASCADE removes messages, participants, models)
_, err = database.DB.ExecContext(c.Request.Context(), database.Q(`
DELETE FROM channels WHERE id = $1
`), channelID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "purge failed"})
return
}
// Audit log
uid := getUserID(c)
h.auditLog(c, uid, "channel.purged", "channel", channelID)
h.auditLog(c, "channel.purged", "channel", channelID, nil)
c.JSON(http.StatusOK, gin.H{"ok": true})
}

View File

@@ -1,21 +1,21 @@
package handlers
import (
"database/sql"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"git.gobha.me/xcaliber/chat-switchboard/database"
"git.gobha.me/xcaliber/chat-switchboard/models"
"git.gobha.me/xcaliber/chat-switchboard/store"
)
// AuditLog inserts an audit entry. Called from mutating handlers.
// AuditLog writes an audit entry via the store interface.
// Non-blocking: errors are logged but don't break the caller.
func AuditLog(c *gin.Context, action, resourceType, resourceID string, metadata map[string]interface{}) {
if database.DB == nil {
func AuditLog(auditStore store.AuditStore, c *gin.Context, action, resourceType, resourceID string, metadata map[string]interface{}) {
if auditStore == nil {
return
}
@@ -24,165 +24,51 @@ func AuditLog(c *gin.Context, action, resourceType, resourceID string, metadata
return
}
ip := c.ClientIP()
ua := c.GetHeader("User-Agent")
metaJSON := "{}"
var meta models.JSONMap
if metadata != nil {
if b, err := json.Marshal(metadata); err == nil {
metaJSON = string(b)
}
b, _ := json.Marshal(metadata)
json.Unmarshal(b, &meta)
}
if database.IsSQLite() {
_, _ = database.DB.Exec(`
INSERT INTO audit_log (id, actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`, uuid.New().String(), actorID, action, resourceType, resourceID, metaJSON, ip, ua)
} else {
_, _ = database.DB.Exec(`
INSERT INTO audit_log (actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent)
VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)
`, actorID, action, resourceType, resourceID, metaJSON, ip, ua)
}
}
// AuditLogAnon inserts an audit entry without a gin context (e.g. system actions).
func AuditLogAnon(action, resourceType, resourceID string, metadata map[string]interface{}) {
if database.DB == nil {
return
}
metaJSON := "{}"
if metadata != nil {
if b, err := json.Marshal(metadata); err == nil {
metaJSON = string(b)
}
entry := &models.AuditEntry{
ActorID: &actorID,
Action: action,
ResourceType: resourceType,
ResourceID: resourceID,
Metadata: meta,
IPAddress: c.ClientIP(),
UserAgent: c.GetHeader("User-Agent"),
}
if database.IsSQLite() {
_, _ = database.DB.Exec(`
INSERT INTO audit_log (id, action, resource_type, resource_id, metadata)
VALUES (?, ?, ?, ?, ?)
`, uuid.New().String(), action, resourceType, resourceID, metaJSON)
} else {
_, _ = database.DB.Exec(`
INSERT INTO audit_log (action, resource_type, resource_id, metadata)
VALUES ($1, $2, $3, $4::jsonb)
`, action, resourceType, resourceID, metaJSON)
}
}
// AuditLogWithActor inserts an audit entry with an explicit actor ID (e.g. pre-auth flows).
func AuditLogWithActor(actorID string, c *gin.Context, action, resourceType, resourceID string, metadata map[string]interface{}) {
if database.DB == nil || actorID == "" {
return
}
ip := c.ClientIP()
ua := c.GetHeader("User-Agent")
metaJSON := "{}"
if metadata != nil {
if b, err := json.Marshal(metadata); err == nil {
metaJSON = string(b)
}
}
if database.IsSQLite() {
_, _ = database.DB.Exec(`
INSERT INTO audit_log (id, actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`, uuid.New().String(), actorID, action, resourceType, resourceID, metaJSON, ip, ua)
} else {
_, _ = database.DB.Exec(`
INSERT INTO audit_log (actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent)
VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)
`, actorID, action, resourceType, resourceID, metaJSON, ip, ua)
if err := auditStore.Log(context.Background(), entry); err != nil {
log.Printf("audit log error: %v", err)
}
}
// ── Admin Audit Viewer ──────────────────────
type auditEntry struct {
ID string `json:"id"`
ActorID *string `json:"actor_id"`
ActorName *string `json:"actor_name"`
Action string `json:"action"`
ResourceType string `json:"resource_type"`
ResourceID *string `json:"resource_id"`
Metadata string `json:"metadata"`
IPAddress *string `json:"ip_address"`
CreatedAt string `json:"created_at"`
}
// ListAuditLog returns paginated audit entries with optional filters.
// GET /api/v1/admin/audit?page=1&per_page=50&action=user.create&actor_id=...&resource_type=...
func (h *AdminHandler) ListAuditLog(c *gin.Context) {
page, perPage, offset := parsePagination(c)
// Build filter clauses with ? placeholders, convert for Postgres later
where := "WHERE 1=1"
args := []interface{}{}
if action := c.Query("action"); action != "" {
where += " AND al.action = ?"
args = append(args, action)
}
if actorID := c.Query("actor_id"); actorID != "" {
where += " AND al.actor_id = ?"
args = append(args, actorID)
}
if rt := c.Query("resource_type"); rt != "" {
where += " AND al.resource_type = ?"
args = append(args, rt)
opts := store.AuditListOptions{
ListOptions: store.ListOptions{
Limit: perPage,
Offset: offset,
},
Action: c.Query("action"),
ActorID: c.Query("actor_id"),
ResourceType: c.Query("resource_type"),
}
// Count
var total int
countArgs := make([]interface{}, len(args))
copy(countArgs, args)
countQ := convertPlaceholders(`SELECT COUNT(*) FROM audit_log al ` + where)
err := database.DB.QueryRow(countQ, countArgs...).Scan(&total)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "count failed"})
return
}
// Query — metadata column needs ::text on Postgres only
metadataCol := "COALESCE(al.metadata::text, '{}')"
if database.IsSQLite() {
metadataCol = "COALESCE(al.metadata, '{}')"
}
query := fmt.Sprintf(`
SELECT al.id, al.actor_id, COALESCE(u.username, '') as actor_name,
al.action, al.resource_type, al.resource_id,
%s, al.ip_address, al.created_at
FROM audit_log al
LEFT JOIN users u ON al.actor_id = u.id
%s
ORDER BY al.created_at DESC
LIMIT ? OFFSET ?`, metadataCol, where)
args = append(args, perPage, offset)
query = convertPlaceholders(query)
rows, err := database.DB.Query(query, args...)
entries, total, err := h.stores.Audit.List(c.Request.Context(), opts)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "query failed"})
return
}
defer rows.Close()
entries := make([]auditEntry, 0)
for rows.Next() {
var e auditEntry
var actorName sql.NullString
if err := rows.Scan(&e.ID, &e.ActorID, &actorName, &e.Action,
&e.ResourceType, &e.ResourceID, &e.Metadata, &e.IPAddress, &e.CreatedAt); err != nil {
continue
}
if actorName.Valid {
e.ActorName = &actorName.String
}
entries = append(entries, e)
if entries == nil {
entries = []models.AuditEntry{}
}
c.JSON(http.StatusOK, gin.H{
@@ -196,24 +82,10 @@ func (h *AdminHandler) ListAuditLog(c *gin.Context) {
// ListAuditActions returns distinct action names for filter dropdowns.
// GET /api/v1/admin/audit/actions
func (h *AdminHandler) ListAuditActions(c *gin.Context) {
rows, err := database.DB.Query(`
SELECT DISTINCT action FROM audit_log ORDER BY action ASC
`)
actions, err := h.stores.Audit.ListActions(c.Request.Context())
if err != nil {
c.JSON(http.StatusOK, gin.H{"actions": []string{}})
return
}
defer rows.Close()
var actions []string
for rows.Next() {
var a string
if rows.Scan(&a) == nil {
actions = append(actions, a)
}
}
if actions == nil {
actions = []string{}
}
c.JSON(http.StatusOK, gin.H{"actions": actions})
}

View File

@@ -107,7 +107,7 @@ func (h *GroupHandler) CreateGroup(c *gin.Context) {
}
c.JSON(http.StatusCreated, g)
AuditLog(c, "group.create", "group", g.ID, map[string]interface{}{
AuditLog(h.stores.Audit, c, "group.create", "group", g.ID, map[string]interface{}{
"name": g.Name, "scope": g.Scope,
})
}
@@ -183,7 +183,7 @@ func (h *GroupHandler) UpdateGroup(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"ok": true})
AuditLog(c, "group.update", "group", id, nil)
AuditLog(h.stores.Audit, c, "group.update", "group", id, nil)
}
// ── Admin: Delete Group ─────────────────────
@@ -206,7 +206,7 @@ func (h *GroupHandler) DeleteGroup(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"ok": true})
AuditLog(c, "group.delete", "group", id, nil)
AuditLog(h.stores.Audit, c, "group.delete", "group", id, nil)
}
// ── Members: List ───────────────────────────
@@ -259,7 +259,7 @@ func (h *GroupHandler) AddMember(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"ok": true})
AuditLog(c, "group.member.add", "group", groupID, map[string]interface{}{
AuditLog(h.stores.Audit, c, "group.member.add", "group", groupID, map[string]interface{}{
"user_id": req.UserID,
})
}
@@ -289,7 +289,7 @@ func (h *GroupHandler) RemoveMember(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"ok": true})
AuditLog(c, "group.member.remove", "group", groupID, map[string]interface{}{
AuditLog(h.stores.Audit, c, "group.member.remove", "group", groupID, map[string]interface{}{
"user_id": userID,
})
}
@@ -375,7 +375,7 @@ func (h *GroupHandler) SetResourceGrant(c *gin.Context) {
if req.GrantScope == models.GrantScopeTeamOnly {
_ = h.stores.ResourceGrants.Delete(c.Request.Context(), resourceType, resourceID)
c.JSON(http.StatusOK, gin.H{"ok": true})
AuditLog(c, "grant.revoke", resourceType, resourceID, nil)
AuditLog(h.stores.Audit, c, "grant.revoke", resourceType, resourceID, nil)
return
}
@@ -393,7 +393,7 @@ func (h *GroupHandler) SetResourceGrant(c *gin.Context) {
}
c.JSON(http.StatusOK, grant)
AuditLog(c, "grant.set", resourceType, resourceID, map[string]interface{}{
AuditLog(h.stores.Audit, c, "grant.set", resourceType, resourceID, map[string]interface{}{
"grant_scope": req.GrantScope,
})
}
@@ -415,7 +415,7 @@ func (h *GroupHandler) DeleteResourceGrant(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"ok": true})
AuditLog(c, "grant.delete", resourceType, resourceID, nil)
AuditLog(h.stores.Audit, c, "grant.delete", resourceType, resourceID, nil)
}
// ListPermissions returns all valid permission strings.

View File

@@ -142,7 +142,7 @@ func setupHarness(t *testing.T) *testHarness {
authGroup.POST("/login", auth.Login)
// Public settings
adm := NewAdminHandler(stores, nil, nil)
adm := NewAdminHandler(stores, nil, nil, nil)
api.GET("/settings/public", adm.PublicSettings)
// Protected routes

View File

@@ -120,7 +120,7 @@ func (h *TeamHandler) CreateTeam(c *gin.Context) {
}
c.JSON(http.StatusCreated, gin.H{"id": team.ID, "name": team.Name})
AuditLog(c, "team.create", "team", team.ID, map[string]interface{}{"name": team.Name})
AuditLog(h.stores.Audit, c, "team.create", "team", team.ID, map[string]interface{}{"name": team.Name})
}
// ── Admin: Get Team ─────────────────────────
@@ -217,7 +217,7 @@ func (h *TeamHandler) UpdateTeam(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"ok": true})
AuditLog(c, "team.update", "team", teamID, nil)
AuditLog(h.stores.Audit, c, "team.update", "team", teamID, nil)
}
// ── Admin: Delete Team ──────────────────────
@@ -242,7 +242,7 @@ func (h *TeamHandler) DeleteTeam(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"ok": true})
AuditLog(c, "team.delete", "team", teamID, nil)
AuditLog(h.stores.Audit, c, "team.delete", "team", teamID, nil)
}
// ── Members: List ───────────────────────────
@@ -303,7 +303,7 @@ func (h *TeamHandler) AddMember(c *gin.Context) {
}
c.JSON(http.StatusCreated, gin.H{"id": id})
AuditLog(c, "team.add_member", "team", getTeamID(c), map[string]interface{}{
AuditLog(h.stores.Audit, c, "team.add_member", "team", getTeamID(c), map[string]interface{}{
"user_id": req.UserID, "role": req.Role,
})
}
@@ -333,7 +333,7 @@ func (h *TeamHandler) UpdateMember(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"ok": true})
AuditLog(c, "team.update_member", "team", getTeamID(c), map[string]interface{}{
AuditLog(h.stores.Audit, c, "team.update_member", "team", getTeamID(c), map[string]interface{}{
"member_id": memberID, "role": req.Role,
})
}
@@ -355,7 +355,7 @@ func (h *TeamHandler) RemoveMember(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"ok": true})
AuditLog(c, "team.remove_member", "team", getTeamID(c), map[string]interface{}{
AuditLog(h.stores.Audit, c, "team.remove_member", "team", getTeamID(c), map[string]interface{}{
"member_id": memberID,
})
}

View File

@@ -141,6 +141,9 @@ func (h *UsageHandler) ListPricing(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list pricing"})
return
}
if entries == nil {
entries = []models.PricingEntry{}
}
c.JSON(http.StatusOK, entries)
}