1
0
forked from wrenn/wrenn
## What's new

Compliance, audit, and account lifecycle improvements — admin actions are now fully auditable, user data is properly anonymized on deletion, and OAuth signup flow gives users control over their profile.

### Audit

- Added audit logging for all admin actions (user activate/deactivate, team BYOC toggle, team delete, template delete, build create/cancel)
- Added admin audit page with infinite scroll and hierarchical filters
- Fixed audit log team assignment — admin/host actions now correctly land under PlatformTeamID
- Anonymize audit logs on user hard-delete (actor name, IDs, emails stripped)
- Deduplicated audit logger internals (665 → 374 lines, no behavior change)

### Authentication

- Separated GitHub OAuth login/signup flows — login no longer auto-creates accounts
- Added name confirmation dialog for new GitHub signups

### Account Lifecycle

- Email notification sent when account is permanently deleted after grace period
- Audit log anonymization tied to user purge (per-user transactional)

### UX

- Removed accent gradient bars from admin host dialogs (border + shadow only)
- Frontend renders deleted users as styled badge in audit log view

### Others

- Version bump
- Bug fixes

Reviewed-on: wrenn/wrenn#36
This commit is contained in:
2026-04-21 10:11:49 +00:00
parent 23dca7d9ff
commit 52ad21c339
25 changed files with 1200 additions and 443 deletions

View File

@ -1 +1 @@
0.1.2 0.1.3

View File

@ -9,4 +9,10 @@ VALUES ('00000000-0000-0000-0000-000000000000', 'Platform', 'platform')
ON CONFLICT (id) DO NOTHING; ON CONFLICT (id) DO NOTHING;
-- +goose Down -- +goose Down
-- Delete dependent rows that reference the platform team via foreign keys.
-- Order matters: children before parent.
DELETE FROM sandboxes WHERE team_id = '00000000-0000-0000-0000-000000000000';
DELETE FROM team_api_keys WHERE team_id = '00000000-0000-0000-0000-000000000000';
DELETE FROM users_teams WHERE team_id = '00000000-0000-0000-0000-000000000000';
DELETE FROM hosts WHERE team_id = '00000000-0000-0000-0000-000000000000';
DELETE FROM teams WHERE id = '00000000-0000-0000-0000-000000000000'; DELETE FROM teams WHERE id = '00000000-0000-0000-0000-000000000000';

View File

@ -1,5 +1,5 @@
// Package migrations embeds the SQL migration files so that external modules // Package migrations embeds the SQL migration files so that external modules
// (such as the enterprise edition) can access them programmatically. // (such as the cloud edition) can access them programmatically.
package migrations package migrations
import "embed" import "embed"

View File

@ -2,6 +2,15 @@
INSERT INTO audit_logs (id, team_id, actor_type, actor_id, actor_name, resource_type, resource_id, action, scope, status, metadata) 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); VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);
-- name: AnonymizeAuditLogsByUserID :exec
UPDATE audit_logs
SET actor_name = CASE WHEN actor_id = $1 THEN 'deleted-user' ELSE actor_name END,
actor_id = CASE WHEN actor_id = $1 THEN NULL ELSE actor_id END,
resource_id = CASE WHEN resource_type = 'member' AND resource_id = $1 THEN NULL ELSE resource_id END,
metadata = CASE WHEN resource_type = 'member' AND resource_id = $1 AND metadata ? 'email' THEN metadata - 'email' ELSE metadata END
WHERE actor_id = $1
OR (resource_type = 'member' AND resource_id = $1);
-- name: ListAuditLogs :many -- name: ListAuditLogs :many
SELECT * FROM audit_logs SELECT * FROM audit_logs
WHERE team_id = $1 WHERE team_id = $1

View File

@ -91,8 +91,8 @@ WHERE ut.user_id = $1
WHERE ut2.team_id = ut.team_id AND ut2.user_id <> $1 WHERE ut2.team_id = ut.team_id AND ut2.user_id <> $1
); );
-- name: HardDeleteExpiredUsers :exec -- name: ListExpiredSoftDeletedUsers :many
DELETE FROM users WHERE deleted_at IS NOT NULL AND deleted_at < NOW() - INTERVAL '15 days'; SELECT id, email FROM users WHERE deleted_at IS NOT NULL AND deleted_at < NOW() - INTERVAL '15 days';
-- name: HardDeleteUser :exec -- name: HardDeleteUser :exec
DELETE FROM users WHERE id = $1; DELETE FROM users WHERE id = $1;

View File

