forked from wrenn/wrenn
Merge pull request 'Added audit logs for users' (#7) from audit-logs into dev
Reviewed-on: wrenn/sandbox#7
This commit is contained in:
@ -14,6 +14,7 @@ import (
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"git.omukk.dev/wrenn/sandbox/internal/api"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/audit"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/auth/oauth"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/config"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/db"
|
||||
@ -90,7 +91,7 @@ func main() {
|
||||
srv := api.New(queries, hostPool, hostScheduler, pool, rdb, []byte(cfg.JWTSecret), oauthRegistry, cfg.OAuthRedirectURL)
|
||||
|
||||
// Start host monitor (passive + active reconciliation every 30s).
|
||||
monitor := api.NewHostMonitor(queries, hostPool, 30*time.Second)
|
||||
monitor := api.NewHostMonitor(queries, hostPool, audit.New(queries), 30*time.Second)
|
||||
monitor.Start(ctx)
|
||||
|
||||
httpServer := &http.Server{
|
||||
|
||||
28
db/migrations/20260324220743_audit_logs.sql
Normal file
28
db/migrations/20260324220743_audit_logs.sql
Normal file
@ -0,0 +1,28 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE audit_logs (
|
||||
id TEXT PRIMARY KEY,
|
||||
team_id TEXT NOT NULL,
|
||||
actor_type TEXT NOT NULL, -- 'user', 'api_key', 'system'
|
||||
actor_id TEXT, -- user_id or api_key_id; NULL for system
|
||||
actor_name TEXT, -- display name snapshotted at write time; NULL for system
|
||||
resource_type TEXT NOT NULL, -- 'sandbox', 'snapshot', 'team', 'api_key', 'member', 'host'
|
||||
resource_id TEXT, -- primary ID of the affected resource; NULL when not applicable
|
||||
action TEXT NOT NULL, -- 'create', 'pause', 'resume', 'destroy', 'delete', 'rename',
|
||||
-- 'revoke', 'add', 'remove', 'leave', 'role_update',
|
||||
-- 'marked_down', 'marked_up'
|
||||
scope TEXT NOT NULL, -- 'team' or 'admin'
|
||||
status TEXT NOT NULL, -- 'success', 'info', 'warning', 'error'
|
||||
metadata JSONB NOT NULL DEFAULT '{}',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Primary access pattern: team feed sorted newest-first with cursor pagination.
|
||||
CREATE INDEX idx_audit_logs_team_time ON audit_logs (team_id, created_at DESC);
|
||||
|
||||
-- Secondary index: filtered by resource_type and action within a team.
|
||||
CREATE INDEX idx_audit_logs_team_resource ON audit_logs (team_id, resource_type, action, created_at DESC);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE audit_logs;
|
||||
@ -0,0 +1,14 @@
|
||||
-- name: InsertAuditLog :exec
|
||||
INSERT INTO audit_logs (id, team_id, actor_type, actor_id, actor_name, resource_type, resource_id, action, scope, status, metadata)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);
|
||||
|
||||
-- name: ListAuditLogs :many
|
||||
SELECT * FROM audit_logs
|
||||
WHERE team_id = $1
|
||||
AND scope = ANY($2::text[])
|
||||
AND (cardinality($3::text[]) = 0 OR resource_type = ANY($3::text[]))
|
||||
AND (cardinality($4::text[]) = 0 OR action = ANY($4::text[]))
|
||||
AND ($5::timestamptz IS NULL OR created_at < $5
|
||||
OR (created_at = $5 AND id < $6))
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT $7;
|
||||
|
||||
38
frontend/src/lib/api/audit.ts
Normal file
38
frontend/src/lib/api/audit.ts
Normal file
@ -0,0 +1,38 @@
|
||||
import { apiFetch, type ApiResult } from '$lib/api/client';
|
||||
|
||||
export type AuditLog = {
|
||||
id: string;
|
||||
actor_type: 'user' | 'api_key' | 'system';
|
||||
actor_id?: string;
|
||||
actor_name?: string;
|
||||
resource_type: string;
|
||||
resource_id?: string;
|
||||
action: string;
|
||||
scope: 'team' | 'admin';
|
||||
status: 'success' | 'info' | 'warning' | 'error';
|
||||
metadata?: Record<string, unknown>;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type AuditListResponse = {
|
||||
items: AuditLog[];
|
||||
next_before?: string;
|
||||
next_before_id?: string;
|
||||
};
|
||||
|
||||
export async function listAuditLogs(params?: {
|
||||
before?: string;
|
||||
before_id?: string;
|
||||
resource_types?: string[];
|
||||
actions?: string[];
|
||||
limit?: number;
|
||||
}): Promise<ApiResult<AuditListResponse>> {
|
||||
const q = new URLSearchParams();
|
||||
if (params?.before) q.set('before', params.before);
|
||||
if (params?.before_id) q.set('before_id', params.before_id);
|
||||
params?.resource_types?.forEach((t) => q.append('resource_type', t));
|
||||
params?.actions?.forEach((a) => q.append('action', a));
|
||||
if (params?.limit != null) q.set('limit', String(params.limit));
|
||||
const qs = q.toString();
|
||||
return apiFetch('GET', `/api/v1/audit-logs${qs ? '?' + qs : ''}`);
|
||||
}
|
||||
585
frontend/src/routes/dashboard/audit/+page.svelte
Normal file
585
frontend/src/routes/dashboard/audit/+page.svelte
Normal file
@ -0,0 +1,585 @@
|
||||
<script lang="ts">
|
||||
import Sidebar from '$lib/components/Sidebar.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import { listAuditLogs, type AuditLog } from '$lib/api/audit';
|
||||
|
||||
let collapsed = $state(
|
||||
typeof window !== 'undefined'
|
||||
? localStorage.getItem('wrenn_sidebar_collapsed') === 'true'
|
||||
: false
|
||||
);
|
||||
|
||||
// ─── Data state ───────────────────────────────────────────────────────────
|
||||
|
||||
let logs = $state<AuditLog[]>([]);
|
||||
let loading = $state(true);
|
||||
let loadingMore = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
let hasMore = $state(false);
|
||||
let nextCursor = $state<{ before: string; before_id: string } | null>(null);
|
||||
|
||||
// ─── UI state ─────────────────────────────────────────────────────────────
|
||||
|
||||
let sentinel = $state<HTMLElement | null>(null);
|
||||
let filterDropdownOpen = $state(false);
|
||||
let filterDropdownEl = $state<HTMLElement | null>(null);
|
||||
|
||||
// ─── Filter state ─────────────────────────────────────────────────────────
|
||||
// Map: resource_type → Set of selected actions for that resource.
|
||||
// An empty set or absent key means no filter for that resource.
|
||||
|
||||
let selectedActions = $state<Map<string, Set<string>>>(new Map());
|
||||
|
||||
// ─── Constants ────────────────────────────────────────────────────────────
|
||||
|
||||
const RESOURCES = ['sandbox', 'snapshot', 'team', 'api_key', 'member', 'host'] as const;
|
||||
|
||||
const RESOURCE_LABELS: Record<string, string> = {
|
||||
sandbox: 'Capsule',
|
||||
snapshot: 'Template',
|
||||
team: 'Team',
|
||||
api_key: 'API Key',
|
||||
member: 'Member',
|
||||
host: 'Host'
|
||||
};
|
||||
|
||||
const ACTIONS_BY_RESOURCE: Record<string, string[]> = {
|
||||
sandbox: ['create', 'pause', 'resume', 'destroy'],
|
||||
snapshot: ['create', 'delete'],
|
||||
team: ['rename'],
|
||||
api_key: ['create', 'revoke'],
|
||||
member: ['add', 'remove', 'leave', 'role_update'],
|
||||
host: ['create', 'delete', 'marked_down', 'marked_up']
|
||||
};
|
||||
|
||||
const ACTION_LABELS: Record<string, string> = {
|
||||
create: 'Created',
|
||||
pause: 'Paused',
|
||||
resume: 'Resumed',
|
||||
destroy: 'Destroyed',
|
||||
delete: 'Deleted',
|
||||
rename: 'Renamed',
|
||||
revoke: 'Revoked',
|
||||
add: 'Added',
|
||||
remove: 'Removed',
|
||||
leave: 'Left',
|
||||
role_update: 'Role updated',
|
||||
marked_down: 'Marked down',
|
||||
marked_up: 'Marked up'
|
||||
};
|
||||
|
||||
// ─── Derived ──────────────────────────────────────────────────────────────
|
||||
|
||||
let activeFilterCount = $derived(
|
||||
[...selectedActions.values()].filter((s) => s.size > 0).length
|
||||
);
|
||||
|
||||
// ─── Filter helpers ───────────────────────────────────────────────────────
|
||||
|
||||
type CheckState = 'all' | 'some' | 'none';
|
||||
|
||||
function getResourceCheckState(r: string): CheckState {
|
||||
const sel = selectedActions.get(r);
|
||||
if (!sel || sel.size === 0) return 'none';
|
||||
if (sel.size === ACTIONS_BY_RESOURCE[r].length) return 'all';
|
||||
return 'some';
|
||||
}
|
||||
|
||||
function toggleResource(r: string) {
|
||||
const state = getResourceCheckState(r);
|
||||
const next = new Map(selectedActions);
|
||||
if (state === 'all') {
|
||||
next.delete(r);
|
||||
} else {
|
||||
next.set(r, new Set(ACTIONS_BY_RESOURCE[r]));
|
||||
}
|
||||
selectedActions = next;
|
||||
resetAndFetch(next);
|
||||
}
|
||||
|
||||
function toggleAction(r: string, a: string) {
|
||||
const next = new Map(selectedActions);
|
||||
const acts = new Set(next.get(r) ?? []);
|
||||
if (acts.has(a)) {
|
||||
acts.delete(a);
|
||||
} else {
|
||||
acts.add(a);
|
||||
}
|
||||
if (acts.size === 0) {
|
||||
next.delete(r);
|
||||
} else {
|
||||
next.set(r, acts);
|
||||
}
|
||||
selectedActions = next;
|
||||
resetAndFetch(next);
|
||||
}
|
||||
|
||||
function clearAllFilters() {
|
||||
selectedActions = new Map();
|
||||
resetAndFetch(new Map());
|
||||
}
|
||||
|
||||
function getApiParams(snap: Map<string, Set<string>>) {
|
||||
const resource_types: string[] = [];
|
||||
const actions = new Set<string>();
|
||||
for (const [r, acts] of snap) {
|
||||
if (acts.size > 0) {
|
||||
resource_types.push(r);
|
||||
acts.forEach((a) => actions.add(a));
|
||||
}
|
||||
}
|
||||
return {
|
||||
resource_types: resource_types.length > 0 ? resource_types : undefined,
|
||||
actions: actions.size > 0 ? [...actions] : undefined
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Click-outside to close dropdown ─────────────────────────────────────
|
||||
|
||||
$effect(() => {
|
||||
if (!filterDropdownOpen) return;
|
||||
function handleMouseDown(e: MouseEvent) {
|
||||
if (filterDropdownEl && !filterDropdownEl.contains(e.target as Node)) {
|
||||
filterDropdownOpen = false;
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleMouseDown);
|
||||
return () => document.removeEventListener('mousedown', handleMouseDown);
|
||||
});
|
||||
|
||||
// ─── Data functions ───────────────────────────────────────────────────────
|
||||
|
||||
let fetchId = 0;
|
||||
|
||||
async function resetAndFetch(snap: Map<string, Set<string>>) {
|
||||
const id = ++fetchId;
|
||||
loading = true;
|
||||
error = null;
|
||||
logs = [];
|
||||
nextCursor = null;
|
||||
hasMore = false;
|
||||
|
||||
const params = getApiParams(snap);
|
||||
const result = await listAuditLogs(params);
|
||||
|
||||
if (id !== fetchId) return;
|
||||
|
||||
if (result.ok) {
|
||||
logs = result.data.items;
|
||||
hasMore = !!result.data.next_before;
|
||||
nextCursor = result.data.next_before
|
||||
? { before: result.data.next_before, before_id: result.data.next_before_id! }
|
||||
: null;
|
||||
} else {
|
||||
error = result.error;
|
||||
}
|
||||
loading = false;
|
||||
}
|
||||
|
||||
async function loadNextPage() {
|
||||
if (!nextCursor || loadingMore) return;
|
||||
loadingMore = true;
|
||||
|
||||
const params = getApiParams(selectedActions);
|
||||
const result = await listAuditLogs({
|
||||
...params,
|
||||
before: nextCursor.before,
|
||||
before_id: nextCursor.before_id
|
||||
});
|
||||
|
||||
if (result.ok) {
|
||||
logs = [...logs, ...result.data.items];
|
||||
hasMore = !!result.data.next_before;
|
||||
nextCursor = result.data.next_before
|
||||
? { before: result.data.next_before, before_id: result.data.next_before_id! }
|
||||
: null;
|
||||
}
|
||||
loadingMore = false;
|
||||
}
|
||||
|
||||
// ─── UI helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
function describeEvent(log: AuditLog): string {
|
||||
const actor = log.actor_name || (log.actor_type === 'system' ? 'System' : 'Unknown');
|
||||
const meta = (log.metadata ?? {}) as Record<string, string>;
|
||||
switch (`${log.resource_type}:${log.action}`) {
|
||||
case 'sandbox:create': return `${actor} created a capsule`;
|
||||
case 'sandbox:pause': return `${actor} paused a capsule`;
|
||||
case 'sandbox:resume': return `${actor} resumed a capsule`;
|
||||
case 'sandbox:destroy': return `${actor} destroyed a capsule`;
|
||||
case 'snapshot:create': return `${actor} created a template`;
|
||||
case 'snapshot:delete': return `${actor} deleted a template`;
|
||||
case 'team:rename': return `${actor} renamed the team from "${meta.old_name}" to "${meta.new_name}"`;
|
||||
case 'api_key:create': return `${actor} created API key "${meta.name}"`;
|
||||
case 'api_key:revoke': return `${actor} revoked an API key`;
|
||||
case 'member:add': return `${actor} added ${meta.email} as ${meta.role}`;
|
||||
case 'member:remove': return `${actor} removed ${meta.email ?? 'a member'}`;
|
||||
case 'member:leave': return `${actor} left the team`;
|
||||
case 'member:role_update': return `${actor} changed a member's role to ${meta.new_role}`;
|
||||
case 'host:create': return `${actor} registered a host`;
|
||||
case 'host:delete': return `${actor} removed a host`;
|
||||
case 'host:marked_down': return `Host was marked as down`;
|
||||
case 'host:marked_up': return `Host was marked as up`;
|
||||
default: return `${actor} performed ${log.action} on ${log.resource_type}`;
|
||||
}
|
||||
}
|
||||
|
||||
function actorLabel(log: AuditLog): string {
|
||||
if (log.actor_type === 'system') return 'System';
|
||||
return log.actor_name ?? '—';
|
||||
}
|
||||
|
||||
function formatEventDate(iso: string): { date: string; time: string } {
|
||||
const d = new Date(iso);
|
||||
return {
|
||||
date: d.toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }),
|
||||
time: d.toLocaleString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false })
|
||||
};
|
||||
}
|
||||
|
||||
function statusColor(status: string): string {
|
||||
switch (status) {
|
||||
case 'success': return 'var(--color-accent)';
|
||||
case 'info': return 'var(--color-blue)';
|
||||
case 'warning': return 'var(--color-amber)';
|
||||
case 'error': return 'var(--color-red)';
|
||||
default: return 'var(--color-text-muted)';
|
||||
}
|
||||
}
|
||||
|
||||
function tagLabel(r: string): string {
|
||||
const sel = selectedActions.get(r);
|
||||
if (!sel || sel.size === 0) return RESOURCE_LABELS[r];
|
||||
const total = ACTIONS_BY_RESOURCE[r].length;
|
||||
if (sel.size === total) return RESOURCE_LABELS[r];
|
||||
const actionNames = [...sel].map((a) => ACTION_LABELS[a]).join(', ');
|
||||
return `${RESOURCE_LABELS[r]}: ${actionNames}`;
|
||||
}
|
||||
|
||||
// ─── Lifecycle ────────────────────────────────────────────────────────────
|
||||
|
||||
onMount(() => {
|
||||
resetAndFetch(new Map());
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const el = sentinel;
|
||||
if (!el) return;
|
||||
const obs = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting && !loadingMore && !loading && hasMore) {
|
||||
loadNextPage();
|
||||
}
|
||||
},
|
||||
{ rootMargin: '300px' }
|
||||
);
|
||||
obs.observe(el);
|
||||
return () => obs.disconnect();
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Wrenn — Audit Logs</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="flex h-screen overflow-hidden">
|
||||
<Sidebar bind:collapsed />
|
||||
|
||||
<div class="flex flex-1 flex-col overflow-hidden">
|
||||
<main class="flex-1 overflow-y-auto bg-[var(--color-bg-0)]">
|
||||
|
||||
<!-- Header -->
|
||||
<div class="px-7 pt-8">
|
||||
<div>
|
||||
<h1 class="font-serif text-page tracking-[-0.02em] text-[var(--color-text-bright)]">
|
||||
Audit Logs
|
||||
</h1>
|
||||
<p class="mt-2 text-ui text-[var(--color-text-secondary)]">
|
||||
A complete record of activity across your team.
|
||||
</p>
|
||||
</div>
|
||||
<div class="mt-6 border-b border-[var(--color-border)]"></div>
|
||||
</div>
|
||||
|
||||
<!-- Filter bar -->
|
||||
<div class="px-7 pt-5">
|
||||
<div class="flex items-center gap-2">
|
||||
|
||||
<!-- Single hierarchical filter dropdown -->
|
||||
<div class="relative" bind:this={filterDropdownEl}>
|
||||
<button
|
||||
onclick={() => (filterDropdownOpen = !filterDropdownOpen)}
|
||||
class="flex items-center gap-2 rounded-[var(--radius-button)] border px-3 py-1.5 text-ui transition-colors duration-150
|
||||
{activeFilterCount > 0
|
||||
? 'border-[var(--color-accent)]/60 bg-[var(--color-accent)]/10 font-medium text-[var(--color-accent)]'
|
||||
: 'border-[var(--color-border)] bg-[var(--color-bg-3)] text-[var(--color-text-secondary)] hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)]'}"
|
||||
>
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<line x1="4" y1="6" x2="20" y2="6" />
|
||||
<line x1="8" y1="12" x2="16" y2="12" />
|
||||
<line x1="11" y1="18" x2="13" y2="18" />
|
||||
</svg>
|
||||
<span>Filter</span>
|
||||
{#if activeFilterCount > 0}
|
||||
<span class="flex h-4 w-4 items-center justify-center rounded-full bg-[var(--color-accent)] text-[10px] font-semibold leading-none text-white">
|
||||
{activeFilterCount}
|
||||
</span>
|
||||
{/if}
|
||||
<svg
|
||||
class="transition-transform duration-150 {filterDropdownOpen ? 'rotate-180' : ''}"
|
||||
width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
|
||||
>
|
||||
<polyline points="6 9 12 15 18 9" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{#if filterDropdownOpen}
|
||||
<div
|
||||
class="absolute left-0 top-full z-20 mt-1.5 w-56 overflow-y-auto rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] py-1.5 shadow-xl"
|
||||
style="max-height: 380px; animation: fadeUp 0.12s ease both"
|
||||
>
|
||||
{#each RESOURCES as r}
|
||||
{@const rState = getResourceCheckState(r)}
|
||||
{@const actions = ACTIONS_BY_RESOURCE[r]}
|
||||
|
||||
<!-- Resource row -->
|
||||
<label class="flex cursor-pointer items-center gap-2.5 px-3 py-2 transition-colors duration-100 hover:bg-[var(--color-bg-3)]">
|
||||
<!-- Tristate checkbox -->
|
||||
<span class="flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-sm border transition-colors duration-100
|
||||
{rState !== 'none' ? 'border-[var(--color-accent)] bg-[var(--color-accent)]' : 'border-[var(--color-border-mid)] bg-[var(--color-bg-4)]'}">
|
||||
{#if rState === 'all'}
|
||||
<svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="20 6 9 17 4 12" />
|
||||
</svg>
|
||||
{:else if rState === 'some'}
|
||||
<svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round">
|
||||
<line x1="5" y1="12" x2="19" y2="12" />
|
||||
</svg>
|
||||
{/if}
|
||||
</span>
|
||||
<input type="checkbox" class="sr-only" checked={rState !== 'none'} onchange={() => toggleResource(r)} />
|
||||
<span class="text-ui font-medium text-[var(--color-text-primary)]">{RESOURCE_LABELS[r]}</span>
|
||||
</label>
|
||||
|
||||
<!-- Action rows (indented) -->
|
||||
{#each actions as a}
|
||||
{@const checked = selectedActions.get(r)?.has(a) ?? false}
|
||||
<label class="flex cursor-pointer items-center gap-2.5 py-1.5 pl-8 pr-3 transition-colors duration-100 hover:bg-[var(--color-bg-3)]">
|
||||
<span class="flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-sm border transition-colors duration-100
|
||||
{checked ? 'border-[var(--color-accent)] bg-[var(--color-accent)]' : 'border-[var(--color-border-mid)] bg-[var(--color-bg-4)]'}">
|
||||
{#if checked}
|
||||
<svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="20 6 9 17 4 12" />
|
||||
</svg>
|
||||
{/if}
|
||||
</span>
|
||||
<input type="checkbox" class="sr-only" {checked} onchange={() => toggleAction(r, a)} />
|
||||
<span class="text-ui text-[var(--color-text-secondary)]">{ACTION_LABELS[a]}</span>
|
||||
</label>
|
||||
{/each}
|
||||
|
||||
<!-- Divider between resource groups -->
|
||||
{#if r !== RESOURCES[RESOURCES.length - 1]}
|
||||
<div class="mx-3 my-1 border-t border-[var(--color-border)]"></div>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Active filter tags -->
|
||||
{#if activeFilterCount > 0}
|
||||
<div class="mt-3 flex flex-wrap items-center gap-2" style="animation: fadeUp 0.2s ease both">
|
||||
{#each RESOURCES as r}
|
||||
{#if (selectedActions.get(r)?.size ?? 0) > 0}
|
||||
<span class="flex items-center gap-1.5 rounded-full border border-[var(--color-accent)]/40 bg-[var(--color-accent)]/10 px-2.5 py-1 text-meta font-medium text-[var(--color-accent)]">
|
||||
{tagLabel(r)}
|
||||
<button
|
||||
onclick={() => toggleResource(r)}
|
||||
class="flex items-center justify-center text-[var(--color-accent)] opacity-60 transition-opacity duration-100 hover:opacity-100"
|
||||
aria-label="Remove {RESOURCE_LABELS[r]} filter"
|
||||
>
|
||||
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
||||
<line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
</span>
|
||||
{/if}
|
||||
{/each}
|
||||
<button
|
||||
onclick={clearAllFilters}
|
||||
class="text-meta text-[var(--color-text-muted)] underline-offset-2 transition-colors duration-100 hover:text-[var(--color-text-secondary)] hover:underline"
|
||||
>
|
||||
Clear all
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="p-8" style="animation: fadeUp 0.35s ease both">
|
||||
|
||||
{#if error}
|
||||
<div class="mb-4 flex items-center justify-between gap-4 rounded-[var(--radius-card)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-4 py-3 text-ui text-[var(--color-red)]">
|
||||
<span>{error}</span>
|
||||
<button
|
||||
onclick={() => resetAndFetch(selectedActions)}
|
||||
class="shrink-0 font-semibold underline-offset-2 hover:underline"
|
||||
>
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if loading}
|
||||
<div class="flex items-center justify-center py-24">
|
||||
<div class="flex items-center gap-3 text-ui text-[var(--color-text-secondary)]">
|
||||
<svg class="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
|
||||
</svg>
|
||||
Loading events...
|
||||
</div>
|
||||
</div>
|
||||
{:else if logs.length === 0}
|
||||
<!-- Empty state -->
|
||||
<div class="flex flex-col items-center justify-center py-[72px]">
|
||||
<div class="relative mb-5">
|
||||
<div class="absolute inset-0 -m-4 rounded-full" style="background: radial-gradient(circle, rgba(94,140,88,0.08) 0%, transparent 70%)"></div>
|
||||
<div
|
||||
class="relative flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-accent)]/20 bg-[var(--color-bg-3)]"
|
||||
style="animation: iconFloat 4s ease-in-out infinite"
|
||||
>
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--color-accent-mid)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<p class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">
|
||||
{activeFilterCount > 0 ? 'No matching events' : 'No activity yet'}
|
||||
</p>
|
||||
<p class="mt-1.5 text-ui text-[var(--color-text-tertiary)]">
|
||||
{activeFilterCount > 0
|
||||
? 'Try adjusting or clearing the filters.'
|
||||
: 'Events will appear here as your team takes actions.'}
|
||||
</p>
|
||||
{#if activeFilterCount > 0}
|
||||
<button
|
||||
onclick={clearAllFilters}
|
||||
class="mt-4 text-ui text-[var(--color-accent)] underline-offset-2 hover:underline"
|
||||
>
|
||||
Clear filters
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Table -->
|
||||
<div class="overflow-hidden rounded-[var(--radius-card)] border border-[var(--color-border)]">
|
||||
|
||||
<!-- Table header -->
|
||||
<div class="grid grid-cols-[168px_1.4fr_3fr] border-b border-[var(--color-border)] bg-[var(--color-bg-3)]">
|
||||
<div class="px-5 py-3 text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Time</div>
|
||||
<div class="px-4 py-3 text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Actor</div>
|
||||
<div class="px-4 py-3 text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-muted)]">Event</div>
|
||||
</div>
|
||||
|
||||
<!-- Rows -->
|
||||
{#each logs as log, i (log.id)}
|
||||
{@const ts = formatEventDate(log.created_at)}
|
||||
<div
|
||||
class="log-entry relative overflow-hidden border-b border-[var(--color-border)] last:border-b-0
|
||||
{log.status === 'error' ? 'log-row-error' : ''}
|
||||
{log.status === 'warning' ? 'log-row-warning' : ''}"
|
||||
style="animation: fadeUp 0.35s ease both; animation-delay: {Math.min(i, 10) * 30}ms"
|
||||
>
|
||||
<!-- Status stripe (absolutely positioned, independent of row animation) -->
|
||||
<div
|
||||
class="status-stripe pointer-events-none absolute inset-y-0 left-0 w-[3px] {log.status === 'error' ? 'stripe-pulse' : ''}"
|
||||
style="background: {statusColor(log.status)}"
|
||||
></div>
|
||||
|
||||
<!-- Main row -->
|
||||
<div class="grid grid-cols-[168px_1.4fr_3fr] items-start">
|
||||
<!-- Time -->
|
||||
<div class="flex flex-col gap-0.5 px-5 py-4">
|
||||
<span class="text-ui text-[var(--color-text-secondary)]">{ts.date}</span>
|
||||
<span class="font-mono text-meta text-[var(--color-text-muted)]">{ts.time}</span>
|
||||
</div>
|
||||
|
||||
<!-- Actor -->
|
||||
<div class="min-w-0 px-4 py-4">
|
||||
<div class="flex flex-col gap-1">
|
||||
<span class="truncate text-ui font-medium text-[var(--color-text-bright)]">
|
||||
{actorLabel(log)}
|
||||
</span>
|
||||
{#if log.actor_type === 'api_key'}
|
||||
<span class="inline-flex w-fit items-center rounded-sm border border-[var(--color-border-mid)] bg-[var(--color-bg-4)] px-1.5 py-0.5 font-mono text-badge text-[var(--color-text-muted)]">key</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Event description + resource ID -->
|
||||
<div class="min-w-0 px-4 py-4">
|
||||
<p class="text-ui font-medium text-[var(--color-text-primary)]">{describeEvent(log)}</p>
|
||||
{#if log.resource_id}
|
||||
<span class="mt-1 inline-flex items-center rounded-sm border border-[var(--color-border-mid)] bg-[var(--color-bg-4)] px-1.5 py-0.5 font-mono text-badge text-[var(--color-text-muted)]">{log.resource_id}</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<!-- Load more sentinel + status -->
|
||||
<div bind:this={sentinel} class="mt-4">
|
||||
{#if loadingMore}
|
||||
<div class="flex items-center justify-center gap-2 py-6 text-meta text-[var(--color-text-muted)]">
|
||||
<svg class="animate-spin" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
|
||||
</svg>
|
||||
Loading more...
|
||||
</div>
|
||||
{:else if !hasMore}
|
||||
<p class="py-4 text-center text-meta text-[var(--color-text-muted)]">
|
||||
{logs.length} {logs.length === 1 ? 'event' : 'events'} total
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="h-px shrink-0 bg-[var(--color-border)]"></footer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@keyframes fadeUp {
|
||||
from { opacity: 0; transform: translateY(8px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
@keyframes iconFloat {
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-6px); }
|
||||
}
|
||||
|
||||
@keyframes stripePulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.3; }
|
||||
}
|
||||
|
||||
.log-row-error {
|
||||
background: rgba(207, 129, 114, 0.04);
|
||||
}
|
||||
|
||||
.log-row-warning {
|
||||
background: rgba(212, 167, 60, 0.03);
|
||||
}
|
||||
|
||||
.stripe-pulse {
|
||||
animation: stripePulse 2.5s ease-in-out infinite;
|
||||
}
|
||||
</style>
|
||||
@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.omukk.dev/wrenn/sandbox/internal/audit"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/auth"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/db"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/service"
|
||||
@ -13,10 +14,11 @@ import (
|
||||
|
||||
type apiKeyHandler struct {
|
||||
svc *service.APIKeyService
|
||||
audit *audit.AuditLogger
|
||||
}
|
||||
|
||||
func newAPIKeyHandler(svc *service.APIKeyService) *apiKeyHandler {
|
||||
return &apiKeyHandler{svc: svc}
|
||||
func newAPIKeyHandler(svc *service.APIKeyService, al *audit.AuditLogger) *apiKeyHandler {
|
||||
return &apiKeyHandler{svc: svc, audit: al}
|
||||
}
|
||||
|
||||
type createAPIKeyRequest struct {
|
||||
@ -91,6 +93,7 @@ func (h *apiKeyHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
resp := apiKeyToResponse(result.Row)
|
||||
resp.Key = &result.Plaintext
|
||||
|
||||
h.audit.LogAPIKeyCreate(r.Context(), ac, result.Row.ID, result.Row.Name)
|
||||
writeJSON(w, http.StatusCreated, resp)
|
||||
}
|
||||
|
||||
@ -122,5 +125,6 @@ func (h *apiKeyHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogAPIKeyRevoke(r.Context(), ac, keyID)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
134
internal/api/handlers_audit.go
Normal file
134
internal/api/handlers_audit.go
Normal file
@ -0,0 +1,134 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.omukk.dev/wrenn/sandbox/internal/auth"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/service"
|
||||
)
|
||||
|
||||
type auditHandler struct {
|
||||
svc *service.AuditService
|
||||
}
|
||||
|
||||
func newAuditHandler(svc *service.AuditService) *auditHandler {
|
||||
return &auditHandler{svc: svc}
|
||||
}
|
||||
|
||||
type auditLogResponse struct {
|
||||
ID string `json:"id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorID string `json:"actor_id,omitempty"`
|
||||
ActorName string `json:"actor_name,omitempty"`
|
||||
ResourceType string `json:"resource_type"`
|
||||
ResourceID string `json:"resource_id,omitempty"`
|
||||
Action string `json:"action"`
|
||||
Scope string `json:"scope"`
|
||||
Status string `json:"status"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
// List handles GET /v1/audit-logs.
|
||||
// Query params:
|
||||
// - before: RFC3339 timestamp cursor (exclusive); omit to start from latest
|
||||
// - limit: page size, default 50, max 200
|
||||
// - resource_type: filter by resource type (sandbox, snapshot, team, api_key, member, host)
|
||||
// - action: filter by action verb
|
||||
//
|
||||
// Members see only team-scoped events; admins/owners see all.
|
||||
func (h *auditHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
ac := auth.MustFromContext(r.Context())
|
||||
|
||||
// Parse ?before cursor.
|
||||
var before time.Time
|
||||
if s := r.URL.Query().Get("before"); s != "" {
|
||||
var err error
|
||||
before, err = time.Parse(time.RFC3339, s)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "before must be an RFC3339 timestamp")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Parse ?limit.
|
||||
limit := 50
|
||||
if s := r.URL.Query().Get("limit"); s != "" {
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil || n < 1 {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "limit must be a positive integer")
|
||||
return
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
|
||||
entries, err := h.svc.List(r.Context(), service.AuditListParams{
|
||||
TeamID: ac.TeamID,
|
||||
AdminScoped: ac.Role == "owner" || ac.Role == "admin",
|
||||
ResourceTypes: parseMultiParam(r.URL.Query()["resource_type"]),
|
||||
Actions: parseMultiParam(r.URL.Query()["action"]),
|
||||
Before: before,
|
||||
BeforeID: r.URL.Query().Get("before_id"),
|
||||
Limit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "db_error", "failed to list audit logs")
|
||||
return
|
||||
}
|
||||
|
||||
items := make([]auditLogResponse, len(entries))
|
||||
for i, e := range entries {
|
||||
items[i] = auditLogResponse{
|
||||
ID: e.ID,
|
||||
ActorType: e.ActorType,
|
||||
ActorID: e.ActorID,
|
||||
ActorName: e.ActorName,
|
||||
ResourceType: e.ResourceType,
|
||||
ResourceID: e.ResourceID,
|
||||
Action: e.Action,
|
||||
Scope: e.Scope,
|
||||
Status: e.Status,
|
||||
Metadata: e.Metadata,
|
||||
CreatedAt: e.CreatedAt.UTC().Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
resp := map[string]any{"items": items}
|
||||
if len(items) > 0 {
|
||||
last := entries[len(entries)-1]
|
||||
resp["next_before"] = last.CreatedAt.UTC().Format(time.RFC3339)
|
||||
resp["next_before_id"] = last.ID
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// parseMultiParam flattens repeated params and comma-separated values into a
|
||||
// single deduplicated slice. Empty strings are dropped. Returns nil (no filter)
|
||||
// when no values are present.
|
||||
//
|
||||
// Both ?resource_type=sandbox&resource_type=snapshot
|
||||
// and ?resource_type=sandbox,snapshot are accepted.
|
||||
func parseMultiParam(values []string) []string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
var out []string
|
||||
for _, v := range values {
|
||||
for _, part := range strings.Split(v, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[part]; !ok {
|
||||
seen[part] = struct{}{}
|
||||
out = append(out, part)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@ -2,11 +2,13 @@ package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.omukk.dev/wrenn/sandbox/internal/audit"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/auth"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/db"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/service"
|
||||
@ -15,10 +17,11 @@ import (
|
||||
type hostHandler struct {
|
||||
svc *service.HostService
|
||||
queries *db.Queries
|
||||
audit *audit.AuditLogger
|
||||
}
|
||||
|
||||
func newHostHandler(svc *service.HostService, queries *db.Queries) *hostHandler {
|
||||
return &hostHandler{svc: svc, queries: queries}
|
||||
func newHostHandler(svc *service.HostService, queries *db.Queries, al *audit.AuditLogger) *hostHandler {
|
||||
return &hostHandler{svc: svc, queries: queries, audit: al}
|
||||
}
|
||||
|
||||
// Request/response types.
|
||||
@ -50,10 +53,6 @@ type deletePreviewResponse struct {
|
||||
SandboxIDs []string `json:"sandbox_ids"`
|
||||
}
|
||||
|
||||
type hasSandboxesErrorResponse struct {
|
||||
SandboxIDs []string `json:"sandbox_ids"`
|
||||
}
|
||||
|
||||
type registerHostRequest struct {
|
||||
Token string `json:"token"`
|
||||
Arch string `json:"arch,omitempty"`
|
||||
@ -166,6 +165,10 @@ func (h *hostHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Log audit for the owning team (BYOC hosts have a team; shared hosts use caller's team).
|
||||
hostTeamID := result.Host.TeamID.String
|
||||
h.audit.LogHostCreate(r.Context(), ac, result.Host.ID, hostTeamID)
|
||||
|
||||
writeJSON(w, http.StatusCreated, createHostResponse{
|
||||
Host: hostToResponse(result.Host),
|
||||
RegistrationToken: result.RegistrationToken,
|
||||
@ -257,8 +260,15 @@ func (h *hostHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
ac := auth.MustFromContext(r.Context())
|
||||
force := r.URL.Query().Get("force") == "true"
|
||||
|
||||
// Fetch host before deletion to capture team_id for audit.
|
||||
deletedHost, hostErr := h.queries.GetHost(r.Context(), hostID)
|
||||
if hostErr != nil {
|
||||
slog.Warn("audit: could not fetch host before delete", "host_id", hostID, "error", hostErr)
|
||||
}
|
||||
|
||||
err := h.svc.Delete(r.Context(), hostID, ac.UserID, ac.TeamID, h.isAdmin(r, ac.UserID), force)
|
||||
if err == nil {
|
||||
h.audit.LogHostDelete(r.Context(), ac, hostID, deletedHost.TeamID.String)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
@ -347,12 +357,20 @@ func (h *hostHandler) Heartbeat(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Capture pre-heartbeat status to detect unreachable → online transition.
|
||||
prevHost, _ := h.queries.GetHost(r.Context(), hc.HostID)
|
||||
|
||||
if err := h.svc.Heartbeat(r.Context(), hc.HostID); err != nil {
|
||||
status, code, msg := serviceErrToHTTP(err)
|
||||
writeError(w, status, code, msg)
|
||||
return
|
||||
}
|
||||
|
||||
// Log marked_up if the host just recovered from unreachable.
|
||||
if prevHost.Status == "unreachable" {
|
||||
h.audit.LogHostMarkedUp(r.Context(), prevHost.TeamID.String, hc.HostID)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.omukk.dev/wrenn/sandbox/internal/audit"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/auth"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/db"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/service"
|
||||
@ -14,10 +15,11 @@ import (
|
||||
|
||||
type sandboxHandler struct {
|
||||
svc *service.SandboxService
|
||||
audit *audit.AuditLogger
|
||||
}
|
||||
|
||||
func newSandboxHandler(svc *service.SandboxService) *sandboxHandler {
|
||||
return &sandboxHandler{svc: svc}
|
||||
func newSandboxHandler(svc *service.SandboxService, al *audit.AuditLogger) *sandboxHandler {
|
||||
return &sandboxHandler{svc: svc, audit: al}
|
||||
}
|
||||
|
||||
type createSandboxRequest struct {
|
||||
@ -97,6 +99,7 @@ func (h *sandboxHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogSandboxCreate(r.Context(), ac, sb.ID, sb.Template)
|
||||
writeJSON(w, http.StatusCreated, sandboxToResponse(sb))
|
||||
}
|
||||
|
||||
@ -143,6 +146,7 @@ func (h *sandboxHandler) Pause(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogSandboxPause(r.Context(), ac, sandboxID)
|
||||
writeJSON(w, http.StatusOK, sandboxToResponse(sb))
|
||||
}
|
||||
|
||||
@ -158,6 +162,7 @@ func (h *sandboxHandler) Resume(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogSandboxResume(r.Context(), ac, sandboxID)
|
||||
writeJSON(w, http.StatusOK, sandboxToResponse(sb))
|
||||
}
|
||||
|
||||
@ -186,5 +191,6 @@ func (h *sandboxHandler) Destroy(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogSandboxDestroy(r.Context(), ac, sandboxID)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@ -12,6 +12,7 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.omukk.dev/wrenn/sandbox/internal/audit"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/auth"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/db"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/id"
|
||||
@ -25,10 +26,11 @@ type snapshotHandler struct {
|
||||
svc *service.TemplateService
|
||||
db *db.Queries
|
||||
pool *lifecycle.HostClientPool
|
||||
audit *audit.AuditLogger
|
||||
}
|
||||
|
||||
func newSnapshotHandler(svc *service.TemplateService, db *db.Queries, pool *lifecycle.HostClientPool) *snapshotHandler {
|
||||
return &snapshotHandler{svc: svc, db: db, pool: pool}
|
||||
func newSnapshotHandler(svc *service.TemplateService, db *db.Queries, pool *lifecycle.HostClientPool, al *audit.AuditLogger) *snapshotHandler {
|
||||
return &snapshotHandler{svc: svc, db: db, pool: pool, audit: al}
|
||||
}
|
||||
|
||||
// deleteSnapshotBroadcast attempts to delete snapshot files on all online hosts.
|
||||
@ -180,6 +182,7 @@ func (h *snapshotHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogSnapshotCreate(r.Context(), ac, req.Name)
|
||||
writeJSON(w, http.StatusCreated, templateToResponse(tmpl))
|
||||
}
|
||||
|
||||
@ -227,5 +230,6 @@ func (h *snapshotHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogSnapshotDelete(r.Context(), ac, name)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@ -1,12 +1,14 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.omukk.dev/wrenn/sandbox/internal/audit"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/auth"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/db"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/service"
|
||||
@ -14,10 +16,11 @@ import (
|
||||
|
||||
type teamHandler struct {
|
||||
svc *service.TeamService
|
||||
audit *audit.AuditLogger
|
||||
}
|
||||
|
||||
func newTeamHandler(svc *service.TeamService) *teamHandler {
|
||||
return &teamHandler{svc: svc}
|
||||
func newTeamHandler(svc *service.TeamService, al *audit.AuditLogger) *teamHandler {
|
||||
return &teamHandler{svc: svc, audit: al}
|
||||
}
|
||||
|
||||
// teamResponse is the JSON shape for a team.
|
||||
@ -179,12 +182,19 @@ func (h *teamHandler) Rename(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
|
||||
// Fetch old name for audit log before renaming.
|
||||
oldTeam, err := h.svc.GetTeam(r.Context(), teamID)
|
||||
if err != nil {
|
||||
slog.Warn("audit: could not fetch old team name for rename log", "team_id", teamID, "error", err)
|
||||
}
|
||||
|
||||
if err := h.svc.RenameTeam(r.Context(), teamID, ac.UserID, req.Name); err != nil {
|
||||
status, code, msg := serviceErrToHTTP(err)
|
||||
writeError(w, status, code, msg)
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogTeamRename(r.Context(), ac, teamID, oldTeam.Name, req.Name)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@ -257,6 +267,7 @@ func (h *teamHandler) AddMember(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogMemberAdd(r.Context(), ac, member.UserID, member.Email, member.Role)
|
||||
writeJSON(w, http.StatusCreated, memberInfoToResponse(member))
|
||||
}
|
||||
|
||||
@ -276,6 +287,7 @@ func (h *teamHandler) RemoveMember(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogMemberRemove(r.Context(), ac, targetUserID)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@ -303,6 +315,7 @@ func (h *teamHandler) UpdateMemberRole(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogMemberRoleUpdate(r.Context(), ac, targetUserID, req.Role)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@ -321,6 +334,7 @@ func (h *teamHandler) Leave(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogMemberLeave(r.Context(), ac)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
@ -5,11 +5,12 @@ import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"connectrpc.com/connect"
|
||||
|
||||
"git.omukk.dev/wrenn/sandbox/internal/audit"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/db"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/lifecycle"
|
||||
pb "git.omukk.dev/wrenn/sandbox/proto/hostagent/gen"
|
||||
|
||||
"connectrpc.com/connect"
|
||||
)
|
||||
|
||||
// unreachableThreshold is how long a host can go without a heartbeat before
|
||||
@ -27,14 +28,16 @@ const unreachableThreshold = 90 * time.Second
|
||||
type HostMonitor struct {
|
||||
db *db.Queries
|
||||
pool *lifecycle.HostClientPool
|
||||
audit *audit.AuditLogger
|
||||
interval time.Duration
|
||||
}
|
||||
|
||||
// NewHostMonitor creates a HostMonitor.
|
||||
func NewHostMonitor(queries *db.Queries, pool *lifecycle.HostClientPool, interval time.Duration) *HostMonitor {
|
||||
func NewHostMonitor(queries *db.Queries, pool *lifecycle.HostClientPool, al *audit.AuditLogger, interval time.Duration) *HostMonitor {
|
||||
return &HostMonitor{
|
||||
db: queries,
|
||||
pool: pool,
|
||||
audit: al,
|
||||
interval: interval,
|
||||
}
|
||||
}
|
||||
@ -87,6 +90,7 @@ func (m *HostMonitor) checkHost(ctx context.Context, host db.Host) {
|
||||
if err := m.db.MarkSandboxesMissingByHost(ctx, host.ID); err != nil {
|
||||
slog.Warn("host monitor: failed to mark sandboxes missing", "host_id", host.ID, "error", err)
|
||||
}
|
||||
m.audit.LogHostMarkedDown(ctx, host.TeamID.String, host.ID)
|
||||
return
|
||||
}
|
||||
|
||||
@ -170,7 +174,9 @@ func (m *HostMonitor) checkHost(ctx context.Context, host db.Host) {
|
||||
}
|
||||
|
||||
var toPause, toStop []string
|
||||
sbTeamID := make(map[string]string, len(runningSandboxes))
|
||||
for _, sb := range runningSandboxes {
|
||||
sbTeamID[sb.ID] = sb.TeamID
|
||||
if _, ok := alive[sb.ID]; ok {
|
||||
continue
|
||||
}
|
||||
@ -189,6 +195,9 @@ func (m *HostMonitor) checkHost(ctx context.Context, host db.Host) {
|
||||
}); err != nil {
|
||||
slog.Warn("host monitor: failed to mark paused", "host_id", host.ID, "error", err)
|
||||
}
|
||||
for _, sbID := range toPause {
|
||||
m.audit.LogSandboxAutoPause(ctx, sbTeamID[sbID], sbID)
|
||||
}
|
||||
}
|
||||
if len(toStop) > 0 {
|
||||
slog.Info("host monitor: marking orphaned sandboxes stopped", "host_id", host.ID, "count", len(toStop))
|
||||
|
||||
@ -27,7 +27,11 @@ func requireAPIKeyOrJWT(queries *db.Queries, jwtSecret []byte) func(http.Handler
|
||||
slog.Warn("failed to update api key last_used", "key_id", row.ID, "error", err)
|
||||
}
|
||||
|
||||
ctx := auth.WithAuthContext(r.Context(), auth.AuthContext{TeamID: row.TeamID})
|
||||
ctx := auth.WithAuthContext(r.Context(), auth.AuthContext{
|
||||
TeamID: row.TeamID,
|
||||
APIKeyID: row.ID,
|
||||
APIKeyName: row.Name,
|
||||
})
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
return
|
||||
}
|
||||
|
||||
@ -9,6 +9,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"git.omukk.dev/wrenn/sandbox/internal/audit"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/auth/oauth"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/db"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/lifecycle"
|
||||
@ -44,19 +45,23 @@ func New(
|
||||
templateSvc := &service.TemplateService{DB: queries}
|
||||
hostSvc := &service.HostService{DB: queries, Redis: rdb, JWT: jwtSecret, Pool: pool}
|
||||
teamSvc := &service.TeamService{DB: queries, Pool: pgPool, HostPool: pool}
|
||||
auditSvc := &service.AuditService{DB: queries}
|
||||
|
||||
sandbox := newSandboxHandler(sandboxSvc)
|
||||
al := audit.New(queries)
|
||||
|
||||
sandbox := newSandboxHandler(sandboxSvc, al)
|
||||
exec := newExecHandler(queries, pool)
|
||||
execStream := newExecStreamHandler(queries, pool)
|
||||
files := newFilesHandler(queries, pool)
|
||||
filesStream := newFilesStreamHandler(queries, pool)
|
||||
snapshots := newSnapshotHandler(templateSvc, queries, pool)
|
||||
snapshots := newSnapshotHandler(templateSvc, queries, pool, al)
|
||||
authH := newAuthHandler(queries, pgPool, jwtSecret)
|
||||
oauthH := newOAuthHandler(queries, pgPool, jwtSecret, oauthRegistry, oauthRedirectURL)
|
||||
apiKeys := newAPIKeyHandler(apiKeySvc)
|
||||
hostH := newHostHandler(hostSvc, queries)
|
||||
teamH := newTeamHandler(teamSvc)
|
||||
apiKeys := newAPIKeyHandler(apiKeySvc, al)
|
||||
hostH := newHostHandler(hostSvc, queries, al)
|
||||
teamH := newTeamHandler(teamSvc, al)
|
||||
usersH := newUsersHandler(teamSvc)
|
||||
auditH := newAuditHandler(auditSvc)
|
||||
|
||||
// OpenAPI spec and docs.
|
||||
r.Get("/openapi.yaml", serveOpenAPI)
|
||||
@ -156,6 +161,9 @@ func New(
|
||||
})
|
||||
})
|
||||
|
||||
// JWT-authenticated: audit log.
|
||||
r.With(requireJWT(jwtSecret)).Get("/v1/audit-logs", auditH.List)
|
||||
|
||||
// Platform admin routes — require JWT + DB-validated admin status.
|
||||
r.Route("/v1/admin", func(r chi.Router) {
|
||||
r.Use(requireJWT(jwtSecret))
|
||||
|
||||
403
internal/audit/logger.go
Normal file
403
internal/audit/logger.go
Normal file
@ -0,0 +1,403 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.omukk.dev/wrenn/sandbox/internal/auth"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/db"
|
||||
"git.omukk.dev/wrenn/sandbox/internal/id"
|
||||
)
|
||||
|
||||
// AuditLogger writes audit log entries for user-initiated and system events.
|
||||
// All methods are fire-and-forget: failures are logged via slog and never
|
||||
// propagated to the caller.
|
||||
type AuditLogger struct {
|
||||
db *db.Queries
|
||||
}
|
||||
|
||||
// New constructs an AuditLogger.
|
||||
func New(queries *db.Queries) *AuditLogger {
|
||||
return &AuditLogger{db: queries}
|
||||
}
|
||||
|
||||
// actorFields extracts actor_type, actor_id, and actor_name from an AuthContext.
|
||||
func actorFields(ac auth.AuthContext) (actorType string, actorID pgtype.Text, actorName pgtype.Text) {
|
||||
if ac.UserID != "" {
|
||||
return "user",
|
||||
pgtype.Text{String: ac.UserID, Valid: true},
|
||||
pgtype.Text{String: ac.Name, Valid: ac.Name != ""}
|
||||
}
|
||||
if ac.APIKeyID != "" {
|
||||
return "api_key",
|
||||
pgtype.Text{String: ac.APIKeyID, Valid: true},
|
||||
pgtype.Text{String: ac.APIKeyName, Valid: true}
|
||||
}
|
||||
return "system", pgtype.Text{}, pgtype.Text{}
|
||||
}
|
||||
|
||||
func (l *AuditLogger) write(ctx context.Context, p db.InsertAuditLogParams) {
|
||||
if err := l.db.InsertAuditLog(ctx, p); err != nil {
|
||||
slog.Warn("audit: failed to write log entry",
|
||||
"action", p.Action,
|
||||
"resource_type", p.ResourceType,
|
||||
"team_id", p.TeamID,
|
||||
"error", err,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func marshalMeta(meta map[string]any) []byte {
|
||||
if len(meta) == 0 {
|
||||
return []byte("{}")
|
||||
}
|
||||
b, err := json.Marshal(meta)
|
||||
if err != nil {
|
||||
return []byte("{}")
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// --- Sandbox events (scope: team) ---
|
||||
|
||||
func (l *AuditLogger) LogSandboxCreate(ctx context.Context, ac auth.AuthContext, sandboxID, template string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "sandbox",
|
||||
ResourceID: pgtype.Text{String: sandboxID, Valid: true},
|
||||
Action: "create",
|
||||
Scope: "team",
|
||||
Status: "success",
|
||||
Metadata: marshalMeta(map[string]any{"template": template}),
|
||||
})
|
||||
}
|
||||
|
||||
func (l *AuditLogger) LogSandboxPause(ctx context.Context, ac auth.AuthContext, sandboxID string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "sandbox",
|
||||
ResourceID: pgtype.Text{String: sandboxID, Valid: true},
|
||||
Action: "pause",
|
||||
Scope: "team",
|
||||
Status: "success",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
// LogSandboxAutoPause records a system-initiated auto-pause (TTL or host reconciler).
|
||||
func (l *AuditLogger) LogSandboxAutoPause(ctx context.Context, teamID, sandboxID string) {
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: teamID,
|
||||
ActorType: "system",
|
||||
ActorID: pgtype.Text{},
|
||||
ActorName: pgtype.Text{},
|
||||
ResourceType: "sandbox",
|
||||
ResourceID: pgtype.Text{String: sandboxID, Valid: true},
|
||||
Action: "pause",
|
||||
Scope: "team",
|
||||
Status: "info",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
func (l *AuditLogger) LogSandboxResume(ctx context.Context, ac auth.AuthContext, sandboxID string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "sandbox",
|
||||
ResourceID: pgtype.Text{String: sandboxID, Valid: true},
|
||||
Action: "resume",
|
||||
Scope: "team",
|
||||
Status: "success",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
func (l *AuditLogger) LogSandboxDestroy(ctx context.Context, ac auth.AuthContext, sandboxID string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "sandbox",
|
||||
ResourceID: pgtype.Text{String: sandboxID, Valid: true},
|
||||
Action: "destroy",
|
||||
Scope: "team",
|
||||
Status: "warning",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
// --- Snapshot events (scope: team) ---
|
||||
|
||||
func (l *AuditLogger) LogSnapshotCreate(ctx context.Context, ac auth.AuthContext, name string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "snapshot",
|
||||
ResourceID: pgtype.Text{String: name, Valid: true},
|
||||
Action: "create",
|
||||
Scope: "team",
|
||||
Status: "success",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
func (l *AuditLogger) LogSnapshotDelete(ctx context.Context, ac auth.AuthContext, name string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "snapshot",
|
||||
ResourceID: pgtype.Text{String: name, Valid: true},
|
||||
Action: "delete",
|
||||
Scope: "team",
|
||||
Status: "warning",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
// --- Team events (scope: team) ---
|
||||
|
||||
func (l *AuditLogger) LogTeamRename(ctx context.Context, ac auth.AuthContext, teamID, oldName, newName string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "team",
|
||||
ResourceID: pgtype.Text{String: teamID, Valid: true},
|
||||
Action: "rename",
|
||||
Scope: "team",
|
||||
Status: "info",
|
||||
Metadata: marshalMeta(map[string]any{"old_name": oldName, "new_name": newName}),
|
||||
})
|
||||
}
|
||||
|
||||
// --- API key events (scope: team) ---
|
||||
|
||||
func (l *AuditLogger) LogAPIKeyCreate(ctx context.Context, ac auth.AuthContext, keyID, keyName string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "api_key",
|
||||
ResourceID: pgtype.Text{String: keyID, Valid: true},
|
||||
Action: "create",
|
||||
Scope: "team",
|
||||
Status: "success",
|
||||
Metadata: marshalMeta(map[string]any{"name": keyName}),
|
||||
})
|
||||
}
|
||||
|
||||
func (l *AuditLogger) LogAPIKeyRevoke(ctx context.Context, ac auth.AuthContext, keyID string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "api_key",
|
||||
ResourceID: pgtype.Text{String: keyID, Valid: true},
|
||||
Action: "revoke",
|
||||
Scope: "team",
|
||||
Status: "warning",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
// --- Member events (scope: admin) ---
|
||||
|
||||
func (l *AuditLogger) LogMemberAdd(ctx context.Context, ac auth.AuthContext, targetUserID, targetEmail, role string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "member",
|
||||
ResourceID: pgtype.Text{String: targetUserID, Valid: true},
|
||||
Action: "add",
|
||||
Scope: "admin",
|
||||
Status: "success",
|
||||
Metadata: marshalMeta(map[string]any{"email": targetEmail, "role": role}),
|
||||
})
|
||||
}
|
||||
|
||||
func (l *AuditLogger) LogMemberRemove(ctx context.Context, ac auth.AuthContext, targetUserID string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "member",
|
||||
ResourceID: pgtype.Text{String: targetUserID, Valid: true},
|
||||
Action: "remove",
|
||||
Scope: "admin",
|
||||
Status: "warning",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
func (l *AuditLogger) LogMemberLeave(ctx context.Context, ac auth.AuthContext) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "member",
|
||||
ResourceID: pgtype.Text{String: ac.UserID, Valid: ac.UserID != ""},
|
||||
Action: "leave",
|
||||
Scope: "admin",
|
||||
Status: "info",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
func (l *AuditLogger) LogMemberRoleUpdate(ctx context.Context, ac auth.AuthContext, targetUserID, newRole string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: ac.TeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "member",
|
||||
ResourceID: pgtype.Text{String: targetUserID, Valid: true},
|
||||
Action: "role_update",
|
||||
Scope: "admin",
|
||||
Status: "info",
|
||||
Metadata: marshalMeta(map[string]any{"new_role": newRole}),
|
||||
})
|
||||
}
|
||||
|
||||
// --- Host events (scope: admin) ---
|
||||
|
||||
func (l *AuditLogger) LogHostCreate(ctx context.Context, ac auth.AuthContext, hostID, teamID string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
// For shared hosts with no owning team, use the caller's team.
|
||||
logTeamID := teamID
|
||||
if logTeamID == "" {
|
||||
logTeamID = ac.TeamID
|
||||
}
|
||||
if logTeamID == "" {
|
||||
return
|
||||
}
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: logTeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "host",
|
||||
ResourceID: pgtype.Text{String: hostID, Valid: true},
|
||||
Action: "create",
|
||||
Scope: "admin",
|
||||
Status: "success",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
func (l *AuditLogger) LogHostDelete(ctx context.Context, ac auth.AuthContext, hostID, teamID string) {
|
||||
actorType, actorID, actorName := actorFields(ac)
|
||||
logTeamID := teamID
|
||||
if logTeamID == "" {
|
||||
logTeamID = ac.TeamID
|
||||
}
|
||||
if logTeamID == "" {
|
||||
return
|
||||
}
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: logTeamID,
|
||||
ActorType: actorType,
|
||||
ActorID: actorID,
|
||||
ActorName: actorName,
|
||||
ResourceType: "host",
|
||||
ResourceID: pgtype.Text{String: hostID, Valid: true},
|
||||
Action: "delete",
|
||||
Scope: "admin",
|
||||
Status: "warning",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
// LogHostMarkedDown records a system-initiated host status transition to unreachable.
|
||||
// teamID must be non-empty (BYOC hosts only); shared hosts are not logged.
|
||||
func (l *AuditLogger) LogHostMarkedDown(ctx context.Context, teamID, hostID string) {
|
||||
if teamID == "" {
|
||||
return
|
||||
}
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: teamID,
|
||||
ActorType: "system",
|
||||
ActorID: pgtype.Text{},
|
||||
ActorName: pgtype.Text{},
|
||||
ResourceType: "host",
|
||||
ResourceID: pgtype.Text{String: hostID, Valid: true},
|
||||
Action: "marked_down",
|
||||
Scope: "admin",
|
||||
Status: "error",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
|
||||
// LogHostMarkedUp records a system-initiated host status transition back to online.
|
||||
// teamID must be non-empty (BYOC hosts only); shared hosts are not logged.
|
||||
func (l *AuditLogger) LogHostMarkedUp(ctx context.Context, teamID, hostID string) {
|
||||
if teamID == "" {
|
||||
return
|
||||
}
|
||||
l.write(ctx, db.InsertAuditLogParams{
|
||||
ID: id.NewAuditLogID(),
|
||||
TeamID: teamID,
|
||||
ActorType: "system",
|
||||
ActorID: pgtype.Text{},
|
||||
ActorName: pgtype.Text{},
|
||||
ResourceType: "host",
|
||||
ResourceID: pgtype.Text{String: hostID, Valid: true},
|
||||
Action: "marked_up",
|
||||
Scope: "admin",
|
||||
Status: "success",
|
||||
Metadata: []byte("{}"),
|
||||
})
|
||||
}
|
||||
@ -14,6 +14,8 @@ type AuthContext struct {
|
||||
Name string // empty when authenticated via API key
|
||||
Role string // owner, admin, or member; empty when authenticated via API key
|
||||
IsAdmin bool // platform-level admin; always false when authenticated via API key
|
||||
APIKeyID string // populated when authenticated via API key; empty for JWT auth
|
||||
APIKeyName string // display name of the key, snapshotted at auth time; empty for JWT auth
|
||||
}
|
||||
|
||||
// WithAuthContext returns a new context with the given AuthContext.
|
||||
|
||||
111
internal/db/audit.sql.go
Normal file
111
internal/db/audit.sql.go
Normal file
@ -0,0 +1,111 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.30.0
|
||||
// source: audit.sql
|
||||
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const insertAuditLog = `-- name: InsertAuditLog :exec
|
||||
INSERT INTO audit_logs (id, team_id, actor_type, actor_id, actor_name, resource_type, resource_id, action, scope, status, metadata)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||
`
|
||||
|
||||
type InsertAuditLogParams struct {
|
||||
ID string `json:"id"`
|
||||
TeamID string `json:"team_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorID pgtype.Text `json:"actor_id"`
|
||||
ActorName pgtype.Text `json:"actor_name"`
|
||||
ResourceType string `json:"resource_type"`
|
||||
ResourceID pgtype.Text `json:"resource_id"`
|
||||
Action string `json:"action"`
|
||||
Scope string `json:"scope"`
|
||||
Status string `json:"status"`
|
||||
Metadata []byte `json:"metadata"`
|
||||
}
|
||||
|
||||
func (q *Queries) InsertAuditLog(ctx context.Context, arg InsertAuditLogParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAuditLog,
|
||||
arg.ID,
|
||||
arg.TeamID,
|
||||
arg.ActorType,
|
||||
arg.ActorID,
|
||||
arg.ActorName,
|
||||
arg.ResourceType,
|
||||
arg.ResourceID,
|
||||
arg.Action,
|
||||
arg.Scope,
|
||||
arg.Status,
|
||||
arg.Metadata,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listAuditLogs = `-- name: ListAuditLogs :many
|
||||
SELECT id, team_id, actor_type, actor_id, actor_name, resource_type, resource_id, action, scope, status, metadata, created_at FROM audit_logs
|
||||
WHERE team_id = $1
|
||||
AND scope = ANY($2::text[])
|
||||
AND (cardinality($3::text[]) = 0 OR resource_type = ANY($3::text[]))
|
||||
AND (cardinality($4::text[]) = 0 OR action = ANY($4::text[]))
|
||||
AND ($5::timestamptz IS NULL OR created_at < $5
|
||||
OR (created_at = $5 AND id < $6))
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT $7
|
||||
`
|
||||
|
||||
type ListAuditLogsParams struct {
|
||||
TeamID string `json:"team_id"`
|
||||
Column2 []string `json:"column_2"`
|
||||
Column3 []string `json:"column_3"`
|
||||
Column4 []string `json:"column_4"`
|
||||
Column5 pgtype.Timestamptz `json:"column_5"`
|
||||
ID string `json:"id"`
|
||||
Limit int32 `json:"limit"`
|
||||
}
|
||||
|
||||
func (q *Queries) ListAuditLogs(ctx context.Context, arg ListAuditLogsParams) ([]AuditLog, error) {
|
||||
rows, err := q.db.Query(ctx, listAuditLogs,
|
||||
arg.TeamID,
|
||||
arg.Column2,
|
||||
arg.Column3,
|
||||
arg.Column4,
|
||||
arg.Column5,
|
||||
arg.ID,
|
||||
arg.Limit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []AuditLog
|
||||
for rows.Next() {
|
||||
var i AuditLog
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.TeamID,
|
||||
&i.ActorType,
|
||||
&i.ActorID,
|
||||
&i.ActorName,
|
||||
&i.ResourceType,
|
||||
&i.ResourceID,
|
||||
&i.Action,
|
||||
&i.Scope,
|
||||
&i.Status,
|
||||
&i.Metadata,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@ -583,10 +583,13 @@ WHERE id = $1
|
||||
`
|
||||
|
||||
// Updates last_heartbeat_at and transitions unreachable hosts back to online.
|
||||
// Returns 0 if no host was found (deleted).
|
||||
// Returns 0 if no host was found (deleted), which the caller treats as 404.
|
||||
func (q *Queries) UpdateHostHeartbeatAndStatus(ctx context.Context, id string) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, updateHostHeartbeatAndStatus, id)
|
||||
return result.RowsAffected(), err
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const updateHostStatus = `-- name: UpdateHostStatus :exec
|
||||
|
||||
@ -15,6 +15,21 @@ type AdminPermission struct {
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
}
|
||||
|
||||
type AuditLog struct {
|
||||
ID string `json:"id"`
|
||||
TeamID string `json:"team_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorID pgtype.Text `json:"actor_id"`
|
||||
ActorName pgtype.Text `json:"actor_name"`
|
||||
ResourceType string `json:"resource_type"`
|
||||
ResourceID pgtype.Text `json:"resource_id"`
|
||||
Action string `json:"action"`
|
||||
Scope string `json:"scope"`
|
||||
Status string `json:"status"`
|
||||
Metadata []byte `json:"metadata"`
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
}
|
||||
|
||||
type Host struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
|
||||
@ -73,6 +73,11 @@ func NewRefreshTokenID() string {
|
||||
return "hrt-" + hex8()
|
||||
}
|
||||
|
||||
// NewAuditLogID generates a new audit log ID in the format "log-" + 8 hex chars.
|
||||
func NewAuditLogID() string {
|
||||
return "log-" + hex8()
|
||||
}
|
||||
|
||||
// NewRefreshToken generates a 64-char hex token (32 bytes of entropy) for use as a host refresh token.
|
||||
func NewRefreshToken() string {
|
||||
b := make([]byte, 32)
|
||||
|
||||
112
internal/service/audit.go
Normal file
112
internal/service/audit.go
Normal file
@ -0,0 +1,112 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"git.omukk.dev/wrenn/sandbox/internal/db"
|
||||
)
|
||||
|
||||
const auditMaxLimit = 200
|
||||
|
||||
// AuditEntry is a single audit log record returned by List.
|
||||
type AuditEntry struct {
|
||||
ID string
|
||||
TeamID string
|
||||
ActorType string
|
||||
ActorID string // empty for system
|
||||
ActorName string // empty for system
|
||||
ResourceType string
|
||||
ResourceID string // empty when not applicable
|
||||
Action string
|
||||
Scope string
|
||||
Status string // 'success', 'info', 'warning', 'error'
|
||||
Metadata map[string]any
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// AuditListParams controls the ListAuditLogs query.
|
||||
type AuditListParams struct {
|
||||
TeamID string
|
||||
AdminScoped bool // true → include admin-scoped events; false → team-scoped only
|
||||
ResourceTypes []string // empty = no filter; multiple values = OR match
|
||||
Actions []string // empty = no filter; multiple values = OR match
|
||||
Before time.Time // zero = no cursor (start from latest)
|
||||
BeforeID string // tie-breaker: id of the last item at the Before timestamp; empty = no tie-break
|
||||
Limit int // clamped to auditMaxLimit by the handler
|
||||
}
|
||||
|
||||
// AuditService provides the read side of the audit log.
|
||||
type AuditService struct {
|
||||
DB *db.Queries
|
||||
}
|
||||
|
||||
// List returns a page of audit log entries for the given team.
|
||||
func (s *AuditService) List(ctx context.Context, p AuditListParams) ([]AuditEntry, error) {
|
||||
limit := p.Limit
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > auditMaxLimit {
|
||||
limit = auditMaxLimit
|
||||
}
|
||||
|
||||
scopes := []string{"team"}
|
||||
if p.AdminScoped {
|
||||
scopes = append(scopes, "admin")
|
||||
}
|
||||
|
||||
var before pgtype.Timestamptz
|
||||
if !p.Before.IsZero() {
|
||||
before = pgtype.Timestamptz{Time: p.Before, Valid: true}
|
||||
}
|
||||
|
||||
resourceTypes := p.ResourceTypes
|
||||
if resourceTypes == nil {
|
||||
resourceTypes = []string{}
|
||||
}
|
||||
actions := p.Actions
|
||||
if actions == nil {
|
||||
actions = []string{}
|
||||
}
|
||||
|
||||
rows, err := s.DB.ListAuditLogs(ctx, db.ListAuditLogsParams{
|
||||
TeamID: p.TeamID,
|
||||
Column2: scopes,
|
||||
Column3: resourceTypes,
|
||||
Column4: actions,
|
||||
Column5: before,
|
||||
ID: p.BeforeID,
|
||||
Limit: int32(limit),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list audit logs: %w", err)
|
||||
}
|
||||
|
||||
entries := make([]AuditEntry, len(rows))
|
||||
for i, row := range rows {
|
||||
var meta map[string]any
|
||||
if len(row.Metadata) > 0 {
|
||||
_ = json.Unmarshal(row.Metadata, &meta)
|
||||
}
|
||||
entries[i] = AuditEntry{
|
||||
ID: row.ID,
|
||||
TeamID: row.TeamID,
|
||||
ActorType: row.ActorType,
|
||||
ActorID: row.ActorID.String,
|
||||
ActorName: row.ActorName.String,
|
||||
ResourceType: row.ResourceType,
|
||||
ResourceID: row.ResourceID.String,
|
||||
Action: row.Action,
|
||||
Scope: row.Scope,
|
||||
Status: row.Status,
|
||||
Metadata: meta,
|
||||
CreatedAt: row.CreatedAt.Time,
|
||||
}
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
Reference in New Issue
Block a user