Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
9aa823f
fix(audit): system audit remediation (P0, P1, P2)
BigSimmo Jul 25, 2026
5474fb6
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
7228a16
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
7050de6
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
77c9b63
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
348c764
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
36f040b
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
3bf226c
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
5f149b5
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
945fc6a
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
c985244
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
a7b6606
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
c043e31
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
09dbc49
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
f712132
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
1c9170b
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
47865cd
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
d67a92b
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
b82de97
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
59f31d2
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
5806b77
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
265ddc6
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
147be0c
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
e54b299
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
a7ea05e
Merge branch 'main' into fix/system-audit-remediation-pr
github-actions[bot] Jul 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions scripts/test-run-lock.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,28 @@ export function acquireHeavyRunLock({
forceLockRelease = false,
}) {
if (!projectRoot) throw new Error("projectRoot is required for the Database heavyweight-run lock.");

if (
command.includes("--standalone") ||
environment.TEST_STANDALONE === "true" ||
environment.TEST_STANDALONE === "1"
) {
return {
path: "standalone-bypass",
owner: {
pid: processId,
token: "standalone",
command,
worktree: projectRoot,
repositoryIdentity,
startedAt: new Date().toISOString(),
},
reentrant: false,
environment: { ...environment },
release() {},
};
}

const lockPath = lockPathFor(repositoryIdentity, baseDirectory);
const inheritedToken = environment[tokenEnvironmentKey];
const inheritedPath = environment[pathEnvironmentKey];
Expand All @@ -105,7 +127,7 @@ export function acquireHeavyRunLock({
}

mkdirSync(path.dirname(lockPath), { recursive: true });
for (let attempt = 0; attempt < 120; attempt += 1) {
for (let attempt = 0; attempt < 2; attempt += 1) {
try {
mkdirSync(lockPath);
const token = randomUUID();
Expand Down Expand Up @@ -174,25 +196,11 @@ export function acquireHeavyRunLock({
}

if (owner && processIsAlive(owner.pid)) {
if (attempt < 15) {
// 15 attempts, approx 30s
const sleepMs = Math.min(3000, 100 * Math.pow(1.5, attempt));
const waitResult = spawnSync("node", ["-e", `setTimeout(() => {}, ${sleepMs})`]);
if (waitResult.error) {
throw new Error("Could not sleep while waiting for run lock");
}
continue;
}
throw new Error(
`Another Database heavyweight command is active (PID ${owner.pid}, worktree ${owner.worktree ?? "unknown"}, started ${owner.startedAt ?? "unknown"}): ${redactSensitiveText(owner.command ?? "unknown command")}`,
);
}
if (!owner && !lockIsOldEnoughToRecover(lockPath)) {
if (attempt < 15) {
const sleepMs = 500;
spawnSync("node", ["-e", `setTimeout(() => {}, ${sleepMs})`]);
continue;
}
throw new Error(`A Database heavyweight lock is being initialized at ${lockPath}; retry after it settles.`);
}
rmSync(lockPath, { recursive: true, force: true });
Expand Down
4 changes: 4 additions & 0 deletions src/lib/rag/rag-query-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ function unsupportedSoftTailEligible(analysis: ClinicalQueryAnalysis) {
return true;
}

export const MEDICAL_TERMS_REGEX =
/\b(?:bipolar|lithium|toxicity|clozapine|schizophrenia|depression|anorexia|anxiety|ssri|ssnri|psychosis|dosing|titration|olanzapine|quetiapine|risperidone|aripiprazole|haloperidol|valproate|lamotrigine|carbamazepine|cbt|ect)\b/i;

export function shouldShortCircuitUnsupportedSearch(query: string, analysis: ClinicalQueryAnalysis) {
if (MEDICAL_TERMS_REGEX.test(query)) return false;
Comment on lines +19 to +23

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not let the medical-term bypass override explicit exclusion rules.

MEDICAL_TERMS_REGEX overlaps clearlyOutsideCorpusMedicalPattern (depression and ssri). Because this return runs first, queries such as adolescent depression or SSRI skip the existing outside-corpus short circuit and proceed to retrieval. Move the hard exclusion checks before this bypass, or remove the overlapping terms and add regression tests that define the intended precedence.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/rag/rag-query-guard.ts` around lines 19 - 23, Update
shouldShortCircuitUnsupportedSearch so the existing
clearlyOutsideCorpusMedicalPattern exclusion checks run before the
MEDICAL_TERMS_REGEX bypass, ensuring explicit outside-corpus matches such as
“adolescent depression” and “SSRI” still short-circuit. Preserve the
medical-term bypass for queries that do not match the hard exclusion rules, and
add regression coverage for this precedence.

if (unavailableDocumentNoisePattern.test(query)) return true;
if (clearlyOutsideCorpusMedicalPattern.test(query) && analysis.documentTitleTerms.length === 0) return true;
if (!unsupportedSoftTailEligible(analysis)) return false;
Expand Down
39 changes: 39 additions & 0 deletions supabase/migrations/20260724163951_revoke_api_grants.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
-- REVOKE ALL on core tables from public/anon/authenticated
revoke all privileges on table
public.import_batches,
public.documents,
public.document_pages,
public.document_images,
public.image_caption_cache,
public.document_labels,
public.document_summaries,
public.document_sections,
public.document_memory_cards,
public.document_chunks,
public.document_table_facts,
public.document_embedding_fields,
public.document_index_quality,
public.ingestion_jobs,
public.ingestion_job_stages,
public.rag_queries,
public.rag_query_misses,
public.rag_aliases,
public.rag_response_cache,
public.api_rate_limits,
public.api_rate_limit_subjects,
public.audit_logs,
public.storage_cleanup_jobs,
public.rag_retrieval_logs
from public, anon, authenticated;

-- REVOKE EXECUTE on 5 internal maintenance RPCs
revoke execute on function public.correct_clinical_query_terms(text, real) from public, anon, authenticated;
revoke execute on function public.purge_expired_rag_response_cache(integer) from public, anon, authenticated;
revoke execute on function public.update_indexing_v3_agent_job_status(uuid, text, text, timestamptz) from public, anon, authenticated;
revoke execute on function public.request_indexing_v3_enrichment(uuid, uuid) from public, anon, authenticated;
revoke execute on function public.cleanup_abandoned_document_index_generations(uuid, integer, boolean) from public, anon, authenticated;
revoke execute on function public.detect_legacy_ivfflat_indexes() from public, anon, authenticated;
revoke execute on function public.document_summary_text(uuid) from public, anon, authenticated;
revoke execute on function public.search_document_chunks(uuid, text, integer, uuid) from public, anon, authenticated;
revoke execute on function public.set_document_embedding_field_content_hash() from public, anon, authenticated;
Comment on lines +29 to +38

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Correct the stale RPC count.

Lines 30-38 revoke execution for nine functions, not five. Update the comment so it remains accurate for future maintainers.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@supabase/migrations/20260724163951_revoke_api_grants.sql` around lines 29 -
38, Update the comment above the revoke statements to state that execution is
being revoked for nine internal maintenance RPCs, matching the nine functions
listed below.


Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
create or replace function public.invoke_ingestion_worker(p_limit integer default 25)
returns bigint
language plpgsql
security definer
set search_path to 'public', 'extensions', 'vault', 'pg_temp'
as $$
declare
v_request_id bigint;
v_jwt text;
v_limit integer := greatest(1, least(coalesce("p_limit", 25), 200));
v_base_url text;
begin
select "decrypted_secret" into v_jwt
from "vault"."decrypted_secrets"
where "name" = 'cron_ingestion_jwt'
limit 1;

if v_jwt is null or length(trim(v_jwt)) = 0 then
raise exception 'Missing Vault secret: cron_ingestion_jwt';
end if;

v_base_url := coalesce(
nullif(current_setting('app.ingestion_worker_base_url', true), ''),
'https://sjrfecxgysukkwxsowpy.supabase.co'
);

select "net"."http_post"(
url := v_base_url || '/functions/v1/ingestion-worker?limit=' || v_limit::text,
headers := jsonb_build_object(
'Content-Type','application/json',
'Authorization','Bearer ' || v_jwt
),
body := jsonb_build_object('source','pg_cron','worker','ingestion-worker','ts', now()),
timeout_milliseconds := 60000
)
into v_request_id;

return v_request_id;
end;
$$;
Comment thread
coderabbitai[bot] marked this conversation as resolved.