@ -0,0 +1,21 @@
import { apiFetch, type ApiResult } from '$lib/api/client';
import type { AuditLog, AuditListResponse } from '$lib/api/audit';
export type { AuditLog, AuditListResponse };
export async function listAdminAuditLogs(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/admin/audit-logs${qs ? '?' + qs : ''}`);
}

View File

@ -13,7 +13,8 @@
IconChevron, IconChevron,
IconShield, IconShield,
IconMembers, IconMembers,
IconUser IconUser,
IconAudit
} from './icons'; } from './icons';
let { collapsed = $bindable(false) }: { collapsed: boolean } = $props(); let { collapsed = $bindable(false) }: { collapsed: boolean } = $props();
@ -26,7 +27,8 @@
const managementItems: NavItem[] = [ const managementItems: NavItem[] = [
{ label: 'Users', icon: IconUser, href: '/admin/users' }, { label: 'Users', icon: IconUser, href: '/admin/users' },
{ label: 'Teams', icon: IconMembers, href: '/admin/teams' } { label: 'Teams', icon: IconMembers, href: '/admin/teams' },
{ label: 'Audit', icon: IconAudit, href: '/admin/audit' }
]; ];
const platformItems: NavItem[] = [ const platformItems: NavItem[] = [

View File

@ -0,0 +1,600 @@
<script lang="ts">
import { onMount } from 'svelte';
import { listAdminAuditLogs, type AuditLog } from '$lib/api/admin-audit';
// ─── 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 ─────────────────────────────────────────────────────────
let selectedActions = $state<Map<string, Set<string>>>(new Map());
// ─── Constants ────────────────────────────────────────────────────────────
const RESOURCES = ['sandbox', 'snapshot', 'template', 'build', 'team', 'api_key', 'member', 'host', 'user', 'channel'] as const;
const RESOURCE_LABELS: Record<string, string> = {
sandbox: 'Capsule',
snapshot: 'Snapshot',
template: 'Template',
build: 'Build',
team: 'Team',
api_key: 'API Key',
member: 'Member',
host: 'Host',
user: 'User',
channel: 'Channel'
};
const ACTIONS_BY_RESOURCE: Record<string, string[]> = {
sandbox: ['create', 'pause', 'resume', 'destroy'],
snapshot: ['create', 'delete'],
template: ['delete'],
build: ['create', 'cancel'],
team: ['rename', 'set_byoc', 'delete'],
api_key: ['create', 'revoke'],
member: ['add', 'remove', 'leave', 'role_update'],
host: ['create', 'delete', 'marked_down', 'marked_up'],
user: ['activate', 'deactivate'],
channel: ['create', 'update', 'rotate_config', 'delete']
};
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',
activate: 'Activated',
deactivate: 'Deactivated',
set_byoc: 'BYOC toggled',
cancel: 'Cancelled',
update: 'Updated',
rotate_config: 'Config rotated'
};
// ─── 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 listAdminAuditLogs(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 listAdminAuditLogs({
...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 ───────────────────────────────────────────────────────────
const DELETED_BADGE = '\x00DELETED\x00';
const deletedBadgeHtml = '<span class="deleted-user-badge">deleted-user</span>';
function renderDeleted(text: string): string {
return text.replaceAll(DELETED_BADGE, deletedBadgeHtml);
}
function describeEvent(log: AuditLog): string {
const actor = log.actor_name === 'deleted-user' ? DELETED_BADGE : (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 snapshot`;
case 'snapshot:delete': return `${actor} deleted a snapshot`;
case 'template:delete': return `${actor} deleted template "${log.resource_id}"`;
case 'build:create': return `${actor} started a build for "${meta.name}"`;
case 'build:cancel': return `${actor} cancelled a build`;
case 'team:rename': return `${actor} renamed a team from "${meta.old_name}" to "${meta.new_name}"`;
case 'team:set_byoc': return `${actor} ${String(meta.enabled) === 'true' ? 'enabled' : 'disabled'} BYOC for a team`;
case 'team:delete': return `${actor} deleted a team`;
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 ?? DELETED_BADGE} as ${meta.role}`;
case 'member:remove': return `${actor} removed ${meta.email ?? DELETED_BADGE}`;
case 'member:leave': return `${actor} left a 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`;
case 'user:activate': return `${actor} activated user ${meta.email ?? ''}`;
case 'user:deactivate': return `${actor} deactivated user ${meta.email ?? ''}`;
case 'channel:create': return `${actor} created channel "${meta.name}"`;
case 'channel:update': return `${actor} updated a channel`;
case 'channel:rotate_config': return `${actor} rotated channel config`;
case 'channel:delete': return `${actor} deleted a channel`;
default: return `${actor} performed ${log.action} on ${log.resource_type}`;
}
}
function actorLabel(log: AuditLog): string {
if (log.actor_type === 'system') return 'System';
if (log.actor_name === 'deleted-user') return DELETED_BADGE;
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 Admin — Audit Logs</title>
</svelte:head>
<main class="flex-1 overflow-y-auto bg-[var(--color-bg-0)]">
<!-- Header -->
<div class="px-7 pt-8">
<h1 class="font-serif text-page text-[var(--color-text-bright)]">
Audit Logs
</h1>
<p class="mt-2 text-ui text-[var(--color-text-secondary)]">
Platform-wide activity log for all admin actions.
</p>
<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 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.'
: 'Admin events will appear here as actions are taken.'}
</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 -->
<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)]">
{@html renderDeleted(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)]">{@html renderDeleted(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>
<style>
@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;
}
:global(.deleted-user-badge) {
display: inline;
padding: 1px 5px;
border-radius: 3px;
font-family: 'JetBrains Mono Variable', monospace;
font-size: var(--text-badge);
color: var(--color-red);
background: rgba(207, 129, 114, 0.12);
border: 1px solid rgba(207, 129, 114, 0.25);
}
</style>

View File

@ -454,12 +454,9 @@
onkeydown={(e) => { if (e.key === 'Escape' && !creating) showCreate = false; }} onkeydown={(e) => { if (e.key === 'Escape' && !creating) showCreate = false; }}
></div> ></div>
<div <div
class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] shadow-dialog" class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)]"
style="animation: fadeUp 0.18s cubic-bezier(0.25,1,0.5,1) both" style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)"
> >
<!-- Top accent edge -->
<div class="h-[2px] rounded-t-[var(--radius-card)] bg-gradient-to-r from-transparent via-[var(--color-accent)] to-transparent"></div>
<div class="p-6"> <div class="p-6">
<h2 class="font-serif text-heading leading-tight text-[var(--color-text-bright)]"> <h2 class="font-serif text-heading leading-tight text-[var(--color-text-bright)]">
Add Platform Host Add Platform Host
@ -534,12 +531,9 @@
<div class="fixed inset-0 z-50 flex items-center justify-center"> <div class="fixed inset-0 z-50 flex items-center justify-center">
<div class="absolute inset-0 bg-black/60"></div> <div class="absolute inset-0 bg-black/60"></div>
<div <div
class="relative w-full max-w-[500px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] shadow-dialog" class="relative w-full max-w-[500px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)]"
style="animation: fadeUp 0.18s cubic-bezier(0.25,1,0.5,1) both" style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)"
> >
<!-- Success accent edge -->
<div class="h-[2px] rounded-t-[var(--radius-card)] bg-gradient-to-r from-transparent via-[var(--color-accent-bright)] to-transparent"></div>
<div class="p-6"> <div class="p-6">
<!-- Animated checkmark --> <!-- Animated checkmark -->
<div class="mb-5 flex h-12 w-12 items-center justify-center rounded-full bg-[var(--color-accent-glow-mid)]"> <div class="mb-5 flex h-12 w-12 items-center justify-center rounded-full bg-[var(--color-accent-glow-mid)]">
@ -607,12 +601,9 @@
onkeydown={(e) => { if (e.key === 'Escape' && !deleting) deleteTarget = null; }} onkeydown={(e) => { if (e.key === 'Escape' && !deleting) deleteTarget = null; }}
></div> ></div>
<div <div
class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] shadow-dialog" class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)]"
style="animation: fadeUp 0.18s cubic-bezier(0.25,1,0.5,1) both" style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)"
> >
<!-- Danger accent edge -->
<div class="h-[2px] rounded-t-[var(--radius-card)] bg-gradient-to-r from-transparent via-[var(--color-red)] to-transparent"></div>
<div class="p-6"> <div class="p-6">
<h2 class="font-serif text-heading leading-tight text-[var(--color-text-bright)]"> <h2 class="font-serif text-heading leading-tight text-[var(--color-text-bright)]">
Delete Host Delete Host

View File

@ -1,12 +1,18 @@
<script lang="ts"> <script lang="ts">
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { page } from '$app/stores'; import { page } from '$app/stores';
import { onMount } from 'svelte';
import { auth } from '$lib/auth.svelte'; import { auth } from '$lib/auth.svelte';
import { teams } from '$lib/teams.svelte'; import { teams } from '$lib/teams.svelte';
import { updateName } from '$lib/api/me';
import { IconUser, IconMail } from '$lib/components/icons';
// Check for error in URL params (errors are still passed via query params). let showConfirmDialog = $state(false);
const params = $page.url.searchParams; let confirmName = $state('');
const error = params.get('error'); let confirmEmail = $state('');
let saving = $state(false);
let nameError = $state('');
let pendingAuth: { token: string; user_id: string; team_id: string; email: string; name: string } | null = null;
function getCookie(name: string): string | null { function getCookie(name: string): string | null {
const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`)); const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
@ -19,33 +25,157 @@
'wrenn_oauth_user_id', 'wrenn_oauth_user_id',
'wrenn_oauth_team_id', 'wrenn_oauth_team_id',
'wrenn_oauth_email', 'wrenn_oauth_email',
'wrenn_oauth_name' 'wrenn_oauth_name',
'wrenn_oauth_new_signup'
]) { ]) {
document.cookie = `${name}=; path=/auth/; max-age=0`; document.cookie = `${name}=; path=/auth/; max-age=0`;
} }
} }
function finishLogin() {
if (!pendingAuth) return;
teams.reset();
auth.login(pendingAuth);
goto('/dashboard');
}
async function handleConfirm() {
if (!pendingAuth) return;
saving = true;
nameError = '';
// Update name if user changed it.
if (confirmName.trim() && confirmName.trim() !== pendingAuth.name) {
// Log in first so the PATCH /v1/me request is authenticated.
teams.reset();
auth.login(pendingAuth);
const result = await updateName(confirmName.trim());
if (result.ok) {
// updateName returns refreshed auth data — re-login with updated info.
auth.login(result.data);
goto('/dashboard');
} else {
nameError = result.error;
saving = false;
}
} else {
finishLogin();
}
}
onMount(() => {
const params = $page.url.searchParams;
const error = params.get('error');
if (error) { if (error) {
goto(`/login?error=${encodeURIComponent(error)}`); goto(`/login?error=${encodeURIComponent(error)}`);
} else { return;
}
const token = getCookie('wrenn_oauth_token'); const token = getCookie('wrenn_oauth_token');
const userId = getCookie('wrenn_oauth_user_id'); const userId = getCookie('wrenn_oauth_user_id');
const teamId = getCookie('wrenn_oauth_team_id'); const teamId = getCookie('wrenn_oauth_team_id');
const email = getCookie('wrenn_oauth_email'); const email = getCookie('wrenn_oauth_email');
const name = getCookie('wrenn_oauth_name') ?? ''; const name = getCookie('wrenn_oauth_name') ?? '';
const isNewSignup = getCookie('wrenn_oauth_new_signup') === '1';
clearOAuthCookies(); clearOAuthCookies();
if (token && userId && teamId && email) { if (token && userId && teamId && email) {
teams.reset(); pendingAuth = { token, user_id: userId, team_id: teamId, email, name };
auth.login({ token, user_id: userId, team_id: teamId, email, name });
goto('/dashboard'); if (isNewSignup) {
confirmName = name;
confirmEmail = email;
showConfirmDialog = true;
} else {
finishLogin();
}
} else { } else {
goto('/login?error=missing_token'); goto('/login?error=missing_token');
} }
} });
</script> </script>
{#if showConfirmDialog}
<div class="flex min-h-screen items-center justify-center bg-[var(--color-bg-0)]">
<div
class="w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)]"
style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)"
>
<div class="p-6">
<h2 class="font-serif text-heading text-[var(--color-text-bright)]">Almost there</h2>
<p class="mt-1.5 text-ui text-[var(--color-text-secondary)]">
We pulled your details from GitHub. Change your display name if you'd like.
</p>
<div class="mt-5 space-y-3">
<!-- Name (editable) -->
<div>
<label for="confirm-name" class="mb-1.5 block text-label uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">
Display name
</label>
<div class="group relative">
<div class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)] transition-colors duration-150 group-focus-within:text-[var(--color-accent)]">
<IconUser size={14} />
</div>
<input
id="confirm-name"
type="text"
bind:value={confirmName}
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-2)] py-3 pl-9 pr-3 text-body text-[var(--color-text-bright)] outline-none transition-all duration-150 placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-accent)]"
/>
</div>
</div>
<!-- Email (read-only) -->
<div>
<label for="confirm-email" class="mb-1.5 block text-label uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]">
Email
</label>
<div class="group relative">
<div class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--color-text-muted)]">
<IconMail size={14} />
</div>
<input
id="confirm-email"
type="email"
value={confirmEmail}
disabled
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-3)] py-3 pl-9 pr-3 text-body text-[var(--color-text-secondary)] outline-none cursor-not-allowed pointer-events-none"
/>
</div>
</div>
</div>
{#if nameError}
<p class="mt-3 text-ui text-[var(--color-red)]">{nameError}</p>
{/if}
<!-- Actions -->
<div class="mt-6 flex justify-end">
<button
type="button"
onclick={handleConfirm}
disabled={saving || !confirmName.trim()}
class="rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2.5 text-body font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:pointer-events-none disabled:opacity-50"
>
{#if saving}
<span class="inline-flex items-center gap-2">
<span class="inline-block h-3.5 w-3.5 animate-spin rounded-full border-2 border-white/30 border-t-white"></span>
Setting up…
</span>
{:else}
Get started
{/if}
</button>
</div>
</div>
</div>
</div>
{:else}
<div class="flex min-h-screen items-center justify-center"> <div class="flex min-h-screen items-center justify-center">
<p class="text-ui text-[var(--color-text-secondary)]">Signing you in...</p> <p class="text-ui text-[var(--color-text-secondary)]">Signing you in...</p>
</div> </div>
{/if}

View File

@ -192,8 +192,15 @@
// ─── UI helpers ─────────────────────────────────────────────────────────── // ─── UI helpers ───────────────────────────────────────────────────────────
const DELETED_BADGE = '\x00DELETED\x00';
const deletedBadgeHtml = '<span class="deleted-user-badge">deleted-user</span>';
function renderDeleted(text: string): string {
return text.replaceAll(DELETED_BADGE, deletedBadgeHtml);
}
function describeEvent(log: AuditLog): string { function describeEvent(log: AuditLog): string {
const actor = log.actor_name || (log.actor_type === 'system' ? 'System' : 'Unknown'); const actor = log.actor_name === 'deleted-user' ? DELETED_BADGE : (log.actor_name || (log.actor_type === 'system' ? 'System' : 'Unknown'));
const meta = (log.metadata ?? {}) as Record<string, string>; const meta = (log.metadata ?? {}) as Record<string, string>;
switch (`${log.resource_type}:${log.action}`) { switch (`${log.resource_type}:${log.action}`) {
case 'sandbox:create': return `${actor} created a capsule`; case 'sandbox:create': return `${actor} created a capsule`;
@ -205,8 +212,8 @@
case 'team:rename': return `${actor} renamed the team from "${meta.old_name}" to "${meta.new_name}"`; 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:create': return `${actor} created API key "${meta.name}"`;
case 'api_key:revoke': return `${actor} revoked an API key`; case 'api_key:revoke': return `${actor} revoked an API key`;
case 'member:add': return `${actor} added ${meta.email} as ${meta.role}`; case 'member:add': return `${actor} added ${meta.email ?? DELETED_BADGE} as ${meta.role}`;
case 'member:remove': return `${actor} removed ${meta.email ?? 'a member'}`; case 'member:remove': return `${actor} removed ${meta.email ?? DELETED_BADGE}`;
case 'member:leave': return `${actor} left the team`; case 'member:leave': return `${actor} left the team`;
case 'member:role_update': return `${actor} changed a member's role to ${meta.new_role}`; 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:create': return `${actor} registered a host`;
@ -219,6 +226,7 @@
function actorLabel(log: AuditLog): string { function actorLabel(log: AuditLog): string {
if (log.actor_type === 'system') return 'System'; if (log.actor_type === 'system') return 'System';
if (log.actor_name === 'deleted-user') return DELETED_BADGE;
return log.actor_name ?? '—'; return log.actor_name ?? '—';
} }
@ -498,7 +506,7 @@
<div class="min-w-0 px-4 py-4"> <div class="min-w-0 px-4 py-4">
<div class="flex flex-col gap-1"> <div class="flex flex-col gap-1">
<span class="truncate text-ui font-medium text-[var(--color-text-bright)]"> <span class="truncate text-ui font-medium text-[var(--color-text-bright)]">
{actorLabel(log)} {@html renderDeleted(actorLabel(log))}
</span> </span>
{#if log.actor_type === 'api_key'} {#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> <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>
@ -508,7 +516,7 @@
<!-- Event description + resource ID --> <!-- Event description + resource ID -->
<div class="min-w-0 px-4 py-4"> <div class="min-w-0 px-4 py-4">
<p class="text-ui font-medium text-[var(--color-text-primary)]">{describeEvent(log)}</p> <p class="text-ui font-medium text-[var(--color-text-primary)]">{@html renderDeleted(describeEvent(log))}</p>
{#if log.resource_id} {#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> <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} {/if}
@ -567,4 +575,15 @@
.stripe-pulse { .stripe-pulse {
animation: stripePulse 2.5s ease-in-out infinite; animation: stripePulse 2.5s ease-in-out infinite;
} }
:global(.deleted-user-badge) {
display: inline;
padding: 1px 5px;
border-radius: 3px;
font-family: 'JetBrains Mono Variable', monospace;
font-size: var(--text-badge);
color: var(--color-red);
background: rgba(207, 129, 114, 0.12);
border: 1px solid rgba(207, 129, 114, 0.25);
}
</style> </style>

View File

@ -29,6 +29,7 @@
access_denied: 'Access was denied by the provider', access_denied: 'Access was denied by the provider',
email_taken: 'An account with this email already exists', email_taken: 'An account with this email already exists',
exchange_failed: 'Authentication failed — please try again', exchange_failed: 'Authentication failed — please try again',
no_account: 'No GitHub account connected — sign up instead',
}; };
// Read OAuth error forwarded from /auth/github/callback // Read OAuth error forwarded from /auth/github/callback
@ -259,7 +260,7 @@
<!-- GitHub OAuth --> <!-- GitHub OAuth -->
<a <a
href="/api/auth/oauth/github" href="/api/auth/oauth/github?intent={mode === 'signin' ? 'login' : 'signup'}"
class="flex w-full items-center justify-center gap-2.5 rounded-[var(--radius-button)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] px-4 py-3 text-body font-medium text-[var(--color-text-bright)] no-underline transition-all duration-150 hover:border-[var(--color-accent)] hover:text-[var(--color-text-bright)]" class="flex w-full items-center justify-center gap-2.5 rounded-[var(--radius-button)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] px-4 py-3 text-body font-medium text-[var(--color-text-bright)] no-underline transition-all duration-150 hover:border-[var(--color-accent)] hover:text-[var(--color-text-bright)]"
> >
<IconGithub size={16} /> <IconGithub size={16} />

View File

@ -55,6 +55,7 @@ func (h *adminCapsuleHandler) Create(w http.ResponseWriter, r *http.Request) {
return return
} }
ac.TeamID = id.PlatformTeamID
h.audit.LogSandboxCreate(r.Context(), ac, sb.ID, sb.Template) h.audit.LogSandboxCreate(r.Context(), ac, sb.ID, sb.Template)
writeJSON(w, http.StatusCreated, sandboxToResponse(sb)) writeJSON(w, http.StatusCreated, sandboxToResponse(sb))
} }

View File

@ -35,64 +35,38 @@ type auditLogResponse struct {
CreatedAt string `json:"created_at"` CreatedAt string `json:"created_at"`
} }
// List handles GET /v1/audit-logs. // parseAuditParams extracts common query parameters for audit log listing.
// Query params: func parseAuditParams(r *http.Request) (before time.Time, beforeID pgtype.UUID, limit int, err error) {
// - before: RFC3339 timestamp cursor (exclusive); omit to start from latest limit = 50
// - 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 != "" { if s := r.URL.Query().Get("before"); s != "" {
var err error
before, err = time.Parse(time.RFC3339, s) before, err = time.Parse(time.RFC3339, s)
if err != nil { if err != nil {
writeError(w, http.StatusBadRequest, "invalid_request", "before must be an RFC3339 timestamp")
return return
} }
} }
// Parse ?limit.
limit := 50
if s := r.URL.Query().Get("limit"); s != "" { if s := r.URL.Query().Get("limit"); s != "" {
n, err := strconv.Atoi(s) n, parseErr := strconv.Atoi(s)
if err != nil || n < 1 { if parseErr != nil || n < 1 {
writeError(w, http.StatusBadRequest, "invalid_request", "limit must be a positive integer") err = parseErr
return return
} }
limit = n limit = n
} }
// Parse ?before_id cursor (UUID).
var beforeID pgtype.UUID
if s := r.URL.Query().Get("before_id"); s != "" { if s := r.URL.Query().Get("before_id"); s != "" {
parsed, err := id.ParseAuditLogID(s) beforeID, err = id.ParseAuditLogID(s)
if err != nil { if err != nil {
writeError(w, http.StatusBadRequest, "invalid_request", "before_id must be a valid audit log ID")
return return
} }
beforeID = parsed
} }
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: beforeID,
Limit: limit,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "db_error", "failed to list audit logs")
return return
} }
// writeAuditResponse serializes audit entries into a paginated JSON response.
func writeAuditResponse(w http.ResponseWriter, entries []service.AuditEntry) {
items := make([]auditLogResponse, len(entries)) items := make([]auditLogResponse, len(entries))
for i, e := range entries { for i, e := range entries {
items[i] = auditLogResponse{ items[i] = auditLogResponse{
@ -120,6 +94,67 @@ func (h *auditHandler) List(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp) writeJSON(w, http.StatusOK, resp)
} }
// 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())
before, beforeID, limit, err := parseAuditParams(r)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid_request", "invalid query parameters")
return
}
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: beforeID,
Limit: limit,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "db_error", "failed to list audit logs")
return
}
writeAuditResponse(w, entries)
}
// AdminList handles GET /v1/admin/audit-logs.
// Returns audit logs for the platform team (team 0) with both team and admin scopes.
// Uses the same query params as List.
func (h *auditHandler) AdminList(w http.ResponseWriter, r *http.Request) {
before, beforeID, limit, err := parseAuditParams(r)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid_request", "invalid query parameters")
return
}
entries, err := h.svc.List(r.Context(), service.AuditListParams{
TeamID: id.PlatformTeamID,
AdminScoped: true,
ResourceTypes: parseMultiParam(r.URL.Query()["resource_type"]),
Actions: parseMultiParam(r.URL.Query()["action"]),
Before: before,
BeforeID: beforeID,
Limit: limit,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "db_error", "failed to list audit logs")
return
}
writeAuditResponse(w, entries)
}
// parseMultiParam flattens repeated params and comma-separated values into a // parseMultiParam flattens repeated params and comma-separated values into a
// single deduplicated slice. Empty strings are dropped. Returns nil (no filter) // single deduplicated slice. Empty strings are dropped. Returns nil (no filter)
// when no values are present. // when no values are present.

