fix(coderd/workspaceapps): prevent race in workspace app audit session updates (#17020)

Fixes coder/internal#520
This commit is contained in:
Mathias Fredriksson
2025-03-20 16:10:45 +02:00
committed by GitHub
parent 68624092a4
commit 72d9876c76
13 changed files with 68 additions and 32 deletions

View File

@ -1,9 +1,11 @@
-- name: UpsertWorkspaceAppAuditSession :one
--
-- Insert a new workspace app audit session or update an existing one, if
-- started_at is updated, it means the session has been restarted.
-- The returned boolean, new_or_stale, can be used to deduce if a new session
-- was started. This means that a new row was inserted (no previous session) or
-- the updated_at is older than stale interval.
INSERT INTO
workspace_app_audit_sessions (
id,
agent_id,
app_id,
user_id,
@ -24,13 +26,20 @@ VALUES
$6,
$7,
$8,
$9
$9,
$10
)
ON CONFLICT
(agent_id, app_id, user_id, ip, user_agent, slug_or_port, status_code)
DO
UPDATE
SET
-- ID is used to know if session was reset on upsert.
id = CASE
WHEN workspace_app_audit_sessions.updated_at > NOW() - (@stale_interval_ms::bigint || ' ms')::interval
THEN workspace_app_audit_sessions.id
ELSE EXCLUDED.id
END,
started_at = CASE
WHEN workspace_app_audit_sessions.updated_at > NOW() - (@stale_interval_ms::bigint || ' ms')::interval
THEN workspace_app_audit_sessions.started_at
@ -38,4 +47,4 @@ DO
END,
updated_at = EXCLUDED.updated_at
RETURNING
started_at;
id = $1 AS new_or_stale;