View File

@ -13,6 +13,8 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"git.omukk.dev/wrenn/wrenn/internal/layout" "git.omukk.dev/wrenn/wrenn/internal/layout"
"git.omukk.dev/wrenn/wrenn/pkg/audit"
"git.omukk.dev/wrenn/wrenn/pkg/auth"
"git.omukk.dev/wrenn/wrenn/pkg/db" "git.omukk.dev/wrenn/wrenn/pkg/db"
"git.omukk.dev/wrenn/wrenn/pkg/id" "git.omukk.dev/wrenn/wrenn/pkg/id"
"git.omukk.dev/wrenn/wrenn/pkg/lifecycle" "git.omukk.dev/wrenn/wrenn/pkg/lifecycle"
@ -25,10 +27,11 @@ type buildHandler struct {
svc *service.BuildService svc *service.BuildService
db *db.Queries db *db.Queries
pool *lifecycle.HostClientPool pool *lifecycle.HostClientPool
audit *audit.AuditLogger
} }
func newBuildHandler(svc *service.BuildService, db *db.Queries, pool *lifecycle.HostClientPool) *buildHandler { func newBuildHandler(svc *service.BuildService, db *db.Queries, pool *lifecycle.HostClientPool, al *audit.AuditLogger) *buildHandler {
return &buildHandler{svc: svc, db: db, pool: pool} return &buildHandler{svc: svc, db: db, pool: pool, audit: al}
} }
type createBuildRequest struct { type createBuildRequest struct {
@ -187,6 +190,8 @@ func (h *buildHandler) Create(w http.ResponseWriter, r *http.Request) {
return return
} }
ac := auth.MustFromContext(r.Context())
h.audit.LogBuildCreate(r.Context(), ac, build.ID, req.Name)
writeJSON(w, http.StatusCreated, buildToResponse(build)) writeJSON(w, http.StatusCreated, buildToResponse(build))
} }
@ -305,6 +310,8 @@ func (h *buildHandler) DeleteTemplate(w http.ResponseWriter, r *http.Request) {
return return
} }
ac := auth.MustFromContext(r.Context())
h.audit.LogTemplateDelete(r.Context(), ac, name)
w.WriteHeader(http.StatusNoContent) w.WriteHeader(http.StatusNoContent)
} }
@ -323,5 +330,7 @@ func (h *buildHandler) Cancel(w http.ResponseWriter, r *http.Request) {
return return
} }
ac := auth.MustFromContext(r.Context())
h.audit.LogBuildCancel(r.Context(), ac, buildID)
w.WriteHeader(http.StatusNoContent) w.WriteHeader(http.StatusNoContent)
} }

View File

@ -55,8 +55,14 @@ func (h *oauthHandler) Redirect(w http.ResponseWriter, r *http.Request) {
return return
} }
mac := computeHMAC(h.jwtSecret, state) // Persist intent (login|signup) in the state cookie so the callback can enforce it.
cookieVal := state + ":" + mac intent := r.URL.Query().Get("intent")
if intent != "signup" {
intent = "login"
}
mac := computeHMAC(h.jwtSecret, state+":"+intent)
cookieVal := state + ":" + mac + ":" + intent
http.SetCookie(w, &http.Cookie{ http.SetCookie(w, &http.Cookie{
Name: "oauth_state", Name: "oauth_state",
@ -105,13 +111,17 @@ func (h *oauthHandler) Callback(w http.ResponseWriter, r *http.Request) {
Secure: isSecure(r), Secure: isSecure(r),
}) })
parts := strings.SplitN(stateCookie.Value, ":", 2) parts := strings.SplitN(stateCookie.Value, ":", 3)
if len(parts) != 2 { if len(parts) < 2 {
redirectWithError(w, r, redirectBase, "invalid_state") redirectWithError(w, r, redirectBase, "invalid_state")
return return
} }
nonce, expectedMAC := parts[0], parts[1] nonce, expectedMAC := parts[0], parts[1]
if !hmac.Equal([]byte(computeHMAC(h.jwtSecret, nonce)), []byte(expectedMAC)) { intent := "login"
if len(parts) == 3 && parts[2] == "signup" {
intent = "signup"
}
if !hmac.Equal([]byte(computeHMAC(h.jwtSecret, nonce+":"+intent)), []byte(expectedMAC)) {
redirectWithError(w, r, redirectBase, "invalid_state") redirectWithError(w, r, redirectBase, "invalid_state")
return return
} }
@ -249,6 +259,12 @@ func (h *oauthHandler) Callback(w http.ResponseWriter, r *http.Request) {
return return
} }
// Block auto-registration when intent is login-only.
if intent == "login" {
redirectWithError(w, r, redirectBase, "no_account")
return
}
// New OAuth identity — check for email collision. // New OAuth identity — check for email collision.
existingUser, err := h.db.GetUserByEmail(ctx, email) existingUser, err := h.db.GetUserByEmail(ctx, email)
if err == nil { if err == nil {
@ -365,6 +381,17 @@ func (h *oauthHandler) Callback(w http.ResponseWriter, r *http.Request) {
return return
} }
// Signal frontend that this is a new signup so it can show the name confirmation dialog.
http.SetCookie(w, &http.Cookie{
Name: "wrenn_oauth_new_signup",
Value: "1",
Path: "/auth/",
MaxAge: 60,
HttpOnly: false,
SameSite: http.SameSiteLaxMode,
Secure: isSecure(r),
})
redirectWithToken(w, r, redirectBase, token, id.FormatUserID(userID), id.FormatTeamID(teamID), email, profile.Name) redirectWithToken(w, r, redirectBase, token, id.FormatUserID(userID), id.FormatTeamID(teamID), email, profile.Name)
} }

View File

@ -392,6 +392,7 @@ func (h *teamHandler) Leave(w http.ResponseWriter, r *http.Request) {
// SetBYOC handles PUT /v1/admin/teams/{id}/byoc (admin only). // SetBYOC handles PUT /v1/admin/teams/{id}/byoc (admin only).
// Enables or disables the BYOC feature flag for a team. // Enables or disables the BYOC feature flag for a team.
func (h *teamHandler) SetBYOC(w http.ResponseWriter, r *http.Request) { func (h *teamHandler) SetBYOC(w http.ResponseWriter, r *http.Request) {
ac := auth.MustFromContext(r.Context())
teamIDStr := chi.URLParam(r, "id") teamIDStr := chi.URLParam(r, "id")
teamID, err := id.ParseTeamID(teamIDStr) teamID, err := id.ParseTeamID(teamIDStr)
@ -414,6 +415,7 @@ func (h *teamHandler) SetBYOC(w http.ResponseWriter, r *http.Request) {
return return
} }
h.audit.LogTeamSetBYOC(r.Context(), ac, teamID, req.Enabled)
w.WriteHeader(http.StatusNoContent) w.WriteHeader(http.StatusNoContent)
} }
@ -484,6 +486,7 @@ func (h *teamHandler) AdminListTeams(w http.ResponseWriter, r *http.Request) {
// AdminDeleteTeam handles DELETE /v1/admin/teams/{id} // AdminDeleteTeam handles DELETE /v1/admin/teams/{id}
// Soft-deletes a team and destroys all its active sandboxes. // Soft-deletes a team and destroys all its active sandboxes.
func (h *teamHandler) AdminDeleteTeam(w http.ResponseWriter, r *http.Request) { func (h *teamHandler) AdminDeleteTeam(w http.ResponseWriter, r *http.Request) {
ac := auth.MustFromContext(r.Context())
teamIDStr := chi.URLParam(r, "id") teamIDStr := chi.URLParam(r, "id")
teamID, err := id.ParseTeamID(teamIDStr) teamID, err := id.ParseTeamID(teamIDStr)
@ -498,5 +501,6 @@ func (h *teamHandler) AdminDeleteTeam(w http.ResponseWriter, r *http.Request) {
return return
} }
h.audit.LogTeamDelete(r.Context(), ac, teamID)
w.WriteHeader(http.StatusNoContent) w.WriteHeader(http.StatusNoContent)
} }

View File

@ -9,6 +9,7 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
"git.omukk.dev/wrenn/wrenn/pkg/audit"
"git.omukk.dev/wrenn/wrenn/pkg/auth" "git.omukk.dev/wrenn/wrenn/pkg/auth"
"git.omukk.dev/wrenn/wrenn/pkg/db" "git.omukk.dev/wrenn/wrenn/pkg/db"
"git.omukk.dev/wrenn/wrenn/pkg/id" "git.omukk.dev/wrenn/wrenn/pkg/id"
@ -18,10 +19,11 @@ import (
type usersHandler struct { type usersHandler struct {
db *db.Queries db *db.Queries
svc *service.UserService svc *service.UserService
audit *audit.AuditLogger
} }
func newUsersHandler(db *db.Queries, svc *service.UserService) *usersHandler { func newUsersHandler(db *db.Queries, svc *service.UserService, al *audit.AuditLogger) *usersHandler {
return &usersHandler{db: db, svc: svc} return &usersHandler{db: db, svc: svc, audit: al}
} }
// Search handles GET /v1/users/search?email=<prefix> // Search handles GET /v1/users/search?email=<prefix>
@ -140,11 +142,23 @@ func (h *usersHandler) SetUserActive(w http.ResponseWriter, r *http.Request) {
newStatus = "disabled" newStatus = "disabled"
} }
// Look up user email for audit log before changing status.
user, err := h.db.GetUserByID(r.Context(), userID)
if err != nil {
writeError(w, http.StatusNotFound, "not_found", "user not found")
return
}
if err := h.svc.SetUserStatus(r.Context(), userID, newStatus); err != nil { if err := h.svc.SetUserStatus(r.Context(), userID, newStatus); err != nil {
httpStatus, code, msg := serviceErrToHTTP(err) httpStatus, code, msg := serviceErrToHTTP(err)
writeError(w, httpStatus, code, msg) writeError(w, httpStatus, code, msg)
return return
} }
if req.Active {
h.audit.LogUserActivate(r.Context(), ac, userID, user.Email)
} else {
h.audit.LogUserDeactivate(r.Context(), ac, userID, user.Email)
}
w.WriteHeader(http.StatusNoContent) w.WriteHeader(http.StatusNoContent)
} }

View File

@ -2,7 +2,7 @@ openapi: "3.1.0"
info: info:
title: Wrenn API title: Wrenn API
description: MicroVM-based code execution platform API. description: MicroVM-based code execution platform API.
version: "0.1.2" version: "0.1.3"
servers: servers:
- url: http://localhost:8080 - url: http://localhost:8080

View File

@ -32,7 +32,7 @@ type Server struct {
} }
// New constructs the chi router and registers all routes. // New constructs the chi router and registers all routes.
// Extensions are called after core routes are registered, allowing enterprise // Extensions are called after core routes are registered, allowing cloud
// or third-party code to add routes and middleware. // or third-party code to add routes and middleware.
func New( func New(
queries *db.Queries, queries *db.Queries,
@ -85,12 +85,12 @@ func New(
apiKeys := newAPIKeyHandler(apiKeySvc, al) apiKeys := newAPIKeyHandler(apiKeySvc, al)
hostH := newHostHandler(hostSvc, queries, al) hostH := newHostHandler(hostSvc, queries, al)
teamH := newTeamHandler(teamSvc, al, mailer) teamH := newTeamHandler(teamSvc, al, mailer)
usersH := newUsersHandler(queries, userSvc) usersH := newUsersHandler(queries, userSvc, al)
auditH := newAuditHandler(auditSvc) auditH := newAuditHandler(auditSvc)
statsH := newStatsHandler(statsSvc) statsH := newStatsHandler(statsSvc)
usageH := newUsageHandler(usageSvc) usageH := newUsageHandler(usageSvc)
metricsH := newSandboxMetricsHandler(queries, pool) metricsH := newSandboxMetricsHandler(queries, pool)
buildH := newBuildHandler(buildSvc, queries, pool) buildH := newBuildHandler(buildSvc, queries, pool, al)
channelH := newChannelHandler(channelSvc, al) channelH := newChannelHandler(channelSvc, al)
ptyH := newPtyHandler(queries, pool, jwtSecret) ptyH := newPtyHandler(queries, pool, jwtSecret)
processH := newProcessHandler(queries, pool, jwtSecret) processH := newProcessHandler(queries, pool, jwtSecret)
@ -255,6 +255,7 @@ func New(
r.Delete("/teams/{id}", teamH.AdminDeleteTeam) r.Delete("/teams/{id}", teamH.AdminDeleteTeam)
r.Get("/users", usersH.AdminListUsers) r.Get("/users", usersH.AdminListUsers)
r.Put("/users/{id}/active", usersH.SetUserActive) r.Put("/users/{id}/active", usersH.SetUserActive)
r.Get("/audit-logs", auditH.AdminList)
r.Get("/templates", buildH.ListTemplates) r.Get("/templates", buildH.ListTemplates)
r.Delete("/templates/{name}", buildH.DeleteTemplate) r.Delete("/templates/{name}", buildH.DeleteTemplate)
r.Post("/builds", buildH.Create) r.Post("/builds", buildH.Create)

View File

@ -82,6 +82,53 @@ func marshalMeta(meta map[string]any) []byte {
return b return b
} }
// Entry describes a single audit log event. Extensions (e.g. the cloud repo)
// use this with AuditLogger.Log to record custom events without modifying the
// OSS typed methods.
type Entry struct {
TeamID pgtype.UUID
ActorType string // "user", "api_key", "system"
ActorID string // prefixed ID string; empty for system
ActorName string // human-readable; empty for system
ResourceType string
ResourceID string // prefixed ID or name; empty when not applicable
Action string
Scope string // "team" or "admin"
Status string // "success", "info", "warning", "error"
Metadata map[string]any
}
// Log writes a custom audit log entry. This is the extension point for the
// cloud repo to record events with resource types and actions not covered by
// the typed helpers (LogSandboxCreate, etc.). Fire-and-forget like all other
// audit methods.
func (l *AuditLogger) Log(ctx context.Context, e Entry) {
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: e.TeamID,
ActorType: e.ActorType,
ActorID: optText(e.ActorID),
ActorName: e.ActorName,
ResourceType: e.ResourceType,
ResourceID: optText(e.ResourceID),
Action: e.Action,
Scope: e.Scope,
Status: e.Status,
Metadata: MarshalMeta(e.Metadata),
})
}
// ActorFromContext extracts actor fields from an auth.AuthContext for use in
// custom audit entries. Returns actor_type, actor_id, and actor_name.
func ActorFromContext(ac auth.AuthContext) (actorType, actorID, actorName string) {
return actorFields(ac)
}
// MarshalMeta serializes metadata to JSON bytes. Returns "{}" for nil/empty maps.
func MarshalMeta(meta map[string]any) []byte {
return marshalMeta(meta)
}
// optText returns a valid pgtype.Text if s is non-empty, otherwise an invalid (NULL) one. // optText returns a valid pgtype.Text if s is non-empty, otherwise an invalid (NULL) one.
func optText(s string) pgtype.Text { func optText(s string) pgtype.Text {
if s == "" { if s == "" {
@ -90,23 +137,42 @@ func optText(s string) pgtype.Text {
return pgtype.Text{String: s, Valid: true} return pgtype.Text{String: s, Valid: true}
} }
// --- Entry builders ---
// newEntry builds an Entry from an auth context with explicit team and scope.
func newEntry(ac auth.AuthContext, teamID pgtype.UUID, scope, resourceType, resourceID, action, status string, meta map[string]any) Entry {
actorType, actorID, actorName := actorFields(ac)
return Entry{
TeamID: teamID,
ActorType: actorType,
ActorID: actorID,
ActorName: actorName,
ResourceType: resourceType,
ResourceID: resourceID,
Action: action,
Scope: scope,
Status: status,
Metadata: meta,
}
}
// newAdminEntry builds an Entry for platform-level admin actions (PlatformTeamID, scope "admin").
func newAdminEntry(ac auth.AuthContext, resourceType, resourceID, action, status string, meta map[string]any) Entry {
return newEntry(ac, id.PlatformTeamID, "admin", resourceType, resourceID, action, status, meta)
}
// resolveHostTeamID returns the owning team for BYOC hosts, or PlatformTeamID for shared hosts.
func resolveHostTeamID(teamID pgtype.UUID) pgtype.UUID {
if teamID.Valid {
return teamID
}
return id.PlatformTeamID
}
// --- Sandbox events (scope: team) --- // --- Sandbox events (scope: team) ---
func (l *AuditLogger) LogSandboxCreate(ctx context.Context, ac auth.AuthContext, sandboxID pgtype.UUID, template string) { func (l *AuditLogger) LogSandboxCreate(ctx context.Context, ac auth.AuthContext, sandboxID pgtype.UUID, template string) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "sandbox", id.FormatSandboxID(sandboxID), "create", "success", map[string]any{"template": template}))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "sandbox",
ResourceID: optText(id.FormatSandboxID(sandboxID)),
Action: "create",
Scope: "team",
Status: "success",
Metadata: marshalMeta(map[string]any{"template": template}),
})
l.publish(ctx, events.Event{ l.publish(ctx, events.Event{
Event: events.CapsuleCreated, Event: events.CapsuleCreated,
Timestamp: events.Now(), Timestamp: events.Now(),
@ -117,20 +183,7 @@ func (l *AuditLogger) LogSandboxCreate(ctx context.Context, ac auth.AuthContext,
} }
func (l *AuditLogger) LogSandboxPause(ctx context.Context, ac auth.AuthContext, sandboxID pgtype.UUID) { func (l *AuditLogger) LogSandboxPause(ctx context.Context, ac auth.AuthContext, sandboxID pgtype.UUID) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "sandbox", id.FormatSandboxID(sandboxID), "pause", "success", nil))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "sandbox",
ResourceID: optText(id.FormatSandboxID(sandboxID)),
Action: "pause",
Scope: "team",
Status: "success",
Metadata: []byte("{}"),
})
l.publish(ctx, events.Event{ l.publish(ctx, events.Event{
Event: events.CapsulePaused, Event: events.CapsulePaused,
Timestamp: events.Now(), Timestamp: events.Now(),
@ -142,18 +195,10 @@ func (l *AuditLogger) LogSandboxPause(ctx context.Context, ac auth.AuthContext,
// LogSandboxAutoPause records a system-initiated auto-pause (TTL or host reconciler). // LogSandboxAutoPause records a system-initiated auto-pause (TTL or host reconciler).
func (l *AuditLogger) LogSandboxAutoPause(ctx context.Context, teamID, sandboxID pgtype.UUID) { func (l *AuditLogger) LogSandboxAutoPause(ctx context.Context, teamID, sandboxID pgtype.UUID) {
l.write(ctx, db.InsertAuditLogParams{ l.Log(ctx, Entry{
ID: id.NewAuditLogID(), TeamID: teamID, ActorType: "system",
TeamID: teamID, ResourceType: "sandbox", ResourceID: id.FormatSandboxID(sandboxID),
ActorType: "system", Action: "pause", Scope: "team", Status: "info",
ActorID: pgtype.Text{},
ActorName: "",
ResourceType: "sandbox",
ResourceID: optText(id.FormatSandboxID(sandboxID)),
Action: "pause",
Scope: "team",
Status: "info",
Metadata: []byte("{}"),
}) })
l.publish(ctx, events.Event{ l.publish(ctx, events.Event{
Event: events.CapsulePaused, Event: events.CapsulePaused,
@ -165,20 +210,7 @@ func (l *AuditLogger) LogSandboxAutoPause(ctx context.Context, teamID, sandboxID
} }
func (l *AuditLogger) LogSandboxResume(ctx context.Context, ac auth.AuthContext, sandboxID pgtype.UUID) { func (l *AuditLogger) LogSandboxResume(ctx context.Context, ac auth.AuthContext, sandboxID pgtype.UUID) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "sandbox", id.FormatSandboxID(sandboxID), "resume", "success", nil))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "sandbox",
ResourceID: optText(id.FormatSandboxID(sandboxID)),
Action: "resume",
Scope: "team",
Status: "success",
Metadata: []byte("{}"),
})
l.publish(ctx, events.Event{ l.publish(ctx, events.Event{
Event: events.CapsuleRunning, Event: events.CapsuleRunning,
Timestamp: events.Now(), Timestamp: events.Now(),
@ -189,20 +221,7 @@ func (l *AuditLogger) LogSandboxResume(ctx context.Context, ac auth.AuthContext,
} }
func (l *AuditLogger) LogSandboxDestroy(ctx context.Context, ac auth.AuthContext, sandboxID pgtype.UUID) { func (l *AuditLogger) LogSandboxDestroy(ctx context.Context, ac auth.AuthContext, sandboxID pgtype.UUID) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "sandbox", id.FormatSandboxID(sandboxID), "destroy", "warning", nil))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "sandbox",
ResourceID: optText(id.FormatSandboxID(sandboxID)),
Action: "destroy",
Scope: "team",
Status: "warning",
Metadata: []byte("{}"),
})
l.publish(ctx, events.Event{ l.publish(ctx, events.Event{
Event: events.CapsuleDestroyed, Event: events.CapsuleDestroyed,
Timestamp: events.Now(), Timestamp: events.Now(),
@ -215,20 +234,7 @@ func (l *AuditLogger) LogSandboxDestroy(ctx context.Context, ac auth.AuthContext
// --- Snapshot events (scope: team) --- // --- Snapshot events (scope: team) ---
func (l *AuditLogger) LogSnapshotCreate(ctx context.Context, ac auth.AuthContext, name string) { func (l *AuditLogger) LogSnapshotCreate(ctx context.Context, ac auth.AuthContext, name string) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "snapshot", name, "create", "success", nil))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "snapshot",
ResourceID: optText(name),
Action: "create",
Scope: "team",
Status: "success",
Metadata: []byte("{}"),
})
l.publish(ctx, events.Event{ l.publish(ctx, events.Event{
Event: events.SnapshotCreated, Event: events.SnapshotCreated,
Timestamp: events.Now(), Timestamp: events.Now(),
@ -239,20 +245,7 @@ func (l *AuditLogger) LogSnapshotCreate(ctx context.Context, ac auth.AuthContext
} }
func (l *AuditLogger) LogSnapshotDelete(ctx context.Context, ac auth.AuthContext, name string) { func (l *AuditLogger) LogSnapshotDelete(ctx context.Context, ac auth.AuthContext, name string) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "snapshot", name, "delete", "warning", nil))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "snapshot",
ResourceID: optText(name),
Action: "delete",
Scope: "team",
Status: "warning",
Metadata: []byte("{}"),
})
l.publish(ctx, events.Event{ l.publish(ctx, events.Event{
Event: events.SnapshotDeleted, Event: events.SnapshotDeleted,
Timestamp: events.Now(), Timestamp: events.Now(),
@ -265,274 +258,96 @@ func (l *AuditLogger) LogSnapshotDelete(ctx context.Context, ac auth.AuthContext
// --- Team events (scope: team) --- // --- Team events (scope: team) ---
func (l *AuditLogger) LogTeamRename(ctx context.Context, ac auth.AuthContext, teamID pgtype.UUID, oldName, newName string) { func (l *AuditLogger) LogTeamRename(ctx context.Context, ac auth.AuthContext, teamID pgtype.UUID, oldName, newName string) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "team", id.FormatTeamID(teamID), "rename", "info", map[string]any{"old_name": oldName, "new_name": newName}))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "team",
ResourceID: optText(id.FormatTeamID(teamID)),
Action: "rename",
Scope: "team",
Status: "info",
Metadata: marshalMeta(map[string]any{"old_name": oldName, "new_name": newName}),
})
} }
// --- Channel events (scope: team) --- // --- Channel events (scope: team) ---
func (l *AuditLogger) LogChannelCreate(ctx context.Context, ac auth.AuthContext, channelID pgtype.UUID, name, provider string) { func (l *AuditLogger) LogChannelCreate(ctx context.Context, ac auth.AuthContext, channelID pgtype.UUID, name, provider string) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "channel", id.FormatChannelID(channelID), "create", "success", map[string]any{"name": name, "provider": provider}))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "channel",
ResourceID: optText(id.FormatChannelID(channelID)),
Action: "create",
Scope: "team",
Status: "success",
Metadata: marshalMeta(map[string]any{"name": name, "provider": provider}),
})
} }
func (l *AuditLogger) LogChannelUpdate(ctx context.Context, ac auth.AuthContext, channelID pgtype.UUID) { func (l *AuditLogger) LogChannelUpdate(ctx context.Context, ac auth.AuthContext, channelID pgtype.UUID) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "channel", id.FormatChannelID(channelID), "update", "info", nil))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "channel",
ResourceID: optText(id.FormatChannelID(channelID)),
Action: "update",
Scope: "team",
Status: "info",
Metadata: []byte("{}"),
})
} }
func (l *AuditLogger) LogChannelRotateConfig(ctx context.Context, ac auth.AuthContext, channelID pgtype.UUID) { func (l *AuditLogger) LogChannelRotateConfig(ctx context.Context, ac auth.AuthContext, channelID pgtype.UUID) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "channel", id.FormatChannelID(channelID), "rotate_config", "info", nil))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "channel",
ResourceID: optText(id.FormatChannelID(channelID)),
Action: "rotate_config",
Scope: "team",
Status: "info",
Metadata: []byte("{}"),
})
} }
func (l *AuditLogger) LogChannelDelete(ctx context.Context, ac auth.AuthContext, channelID pgtype.UUID) { func (l *AuditLogger) LogChannelDelete(ctx context.Context, ac auth.AuthContext, channelID pgtype.UUID) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "channel", id.FormatChannelID(channelID), "delete", "warning", nil))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "channel",
ResourceID: optText(id.FormatChannelID(channelID)),
Action: "delete",
Scope: "team",
Status: "warning",
Metadata: []byte("{}"),
})
} }
// --- API key events (scope: team) --- // --- API key events (scope: team) ---
func (l *AuditLogger) LogAPIKeyCreate(ctx context.Context, ac auth.AuthContext, keyID pgtype.UUID, keyName string) { func (l *AuditLogger) LogAPIKeyCreate(ctx context.Context, ac auth.AuthContext, keyID pgtype.UUID, keyName string) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "api_key", id.FormatAPIKeyID(keyID), "create", "success", map[string]any{"name": keyName}))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "api_key",
ResourceID: optText(id.FormatAPIKeyID(keyID)),
Action: "create",
Scope: "team",
Status: "success",
Metadata: marshalMeta(map[string]any{"name": keyName}),
})
} }
func (l *AuditLogger) LogAPIKeyRevoke(ctx context.Context, ac auth.AuthContext, keyID pgtype.UUID) { func (l *AuditLogger) LogAPIKeyRevoke(ctx context.Context, ac auth.AuthContext, keyID pgtype.UUID) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "team", "api_key", id.FormatAPIKeyID(keyID), "revoke", "warning", nil))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "api_key",
ResourceID: optText(id.FormatAPIKeyID(keyID)),
Action: "revoke",
Scope: "team",
Status: "warning",
Metadata: []byte("{}"),
})
} }
// --- Member events (scope: admin) --- // --- Member events (scope: admin) ---
func (l *AuditLogger) LogMemberAdd(ctx context.Context, ac auth.AuthContext, targetUserID pgtype.UUID, targetEmail, role string) { func (l *AuditLogger) LogMemberAdd(ctx context.Context, ac auth.AuthContext, targetUserID pgtype.UUID, targetEmail, role string) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "admin", "member", id.FormatUserID(targetUserID), "add", "success", map[string]any{"email": targetEmail, "role": role}))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "member",
ResourceID: optText(id.FormatUserID(targetUserID)),
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 pgtype.UUID) { func (l *AuditLogger) LogMemberRemove(ctx context.Context, ac auth.AuthContext, targetUserID pgtype.UUID) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "admin", "member", id.FormatUserID(targetUserID), "remove", "warning", nil))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "member",
ResourceID: optText(id.FormatUserID(targetUserID)),
Action: "remove",
Scope: "admin",
Status: "warning",
Metadata: []byte("{}"),
})
} }
func (l *AuditLogger) LogMemberLeave(ctx context.Context, ac auth.AuthContext) { func (l *AuditLogger) LogMemberLeave(ctx context.Context, ac auth.AuthContext) {
actorType, actorID, actorName := actorFields(ac)
resourceID := "" resourceID := ""
if ac.UserID.Valid { if ac.UserID.Valid {
resourceID = id.FormatUserID(ac.UserID) resourceID = id.FormatUserID(ac.UserID)
} }
l.write(ctx, db.InsertAuditLogParams{ l.Log(ctx, newEntry(ac, ac.TeamID, "admin", "member", resourceID, "leave", "info", nil))
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "member",
ResourceID: optText(resourceID),
Action: "leave",
Scope: "admin",
Status: "info",
Metadata: []byte("{}"),
})
} }
func (l *AuditLogger) LogMemberRoleUpdate(ctx context.Context, ac auth.AuthContext, targetUserID pgtype.UUID, newRole string) { func (l *AuditLogger) LogMemberRoleUpdate(ctx context.Context, ac auth.AuthContext, targetUserID pgtype.UUID, newRole string) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, ac.TeamID, "admin", "member", id.FormatUserID(targetUserID), "role_update", "info", map[string]any{"new_role": newRole}))
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: ac.TeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "member",
ResourceID: optText(id.FormatUserID(targetUserID)),
Action: "role_update",
Scope: "admin",
Status: "info",
Metadata: marshalMeta(map[string]any{"new_role": newRole}),
})
} }
// --- Host events (scope: admin) --- // --- Host events (scope: admin) ---
// LogHostCreate records a user-initiated host registration.
// BYOC hosts log to the owning team; shared hosts log to the platform team.
func (l *AuditLogger) LogHostCreate(ctx context.Context, ac auth.AuthContext, hostID, teamID pgtype.UUID) { func (l *AuditLogger) LogHostCreate(ctx context.Context, ac auth.AuthContext, hostID, teamID pgtype.UUID) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, resolveHostTeamID(teamID), "admin", "host", id.FormatHostID(hostID), "create", "success", nil))
// For shared hosts with no owning team, use the caller's team.
logTeamID := teamID
if !logTeamID.Valid {
logTeamID = ac.TeamID
}
if !logTeamID.Valid {
return
}
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: logTeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "host",
ResourceID: optText(id.FormatHostID(hostID)),
Action: "create",
Scope: "admin",
Status: "success",
Metadata: []byte("{}"),
})
} }
// LogHostDelete records a user-initiated host removal.
// BYOC hosts log to the owning team; shared hosts log to the platform team.
func (l *AuditLogger) LogHostDelete(ctx context.Context, ac auth.AuthContext, hostID, teamID pgtype.UUID) { func (l *AuditLogger) LogHostDelete(ctx context.Context, ac auth.AuthContext, hostID, teamID pgtype.UUID) {
actorType, actorID, actorName := actorFields(ac) l.Log(ctx, newEntry(ac, resolveHostTeamID(teamID), "admin", "host", id.FormatHostID(hostID), "delete", "warning", nil))
logTeamID := teamID
if !logTeamID.Valid {
logTeamID = ac.TeamID
}
if !logTeamID.Valid {
return
}
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(),
TeamID: logTeamID,
ActorType: actorType,
ActorID: optText(actorID),
ActorName: actorName,
ResourceType: "host",
ResourceID: optText(id.FormatHostID(hostID)),
Action: "delete",
Scope: "admin",
Status: "warning",
Metadata: []byte("{}"),
})
} }
// LogHostMarkedDown records a system-initiated host status transition to unreachable. // LogHostMarkedDown records a system-initiated host status transition to unreachable.
// Scoped to "team" so BYOC team members can see when their hosts go down. // Scoped to "team" so BYOC team members can see when their hosts go down.
func (l *AuditLogger) LogHostMarkedDown(ctx context.Context, teamID, hostID pgtype.UUID) { func (l *AuditLogger) LogHostMarkedDown(ctx context.Context, teamID, hostID pgtype.UUID) {
l.logSystemHostEvent(ctx, teamID, hostID, "marked_down", "error", events.HostDown)
}
// LogHostMarkedUp records a system-initiated host status transition back to online.
// Scoped to "team" so BYOC team members can see when their hosts recover.
func (l *AuditLogger) LogHostMarkedUp(ctx context.Context, teamID, hostID pgtype.UUID) {
l.logSystemHostEvent(ctx, teamID, hostID, "marked_up", "success", events.HostUp)
}
func (l *AuditLogger) logSystemHostEvent(ctx context.Context, teamID, hostID pgtype.UUID, action, status, ev string) {
if !teamID.Valid { if !teamID.Valid {
return return
} }
l.write(ctx, db.InsertAuditLogParams{ l.Log(ctx, Entry{
ID: id.NewAuditLogID(), TeamID: teamID, ActorType: "system",
TeamID: teamID, ResourceType: "host", ResourceID: id.FormatHostID(hostID),
ActorType: "system", Action: action, Scope: "team", Status: status,
ActorID: pgtype.Text{},
ActorName: "",
ResourceType: "host",
ResourceID: optText(id.FormatHostID(hostID)),
Action: "marked_down",
Scope: "team",
Status: "error",
Metadata: []byte("{}"),
}) })
l.publish(ctx, events.Event{ l.publish(ctx, events.Event{
Event: events.HostDown, Event: ev,
Timestamp: events.Now(), Timestamp: events.Now(),
TeamID: id.FormatTeamID(teamID), TeamID: id.FormatTeamID(teamID),
Actor: systemActor(), Actor: systemActor(),
@ -540,30 +355,38 @@ func (l *AuditLogger) LogHostMarkedDown(ctx context.Context, teamID, hostID pgty
}) })
} }
// LogHostMarkedUp records a system-initiated host status transition back to online. // --- User events (scope: admin) ---
// Scoped to "team" so BYOC team members can see when their hosts recover.
func (l *AuditLogger) LogHostMarkedUp(ctx context.Context, teamID, hostID pgtype.UUID) { func (l *AuditLogger) LogUserActivate(ctx context.Context, ac auth.AuthContext, userID pgtype.UUID, email string) {
if !teamID.Valid { l.Log(ctx, newAdminEntry(ac, "user", id.FormatUserID(userID), "activate", "success", map[string]any{"email": email}))
return
} }
l.write(ctx, db.InsertAuditLogParams{
ID: id.NewAuditLogID(), func (l *AuditLogger) LogUserDeactivate(ctx context.Context, ac auth.AuthContext, userID pgtype.UUID, email string) {
TeamID: teamID, l.Log(ctx, newAdminEntry(ac, "user", id.FormatUserID(userID), "deactivate", "warning", map[string]any{"email": email}))
ActorType: "system", }
ActorID: pgtype.Text{},
ActorName: "", // --- Team admin events (scope: admin) ---
ResourceType: "host",
ResourceID: optText(id.FormatHostID(hostID)), func (l *AuditLogger) LogTeamSetBYOC(ctx context.Context, ac auth.AuthContext, teamID pgtype.UUID, enabled bool) {
Action: "marked_up", l.Log(ctx, newAdminEntry(ac, "team", id.FormatTeamID(teamID), "set_byoc", "info", map[string]any{"enabled": enabled}))
Scope: "team", }
Status: "success",
Metadata: []byte("{}"), func (l *AuditLogger) LogTeamDelete(ctx context.Context, ac auth.AuthContext, teamID pgtype.UUID) {
}) l.Log(ctx, newAdminEntry(ac, "team", id.FormatTeamID(teamID), "delete", "warning", nil))
l.publish(ctx, events.Event{ }
Event: events.HostUp,
Timestamp: events.Now(), // --- Template events (scope: admin) ---
TeamID: id.FormatTeamID(teamID),
Actor: systemActor(), func (l *AuditLogger) LogTemplateDelete(ctx context.Context, ac auth.AuthContext, name string) {
Resource: events.Resource{ID: id.FormatHostID(hostID), Type: "host"}, l.Log(ctx, newAdminEntry(ac, "template", name, "delete", "warning", nil))
}) }
// --- Build events (scope: admin) ---
func (l *AuditLogger) LogBuildCreate(ctx context.Context, ac auth.AuthContext, buildID pgtype.UUID, name string) {
l.Log(ctx, newAdminEntry(ac, "build", id.FormatBuildID(buildID), "create", "success", map[string]any{"name": name}))
}
func (l *AuditLogger) LogBuildCancel(ctx context.Context, ac auth.AuthContext, buildID pgtype.UUID) {
l.Log(ctx, newAdminEntry(ac, "build", id.FormatBuildID(buildID), "cancel", "warning", nil))
} }

View File

@ -36,7 +36,7 @@ type ServerContext struct {
Config config.Config Config config.Config
} }
// Extension allows enterprise (or any external) code to plug additional // Extension allows cloud (or any external) code to plug additional
// routes and background workers into the control plane without modifying // routes and background workers into the control plane without modifying
// the core server. // the core server.
type Extension interface { type Extension interface {

View File

@ -14,6 +14,8 @@ import (
"github.com/jackc/pgx/v5/pgxpool" "github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"github.com/jackc/pgx/v5/pgtype"
"git.omukk.dev/wrenn/wrenn/internal/api" "git.omukk.dev/wrenn/wrenn/internal/api"
"git.omukk.dev/wrenn/wrenn/internal/email" "git.omukk.dev/wrenn/wrenn/internal/email"
"git.omukk.dev/wrenn/wrenn/pkg/audit" "git.omukk.dev/wrenn/wrenn/pkg/audit"
@ -22,6 +24,7 @@ import (
"git.omukk.dev/wrenn/wrenn/pkg/channels" "git.omukk.dev/wrenn/wrenn/pkg/channels"
"git.omukk.dev/wrenn/wrenn/pkg/config" "git.omukk.dev/wrenn/wrenn/pkg/config"
"git.omukk.dev/wrenn/wrenn/pkg/db" "git.omukk.dev/wrenn/wrenn/pkg/db"
"git.omukk.dev/wrenn/wrenn/pkg/id"
"git.omukk.dev/wrenn/wrenn/pkg/lifecycle" "git.omukk.dev/wrenn/wrenn/pkg/lifecycle"
"git.omukk.dev/wrenn/wrenn/pkg/logging" "git.omukk.dev/wrenn/wrenn/pkg/logging"
"git.omukk.dev/wrenn/wrenn/pkg/scheduler" "git.omukk.dev/wrenn/wrenn/pkg/scheduler"
@ -185,10 +188,12 @@ func Run(opts ...Option) {
channelDispatcher.Start(ctx) channelDispatcher.Start(ctx)
// Start host monitor (passive + active reconciliation every 30s). // Start host monitor (passive + active reconciliation every 30s).
monitor := api.NewHostMonitor(queries, hostPool, al, 30*time.Second) monitor := api.NewHostMonitor(queries, hostPool, al, 15*time.Second)
monitor.Start(ctx) monitor.Start(ctx)
// Hard-delete accounts that have been soft-deleted for more than 15 days (runs every 24h). // Hard-delete accounts that have been soft-deleted for more than 15 days (runs every 24h).
// Audit logs referencing deleted users are anonymized before the user row is removed.
// A notification email is sent to the user before their data is permanently removed.
go func() { go func() {
ticker := time.NewTicker(24 * time.Hour) ticker := time.NewTicker(24 * time.Hour)
defer ticker.Stop() defer ticker.Stop()
@ -197,10 +202,34 @@ func Run(opts ...Option) {
case <-ctx.Done(): case <-ctx.Done():
return return
case <-ticker.C: case <-ticker.C:
if err := queries.HardDeleteExpiredUsers(ctx); err != nil { expired, err := queries.ListExpiredSoftDeletedUsers(ctx)
slog.Error("account cleanup: failed to hard-delete expired users", "error", err) if err != nil {
} else { slog.Error("account cleanup: failed to list expired users", "error", err)
slog.Info("account cleanup: hard-deleted expired users") continue
}
var deleted int
for _, row := range expired {
prefixedID := id.FormatUserID(row.ID)
if err := queries.AnonymizeAuditLogsByUserID(ctx, pgtype.Text{String: prefixedID, Valid: true}); err != nil {
slog.Error("account cleanup: failed to anonymize audit logs, skipping delete", "user_id", prefixedID, "error", err)
continue
}
if err := queries.HardDeleteUser(ctx, row.ID); err != nil {
slog.Error("account cleanup: failed to hard-delete user", "user_id", prefixedID, "error", err)
continue
}
if err := mailer.Send(ctx, row.Email, "Your Wrenn account has been deleted", email.EmailData{
Message: "Your Wrenn account and all associated data have been permanently deleted. " +
"This action was taken automatically because your account was scheduled for deletion more than 15 days ago.\n\n" +
"If you believe this was done in error, please contact support.",
Closing: "Thank you for using Wrenn.",
}); err != nil {
slog.Warn("account cleanup: failed to send deletion notification", "email", row.Email, "error", err)
}
deleted++
}
if len(expired) > 0 {
slog.Info("account cleanup: processed expired users", "total", len(expired), "deleted", deleted)
} }
} }
} }

View File

@ -11,6 +11,21 @@ import (
"github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgtype"
) )
const anonymizeAuditLogsByUserID = `-- name: AnonymizeAuditLogsByUserID :exec
UPDATE audit_logs
SET actor_name = CASE WHEN actor_id = $1 THEN 'deleted-user' ELSE actor_name END,
actor_id = CASE WHEN actor_id = $1 THEN NULL ELSE actor_id END,
resource_id = CASE WHEN resource_type = 'member' AND resource_id = $1 THEN NULL ELSE resource_id END,
metadata = CASE WHEN resource_type = 'member' AND resource_id = $1 AND metadata ? 'email' THEN metadata - 'email' ELSE metadata END
WHERE actor_id = $1
OR (resource_type = 'member' AND resource_id = $1)
`
func (q *Queries) AnonymizeAuditLogsByUserID(ctx context.Context, actorID pgtype.Text) error {
_, err := q.db.Exec(ctx, anonymizeAuditLogsByUserID, actorID)
return err
}
const insertAuditLog = `-- name: InsertAuditLog :exec 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) 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) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)

View File

@ -183,15 +183,6 @@ func (q *Queries) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
return i, err return i, err
} }
const hardDeleteExpiredUsers = `-- name: HardDeleteExpiredUsers :exec
DELETE FROM users WHERE deleted_at IS NOT NULL AND deleted_at < NOW() - INTERVAL '15 days'
`
func (q *Queries) HardDeleteExpiredUsers(ctx context.Context) error {
_, err := q.db.Exec(ctx, hardDeleteExpiredUsers)
return err
}
const hardDeleteUser = `-- name: HardDeleteUser :exec const hardDeleteUser = `-- name: HardDeleteUser :exec
DELETE FROM users WHERE id = $1 DELETE FROM users WHERE id = $1
` `
@ -334,6 +325,35 @@ func (q *Queries) InsertUserOAuth(ctx context.Context, arg InsertUserOAuthParams
return i, err return i, err
} }
const listExpiredSoftDeletedUsers = `-- name: ListExpiredSoftDeletedUsers :many
SELECT id, email FROM users WHERE deleted_at IS NOT NULL AND deleted_at < NOW() - INTERVAL '15 days'
`
type ListExpiredSoftDeletedUsersRow struct {
ID pgtype.UUID `json:"id"`
Email string `json:"email"`
}
func (q *Queries) ListExpiredSoftDeletedUsers(ctx context.Context) ([]ListExpiredSoftDeletedUsersRow, error) {
rows, err := q.db.Query(ctx, listExpiredSoftDeletedUsers)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListExpiredSoftDeletedUsersRow
for rows.Next() {
var i ListExpiredSoftDeletedUsersRow
if err := rows.Scan(&i.ID, &i.Email); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listUsersAdmin = `-- name: ListUsersAdmin :many const listUsersAdmin = `-- name: ListUsersAdmin :many
SELECT SELECT
u.id, u.id,