From 2acaaced93ed6b3f80810da086d4833b69f8faa9 Mon Sep 17 00:00:00 2001 From: Jonny Date: Mon, 12 Oct 2026 09:39:23 +0200 Subject: [PATCH 01/16] feat: Firmen, firma_id in allen Fachtabellen, Trigger und Eindeutigkeit pro Firma Co-Authored-By: Claude Sonnet 5.5 --- .../20261012090000_superadmin_rolle.sql | 3 + .../20261012090100_mandanten_struktur.sql | 411 ++++++++++++++++++ supabase/tests/arbeitszeiten_rls_test.sql | 5 +- supabase/tests/auftraege_rls_test.sql | 13 +- supabase/tests/auftrag_fotos_rls_test.sql | 26 +- .../tests/auftrag_unterschrift_rls_test.sql | 26 +- supabase/tests/auftragsnummer_test.sql | 13 +- supabase/tests/fahrzeug_fin_test.sql | 40 +- supabase/tests/mandanten_struktur_test.sql | 181 ++++++++ .../tests/notification_outbox_rls_test.sql | 24 +- supabase/tests/nutzer_details_rls_test.sql | 1 + supabase/tests/orte_fahrzeuge_rls_test.sql | 1 + supabase/tests/profiles_rls_test.sql | 1 + supabase/tests/protokoll_email_test.sql | 25 +- supabase/tests/zeitplanung_test.sql | 11 +- web/lib/orte-fahrzeuge/mutations.test.ts | 16 + web/lib/orte-fahrzeuge/mutations.ts | 7 +- 17 files changed, 718 insertions(+), 86 deletions(-) create mode 100644 supabase/migrations/20261012090000_superadmin_rolle.sql create mode 100644 supabase/migrations/20261012090100_mandanten_struktur.sql create mode 100644 supabase/tests/mandanten_struktur_test.sql create mode 100644 web/lib/orte-fahrzeuge/mutations.test.ts diff --git a/supabase/migrations/20261012090000_superadmin_rolle.sql b/supabase/migrations/20261012090000_superadmin_rolle.sql new file mode 100644 index 0000000..981f999 --- /dev/null +++ b/supabase/migrations/20261012090000_superadmin_rolle.sql @@ -0,0 +1,3 @@ +-- Eigene Migration: ein neuer Enum-Wert ist erst nach dem Commit der +-- Transaktion verwendbar, die ihn anlegt (die Folgemigration nutzt ihn). +alter type public.app_role add value if not exists 'superadmin'; diff --git a/supabase/migrations/20261012090100_mandanten_struktur.sql b/supabase/migrations/20261012090100_mandanten_struktur.sql new file mode 100644 index 0000000..f38db09 --- /dev/null +++ b/supabase/migrations/20261012090100_mandanten_struktur.sql @@ -0,0 +1,411 @@ +-- Mandantenfaehigkeit, Teil 1: Firmen, firma_id in allen Fachtabellen, +-- Trigger zum Setzen/Schuetzen der firma_id, Eindeutigkeit pro Firma. +-- Die RLS-Policies folgen in 20261012090200_mandanten_rls.sql. + +-- ---------------------------------------------------------------- firmen +create table public.firmen ( + id uuid primary key default gen_random_uuid(), + name text not null, + aktiv boolean not null default true, + logo_pfad text, + whatsapp_empfaenger text, + farbe_primaer text, + farbe_dunkel text, + created_at timestamptz not null default now(), + constraint firmen_name_nicht_leer check (length(btrim(name)) > 0), + constraint firmen_whatsapp_e164 check (whatsapp_empfaenger is null or whatsapp_empfaenger ~ '^\+[1-9][0-9]{7,14}$'), + constraint firmen_farbe_primaer_hex check (farbe_primaer is null or farbe_primaer ~ '^#[0-9a-f]{6}$'), + constraint firmen_farbe_dunkel_hex check (farbe_dunkel is null or farbe_dunkel ~ '^#[0-9a-f]{6}$') +); + +alter table public.firmen enable row level security; +-- Supabase vergibt per Default-Privileges alle Rechte an anon/authenticated +-- (siehe information_schema.role_table_grants). Explizit entziehen und nur +-- das Noetige granten. +revoke all on public.firmen from anon, authenticated; +grant select, update on public.firmen to authenticated; + +-- Feste ID, damit Tests und das Layout (Standard-Logo) die Bestandsfirma kennen. +insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f001', 'Widmann'); + +-- Status und ID einer Firma aendert nur der Service-Client (Plattform-Actions). +create or replace function public.schuetze_firmen_status() +returns trigger +language plpgsql +as $$ +begin + if auth.uid() is not null and (new.aktiv is distinct from old.aktiv or new.id is distinct from old.id) then + raise exception 'Status und ID einer Firma kann nur der Plattform-Betreiber aendern' using errcode = '42501'; + end if; + return new; +end; +$$; + +create trigger schuetze_firmen_status + before update on public.firmen + for each row execute function public.schuetze_firmen_status(); + +-- ---------------------------------------------------------- firmen_smtp +-- Kein Grant, keine Policy: nur der Service-Client kommt heran, das +-- (verschluesselte) Passwort verlaesst die REST-API also nie. +create table public.firmen_smtp ( + firma_id uuid primary key references public.firmen (id) on delete cascade, + host text not null, + port int not null, + secure boolean not null default false, + benutzer text, + passwort_verschluesselt text, + absender_adresse text not null, + absender_name text, + updated_at timestamptz not null default now(), + constraint firmen_smtp_port check (port between 1 and 65535) +); + +alter table public.firmen_smtp enable row level security; +revoke all on public.firmen_smtp from anon, authenticated; + +-- --------------------------------------------------------------- profiles +alter table public.profiles add column firma_id uuid references public.firmen (id); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where role <> 'superadmin'; +alter table public.profiles + add constraint profiles_superadmin_ohne_firma check (role <> 'superadmin' or firma_id is null); +create index profiles_firma_id_idx on public.profiles (firma_id); + +-- Firma des angemeldeten Nutzers, nur wenn die Firma aktiv ist. null = kein +-- Zugriff auf Fachdaten (Superadmin, deaktivierte Firma, nicht zugeordnet). +create or replace function public.user_firma_id() +returns uuid +language sql +stable +security definer +set search_path = public +as $$ + select p.firma_id + from public.profiles p + join public.firmen f on f.id = p.firma_id + where p.id = auth.uid() and f.aktiv; +$$; + +-- ------------------------------------------------- firma_id in Fachtabellen +alter table public.orte add column firma_id uuid references public.firmen (id); +alter table public.fahrzeuge add column firma_id uuid references public.firmen (id); +alter table public.auftraege add column firma_id uuid references public.firmen (id); +alter table public.auftrag_fotos add column firma_id uuid references public.firmen (id); +alter table public.arbeitszeiten add column firma_id uuid references public.firmen (id); +alter table public.nutzer_details add column firma_id uuid references public.firmen (id); +alter table public.notification_outbox add column firma_id uuid references public.firmen (id); +alter table public.auftragsnummer_zaehler add column firma_id uuid references public.firmen (id); + +update public.orte set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.fahrzeuge set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.auftraege set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.auftrag_fotos set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.arbeitszeiten set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.nutzer_details set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.notification_outbox set firma_id = '00000000-0000-0000-0000-00000000f001'; +update public.auftragsnummer_zaehler set firma_id = '00000000-0000-0000-0000-00000000f001'; + +alter table public.orte alter column firma_id set not null; +alter table public.fahrzeuge alter column firma_id set not null; +alter table public.auftraege alter column firma_id set not null; +alter table public.auftrag_fotos alter column firma_id set not null; +alter table public.arbeitszeiten alter column firma_id set not null; +alter table public.nutzer_details alter column firma_id set not null; +alter table public.notification_outbox alter column firma_id set not null; +alter table public.auftragsnummer_zaehler alter column firma_id set not null; + +create index orte_firma_id_idx on public.orte (firma_id); +create index fahrzeuge_firma_id_idx on public.fahrzeuge (firma_id); +create index auftraege_firma_id_idx on public.auftraege (firma_id); +create index auftrag_fotos_firma_id_idx on public.auftrag_fotos (firma_id); +create index arbeitszeiten_firma_id_idx on public.arbeitszeiten (firma_id); +create index nutzer_details_firma_id_idx on public.nutzer_details (firma_id); +create index notification_outbox_firma_id_idx on public.notification_outbox (firma_id); + +-- ---------------------------------------------------- Trigger: firma_id setzen +-- Mit Nutzer-Session: immer die eigene Firma (ueberschreibt jeden +-- mitgeschickten Wert). Ohne Session (Service-Client, Migrationen, Tests als +-- postgres): firma_id muss mitgegeben werden. +create or replace function public.firma_aus_sitzung_setzen() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + if auth.uid() is not null then + new.firma_id := public.user_firma_id(); + if new.firma_id is null then + raise exception 'Keine aktive Firma fuer den angemeldeten Nutzer' using errcode = '42501'; + end if; + elsif new.firma_id is null then + raise exception 'firma_id fehlt' using errcode = '23502'; + end if; + return new; +end; +$$; + +create or replace function public.firma_aus_auftrag_setzen() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + if new.auftrag_id is not null then + new.firma_id := (select a.firma_id from public.auftraege a where a.id = new.auftrag_id); + end if; + if new.firma_id is null then + raise exception 'firma_id fehlt' using errcode = '23502'; + end if; + return new; +end; +$$; + +create or replace function public.firma_aus_profil_setzen() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + new.firma_id := (select p.firma_id from public.profiles p where p.id = new.user_id); + if new.firma_id is null then + raise exception 'firma_id fehlt' using errcode = '23502'; + end if; + return new; +end; +$$; + +-- Nur der Erstzuordnung null -> Wert ohne Session (Service-Client nach +-- auth.admin.createUser) ist erlaubt; jede andere Aenderung wirft. +create or replace function public.firma_id_unveraenderlich() +returns trigger +language plpgsql +as $$ +begin + if new.firma_id is distinct from old.firma_id + and not (old.firma_id is null and auth.uid() is null) then + raise exception 'firma_id darf nicht geaendert werden' using errcode = '42501'; + end if; + return new; +end; +$$; + +-- Trigger-Namen mit Praefix a0_/a1_: Postgres feuert gleichartige Trigger +-- alphabetisch, die firma_id muss vor auftragsnummer_generieren stehen. +create trigger a0_firma_setzen before insert on public.orte + for each row execute function public.firma_aus_sitzung_setzen(); +create trigger a0_firma_setzen before insert on public.fahrzeuge + for each row execute function public.firma_aus_sitzung_setzen(); +create trigger a0_firma_setzen before insert on public.auftraege + for each row execute function public.firma_aus_sitzung_setzen(); +create trigger a0_firma_setzen before insert on public.arbeitszeiten + for each row execute function public.firma_aus_sitzung_setzen(); +create trigger a0_firma_setzen before insert on public.auftrag_fotos + for each row execute function public.firma_aus_auftrag_setzen(); +create trigger a0_firma_setzen before insert on public.notification_outbox + for each row execute function public.firma_aus_auftrag_setzen(); +create trigger a0_firma_setzen before insert on public.nutzer_details + for each row execute function public.firma_aus_profil_setzen(); + +create trigger a0_firma_fix before update on public.profiles + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.orte + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.fahrzeuge + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.auftraege + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.arbeitszeiten + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.auftrag_fotos + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.notification_outbox + for each row execute function public.firma_id_unveraenderlich(); +create trigger a0_firma_fix before update on public.nutzer_details + for each row execute function public.firma_id_unveraenderlich(); + +-- ------------------------------------------- Trigger: firmenfremde Verweise +create or replace function public.auftrag_firma_konsistenz() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + if exists (select 1 from public.orte o + where o.id in (new.abholort_id, new.zielort_id) and o.firma_id <> new.firma_id) + or exists (select 1 from public.fahrzeuge f + where f.id = new.fahrzeug_id and f.firma_id <> new.firma_id) + or exists (select 1 from public.profiles p + where p.id in (new.zugewiesen_an, new.erstellt_von) and p.firma_id is distinct from new.firma_id) + or exists (select 1 from public.auftraege v + where v.id = new.vorgaenger_auftrag_id and v.firma_id <> new.firma_id) then + raise exception 'Firmenfremder Verweis' using errcode = '42501'; + end if; + return new; +end; +$$; + +create trigger a1_firma_konsistenz before insert or update on public.auftraege + for each row execute function public.auftrag_firma_konsistenz(); + +create or replace function public.arbeitszeit_firma_konsistenz() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + if exists (select 1 from public.profiles p + where p.id in (new.fahrer_id, new.korrigiert_von) and p.firma_id is distinct from new.firma_id) then + raise exception 'Firmenfremder Verweis' using errcode = '42501'; + end if; + return new; +end; +$$; + +create trigger a1_firma_konsistenz before insert or update on public.arbeitszeiten + for each row execute function public.arbeitszeit_firma_konsistenz(); + +-- ------------------------------------------------- Eindeutigkeit pro Firma +alter table public.fahrzeuge + drop constraint fahrzeuge_kennzeichen_key, + drop constraint fahrzeuge_fin_key, + add constraint fahrzeuge_firma_kennzeichen_key unique (firma_id, kennzeichen), + add constraint fahrzeuge_firma_fin_key unique (firma_id, fin); + +alter table public.auftraege + drop constraint auftraege_auftragsnummer_key, + add constraint auftraege_firma_auftragsnummer_key unique (firma_id, auftragsnummer); + +alter table public.auftragsnummer_zaehler drop constraint auftragsnummer_zaehler_pkey; +alter table public.auftragsnummer_zaehler add primary key (firma_id, tag); + +create or replace function public.generiere_auftragsnummer() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +declare + naechste int; +begin + if new.auftragsnummer is null or new.auftragsnummer = '' then + insert into public.auftragsnummer_zaehler (firma_id, tag, letzte_nummer) + values (new.firma_id, current_date, 1) + on conflict (firma_id, tag) do update set letzte_nummer = auftragsnummer_zaehler.letzte_nummer + 1 + returning letzte_nummer into naechste; + new.auftragsnummer := to_char(current_date, 'YY-MM-DD') || '-' || lpad(naechste::text, 4, '0'); + end if; + return new; +end; +$$; + +-- ------------------------------------------- FIN-Abgleich nur innerhalb der Firma +create or replace function public.fin_bei_fahrtbeginn(p_auftrag_id uuid, p_fin text) +returns public.app_fin_abgleich +language plpgsql +security definer +set search_path = '' +as $$ +declare + v_fin text := upper(btrim(coalesce(p_fin, ''))); + v_fahrzeug_id uuid; + v_firma_id uuid; + v_hinterlegt text; + v_alt_fin text; + v_alt_status public.app_fin_abgleich; + v_status public.app_fin_abgleich; +begin + if public.user_role() is distinct from 'fahrer'::public.app_role then + raise exception 'Nur Fahrer duerfen den FIN-Abgleich durchfuehren'; + end if; + + if v_fin !~ '^[A-HJ-NPR-Z0-9]{17}$' then + raise exception 'Die FIN muss 17 Zeichen lang sein (A–Z, 0–9, ohne I, O, Q).'; + end if; + + select a.fahrzeug_id, a.firma_id, a.start_fin, a.start_fin_status + into v_fahrzeug_id, v_firma_id, v_alt_fin, v_alt_status + from public.auftraege a + where a.id = p_auftrag_id + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + and a.status = 'zugewiesen'::public.app_auftrag_status + for update; + + if not found then + raise exception 'Auftrag nicht gefunden oder nicht im Status zugewiesen'; + end if; + + select f.fin into v_hinterlegt + from public.fahrzeuge f + where f.id = v_fahrzeug_id + for update; + + if v_alt_status = 'abweichend' then + -- Sticky: ein einmal vermerkter Abweichungs-Nachweis wird nicht + -- ueberschrieben (auch nicht durch erneuten Aufruf mit der hinterlegten FIN). + return v_alt_status; + end if; + + if v_alt_status = 'nachgetragen' and v_alt_fin = v_fin then + -- Wiederholter Aufruf mit derselben FIN: Ergebnis bleibt 'nachgetragen'. + v_status := 'nachgetragen'; + elsif v_hinterlegt is null then + if exists (select 1 from public.fahrzeuge f + where f.fin = v_fin and f.id <> v_fahrzeug_id and f.firma_id = v_firma_id) then + v_status := 'abweichend'; + else + begin + update public.fahrzeuge set fin = v_fin where id = v_fahrzeug_id; + v_status := 'nachgetragen'; + exception when unique_violation then + -- Race: parallel wurde dieselbe FIN einem anderen Fahrzeug gegeben. + v_status := 'abweichend'; + end; + end if; + elsif v_hinterlegt = v_fin then + v_status := 'bestaetigt'; + else + v_status := 'abweichend'; + end if; + + perform set_config('app.fin_abgleich', 'an', true); + update public.auftraege + set start_fin = v_fin, start_fin_status = v_status + where id = p_auftrag_id; + perform set_config('app.fin_abgleich', '', true); + + return v_status; +end; +$$; + +-- ------------------------------------- WhatsApp nur bei Firma mit Empfaenger +create or replace function public.auftrag_notification_enqueue() +returns trigger +language plpgsql +security definer +set search_path = public +as $$ +begin + insert into public.notification_outbox (event_type, auftrag_id, payload) + select + 'auftrag_erstellt', + new.id, + jsonb_build_object( + 'auftragsnummer', new.auftragsnummer, + 'abholort_adresse', abhol.adresse, + 'zielort_adresse', ziel.adresse, + 'kennzeichen', coalesce(fz.kennzeichen, fz.fin)) + from public.orte abhol + join public.orte ziel on ziel.id = new.zielort_id + join public.fahrzeuge fz on fz.id = new.fahrzeug_id + join public.firmen fi on fi.id = new.firma_id + where abhol.id = new.abholort_id + and fi.whatsapp_empfaenger is not null; + return new; +end; +$$; diff --git a/supabase/tests/arbeitszeiten_rls_test.sql b/supabase/tests/arbeitszeiten_rls_test.sql index caa2e11..7a79cdc 100644 --- a/supabase/tests/arbeitszeiten_rls_test.sql +++ b/supabase/tests/arbeitszeiten_rls_test.sql @@ -8,6 +8,7 @@ insert into auth.users (id, email) values ('aa444444-4444-4444-4444-444444444444', 'fahrer-zwei@arbeitszeiten.test.local'), ('aa555555-5555-5555-5555-555555555555', 'readonly@arbeitszeiten.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'aa111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = 'aa222222-2222-2222-2222-222222222222'; update public.profiles set role = 'fahrer' where id = 'aa333333-3333-3333-3333-333333333333'; @@ -74,8 +75,8 @@ select throws_ok( reset role; -insert into public.arbeitszeiten (id, fahrer_id, kommt_um) values - ('b2222222-2222-2222-2222-222222222222', 'aa444444-4444-4444-4444-444444444444', '2026-07-13 07:00:00+00'); +insert into public.arbeitszeiten (id, fahrer_id, kommt_um, firma_id) values + ('b2222222-2222-2222-2222-222222222222', 'aa444444-4444-4444-4444-444444444444', '2026-07-13 07:00:00+00', '00000000-0000-0000-0000-00000000f001'); set local role authenticated; set local request.jwt.claims to '{"sub": "aa333333-3333-3333-3333-333333333333", "role": "authenticated"}'; diff --git a/supabase/tests/auftraege_rls_test.sql b/supabase/tests/auftraege_rls_test.sql index 2a01208..7674a46 100644 --- a/supabase/tests/auftraege_rls_test.sql +++ b/supabase/tests/auftraege_rls_test.sql @@ -8,6 +8,7 @@ insert into auth.users (id, email) values ('f4444444-4444-4444-4444-444444444444', 'fahrer-zwei@auftraege.test.local'), ('05555555-5555-5555-5555-555555555555', 'readonly@auftraege.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = 'd2222222-2222-2222-2222-222222222222'; update public.profiles set role = 'fahrer' where id = 'f3333333-3333-3333-3333-333333333333'; @@ -15,13 +16,13 @@ update public.profiles set role = 'fahrer' where id = 'f4444444-4444-4444-4444-4 -- readonly bleibt auf dem Trigger-Default 'readonly' (siehe Fundament, -- handle_new_user()), kein explizites update noetig. -insert into public.orte (id, adresse, ansprechpartner) values - ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('f0000000-0000-0000-0000-000000000001', 'M-AB 123'), - ('f0000000-0000-0000-0000-000000000002', 'M-CD 456'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('f0000000-0000-0000-0000-000000000001', 'M-AB 123', '00000000-0000-0000-0000-00000000f001'), + ('f0000000-0000-0000-0000-000000000002', 'M-CD 456', '00000000-0000-0000-0000-00000000f001'); set local role authenticated; set local request.jwt.claims to '{"sub": "d2222222-2222-2222-2222-222222222222", "role": "authenticated"}'; diff --git a/supabase/tests/auftrag_fotos_rls_test.sql b/supabase/tests/auftrag_fotos_rls_test.sql index 2ca0d78..206d6d5 100644 --- a/supabase/tests/auftrag_fotos_rls_test.sql +++ b/supabase/tests/auftrag_fotos_rls_test.sql @@ -7,23 +7,24 @@ insert into auth.users (id, email) values ('ff333333-3333-3333-3333-333333333333', 'fahrer-eins-fotos@auftraege.test.local'), ('ff444444-4444-4444-4444-444444444444', 'fahrer-zwei-fotos@auftraege.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'aa111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = 'dd222222-2222-2222-2222-222222222222'; update public.profiles set role = 'fahrer' where id = 'ff333333-3333-3333-3333-333333333333'; update public.profiles set role = 'fahrer' where id = 'ff444444-4444-4444-4444-444444444444'; -insert into public.orte (id, adresse, ansprechpartner) values - ('20111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('20222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('20111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('20222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('20333333-0000-0000-0000-000000000001', 'M-EF 789'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('20333333-0000-0000-0000-000000000001', 'M-EF 789', '00000000-0000-0000-0000-00000000f001'); -- Auftrag A: dem Fahrer "eins" zugewiesen, status = 'zugewiesen' -- fuer die -- "eigener, noch nicht gestarteter Auftrag"-Faelle (Pflichtfoto UND -- Schadensfoto duerfen hier hochgeladen werden). insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '20000000-0000-0000-0000-000000000001', '20111111-1111-1111-1111-111111111111', @@ -32,13 +33,14 @@ insert into public.auftraege ( 'dd222222-2222-2222-2222-222222222222', 'zugewiesen', 'ff333333-3333-3333-3333-333333333333', - 1000 + 1000, + '00000000-0000-0000-0000-00000000f001' ); -- Auftrag B: dem Fahrer "zwei" zugewiesen -- aus Sicht von Fahrer "eins" ein -- fremder Auftrag, fuer die SELECT- und INSERT-RLS-Blockade-Faelle. insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '20000000-0000-0000-0000-000000000002', '20111111-1111-1111-1111-111111111111', @@ -47,7 +49,8 @@ insert into public.auftraege ( 'dd222222-2222-2222-2222-222222222222', 'zugewiesen', 'ff444444-4444-4444-4444-444444444444', - 500 + 500, + '00000000-0000-0000-0000-00000000f001' ); -- Auftrag C: dem Fahrer "eins" zugewiesen, aber direkt mit status = @@ -58,7 +61,7 @@ insert into public.auftraege ( -- unabhaengig von auftraege_rls_test.sql und fokussiert sie ausschliesslich -- auf die auftrag_fotos/storage.objects-Policies statt auf den Trigger. insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '20000000-0000-0000-0000-000000000003', '20111111-1111-1111-1111-111111111111', @@ -67,7 +70,8 @@ insert into public.auftraege ( 'dd222222-2222-2222-2222-222222222222', 'unterwegs', 'ff333333-3333-3333-3333-333333333333', - 2000 + 2000, + '00000000-0000-0000-0000-00000000f001' ); -- Ein Foto + ein Storage-Objekt fuer Auftrag B, als postgres (RLS-frei) diff --git a/supabase/tests/auftrag_unterschrift_rls_test.sql b/supabase/tests/auftrag_unterschrift_rls_test.sql index 96dcfa1..7052e92 100644 --- a/supabase/tests/auftrag_unterschrift_rls_test.sql +++ b/supabase/tests/auftrag_unterschrift_rls_test.sql @@ -6,20 +6,21 @@ insert into auth.users (id, email) values ('ff666666-6666-6666-6666-666666666666', 'fahrer-eins-unterschrift@auftraege.test.local'), ('ff777777-7777-7777-7777-777777777777', 'fahrer-zwei-unterschrift@auftraege.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'aa555555-5555-5555-5555-555555555555'; update public.profiles set role = 'fahrer' where id = 'ff666666-6666-6666-6666-666666666666'; update public.profiles set role = 'fahrer' where id = 'ff777777-7777-7777-7777-777777777777'; -insert into public.orte (id, adresse, ansprechpartner) values - ('21111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('21222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('21111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('21222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('21333333-0000-0000-0000-000000000001', 'M-UN 001'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('21333333-0000-0000-0000-000000000001', 'M-UN 001', '00000000-0000-0000-0000-00000000f001'); -- Auftrag A: Fahrer "eins", status 'unterwegs' -- Upload muss hier gelingen. insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '21000000-0000-0000-0000-000000000001', '21111111-1111-1111-1111-111111111111', @@ -28,13 +29,14 @@ insert into public.auftraege ( 'aa555555-5555-5555-5555-555555555555', 'unterwegs', 'ff666666-6666-6666-6666-666666666666', - 1000 + 1000, + '00000000-0000-0000-0000-00000000f001' ); -- Auftrag B: Fahrer "eins", status 'zugewiesen' -- Upload muss hier verboten -- bleiben (Unterschrift ist nur bei Fahrtende/status='unterwegs' erlaubt). insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '21000000-0000-0000-0000-000000000002', '21111111-1111-1111-1111-111111111111', @@ -43,13 +45,14 @@ insert into public.auftraege ( 'aa555555-5555-5555-5555-555555555555', 'zugewiesen', 'ff666666-6666-6666-6666-666666666666', - 1000 + 1000, + '00000000-0000-0000-0000-00000000f001' ); -- Auftrag C: Fahrer "zwei", status 'unterwegs' -- aus Sicht von Fahrer -- "eins" ein fremder Auftrag. insert into public.auftraege ( - id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km + id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id ) values ( '21000000-0000-0000-0000-000000000003', '21111111-1111-1111-1111-111111111111', @@ -58,7 +61,8 @@ insert into public.auftraege ( 'aa555555-5555-5555-5555-555555555555', 'unterwegs', 'ff777777-7777-7777-7777-777777777777', - 500 + 500, + '00000000-0000-0000-0000-00000000f001' ); insert into storage.buckets (id, name, public) values ('auftrag-unterschriften', 'auftrag-unterschriften', false) diff --git a/supabase/tests/auftragsnummer_test.sql b/supabase/tests/auftragsnummer_test.sql index 0177726..4397aca 100644 --- a/supabase/tests/auftragsnummer_test.sql +++ b/supabase/tests/auftragsnummer_test.sql @@ -3,14 +3,15 @@ select plan(5); insert into auth.users (id, email) values ('a1111111-1111-1111-1111-111111111111', 'admin@auftragsnummer.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111'; -insert into public.orte (id, adresse, ansprechpartner) values - ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('f0000000-0000-0000-0000-000000000001', 'M-AB 123'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('f0000000-0000-0000-0000-000000000001', 'M-AB 123', '00000000-0000-0000-0000-00000000f001'); set local role authenticated; set local request.jwt.claims to '{"sub": "a1111111-1111-1111-1111-111111111111", "role": "authenticated"}'; @@ -55,7 +56,7 @@ select throws_ok( ('30000000-0000-0000-0000-000000000004', '01111111-1111-1111-1111-111111111111', '02222222-2222-2222-2222-222222222222', 'f0000000-0000-0000-0000-000000000001', 'a1111111-1111-1111-1111-111111111111', 'MEINE-EIGENE-NUMMER') $$, '23505', - 'duplicate key value violates unique constraint "auftraege_auftragsnummer_key"', + 'duplicate key value violates unique constraint "auftraege_firma_auftragsnummer_key"', 'Doppelte, manuell eingegebene Auftragsnummer wird durch den Unique-Constraint abgelehnt' ); diff --git a/supabase/tests/fahrzeug_fin_test.sql b/supabase/tests/fahrzeug_fin_test.sql index f6f9909..2843a3b 100644 --- a/supabase/tests/fahrzeug_fin_test.sql +++ b/supabase/tests/fahrzeug_fin_test.sql @@ -8,27 +8,29 @@ insert into auth.users (id, email) values ('f1a00000-0000-0000-0000-000000000004', 'fahrer-zwei-fin@test.local'), ('f1a00000-0000-0000-0000-000000000005', 'readonly-fin@test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; +update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001'; update public.profiles set role = 'admin' where id = 'f1a00000-0000-0000-0000-000000000001'; update public.profiles set role = 'disponent' where id = 'f1a00000-0000-0000-0000-000000000002'; update public.profiles set role = 'fahrer' where id = 'f1a00000-0000-0000-0000-000000000003'; update public.profiles set role = 'fahrer' where id = 'f1a00000-0000-0000-0000-000000000004'; -- readonly bleibt auf dem Trigger-Default. -insert into public.orte (id, adresse, ansprechpartner) values - ('f1b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('f1b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('f1b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('f1b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -- F1: nur Kennzeichen (FIN wird nachgetragen) -- F2: FIN A hinterlegt -- F3: nur Kennzeichen (Fahrer gibt FIN von F2 ein) -insert into public.fahrzeuge (id, kennzeichen, fin) values - ('f1c00000-0000-0000-0000-000000000001', 'M-FN 001', null), - ('f1c00000-0000-0000-0000-000000000002', 'M-FN 002', 'WDB9066331S123456'), - ('f1c00000-0000-0000-0000-000000000003', 'M-FN 003', null); +insert into public.fahrzeuge (id, kennzeichen, fin, firma_id) values + ('f1c00000-0000-0000-0000-000000000001', 'M-FN 001', null, '00000000-0000-0000-0000-00000000f001'), + ('f1c00000-0000-0000-0000-000000000002', 'M-FN 002', 'WDB9066331S123456', '00000000-0000-0000-0000-00000000f001'), + ('f1c00000-0000-0000-0000-000000000003', 'M-FN 003', null, '00000000-0000-0000-0000-00000000f001'); -- 1) Format-Check select throws_ok( - $$ insert into public.fahrzeuge (kennzeichen, fin) values ('M-FN 010', 'WDB906633IS12345X') $$, + $$ insert into public.fahrzeuge (kennzeichen, fin, firma_id) values ('M-FN 010', 'WDB906633IS12345X', '00000000-0000-0000-0000-00000000f001') $$, '23514', null, 'FIN mit I wird vom Format-Check abgelehnt' @@ -36,7 +38,7 @@ select throws_ok( -- 2) Kennzeichen oder FIN select throws_ok( - $$ insert into public.fahrzeuge (kennzeichen, fin) values (null, null) $$, + $$ insert into public.fahrzeuge (kennzeichen, fin, firma_id) values (null, null, '00000000-0000-0000-0000-00000000f001') $$, '23514', null, 'Fahrzeug ohne Kennzeichen und ohne FIN wird abgelehnt' @@ -44,27 +46,27 @@ select throws_ok( -- 3) Nur FIN ist erlaubt select lives_ok( - $$ insert into public.fahrzeuge (id, kennzeichen, fin) values ('f1c00000-0000-0000-0000-000000000004', null, 'VF1RFB00X12345678') $$, + $$ insert into public.fahrzeuge (id, kennzeichen, fin, firma_id) values ('f1c00000-0000-0000-0000-000000000004', null, 'VF1RFB00X12345678', '00000000-0000-0000-0000-00000000f001') $$, 'Fahrzeug nur mit FIN kann angelegt werden' ); -- 4) FIN eindeutig select throws_ok( - $$ insert into public.fahrzeuge (kennzeichen, fin) values ('M-FN 011', 'WDB9066331S123456') $$, + $$ insert into public.fahrzeuge (kennzeichen, fin, firma_id) values ('M-FN 011', 'WDB9066331S123456', '00000000-0000-0000-0000-00000000f001') $$, '23505', null, 'Doppelte FIN wird abgelehnt' ); -- Auftraege (als postgres angelegt) -insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km) values - ('f1d00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000001', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null), - ('f1d00000-0000-0000-0000-000000000002', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null), - ('f1d00000-0000-0000-0000-000000000003', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null), - ('f1d00000-0000-0000-0000-000000000004', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000003', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null), - ('f1d00000-0000-0000-0000-000000000005', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000004', null), - ('f1d00000-0000-0000-0000-000000000006', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'unterwegs', 'f1a00000-0000-0000-0000-000000000003', 1000), - ('f1d00000-0000-0000-0000-000000000007', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000004', 'f1a00000-0000-0000-0000-000000000001', 'offen', null, null); +insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, start_km, firma_id) values + ('f1d00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000001', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000002', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000003', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000004', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000003', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000003', null, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000005', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'zugewiesen', 'f1a00000-0000-0000-0000-000000000004', null, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000006', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000002', 'f1a00000-0000-0000-0000-000000000001', 'unterwegs', 'f1a00000-0000-0000-0000-000000000003', 1000, '00000000-0000-0000-0000-00000000f001'), + ('f1d00000-0000-0000-0000-000000000007', 'f1b00000-0000-0000-0000-000000000001', 'f1b00000-0000-0000-0000-000000000002', 'f1c00000-0000-0000-0000-000000000004', 'f1a00000-0000-0000-0000-000000000001', 'offen', null, null, '00000000-0000-0000-0000-00000000f001'); -- 5) Outbox: Fahrzeug ohne Kennzeichen -> FIN im Payload select is( diff --git a/supabase/tests/mandanten_struktur_test.sql b/supabase/tests/mandanten_struktur_test.sql new file mode 100644 index 0000000..96fb37a --- /dev/null +++ b/supabase/tests/mandanten_struktur_test.sql @@ -0,0 +1,181 @@ +begin; +select plan(16); + +-- Firma B neben der Bestandsfirma Widmann (f001) +insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f002', 'Firma B'); + +insert into auth.users (id, email) values + ('a0000000-0000-0000-0000-0000000000a1', 'admin-a@mandant.test.local'), + ('a0000000-0000-0000-0000-0000000000a3', 'fahrer-a@mandant.test.local'), + ('b0000000-0000-0000-0000-0000000000b1', 'admin-b@mandant.test.local'), + ('b0000000-0000-0000-0000-0000000000b3', 'fahrer-b@mandant.test.local'), + ('5a000000-0000-0000-0000-000000000001', 'superadmin@mandant.test.local'); + +-- 1) Neues Profil hat keine Firma (handle_new_user bleibt unveraendert) +select is( + (select firma_id from public.profiles where id = 'a0000000-0000-0000-0000-0000000000a1'), + null::uuid, + 'Neues Profil startet ohne Firma' +); + +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'admin' + where id = 'a0000000-0000-0000-0000-0000000000a1'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'fahrer' + where id = 'a0000000-0000-0000-0000-0000000000a3'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'admin' + where id = 'b0000000-0000-0000-0000-0000000000b1'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'fahrer' + where id = 'b0000000-0000-0000-0000-0000000000b3'; +update public.profiles set role = 'superadmin' where id = '5a000000-0000-0000-0000-000000000001'; + +-- 2) Superadmin mit Firma ist verboten +select throws_ok( + $$ update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' + where id = '5a000000-0000-0000-0000-000000000001' $$, + '23514', null, + 'Superadmin darf keiner Firma angehoeren' +); + +-- 3) Firmenwechsel eines Profils ist verboten (auch ohne Session, wenn schon gesetzt) +select throws_ok( + $$ update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002' + where id = 'a0000000-0000-0000-0000-0000000000a3' $$, + '42501', 'firma_id darf nicht geaendert werden', + 'firma_id eines Profils ist unveraenderlich' +); + +-- Stammdaten ohne Session: firma_id explizit +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('a0000000-0000-0000-0000-0000000000c1', 'Ort A', 'Herr A', '00000000-0000-0000-0000-00000000f001'), + ('b0000000-0000-0000-0000-0000000000c1', 'Ort B', 'Frau B', '00000000-0000-0000-0000-00000000f002'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('a0000000-0000-0000-0000-0000000000d1', 'MT-AB 1', '00000000-0000-0000-0000-00000000f001'); + +-- 4) Ohne Session und ohne firma_id: Fehler +select throws_ok( + $$ insert into public.orte (adresse, ansprechpartner) values ('X', 'Y') $$, + '23502', 'firma_id fehlt', + 'Insert ohne Session braucht eine firma_id' +); + +-- 5) Gleiches Kennzeichen in zwei Firmen ist erlaubt +select lives_ok( + $$ insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('b0000000-0000-0000-0000-0000000000d1', 'MT-AB 1', '00000000-0000-0000-0000-00000000f002') $$, + 'Gleiches Kennzeichen in einer anderen Firma ist erlaubt' +); + +-- 6) Doppeltes Kennzeichen in derselben Firma nicht +select throws_ok( + $$ insert into public.fahrzeuge (kennzeichen, firma_id) values ('MT-AB 1', '00000000-0000-0000-0000-00000000f001') $$, + '23505', null, + 'Doppeltes Kennzeichen in derselben Firma scheitert' +); + +-- Session als Admin B +set local role authenticated; +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; + +-- 7) Mitgeschickte fremde firma_id wird ueberschrieben +select is( + (select public.user_firma_id()), + '00000000-0000-0000-0000-00000000f002'::uuid, + 'user_firma_id liefert die Firma des angemeldeten Nutzers' +); + +reset role; +reset request.jwt.claims; + +-- Insert mit Session, Rueckgabe ueber eine Hilfstabelle (RLS-Policies sind in Task 1 noch rollenbasiert) +set local role authenticated; +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; +insert into public.orte (id, adresse, ansprechpartner, firma_id) + values ('b0000000-0000-0000-0000-0000000000c2', 'Ort B2', 'Herr B2', '00000000-0000-0000-0000-00000000f001'); +reset role; +reset request.jwt.claims; + +select is( + (select firma_id from public.orte where id = 'b0000000-0000-0000-0000-0000000000c2'), + '00000000-0000-0000-0000-00000000f002'::uuid, + 'Mitgeschickte fremde firma_id wird durch die eigene Firma ersetzt' +); + +-- 9) Auftrag mit Ort einer fremden Firma: Exception +select throws_ok( + $$ insert into public.auftraege (abholort_id, zielort_id, fahrzeug_id, erstellt_von, firma_id) values + ('a0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000c1', + 'b0000000-0000-0000-0000-0000000000d1', 'b0000000-0000-0000-0000-0000000000b1', + '00000000-0000-0000-0000-00000000f002') $$, + '42501', 'Firmenfremder Verweis', + 'Auftrag mit Ort einer fremden Firma scheitert' +); + +-- 10) Auftrag mit Fahrer einer fremden Firma: Exception +select throws_ok( + $$ insert into public.auftraege (abholort_id, zielort_id, fahrzeug_id, erstellt_von, zugewiesen_an, status, firma_id) values + ('b0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000c1', + 'b0000000-0000-0000-0000-0000000000d1', 'b0000000-0000-0000-0000-0000000000b1', + 'a0000000-0000-0000-0000-0000000000a3', 'zugewiesen', '00000000-0000-0000-0000-00000000f002') $$, + '42501', 'Firmenfremder Verweis', + 'Auftrag mit Fahrer einer fremden Firma scheitert' +); + +-- Je ein gueltiger Auftrag pro Firma +update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001'; +insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, firma_id) values + ('a0000000-0000-0000-0000-0000000000e1', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1', + 'a0000000-0000-0000-0000-0000000000d1', 'a0000000-0000-0000-0000-0000000000a1', '00000000-0000-0000-0000-00000000f001'), + ('b0000000-0000-0000-0000-0000000000e1', 'b0000000-0000-0000-0000-0000000000c1', 'b0000000-0000-0000-0000-0000000000c1', + 'b0000000-0000-0000-0000-0000000000d1', 'b0000000-0000-0000-0000-0000000000b1', '00000000-0000-0000-0000-00000000f002'); + +-- 11) Auftragsnummer zaehlt pro Firma: der erste B-Auftrag des Tages endet auf -0001 +select is( + (select right(auftragsnummer, 4) from public.auftraege where id = 'b0000000-0000-0000-0000-0000000000e1'), + '0001', + 'Auftragsnummer zaehlt pro Firma' +); + +-- 12) firma_id eines Auftrags ist unveraenderlich +select throws_ok( + $$ update public.auftraege set firma_id = '00000000-0000-0000-0000-00000000f002' + where id = 'a0000000-0000-0000-0000-0000000000e1' $$, + '42501', 'firma_id darf nicht geaendert werden', + 'firma_id eines Auftrags ist unveraenderlich' +); + +-- 13) WhatsApp-Outbox nur fuer Firma mit Empfaenger, mit firma_id aus dem Auftrag +select is( + (select count(*) from public.notification_outbox + where event_type = 'auftrag_erstellt' + and auftrag_id = 'a0000000-0000-0000-0000-0000000000e1' + and firma_id = '00000000-0000-0000-0000-00000000f001'), + 1::bigint, + 'Firma mit WhatsApp-Empfaenger bekommt eine Outbox-Zeile mit ihrer firma_id' +); +select is( + (select count(*) from public.notification_outbox where auftrag_id = 'b0000000-0000-0000-0000-0000000000e1'), + 0::bigint, + 'Firma ohne WhatsApp-Empfaenger bekommt keine Outbox-Zeile' +); + +-- 15) Mit Nutzer-Session kann aktiv nicht geaendert werden. Nur Claims setzen, +-- Rolle bleibt postgres: in Task 1 gibt es noch keine Policy auf firmen, der +-- Trigger soll aber trotzdem greifen. +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; +select throws_ok( + $$ update public.firmen set aktiv = false where id = '00000000-0000-0000-0000-00000000f002' $$, + '42501', 'Status und ID einer Firma kann nur der Plattform-Betreiber aendern', + 'Admin kann seine Firma nicht deaktivieren' +); +reset request.jwt.claims; + +-- 16) Deaktivierte Firma: user_firma_id() liefert null +update public.firmen set aktiv = false where id = '00000000-0000-0000-0000-00000000f002'; +set local role authenticated; +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; +select is((select public.user_firma_id()), null::uuid, 'Deaktivierte Firma: user_firma_id() ist null'); +reset role; +reset request.jwt.claims; + +select * from finish(); +rollback; diff --git a/supabase/tests/notification_outbox_rls_test.sql b/supabase/tests/notification_outbox_rls_test.sql index 45002da..ca460c8 100644 --- a/supabase/tests/notification_outbox_rls_test.sql +++ b/supabase/tests/notification_outbox_rls_test.sql @@ -5,15 +5,17 @@ insert into auth.users (id, email) values ('c1111111-1111-1111-1111-111111111111', 'admin-outbox@auftraege.test.local'), ('c2222222-2222-2222-2222-222222222222', 'disponent-outbox@auftraege.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; +update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001'; update public.profiles set role = 'admin' where id = 'c1111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = 'c2222222-2222-2222-2222-222222222222'; -insert into public.orte (id, adresse, ansprechpartner) values - ('c3111111-1111-1111-1111-111111111111', 'Startstr. 1, Teststadt', 'Frau A'), - ('c3222222-2222-2222-2222-222222222222', 'Zielstr. 2, Teststadt', 'Herr B'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('c3111111-1111-1111-1111-111111111111', 'Startstr. 1, Teststadt', 'Frau A', '00000000-0000-0000-0000-00000000f001'), + ('c3222222-2222-2222-2222-222222222222', 'Zielstr. 2, Teststadt', 'Herr B', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('c3333333-0000-0000-0000-000000000001', 'S-WA 42'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('c3333333-0000-0000-0000-000000000001', 'S-WA 42', '00000000-0000-0000-0000-00000000f001'); set local role authenticated; set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}'; @@ -105,20 +107,20 @@ delete from public.notification_outbox where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'; insert into public.notification_outbox - (id, event_type, status, payload, naechster_versuch_ab, updated_at) + (id, event_type, status, payload, naechster_versuch_ab, updated_at, firma_id) values -- faellig: pending, Zeitpunkt erreicht ('c5000000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb, - now() - interval '1 minute', now()), + now() - interval '1 minute', now(), '00000000-0000-0000-0000-00000000f001'), -- nicht faellig: failed, Backoff noch in der Zukunft ('c5000000-0000-0000-0000-000000000002', 'auftrag_erstellt', 'failed', '{}'::jsonb, - now() + interval '1 hour', now()), + now() + interval '1 hour', now(), '00000000-0000-0000-0000-00000000f001'), -- nicht reclaimt: sending, erst vor 2 Minuten uebernommen ('c5000000-0000-0000-0000-000000000003', 'auftrag_erstellt', 'sending', '{}'::jsonb, - now(), now() - interval '2 minutes'), + now(), now() - interval '2 minutes', '00000000-0000-0000-0000-00000000f001'), -- reclaimt: sending, seit 20 Minuten haengengeblieben ('c5000000-0000-0000-0000-000000000004', 'auftrag_erstellt', 'sending', '{}'::jsonb, - now(), now() - interval '20 minutes'); + now(), now() - interval '20 minutes', '00000000-0000-0000-0000-00000000f001'); select results_eq( $$ select id::text from public.claim_notification_batch(10, array['auftrag_erstellt']) order by id $$, @@ -135,7 +137,7 @@ set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", -- wuerde die Beschreibung als erwartete Fehlermeldung interpretieren. Geprueft wird -- nur, dass der INSERT in SQLSTATE 42501 (RLS: keine INSERT-Policy) laeuft. select throws_ok( - $$ insert into public.notification_outbox (event_type, payload) values ('x', '{}'::jsonb) $$, + $$ insert into public.notification_outbox (event_type, payload, firma_id) values ('x', '{}'::jsonb, '00000000-0000-0000-0000-00000000f001') $$, '42501' ); diff --git a/supabase/tests/nutzer_details_rls_test.sql b/supabase/tests/nutzer_details_rls_test.sql index 27d63bb..6bc0558 100644 --- a/supabase/tests/nutzer_details_rls_test.sql +++ b/supabase/tests/nutzer_details_rls_test.sql @@ -7,6 +7,7 @@ insert into auth.users (id, email) values ('33333333-3333-3333-3333-333333333333', 'fahrer-a@test.local'), ('44444444-4444-4444-4444-444444444444', 'fahrer-b@test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = '11111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = '22222222-2222-2222-2222-222222222222'; update public.profiles set role = 'fahrer' where id = '33333333-3333-3333-3333-333333333333'; diff --git a/supabase/tests/orte_fahrzeuge_rls_test.sql b/supabase/tests/orte_fahrzeuge_rls_test.sql index 6ad1783..1b91616 100644 --- a/supabase/tests/orte_fahrzeuge_rls_test.sql +++ b/supabase/tests/orte_fahrzeuge_rls_test.sql @@ -7,6 +7,7 @@ insert into auth.users (id, email) values ('f3333333-3333-3333-3333-333333333333', 'fahrer@stammdaten.test.local'), ('05555555-5555-5555-5555-555555555555', 'readonly@stammdaten.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111'; update public.profiles set role = 'disponent' where id = 'd2222222-2222-2222-2222-222222222222'; update public.profiles set role = 'fahrer' where id = 'f3333333-3333-3333-3333-333333333333'; diff --git a/supabase/tests/profiles_rls_test.sql b/supabase/tests/profiles_rls_test.sql index 7311df4..661a87c 100644 --- a/supabase/tests/profiles_rls_test.sql +++ b/supabase/tests/profiles_rls_test.sql @@ -5,6 +5,7 @@ insert into auth.users (id, email) values ('11111111-1111-1111-1111-111111111111', 'admin@test.local'), ('22222222-2222-2222-2222-222222222222', 'fahrer@test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = '11111111-1111-1111-1111-111111111111'; update public.profiles set role = 'fahrer' where id = '22222222-2222-2222-2222-222222222222'; diff --git a/supabase/tests/protokoll_email_test.sql b/supabase/tests/protokoll_email_test.sql index 7408781..b807dca 100644 --- a/supabase/tests/protokoll_email_test.sql +++ b/supabase/tests/protokoll_email_test.sql @@ -7,23 +7,24 @@ insert into auth.users (id, email, raw_user_meta_data) values ('e5a00000-0000-0000-0000-000000000001', 'dispo-mail@test.local', '{}'::jsonb), ('e5a00000-0000-0000-0000-000000000002', null, '{"name": "Dispo ohne Mail"}'::jsonb); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'disponent' where id = 'e5a00000-0000-0000-0000-000000000001'; update public.profiles set role = 'disponent' where id = 'e5a00000-0000-0000-0000-000000000002'; -insert into public.orte (id, adresse, ansprechpartner) values - ('e5b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('e5b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('e5b00000-0000-0000-0000-000000000001', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('e5b00000-0000-0000-0000-000000000002', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('e5c00000-0000-0000-0000-000000000001', 'M-ML 001'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('e5c00000-0000-0000-0000-000000000001', 'M-ML 001', '00000000-0000-0000-0000-00000000f001'); -- A: Ersteller mit E-Mail, unterwegs -- B: Ersteller ohne E-Mail, unterwegs -- C: Ersteller mit E-Mail, zugewiesen (wird nur storniert) -insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, start_km) values - ('e5d00000-0000-0000-0000-00000000000a', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'unterwegs', 100), - ('e5d00000-0000-0000-0000-00000000000b', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000002', 'unterwegs', 100), - ('e5d00000-0000-0000-0000-00000000000c', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'zugewiesen', null); +insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, start_km, firma_id) values + ('e5d00000-0000-0000-0000-00000000000a', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'unterwegs', 100, '00000000-0000-0000-0000-00000000f001'), + ('e5d00000-0000-0000-0000-00000000000b', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000002', 'unterwegs', 100, '00000000-0000-0000-0000-00000000f001'), + ('e5d00000-0000-0000-0000-00000000000c', 'e5b00000-0000-0000-0000-000000000001', 'e5b00000-0000-0000-0000-000000000002', 'e5c00000-0000-0000-0000-000000000001', 'e5a00000-0000-0000-0000-000000000001', 'zugewiesen', null, '00000000-0000-0000-0000-00000000f001'); -- 1) Abschluss legt genau eine Zeile an update public.auftraege @@ -88,9 +89,9 @@ select is( -- 6) claim_notification_batch claimt nur die angefragten Ereignis-Arten delete from public.notification_outbox; -insert into public.notification_outbox (id, event_type, status, payload, naechster_versuch_ab) values - ('e5e00000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb, now() - interval '1 minute'), - ('e5e00000-0000-0000-0000-000000000002', 'protokoll_abgeschlossen', 'pending', '{}'::jsonb, now() - interval '1 minute'); +insert into public.notification_outbox (id, event_type, status, payload, naechster_versuch_ab, firma_id) values + ('e5e00000-0000-0000-0000-000000000001', 'auftrag_erstellt', 'pending', '{}'::jsonb, now() - interval '1 minute', '00000000-0000-0000-0000-00000000f001'), + ('e5e00000-0000-0000-0000-000000000002', 'protokoll_abgeschlossen', 'pending', '{}'::jsonb, now() - interval '1 minute', '00000000-0000-0000-0000-00000000f001'); select results_eq( $$ select id::text from public.claim_notification_batch(10, array['protokoll_abgeschlossen']) $$, diff --git a/supabase/tests/zeitplanung_test.sql b/supabase/tests/zeitplanung_test.sql index 9dba940..b947b33 100644 --- a/supabase/tests/zeitplanung_test.sql +++ b/supabase/tests/zeitplanung_test.sql @@ -3,14 +3,15 @@ select plan(5); insert into auth.users (id, email) values ('a1111111-1111-1111-1111-111111111111', 'admin@zeitplanung.test.local'); +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'admin' where id = 'a1111111-1111-1111-1111-111111111111'; -insert into public.orte (id, adresse, ansprechpartner) values - ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster'), - ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel'); +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('01111111-1111-1111-1111-111111111111', 'Hauptstr. 1, Musterstadt', 'Frau Muster', '00000000-0000-0000-0000-00000000f001'), + ('02222222-2222-2222-2222-222222222222', 'Nebenweg 2, Musterstadt', 'Herr Beispiel', '00000000-0000-0000-0000-00000000f001'); -insert into public.fahrzeuge (id, kennzeichen) values - ('f0000000-0000-0000-0000-000000000001', 'M-AB 123'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('f0000000-0000-0000-0000-000000000001', 'M-AB 123', '00000000-0000-0000-0000-00000000f001'); set local role authenticated; set local request.jwt.claims to '{"sub": "a1111111-1111-1111-1111-111111111111", "role": "authenticated"}'; diff --git a/web/lib/orte-fahrzeuge/mutations.test.ts b/web/lib/orte-fahrzeuge/mutations.test.ts new file mode 100644 index 0000000..82513d2 --- /dev/null +++ b/web/lib/orte-fahrzeuge/mutations.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; +import { duplikatFehler } from "./mutations"; + +describe("duplikatFehler", () => { + it("erkennt den FIN-Constraint pro Firma", () => { + expect( + duplikatFehler({ message: 'duplicate key value violates unique constraint "fahrzeuge_firma_fin_key"' }) + ).toBe("Diese FIN ist bereits vergeben."); + }); + + it("meldet sonst ein doppeltes Kennzeichen", () => { + expect( + duplikatFehler({ message: 'duplicate key value violates unique constraint "fahrzeuge_firma_kennzeichen_key"' }) + ).toBe("Dieses Kennzeichen ist bereits vergeben."); + }); +}); diff --git a/web/lib/orte-fahrzeuge/mutations.ts b/web/lib/orte-fahrzeuge/mutations.ts index 135cd0f..9aeb84d 100644 --- a/web/lib/orte-fahrzeuge/mutations.ts +++ b/web/lib/orte-fahrzeuge/mutations.ts @@ -55,9 +55,10 @@ export async function updateOrtZeile(input: { } // Beide Unique-Constraints liefern 23505; unterschieden wird am -// Constraint-Namen in der Postgres-Meldung. -function duplikatFehler(error: { message: string }): string { - return error.message.includes("fahrzeuge_fin_key") +// Constraint-Namen in der Postgres-Meldung (fahrzeuge_firma_fin_key / +// fahrzeuge_firma_kennzeichen_key, eindeutig pro Firma). +export function duplikatFehler(error: { message: string }): string { + return error.message.includes("_fin_key") ? "Diese FIN ist bereits vergeben." : "Dieses Kennzeichen ist bereits vergeben."; } From f9a154603a92f44f02de83fc7ebd21d2c701ae41 Mon Sep 17 00:00:00 2001 From: Jonny Date: Mon, 12 Oct 2026 09:57:19 +0200 Subject: [PATCH 02/16] feat: RLS und Storage pro Firma, Bucket firmen-logos Co-Authored-By: Claude Sonnet 5.5 --- .../20261012090200_mandanten_rls.sql | 418 ++++++++++++++++++ supabase/tests/mandanten_rls_test.sql | 147 ++++++ supabase/tests/profiles_rls_test.sql | 3 + 3 files changed, 568 insertions(+) create mode 100644 supabase/migrations/20261012090200_mandanten_rls.sql create mode 100644 supabase/tests/mandanten_rls_test.sql diff --git a/supabase/migrations/20261012090200_mandanten_rls.sql b/supabase/migrations/20261012090200_mandanten_rls.sql new file mode 100644 index 0000000..3f0fb91 --- /dev/null +++ b/supabase/migrations/20261012090200_mandanten_rls.sql @@ -0,0 +1,418 @@ +-- Mandantenfaehigkeit, Teil 2: jede Policy prueft zusaetzlich die Firma. +-- Rollenlogik unveraendert; der Superadmin hat keine Policy auf Fachdaten. +-- Ausnahme: "Nutzer sehen ihr eigenes Profil" bleibt ohne Firmenbedingung +-- (Login-Pruefung, Layout, Superadmin). + +-- ------------------------------------------------------------------ firmen +create policy "Nutzer sehen die eigene Firma" + on public.firmen for select + using (id = public.user_firma_id()); + +create policy "Admin aktualisiert die eigene Firma" + on public.firmen for update + using (id = public.user_firma_id() and public.user_role() = 'admin') + with check (id = public.user_firma_id() and public.user_role() = 'admin'); + +-- ---------------------------------------------------------------- profiles +drop policy "Admins sehen alle Profile" on public.profiles; +create policy "Admins sehen alle Profile" + on public.profiles for select + using (public.user_role() = 'admin' and firma_id = public.user_firma_id()); + +drop policy "Admins aktualisieren alle Profile" on public.profiles; +create policy "Admins aktualisieren alle Profile" + on public.profiles for update + using (public.user_role() = 'admin' and firma_id = public.user_firma_id()) + with check (public.user_role() = 'admin' and firma_id = public.user_firma_id() and role <> 'superadmin'); + +drop policy "Disponent sieht Fahrer-Profile" on public.profiles; +create policy "Disponent sieht Fahrer-Profile" + on public.profiles for select + using (public.user_role() = 'disponent' and role = 'fahrer' and firma_id = public.user_firma_id()); + +drop policy "Fahrer und Readonly sehen Admin/Disponent-Profile" on public.profiles; +create policy "Fahrer und Readonly sehen Admin/Disponent-Profile" + on public.profiles for select + using ( + public.user_role() in ('fahrer', 'readonly') + and role in ('admin', 'disponent') + and firma_id = public.user_firma_id() + ); + +-- -------------------------------------------------------------------- orte +drop policy "Eingeloggte Nutzer sehen alle Orte" on public.orte; +create policy "Eingeloggte Nutzer sehen alle Orte" + on public.orte for select + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent', 'fahrer', 'readonly')); + +drop policy "Disponent und Admin legen Orte an" on public.orte; +create policy "Disponent und Admin legen Orte an" + on public.orte for insert + with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +drop policy "Disponent und Admin bearbeiten Orte" on public.orte; +create policy "Disponent und Admin bearbeiten Orte" + on public.orte for update + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')) + with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +-- --------------------------------------------------------------- fahrzeuge +drop policy "Eingeloggte Nutzer sehen alle Fahrzeuge" on public.fahrzeuge; +create policy "Eingeloggte Nutzer sehen alle Fahrzeuge" + on public.fahrzeuge for select + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent', 'fahrer', 'readonly')); + +drop policy "Disponent und Admin legen Fahrzeuge an" on public.fahrzeuge; +create policy "Disponent und Admin legen Fahrzeuge an" + on public.fahrzeuge for insert + with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +drop policy "Disponent und Admin bearbeiten Fahrzeuge" on public.fahrzeuge; +create policy "Disponent und Admin bearbeiten Fahrzeuge" + on public.fahrzeuge for update + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')) + with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +-- --------------------------------------------------------------- auftraege +drop policy "Sichtbarkeit von Auftraegen nach Rolle" on public.auftraege; +create policy "Sichtbarkeit von Auftraegen nach Rolle" + on public.auftraege for select + using ( + firma_id = public.user_firma_id() + and ( + public.user_role() in ('admin', 'disponent', 'readonly') + or zugewiesen_an = auth.uid() + or status = 'offen' + ) + ); + +drop policy "Disponent und Admin legen Auftraege an" on public.auftraege; +create policy "Disponent und Admin legen Auftraege an" + on public.auftraege for insert + with check ( + firma_id = public.user_firma_id() + and public.user_role() in ('admin', 'disponent') + and erstellt_von = auth.uid() + ); + +drop policy "Disponent und Admin bearbeiten alle Auftraege" on public.auftraege; +create policy "Disponent und Admin bearbeiten alle Auftraege" + on public.auftraege for update + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')) + with check (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +drop policy "Fahrer uebernimmt offene oder bearbeitet eigene Auftraege" on public.auftraege; +create policy "Fahrer uebernimmt offene oder bearbeitet eigene Auftraege" + on public.auftraege for update + using ( + firma_id = public.user_firma_id() + and public.user_role() = 'fahrer' + and (zugewiesen_an = auth.uid() or status = 'offen') + ) + with check ( + firma_id = public.user_firma_id() + and public.user_role() = 'fahrer' + and (zugewiesen_an = auth.uid() or zugewiesen_an is null) + ); + +-- ----------------------------------------------------------- auftrag_fotos +drop policy "Disponent Admin Readonly sehen alle Auftragsfotos" on public.auftrag_fotos; +create policy "Disponent Admin Readonly sehen alle Auftragsfotos" + on public.auftrag_fotos for select + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent', 'readonly')); + +drop policy "Fahrer sieht Fotos des eigenen zugewiesenen Auftrags" on public.auftrag_fotos; +create policy "Fahrer sieht Fotos des eigenen zugewiesenen Auftrags" + on public.auftrag_fotos for select + using ( + firma_id = public.user_firma_id() + and exists ( + select 1 from public.auftraege + where auftraege.id = auftrag_fotos.auftrag_id and auftraege.zugewiesen_an = auth.uid() + ) + ); + +drop policy "Fahrer laedt Fotos fuer eigenen zugewiesenen Auftrag hoch" on public.auftrag_fotos; +create policy "Fahrer laedt Fotos fuer eigenen zugewiesenen Auftrag hoch" + on public.auftrag_fotos for insert + with check ( + firma_id = public.user_firma_id() + and public.user_role() = 'fahrer' + and uploaded_by = auth.uid() + and exists ( + select 1 from public.auftraege + where auftraege.id = auftrag_fotos.auftrag_id + and auftraege.zugewiesen_an = auth.uid() + and ( + (auftrag_fotos.position <> 'schaden' and auftraege.status = 'zugewiesen') + or (auftrag_fotos.position = 'schaden' and auftraege.status in ('zugewiesen', 'unterwegs')) + ) + ) + ); + +drop policy "Admin aktualisiert Auftragsfotos" on public.auftrag_fotos; +create policy "Admin aktualisiert Auftragsfotos" + on public.auftrag_fotos for update + using (firma_id = public.user_firma_id() and public.user_role() = 'admin') + with check (firma_id = public.user_firma_id() and public.user_role() = 'admin'); + +drop policy "Admin loescht Auftragsfotos" on public.auftrag_fotos; +create policy "Admin loescht Auftragsfotos" + on public.auftrag_fotos for delete + using (firma_id = public.user_firma_id() and public.user_role() = 'admin'); + +-- ----------------------------------------------------------- arbeitszeiten +drop policy "Fahrer sieht eigene Arbeitszeiten, Disponent/Admin sehen alle" on public.arbeitszeiten; +create policy "Fahrer sieht eigene Arbeitszeiten, Disponent/Admin sehen alle" + on public.arbeitszeiten for select + using ( + firma_id = public.user_firma_id() + and (fahrer_id = auth.uid() or public.user_role() in ('admin', 'disponent')) + ); + +drop policy "Fahrer stempelt sich selbst ein" on public.arbeitszeiten; +create policy "Fahrer stempelt sich selbst ein" + on public.arbeitszeiten for insert + with check ( + firma_id = public.user_firma_id() + and public.user_role() = 'fahrer' + and fahrer_id = auth.uid() + and geht_um is null + and korrigiert_von is null + and korrigiert_am is null + ); + +drop policy "Fahrer schliesst Schicht, Disponent/Admin korrigieren" on public.arbeitszeiten; +create policy "Fahrer schliesst Schicht, Disponent/Admin korrigieren" + on public.arbeitszeiten for update + using ( + firma_id = public.user_firma_id() + and (fahrer_id = auth.uid() or public.user_role() in ('admin', 'disponent')) + ) + with check ( + firma_id = public.user_firma_id() + and (fahrer_id = auth.uid() or public.user_role() in ('admin', 'disponent')) + ); + +-- ---------------------------------------------------------- nutzer_details +drop policy "Admin und Disponent sehen alle Details" on public.nutzer_details; +create policy "Admin und Disponent sehen alle Details" + on public.nutzer_details for select + using (firma_id = public.user_firma_id() and public.user_role() in ('admin', 'disponent')); + +drop policy "Nutzer und Admin legen Details an" on public.nutzer_details; +create policy "Nutzer und Admin legen Details an" + on public.nutzer_details for insert + with check (firma_id = public.user_firma_id() and (auth.uid() = user_id or public.user_role() = 'admin')); + +drop policy "Nutzer und Admin aktualisieren Details" on public.nutzer_details; +create policy "Nutzer und Admin aktualisieren Details" + on public.nutzer_details for update + using (firma_id = public.user_firma_id() and (auth.uid() = user_id or public.user_role() = 'admin')) + with check (firma_id = public.user_firma_id() and (auth.uid() = user_id or public.user_role() = 'admin')); + +-- "Nutzer sehen ihre eigenen Details" (auth.uid() = user_id) bleibt unveraendert. + +-- ----------------------------------------------------- notification_outbox +drop policy "Admin liest notification_outbox" on public.notification_outbox; +create policy "Admin liest notification_outbox" + on public.notification_outbox for select + using (firma_id = public.user_firma_id() and public.user_role() = 'admin'); + +-- ================================================================ Storage +-- Pfade /...: Zugriff nur, wenn der Auftrag zur eigenen Firma gehoert. + +drop policy "Fahrer liest Fotos des eigenen zugewiesenen Auftrags" on storage.objects; +create policy "Fahrer liest Fotos des eigenen zugewiesenen Auftrags" + on storage.objects for select + using ( + bucket_id = 'auftrag-fotos' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Disponent Admin Readonly lesen alle Auftragsfotos im Storage" on storage.objects; +create policy "Disponent Admin Readonly lesen alle Auftragsfotos im Storage" + on storage.objects for select + using ( + bucket_id = 'auftrag-fotos' + and public.user_role() in ('admin', 'disponent', 'readonly') + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Fahrer laedt Auftragsfotos hoch" on storage.objects; +create policy "Fahrer laedt Auftragsfotos hoch" + on storage.objects for insert + with check ( + bucket_id = 'auftrag-fotos' + and public.user_role() = 'fahrer' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + and ( + (split_part(name, '/', 2) not like 'schaden-%' and a.status = 'zugewiesen') + or (split_part(name, '/', 2) like 'schaden-%' and a.status in ('zugewiesen', 'unterwegs')) + ) + ) + ); + +drop policy "Admin aktualisiert Auftragsfotos im Storage" on storage.objects; +create policy "Admin aktualisiert Auftragsfotos im Storage" + on storage.objects for update + using ( + bucket_id = 'auftrag-fotos' + and public.user_role() = 'admin' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Admin loescht Auftragsfotos im Storage" on storage.objects; +create policy "Admin loescht Auftragsfotos im Storage" + on storage.objects for delete + using ( + bucket_id = 'auftrag-fotos' + and public.user_role() = 'admin' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Fahrer liest Unterschrift des eigenen zugewiesenen Auftrags" on storage.objects; +create policy "Fahrer liest Unterschrift des eigenen zugewiesenen Auftrags" + on storage.objects for select + using ( + bucket_id = 'auftrag-unterschriften' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Disponent Admin Readonly lesen alle Unterschriften im Storage" on storage.objects; +create policy "Disponent Admin Readonly lesen alle Unterschriften im Storage" + on storage.objects for select + using ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() in ('admin', 'disponent', 'readonly') + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Fahrer laedt Unterschrift bei Fahrtende hoch" on storage.objects; +create policy "Fahrer laedt Unterschrift bei Fahrtende hoch" + on storage.objects for insert + with check ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() = 'fahrer' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + and a.status = 'unterwegs' + ) + ); + +drop policy "Fahrer aktualisiert eigene Unterschrift bei Fahrtende" on storage.objects; +create policy "Fahrer aktualisiert eigene Unterschrift bei Fahrtende" + on storage.objects for update + using ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() = 'fahrer' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + and a.status = 'unterwegs' + ) + ) + with check ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() = 'fahrer' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid + and a.zugewiesen_an = auth.uid() + and a.firma_id = public.user_firma_id() + and a.status = 'unterwegs' + ) + ); + +drop policy "Admin aktualisiert Unterschriften im Storage" on storage.objects; +create policy "Admin aktualisiert Unterschriften im Storage" + on storage.objects for update + using ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() = 'admin' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +drop policy "Admin loescht Unterschriften im Storage" on storage.objects; +create policy "Admin loescht Unterschriften im Storage" + on storage.objects for delete + using ( + bucket_id = 'auftrag-unterschriften' + and public.user_role() = 'admin' + and exists ( + select 1 from public.auftraege a + where a.id = (storage.foldername(name))[1]::uuid and a.firma_id = public.user_firma_id() + ) + ); + +-- ------------------------------------------------------------ firmen-logos +insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types) +values ('firmen-logos', 'firmen-logos', false, 1048576, array['image/png', 'image/jpeg', 'image/svg+xml']) +on conflict (id) do nothing; + +create policy "Nutzer lesen das Logo der eigenen Firma" + on storage.objects for select + using (bucket_id = 'firmen-logos' and (storage.foldername(name))[1] = public.user_firma_id()::text); + +create policy "Admin laedt das Logo der eigenen Firma hoch" + on storage.objects for insert + with check ( + bucket_id = 'firmen-logos' + and public.user_role() = 'admin' + and (storage.foldername(name))[1] = public.user_firma_id()::text + ); + +create policy "Admin aktualisiert das Logo der eigenen Firma" + on storage.objects for update + using ( + bucket_id = 'firmen-logos' + and public.user_role() = 'admin' + and (storage.foldername(name))[1] = public.user_firma_id()::text + ) + with check ( + bucket_id = 'firmen-logos' + and public.user_role() = 'admin' + and (storage.foldername(name))[1] = public.user_firma_id()::text + ); + +create policy "Admin loescht das Logo der eigenen Firma" + on storage.objects for delete + using ( + bucket_id = 'firmen-logos' + and public.user_role() = 'admin' + and (storage.foldername(name))[1] = public.user_firma_id()::text + ); diff --git a/supabase/tests/mandanten_rls_test.sql b/supabase/tests/mandanten_rls_test.sql new file mode 100644 index 0000000..8fb3a85 --- /dev/null +++ b/supabase/tests/mandanten_rls_test.sql @@ -0,0 +1,147 @@ +begin; +select plan(30); + +insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f002', 'Firma B'); + +insert into auth.users (id, email) values + ('a0000000-0000-0000-0000-0000000000a1', 'admin-a@rls.test.local'), + ('a0000000-0000-0000-0000-0000000000a2', 'dispo-a@rls.test.local'), + ('a0000000-0000-0000-0000-0000000000a3', 'fahrer-a@rls.test.local'), + ('b0000000-0000-0000-0000-0000000000b1', 'admin-b@rls.test.local'), + ('b0000000-0000-0000-0000-0000000000b2', 'dispo-b@rls.test.local'), + ('b0000000-0000-0000-0000-0000000000b3', 'fahrer-b@rls.test.local'), + ('5a000000-0000-0000-0000-000000000001', 'superadmin@rls.test.local'); + +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'admin' where id = 'a0000000-0000-0000-0000-0000000000a1'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'disponent' where id = 'a0000000-0000-0000-0000-0000000000a2'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001', role = 'fahrer' where id = 'a0000000-0000-0000-0000-0000000000a3'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'admin' where id = 'b0000000-0000-0000-0000-0000000000b1'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'disponent' where id = 'b0000000-0000-0000-0000-0000000000b2'; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f002', role = 'fahrer' where id = 'b0000000-0000-0000-0000-0000000000b3'; +update public.profiles set role = 'superadmin' where id = '5a000000-0000-0000-0000-000000000001'; + +update public.firmen set whatsapp_empfaenger = '+4915100000001' where id = '00000000-0000-0000-0000-00000000f001'; + +-- Daten Firma A +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('a0000000-0000-0000-0000-0000000000c1', 'Ort A', 'Herr A', '00000000-0000-0000-0000-00000000f001'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('a0000000-0000-0000-0000-0000000000d1', 'MT-A 1', '00000000-0000-0000-0000-00000000f001'); +insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status, zugewiesen_an, firma_id) values + ('a0000000-0000-0000-0000-0000000000e1', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1', + 'a0000000-0000-0000-0000-0000000000d1', 'a0000000-0000-0000-0000-0000000000a1', 'zugewiesen', + 'a0000000-0000-0000-0000-0000000000a3', '00000000-0000-0000-0000-00000000f001'), + ('a0000000-0000-0000-0000-0000000000e2', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1', + 'a0000000-0000-0000-0000-0000000000d1', 'a0000000-0000-0000-0000-0000000000a1', 'offen', null, + '00000000-0000-0000-0000-00000000f001'); +insert into public.auftrag_fotos (auftrag_id, position, storage_path, uploaded_by) values + ('a0000000-0000-0000-0000-0000000000e1', 'front', 'a0000000-0000-0000-0000-0000000000e1/front.jpg', 'a0000000-0000-0000-0000-0000000000a3'); +insert into public.arbeitszeiten (fahrer_id, kommt_um, firma_id) values + ('a0000000-0000-0000-0000-0000000000a3', now(), '00000000-0000-0000-0000-00000000f001'); +insert into public.nutzer_details (user_id, telefon) values + ('a0000000-0000-0000-0000-0000000000a3', '+4915100000002'); +insert into storage.objects (bucket_id, name, owner) values + ('auftrag-fotos', 'a0000000-0000-0000-0000-0000000000e1/front.jpg', 'a0000000-0000-0000-0000-0000000000a3'), + ('auftrag-unterschriften', 'a0000000-0000-0000-0000-0000000000e1/unterschrift.png', 'a0000000-0000-0000-0000-0000000000a3'), + ('firmen-logos', '00000000-0000-0000-0000-00000000f001/logo-1.png', 'a0000000-0000-0000-0000-0000000000a1'); + +-- Daten Firma B +insert into public.orte (id, adresse, ansprechpartner, firma_id) values + ('b0000000-0000-0000-0000-0000000000c1', 'Ort B', 'Frau B', '00000000-0000-0000-0000-00000000f002'); + +-- ====================== Admin B +set local role authenticated; +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b1", "role": "authenticated"}'; + +select ok(not exists (select 1 from public.orte where firma_id <> '00000000-0000-0000-0000-00000000f002'), 'Admin B sieht keine Orte von A'); +select ok(exists (select 1 from public.orte where id = 'b0000000-0000-0000-0000-0000000000c1'), 'Admin B sieht eigene Orte'); +select ok(not exists (select 1 from public.fahrzeuge where firma_id <> '00000000-0000-0000-0000-00000000f002'), 'Admin B sieht keine Fahrzeuge von A'); +select ok(not exists (select 1 from public.auftraege where firma_id <> '00000000-0000-0000-0000-00000000f002'), 'Admin B sieht keine Auftraege von A'); +select ok(not exists (select 1 from public.auftrag_fotos), 'Admin B sieht keine Auftragsfotos von A'); +select ok(not exists (select 1 from public.arbeitszeiten), 'Admin B sieht keine Arbeitszeiten von A'); +select ok(not exists (select 1 from public.nutzer_details), 'Admin B sieht keine Nutzer-Details von A'); +select ok(not exists (select 1 from public.profiles where firma_id = '00000000-0000-0000-0000-00000000f001'), 'Admin B sieht keine Profile von A'); +select ok(not exists (select 1 from public.notification_outbox), 'Admin B sieht keine Outbox-Zeilen von A'); +select is((select array_agg(id) from public.firmen), array['00000000-0000-0000-0000-00000000f002'::uuid], 'Admin B sieht nur die eigene Firma'); +select ok(not exists (select 1 from storage.objects where name like 'a0000000-0000-0000-0000-0000000000e1/%' or name like '00000000-0000-0000-0000-00000000f001/%'), 'Admin B sieht keine Storage-Objekte von A'); + +select is_empty( + $$ update public.orte set adresse = 'x' where id = 'a0000000-0000-0000-0000-0000000000c1' returning 1 $$, + 'Admin B kann keinen Ort von A aendern'); +select is_empty( + $$ update public.auftraege set status = 'storniert' where id = 'a0000000-0000-0000-0000-0000000000e2' returning 1 $$, + 'Admin B kann keinen Auftrag von A aendern'); +select is_empty( + $$ update public.profiles set name = 'x' where id = 'a0000000-0000-0000-0000-0000000000a3' returning 1 $$, + 'Admin B kann kein Profil von A aendern'); +select is_empty( + $$ update public.firmen set name = 'x' where id = '00000000-0000-0000-0000-00000000f001' returning 1 $$, + 'Admin B kann Firma A nicht umbenennen'); +select isnt_empty( + $$ update public.firmen set name = 'Firma B neu' where id = '00000000-0000-0000-0000-00000000f002' returning 1 $$, + 'Admin B kann die eigene Firma umbenennen'); + +select throws_ok( + $$ update public.profiles set role = 'superadmin' where id = 'b0000000-0000-0000-0000-0000000000b3' $$, + null, null, + 'Admin B kann niemanden zum Superadmin machen'); +select throws_ok( + $$ insert into public.nutzer_details (user_id, telefon) values ('a0000000-0000-0000-0000-0000000000a1', '+4915100000003') $$, + '42501', 'new row violates row-level security policy for table "nutzer_details"', + 'Admin B kann keine Details fuer Nutzer von A anlegen'); +select throws_ok( + $$ insert into storage.objects (bucket_id, name, owner) values ('firmen-logos', '00000000-0000-0000-0000-00000000f001/logo-2.png', 'b0000000-0000-0000-0000-0000000000b1') $$, + '42501', 'new row violates row-level security policy for table "objects"', + 'Admin B kann kein Logo fuer Firma A hochladen'); +select lives_ok( + $$ insert into storage.objects (bucket_id, name, owner) values ('firmen-logos', '00000000-0000-0000-0000-00000000f002/logo-1.png', 'b0000000-0000-0000-0000-0000000000b1') $$, + 'Admin B kann ein Logo fuer die eigene Firma hochladen'); +select throws_ok( + $$ select * from public.firmen_smtp $$, + '42501', null, + 'firmen_smtp ist fuer angemeldete Nutzer gesperrt'); + +reset role; +reset request.jwt.claims; + +-- ====================== Fahrer B +set local role authenticated; +set local request.jwt.claims to '{"sub": "b0000000-0000-0000-0000-0000000000b3", "role": "authenticated"}'; +select ok(not exists (select 1 from public.auftraege where id = 'a0000000-0000-0000-0000-0000000000e2'), 'Fahrer B sieht den offenen Auftrag von A nicht'); +select is_empty( + $$ update public.auftraege set zugewiesen_an = 'b0000000-0000-0000-0000-0000000000b3', status = 'zugewiesen' where id = 'a0000000-0000-0000-0000-0000000000e2' returning 1 $$, + 'Fahrer B kann den offenen Auftrag von A nicht uebernehmen'); +reset role; +reset request.jwt.claims; + +-- ====================== Disponent A +set local role authenticated; +set local request.jwt.claims to '{"sub": "a0000000-0000-0000-0000-0000000000a2", "role": "authenticated"}'; +select ok( + exists (select 1 from public.profiles where id = 'a0000000-0000-0000-0000-0000000000a3') + and not exists (select 1 from public.profiles where id = 'b0000000-0000-0000-0000-0000000000b3'), + 'Disponent A sieht nur Fahrer der eigenen Firma'); +select ok(exists (select 1 from public.auftraege where id = 'a0000000-0000-0000-0000-0000000000e1'), 'Disponent A sieht eigene Auftraege'); +reset role; +reset request.jwt.claims; + +-- ====================== Superadmin +set local role authenticated; +set local request.jwt.claims to '{"sub": "5a000000-0000-0000-0000-000000000001", "role": "authenticated"}'; +select ok(not exists (select 1 from public.auftraege), 'Superadmin sieht keine Auftraege'); +select ok(not exists (select 1 from public.firmen), 'Superadmin sieht ueber RLS keine Firmen'); +select ok(exists (select 1 from public.profiles where id = '5a000000-0000-0000-0000-000000000001'), 'Superadmin sieht sein eigenes Profil'); +reset role; +reset request.jwt.claims; + +-- ====================== Firma A deaktiviert +update public.firmen set aktiv = false where id = '00000000-0000-0000-0000-00000000f001'; +set local role authenticated; +set local request.jwt.claims to '{"sub": "a0000000-0000-0000-0000-0000000000a1", "role": "authenticated"}'; +select ok(not exists (select 1 from public.auftraege), 'Deaktivierte Firma: Admin sieht keine Auftraege mehr'); +select ok(exists (select 1 from public.profiles where id = 'a0000000-0000-0000-0000-0000000000a1'), 'Deaktivierte Firma: eigenes Profil bleibt lesbar'); +reset role; +reset request.jwt.claims; + +select * from finish(); +rollback; diff --git a/supabase/tests/profiles_rls_test.sql b/supabase/tests/profiles_rls_test.sql index 661a87c..7007390 100644 --- a/supabase/tests/profiles_rls_test.sql +++ b/supabase/tests/profiles_rls_test.sql @@ -81,6 +81,9 @@ select is( -- Admin-Update zu 'disponent' geaendert). insert into auth.users (id, email) values ('44444444-4444-4444-4444-444444444444', 'fahrer2@test.local'); +-- Firmenzuordnung neuer Fixture-Nutzer: nur ohne JWT-Kontext erlaubt (Trigger firma_id_unveraenderlich) +reset request.jwt.claims; +update public.profiles set firma_id = '00000000-0000-0000-0000-00000000f001' where firma_id is null; update public.profiles set role = 'fahrer' where id = '44444444-4444-4444-4444-444444444444'; set local role authenticated; From 88693282f824806089c246a7faa2617e53467b56 Mon Sep 17 00:00:00 2001 From: Jonny Date: Mon, 12 Oct 2026 10:02:38 +0200 Subject: [PATCH 03/16] feat: Farb-Kontrastpruefung und SMTP-Passwort-Verschluesselung Co-Authored-By: Claude Opus 5.5 --- web/lib/firma/farben.test.ts | 47 +++++++++++++++++++++++++++++++ web/lib/firma/farben.ts | 33 ++++++++++++++++++++++ web/lib/firma/smtp-crypto.test.ts | 46 ++++++++++++++++++++++++++++++ web/lib/firma/smtp-crypto.ts | 36 +++++++++++++++++++++++ 4 files changed, 162 insertions(+) create mode 100644 web/lib/firma/farben.test.ts create mode 100644 web/lib/firma/farben.ts create mode 100644 web/lib/firma/smtp-crypto.test.ts create mode 100644 web/lib/firma/smtp-crypto.ts diff --git a/web/lib/firma/farben.test.ts b/web/lib/firma/farben.test.ts new file mode 100644 index 0000000..f80ad95 --- /dev/null +++ b/web/lib/firma/farben.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from "vitest"; +import { + MIN_KONTRAST, + STANDARD_FARBE_DUNKEL, + STANDARD_FARBE_PRIMAER, + kontrastZuWeiss, + normalisiereFarbe, + themeVariablen, +} from "./farben"; + +describe("normalisiereFarbe", () => { + it("akzeptiert #rrggbb und schreibt klein", () => { + expect(normalisiereFarbe(" #0A185C ")).toBe("#0a185c"); + }); + it("lehnt andere Formate ab", () => { + expect(normalisiereFarbe("#abc")).toBeNull(); + expect(normalisiereFarbe("0071ed")).toBeNull(); + expect(normalisiereFarbe("#gggggg")).toBeNull(); + expect(normalisiereFarbe("")).toBeNull(); + }); +}); + +describe("kontrastZuWeiss", () => { + it("liefert 21 fuer Schwarz und 1 fuer Weiss", () => { + expect(kontrastZuWeiss("#000000")).toBeCloseTo(21, 1); + expect(kontrastZuWeiss("#ffffff")).toBeCloseTo(1, 5); + }); + it("Standardfarben bestehen den Mindestkontrast", () => { + expect(kontrastZuWeiss(STANDARD_FARBE_PRIMAER)).toBeGreaterThanOrEqual(MIN_KONTRAST); + expect(kontrastZuWeiss(STANDARD_FARBE_DUNKEL)).toBeGreaterThanOrEqual(MIN_KONTRAST); + }); + it("Gelb faellt durch", () => { + expect(kontrastZuWeiss("#ffff00")).toBeLessThan(MIN_KONTRAST); + }); +}); + +describe("themeVariablen", () => { + it("setzt nur vorhandene Farben", () => { + expect(themeVariablen({ farbe_primaer: "#112233", farbe_dunkel: null })).toEqual({ + "--color-performance-blue": "#112233", + }); + expect(themeVariablen({ farbe_primaer: null, farbe_dunkel: "#000000" })).toEqual({ + "--color-night-blue": "#000000", + }); + expect(themeVariablen({ farbe_primaer: null, farbe_dunkel: null })).toEqual({}); + }); +}); diff --git a/web/lib/firma/farben.ts b/web/lib/firma/farben.ts new file mode 100644 index 0000000..772e4f5 --- /dev/null +++ b/web/lib/firma/farben.ts @@ -0,0 +1,33 @@ +export const STANDARD_FARBE_PRIMAER = "#0071ed"; +export const STANDARD_FARBE_DUNKEL = "#0a185c"; +// WCAG AA fuer normalen Text: Buttons tragen weisse Schrift auf der Hauptfarbe. +export const MIN_KONTRAST = 4.5; + +const HEX_REGEX = /^#[0-9a-f]{6}$/; + +export function normalisiereFarbe(eingabe: string): string | null { + const wert = eingabe.trim().toLowerCase(); + return HEX_REGEX.test(wert) ? wert : null; +} + +function kanal(wert: number): number { + const c = wert / 255; + return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; +} + +// Kontrastverhaeltnis nach WCAG 2.x zwischen der Farbe und Weiss. +export function kontrastZuWeiss(hex: string): number { + const r = parseInt(hex.slice(1, 3), 16); + const g = parseInt(hex.slice(3, 5), 16); + const b = parseInt(hex.slice(5, 7), 16); + const luminanz = 0.2126 * kanal(r) + 0.7152 * kanal(g) + 0.0722 * kanal(b); + return 1.05 / (luminanz + 0.05); +} + +// CSS-Variablen aus globals.css (@theme), die das Layout am ueberschreibt. +export function themeVariablen(f: { farbe_primaer: string | null; farbe_dunkel: string | null }): Record { + const variablen: Record = {}; + if (f.farbe_primaer) variablen["--color-performance-blue"] = f.farbe_primaer; + if (f.farbe_dunkel) variablen["--color-night-blue"] = f.farbe_dunkel; + return variablen; +} diff --git a/web/lib/firma/smtp-crypto.test.ts b/web/lib/firma/smtp-crypto.test.ts new file mode 100644 index 0000000..0c42459 --- /dev/null +++ b/web/lib/firma/smtp-crypto.test.ts @@ -0,0 +1,46 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { entschluessele, verschluessele } from "./smtp-crypto"; + +const KEY = Buffer.alloc(32, 7).toString("base64"); + +describe("smtp-crypto", () => { + const alt = process.env.SMTP_VERSCHLUESSELUNG_KEY; + beforeEach(() => { + process.env.SMTP_VERSCHLUESSELUNG_KEY = KEY; + }); + afterEach(() => { + process.env.SMTP_VERSCHLUESSELUNG_KEY = alt; + }); + + it("Roundtrip liefert den Klartext", () => { + const wert = verschluessele("geheim-äöü"); + expect(wert.startsWith("v1:")).toBe(true); + expect(wert).not.toContain("geheim"); + expect(entschluessele(wert)).toBe("geheim-äöü"); + }); + + it("zwei Verschluesselungen desselben Texts unterscheiden sich (zufaelliger IV)", () => { + expect(verschluessele("x")).not.toBe(verschluessele("x")); + }); + + it("manipulierter Ciphertext scheitert", () => { + const [v, iv, tag, ct] = verschluessele("geheim").split(":"); + const kaputt = Buffer.from(ct, "base64"); + kaputt[0] ^= 1; + expect(() => entschluessele([v, iv, tag, kaputt.toString("base64")].join(":"))).toThrow(); + }); + + it("unbekanntes Format scheitert", () => { + expect(() => entschluessele("klartext")).toThrow("Unbekanntes Format"); + }); + + it("fehlender Schluessel scheitert mit klarer Meldung", () => { + delete process.env.SMTP_VERSCHLUESSELUNG_KEY; + expect(() => verschluessele("x")).toThrow("SMTP_VERSCHLUESSELUNG_KEY ist nicht gesetzt"); + }); + + it("Schluessel falscher Laenge scheitert", () => { + process.env.SMTP_VERSCHLUESSELUNG_KEY = Buffer.alloc(16).toString("base64"); + expect(() => verschluessele("x")).toThrow("32 Byte"); + }); +}); diff --git a/web/lib/firma/smtp-crypto.ts b/web/lib/firma/smtp-crypto.ts new file mode 100644 index 0000000..6c7276c --- /dev/null +++ b/web/lib/firma/smtp-crypto.ts @@ -0,0 +1,36 @@ +import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"; + +const ALGORITHMUS = "aes-256-gcm"; + +function schluessel(): Buffer { + const roh = process.env.SMTP_VERSCHLUESSELUNG_KEY; + if (!roh) { + throw new Error("SMTP_VERSCHLUESSELUNG_KEY ist nicht gesetzt"); + } + const key = Buffer.from(roh, "base64"); + if (key.length !== 32) { + throw new Error("SMTP_VERSCHLUESSELUNG_KEY muss 32 Byte (base64) lang sein"); + } + return key; +} + +// Format v1:::, alles base64. Die Version erlaubt einen +// spaeteren Schluesselwechsel ohne Raten. +export function verschluessele(klartext: string): string { + const iv = randomBytes(12); + const cipher = createCipheriv(ALGORITHMUS, schluessel(), iv); + const ciphertext = Buffer.concat([cipher.update(klartext, "utf8"), cipher.final()]); + const tag = cipher.getAuthTag(); + return ["v1", iv.toString("base64"), tag.toString("base64"), ciphertext.toString("base64")].join(":"); +} + +export function entschluessele(wert: string): string { + const teile = wert.split(":"); + if (teile.length !== 4 || teile[0] !== "v1") { + throw new Error("Unbekanntes Format des verschluesselten SMTP-Passworts"); + } + const [, iv, tag, ciphertext] = teile; + const decipher = createDecipheriv(ALGORITHMUS, schluessel(), Buffer.from(iv, "base64")); + decipher.setAuthTag(Buffer.from(tag, "base64")); + return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64")), decipher.final()]).toString("utf8"); +} From 61f531552c82b58ce26b89a69121a8869718bde6 Mon Sep 17 00:00:00 2001 From: Jonny Date: Mon, 12 Oct 2026 10:08:37 +0200 Subject: [PATCH 04/16] feat: Firmenzugang beim Login, Branding im Layout, Logo-Route, Superadmin-Navigation Co-Authored-By: Claude Sonnet 5.5 --- web/app/abmelden/route.ts | 15 +++++++++++ web/app/firma/logo/route.ts | 27 ++++++++++++++++++++ web/app/layout.tsx | 17 ++++++++++--- web/app/login/actions.ts | 13 +++++++++- web/components/FirmenLogo.tsx | 22 ++++++++++++++++ web/components/NavLinks.tsx | 23 ++++++++++++++++- web/lib/auth/profile.ts | 3 ++- web/lib/auth/roles.ts | 10 +++++++- web/lib/firma/eigene-firma.ts | 23 +++++++++++++++++ web/lib/firma/logo.test.ts | 40 +++++++++++++++++++++++++++++ web/lib/firma/logo.ts | 42 ++++++++++++++++++++++++++++++ web/lib/firma/queries.test.ts | 37 +++++++++++++++++++++++++++ web/lib/firma/queries.ts | 48 +++++++++++++++++++++++++++++++++++ 13 files changed, 312 insertions(+), 8 deletions(-) create mode 100644 web/app/abmelden/route.ts create mode 100644 web/app/firma/logo/route.ts create mode 100644 web/components/FirmenLogo.tsx create mode 100644 web/lib/firma/eigene-firma.ts create mode 100644 web/lib/firma/logo.test.ts create mode 100644 web/lib/firma/logo.ts create mode 100644 web/lib/firma/queries.test.ts create mode 100644 web/lib/firma/queries.ts diff --git a/web/app/abmelden/route.ts b/web/app/abmelden/route.ts new file mode 100644 index 0000000..268fc50 --- /dev/null +++ b/web/app/abmelden/route.ts @@ -0,0 +1,15 @@ +import { NextResponse } from "next/server"; +import { createClient } from "@/lib/supabase/server"; +import { FIRMA_GESPERRT } from "@/lib/firma/eigene-firma"; + +// Server Components koennen keine Cookies loeschen; das Layout leitet bei +// gesperrter Firma hierher um. +export async function GET(request: Request): Promise { + const supabase = await createClient(); + await supabase.auth.signOut(); + const ziel = new URL("/login", request.url); + if (new URL(request.url).searchParams.get("grund") === "firma") { + ziel.searchParams.set("error", FIRMA_GESPERRT); + } + return NextResponse.redirect(ziel); +} diff --git a/web/app/firma/logo/route.ts b/web/app/firma/logo/route.ts new file mode 100644 index 0000000..370a8d1 --- /dev/null +++ b/web/app/firma/logo/route.ts @@ -0,0 +1,27 @@ +import { createClient } from "@/lib/supabase/server"; +import { ladeEigeneFirma } from "@/lib/firma/eigene-firma"; +import { LOGO_SICHERHEITS_HEADER, logoContentType } from "@/lib/firma/logo"; + +export const dynamic = "force-dynamic"; + +// Signierte Storage-URLs scheiden aus: im Docker-Stack enthielten sie die +// interne Kong-Adresse. Die Datei wird mit dem Nutzer-Client geladen (RLS). +export async function GET(): Promise { + const ergebnis = await ladeEigeneFirma(); + if (ergebnis.status !== "ok" || !ergebnis.firma.logo_pfad) { + return new Response(null, { status: 404 }); + } + const pfad = ergebnis.firma.logo_pfad; + const supabase = await createClient(); + const { data, error } = await supabase.storage.from("firmen-logos").download(pfad); + if (error || !data) { + return new Response(null, { status: 404 }); + } + return new Response(await data.arrayBuffer(), { + headers: { + "Content-Type": logoContentType(pfad), + "Cache-Control": "private, max-age=86400", + ...LOGO_SICHERHEITS_HEADER, + }, + }); +} diff --git a/web/app/layout.tsx b/web/app/layout.tsx index 2f82e23..907667e 100644 --- a/web/app/layout.tsx +++ b/web/app/layout.tsx @@ -1,8 +1,11 @@ -import Image from "next/image"; import Link from "next/link"; +import { redirect } from "next/navigation"; import { Inter } from "next/font/google"; import "./globals.css"; import { loadProfile } from "@/lib/auth/profile"; +import { ladeEigeneFirma } from "@/lib/firma/eigene-firma"; +import { themeVariablen } from "@/lib/firma/farben"; +import { FirmenLogo } from "@/components/FirmenLogo"; import { NavLinks } from "@/components/NavLinks"; import { LogoutButton } from "@/components/LogoutButton"; import { MobileNav } from "@/components/MobileNav"; @@ -17,6 +20,12 @@ export default async function RootLayout({ children, }: Readonly<{ children: React.ReactNode }>) { const result = await loadProfile(); + const firmaErgebnis = await ladeEigeneFirma(); + if (result.status === "ok" && firmaErgebnis.status === "keine-firma") { + redirect("/abmelden?grund=firma"); + } + const firma = firmaErgebnis.status === "ok" ? firmaErgebnis.firma : null; + const themeStyle = firma ? (themeVariablen(firma) as React.CSSProperties) : undefined; if (result.status === "missing-profile") { return ( @@ -36,12 +45,12 @@ export default async function RootLayout({ } return ( - + {result.status === "ok" && (
- - Widmann + +
diff --git a/web/app/login/actions.ts b/web/app/login/actions.ts index 70f9947..98ec108 100644 --- a/web/app/login/actions.ts +++ b/web/app/login/actions.ts @@ -4,6 +4,8 @@ import { redirect } from "next/navigation"; import { createClient } from "@/lib/supabase/server"; import { createAdminClient } from "@/lib/supabase/admin"; import { PASSWORT_AENDERN_PFAD, hatPasswortAenderPflicht } from "@/lib/auth/passwort"; +import { pruefeFirmenzugang } from "@/lib/firma/queries"; +import { FIRMA_GESPERRT } from "@/lib/firma/eigene-firma"; import { validateLogin } from "@/lib/validate-login"; const LOGIN_FEHLER = "E-Mail oder Passwort ist falsch."; @@ -57,7 +59,16 @@ export async function login(formData: FormData): Promise { redirect(`/login?error=${encodeURIComponent(LOGIN_FEHLER)}`); } - redirect(hatPasswortAenderPflicht(data.user) ? PASSWORT_AENDERN_PFAD : "/dashboard"); + const zugang = await pruefeFirmenzugang(supabase, data.user.id); + if (zugang === "gesperrt") { + await supabase.auth.signOut(); + redirect(`/login?error=${encodeURIComponent(FIRMA_GESPERRT)}`); + } + + if (hatPasswortAenderPflicht(data.user)) { + redirect(PASSWORT_AENDERN_PFAD); + } + redirect(zugang === "superadmin" ? "/plattform" : "/dashboard"); } export async function logout(): Promise { diff --git a/web/components/FirmenLogo.tsx b/web/components/FirmenLogo.tsx new file mode 100644 index 0000000..448bfa3 --- /dev/null +++ b/web/components/FirmenLogo.tsx @@ -0,0 +1,22 @@ +import Image from "next/image"; +import { WIDMANN_FIRMA_ID, type Firma } from "@/lib/firma/queries"; + +export function FirmenLogo({ firma }: { firma: Firma | null }) { + if (!firma) { + return Plattform-Verwaltung; + } + if (firma.logo_pfad) { + return ( + // eslint-disable-next-line @next/next/no-img-element -- Logo kommt aus einer eigenen Route mit Session-Cookie + {firma.name} + ); + } + if (firma.id === WIDMANN_FIRMA_ID) { + return Widmann; + } + return {firma.name}; +} diff --git a/web/components/NavLinks.tsx b/web/components/NavLinks.tsx index fad29cf..d92dd9d 100644 --- a/web/components/NavLinks.tsx +++ b/web/components/NavLinks.tsx @@ -1,5 +1,5 @@ import Link from "next/link"; -import { canManageUsers, kannAuslastungSehen, kannFahrerdetailsSehen, kannStammdatenPflegen, kannZeiterfassungNutzen, type Role } from "@/lib/auth/roles"; +import { canManageUsers, istSuperadmin, kannFirmaVerwalten, kannAuslastungSehen, kannFahrerdetailsSehen, kannStammdatenPflegen, kannZeiterfassungNutzen, type Role } from "@/lib/auth/roles"; export function NavLinks({ role, @@ -10,6 +10,22 @@ export function NavLinks({ }) { const layoutClass = orientation === "horizontal" ? "flex flex-row items-center gap-6" : "flex flex-col gap-4"; + const linkClass = + "flex min-h-11 items-center text-asphalt-grey hover:text-performance-blue focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-performance-blue"; + + if (istSuperadmin(role)) { + return ( + + ); + } + return (
); diff --git a/web/lib/auth/passwort.test.ts b/web/lib/auth/passwort.test.ts index 6fffdbe..a7eb7f1 100644 --- a/web/lib/auth/passwort.test.ts +++ b/web/lib/auth/passwort.test.ts @@ -95,6 +95,10 @@ describe("mussPasswortAendern", () => { expect(mussPasswortAendern(MIT_PFLICHT, `${PASSWORT_AENDERN_PFAD}/`)).toBe(false); }); + it("leitet /abmelden nicht um (sonst Redirect-Schleife)", () => { + expect(mussPasswortAendern(MIT_PFLICHT, "/abmelden")).toBe(false); + }); + it("leitet bei einem Pfad mit ähnlichem Präfix trotzdem um", () => { expect(mussPasswortAendern(MIT_PFLICHT, "/passwort-aendern-x")).toBe(true); }); diff --git a/web/lib/auth/passwort.ts b/web/lib/auth/passwort.ts index f71290a..d91c514 100644 --- a/web/lib/auth/passwort.ts +++ b/web/lib/auth/passwort.ts @@ -38,6 +38,11 @@ export function mussPasswortAendern(user: AuthUserLike, pathname: string): boole if (!hatPasswortAenderPflicht(user)) { return false; } + // /abmelden muss erreichbar bleiben, sonst entsteht eine Redirect-Schleife + // (Layout: keine aktive Firma -> /abmelden -> Middleware -> /passwort-aendern). + if (pathname === "/abmelden") { + return false; + } const aufPasswortSeite = pathname === PASSWORT_AENDERN_PFAD || pathname.startsWith(`${PASSWORT_AENDERN_PFAD}/`); return !aufPasswortSeite; } From 9b90bf6335bdcf101f31cf0a1a59cab5f9560613 Mon Sep 17 00:00:00 2001 From: Jonny Date: Mon, 12 Oct 2026 14:32:14 +0200 Subject: [PATCH 14/16] fix: GCM-Tag- und IV-Laenge beim SMTP-Passwort festschreiben Co-Authored-By: Claude Sonnet 5.5 --- web/lib/firma/smtp-crypto.test.ts | 12 ++++++++++++ web/lib/firma/smtp-crypto.ts | 16 ++++++++++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/web/lib/firma/smtp-crypto.test.ts b/web/lib/firma/smtp-crypto.test.ts index 0c42459..60a6159 100644 --- a/web/lib/firma/smtp-crypto.test.ts +++ b/web/lib/firma/smtp-crypto.test.ts @@ -30,6 +30,18 @@ describe("smtp-crypto", () => { expect(() => entschluessele([v, iv, tag, kaputt.toString("base64")].join(":"))).toThrow(); }); + it("gekuerzter Auth-Tag scheitert", () => { + const [v, iv, tag, ct] = verschluessele("geheim").split(":"); + const kurz = Buffer.from(tag, "base64").subarray(0, 4).toString("base64"); + expect(() => entschluessele([v, iv, kurz, ct].join(":"))).toThrow("Unbekanntes Format"); + }); + + it("falsche IV-Laenge scheitert", () => { + const [v, iv, tag, ct] = verschluessele("geheim").split(":"); + const kurz = Buffer.from(iv, "base64").subarray(0, 8).toString("base64"); + expect(() => entschluessele([v, kurz, tag, ct].join(":"))).toThrow("Unbekanntes Format"); + }); + it("unbekanntes Format scheitert", () => { expect(() => entschluessele("klartext")).toThrow("Unbekanntes Format"); }); diff --git a/web/lib/firma/smtp-crypto.ts b/web/lib/firma/smtp-crypto.ts index 6c7276c..9dbe7a7 100644 --- a/web/lib/firma/smtp-crypto.ts +++ b/web/lib/firma/smtp-crypto.ts @@ -1,6 +1,8 @@ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"; const ALGORITHMUS = "aes-256-gcm"; +const IV_LAENGE = 12; +const TAG_LAENGE = 16; function schluessel(): Buffer { const roh = process.env.SMTP_VERSCHLUESSELUNG_KEY; @@ -17,8 +19,8 @@ function schluessel(): Buffer { // Format v1:::, alles base64. Die Version erlaubt einen // spaeteren Schluesselwechsel ohne Raten. export function verschluessele(klartext: string): string { - const iv = randomBytes(12); - const cipher = createCipheriv(ALGORITHMUS, schluessel(), iv); + const iv = randomBytes(IV_LAENGE); + const cipher = createCipheriv(ALGORITHMUS, schluessel(), iv, { authTagLength: TAG_LAENGE }); const ciphertext = Buffer.concat([cipher.update(klartext, "utf8"), cipher.final()]); const tag = cipher.getAuthTag(); return ["v1", iv.toString("base64"), tag.toString("base64"), ciphertext.toString("base64")].join(":"); @@ -30,7 +32,13 @@ export function entschluessele(wert: string): string { throw new Error("Unbekanntes Format des verschluesselten SMTP-Passworts"); } const [, iv, tag, ciphertext] = teile; - const decipher = createDecipheriv(ALGORITHMUS, schluessel(), Buffer.from(iv, "base64")); - decipher.setAuthTag(Buffer.from(tag, "base64")); + const ivBytes = Buffer.from(iv, "base64"); + const tagBytes = Buffer.from(tag, "base64"); + // Node akzeptiert sonst gekuerzte GCM-Tags; Laengen daher fest vorgeben. + if (ivBytes.length !== IV_LAENGE || tagBytes.length !== TAG_LAENGE) { + throw new Error("Unbekanntes Format des verschluesselten SMTP-Passworts"); + } + const decipher = createDecipheriv(ALGORITHMUS, schluessel(), ivBytes, { authTagLength: TAG_LAENGE }); + decipher.setAuthTag(tagBytes); return Buffer.concat([decipher.update(Buffer.from(ciphertext, "base64")), decipher.final()]).toString("utf8"); } From c797fe62ecd65754ef7a28e8aa112d1c7abb5680 Mon Sep 17 00:00:00 2001 From: Jonny Date: Mon, 12 Oct 2026 14:32:14 +0200 Subject: [PATCH 15/16] fix: SMTP-SSRF-Schutz, Port-Whitelist, Passwort nur bei gleichem Ziel behalten Co-Authored-By: Claude Sonnet 5.5 --- web/app/firma/smtp-actions.ts | 29 +++++++-- web/lib/firma/smtp-ziel.test.ts | 71 ++++++++++++++++++++++ web/lib/firma/smtp-ziel.ts | 65 ++++++++++++++++++++ web/lib/firma/smtp.test.ts | 86 ++++++++++++++++++++++----- web/lib/firma/smtp.ts | 45 ++++++++++++-- web/lib/notifications/email-config.ts | 3 + web/lib/notifications/email.test.ts | 15 +++++ web/lib/notifications/email.ts | 1 + web/lib/notifications/handler.test.ts | 15 +++++ web/lib/notifications/handler.ts | 6 +- 10 files changed, 311 insertions(+), 25 deletions(-) create mode 100644 web/lib/firma/smtp-ziel.test.ts create mode 100644 web/lib/firma/smtp-ziel.ts diff --git a/web/app/firma/smtp-actions.ts b/web/app/firma/smtp-actions.ts index 7b3d7ac..76792b5 100644 --- a/web/app/firma/smtp-actions.ts +++ b/web/app/firma/smtp-actions.ts @@ -4,8 +4,16 @@ import { revalidatePath } from "next/cache"; import { createClient } from "@/lib/supabase/server"; import { createAdminClient } from "@/lib/supabase/admin"; import { ladeAdminKontext } from "@/lib/firma/admin-kontext"; -import { firmenSmtpZuConfig, ladeFirmenSmtp, validateSmtpEingabe } from "@/lib/firma/smtp"; +import { + SMTP_ZIEL_NICHT_ERLAUBT, + SmtpZielFehler, + firmenSmtpZuConfig, + ladeFirmenSmtp, + pinneSmtpZiel, + validateSmtpEingabe, +} from "@/lib/firma/smtp"; import { verschluessele } from "@/lib/firma/smtp-crypto"; +import { pruefeSmtpZiel } from "@/lib/firma/smtp-ziel"; import { sendeProtokollMail } from "@/lib/notifications/email"; export type ActionResult = { success: true } | { success: false; error: string }; @@ -29,15 +37,22 @@ export async function speichereSmtp(formData: FormData): Promise { absenderAdresse: formData.get("absender_adresse"), absenderName: formData.get("absender_name"), }, - Boolean(bestehend?.passwort_verschluesselt) + bestehend ); if (!validation.valid) return { success: false, error: validation.error }; const w = validation.werte; + const ziel = await pruefeSmtpZiel(w.host); + if (!ziel.ok) return { success: false, error: `${SMTP_ZIEL_NICHT_ERLAUBT}.` }; + let passwortVerschluesselt: string | null = null; if (w.benutzer) { try { - passwortVerschluesselt = w.neuesPasswort ? verschluessele(w.neuesPasswort) : bestehend?.passwort_verschluesselt ?? null; + passwortVerschluesselt = w.neuesPasswort + ? verschluessele(w.neuesPasswort) + : w.passwortBehalten + ? (bestehend?.passwort_verschluesselt ?? null) + : null; } catch (fehler) { return { success: false, error: fehler instanceof Error ? fehler.message : "Verschlüsselung fehlgeschlagen." }; } @@ -86,8 +101,9 @@ export async function sendeTestmail(): Promise { let cfg; try { - cfg = firmenSmtpZuConfig(zeile); + cfg = await pinneSmtpZiel(firmenSmtpZuConfig(zeile)); } catch (fehler) { + if (fehler instanceof SmtpZielFehler) return { success: false, error: `${SMTP_ZIEL_NICHT_ERLAUBT}.` }; return { success: false, error: fehler instanceof Error ? fehler.message : "Konfiguration ungültig." }; } @@ -97,5 +113,8 @@ export async function sendeTestmail(): Promise { text: "Diese Testmail bestätigt, dass der SMTP-Versand Ihrer Firma funktioniert.", attachments: [], }); - return ergebnis.ok ? { success: true } : { success: false, error: ergebnis.fehler.slice(0, 500) }; + if (ergebnis.ok) return { success: true }; + // Kein Rohtext an den Admin: Fehlermeldungen koennten interne Ziele verraten. + console.error("Testmail fehlgeschlagen:", ergebnis.fehler); + return { success: false, error: "Verbindung zum SMTP-Server fehlgeschlagen." }; } diff --git a/web/lib/firma/smtp-ziel.test.ts b/web/lib/firma/smtp-ziel.test.ts new file mode 100644 index 0000000..e8aa048 --- /dev/null +++ b/web/lib/firma/smtp-ziel.test.ts @@ -0,0 +1,71 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("node:dns/promises", () => ({ lookup: vi.fn() })); + +import { lookup } from "node:dns/promises"; +import { pruefeSmtpZiel } from "./smtp-ziel"; + +const lookupMock = vi.mocked(lookup) as unknown as ReturnType; + +describe("pruefeSmtpZiel", () => { + beforeEach(() => { + lookupMock.mockReset(); + }); + + it.each([ + "127.0.0.1", + "10.0.0.1", + "0.0.0.0", + "100.64.0.1", + "169.254.169.254", + "172.16.5.4", + "192.168.1.1", + "198.18.0.1", + "224.0.0.1", + "255.255.255.255", + "::", + "::1", + "fc00::1", + "fd12:3456::1", + "fe80::1", + "ff02::1", + "::ffff:127.0.0.1", + "::ffff:7f00:1", + "::ffff:169.254.169.254", + ])("lehnt das IP-Literal %s ab", async (ip) => { + expect(await pruefeSmtpZiel(ip)).toEqual({ ok: false }); + expect(lookupMock).not.toHaveBeenCalled(); + }); + + it("akzeptiert eine oeffentliche IP direkt und pinnt sie", async () => { + expect(await pruefeSmtpZiel("93.184.216.34")).toEqual({ ok: true, ip: "93.184.216.34" }); + expect(await pruefeSmtpZiel("2606:4700::1111")).toEqual({ ok: true, ip: "2606:4700::1111" }); + expect(lookupMock).not.toHaveBeenCalled(); + }); + + it("lehnt einen Namen ab, der privat aufloest", async () => { + lookupMock.mockResolvedValue([{ address: "10.1.2.3", family: 4 }]); + expect(await pruefeSmtpZiel("intern.example.de")).toEqual({ ok: false }); + expect(lookupMock).toHaveBeenCalledWith("intern.example.de", { all: true }); + }); + + it("lehnt ab, wenn nur eine von mehreren Adressen privat ist", async () => { + lookupMock.mockResolvedValue([ + { address: "93.184.216.34", family: 4 }, + { address: "127.0.0.1", family: 4 }, + ]); + expect(await pruefeSmtpZiel("mix.example.de")).toEqual({ ok: false }); + }); + + it("akzeptiert einen Namen mit oeffentlicher Adresse und liefert die erste IP", async () => { + lookupMock.mockResolvedValue([{ address: "93.184.216.34", family: 4 }]); + expect(await pruefeSmtpZiel("smtp.example.de")).toEqual({ ok: true, ip: "93.184.216.34" }); + }); + + it("lehnt ab, wenn die Aufloesung scheitert oder nichts liefert", async () => { + lookupMock.mockRejectedValueOnce(new Error("ENOTFOUND")); + expect(await pruefeSmtpZiel("gibt-es-nicht.example.de")).toEqual({ ok: false }); + lookupMock.mockResolvedValueOnce([]); + expect(await pruefeSmtpZiel("leer.example.de")).toEqual({ ok: false }); + }); +}); diff --git a/web/lib/firma/smtp-ziel.ts b/web/lib/firma/smtp-ziel.ts new file mode 100644 index 0000000..d09730d --- /dev/null +++ b/web/lib/firma/smtp-ziel.ts @@ -0,0 +1,65 @@ +import { lookup } from "node:dns/promises"; +import { BlockList, isIP } from "node:net"; + +// Nicht oeffentliche Ziele (SSRF-Schutz fuer den firmeneigenen SMTP-Server). +const GESPERRT = new BlockList(); +for (const [netz, laenge] of [ + ["0.0.0.0", 8], + ["10.0.0.0", 8], + ["100.64.0.0", 10], + ["127.0.0.0", 8], + ["169.254.0.0", 16], + ["172.16.0.0", 12], + ["192.0.0.0", 24], + ["192.168.0.0", 16], + ["198.18.0.0", 15], + ["224.0.0.0", 4], + ["240.0.0.0", 4], +] as const) { + GESPERRT.addSubnet(netz, laenge, "ipv4"); +} +GESPERRT.addAddress("::", "ipv6"); +GESPERRT.addAddress("::1", "ipv6"); +GESPERRT.addSubnet("fc00::", 7, "ipv6"); +GESPERRT.addSubnet("fe80::", 10, "ipv6"); +GESPERRT.addSubnet("ff00::", 8, "ipv6"); + +// ::ffff:a.b.c.d bzw. ::ffff:xxxx:yyyy auf die eingebettete IPv4-Adresse abbilden. +function normalisiere(ip: string): string { + const punkt = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(ip); + if (punkt) return punkt[1]; + const hex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(ip); + if (hex) { + const hoch = parseInt(hex[1], 16); + const tief = parseInt(hex[2], 16); + return `${hoch >> 8}.${hoch & 255}.${tief >> 8}.${tief & 255}`; + } + return ip; +} + +function istOeffentlich(ip: string): boolean { + const norm = normalisiere(ip); + const art = isIP(norm); + if (art === 0) return false; + return !GESPERRT.check(norm, art === 4 ? "ipv4" : "ipv6"); +} + +export type SmtpZielErgebnis = { ok: true; ip: string } | { ok: false }; + +// Loest den Host auf und liefert die zu verwendende (gepinnte) IP. Alle Adressen +// muessen oeffentlich sein; sonst ok:false (ohne Grund, kein Orakel fuer Admins). +export async function pruefeSmtpZiel(host: string): Promise { + if (isIP(host) !== 0) { + return istOeffentlich(host) ? { ok: true, ip: host } : { ok: false }; + } + let adressen: { address: string }[]; + try { + adressen = await lookup(host, { all: true }); + } catch { + return { ok: false }; + } + if (adressen.length === 0 || !adressen.every((a) => istOeffentlich(a.address))) { + return { ok: false }; + } + return { ok: true, ip: adressen[0].address }; +} diff --git a/web/lib/firma/smtp.test.ts b/web/lib/firma/smtp.test.ts index 5d214c1..cca537b 100644 --- a/web/lib/firma/smtp.test.ts +++ b/web/lib/firma/smtp.test.ts @@ -1,6 +1,16 @@ -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("node:dns/promises", () => ({ lookup: vi.fn() })); +import { lookup } from "node:dns/promises"; import type { SupabaseClient } from "@supabase/supabase-js"; -import { ermittleEmailConfig, firmenSmtpZuConfig, validateSmtpEingabe, type FirmenSmtpZeile } from "./smtp"; +import { + SmtpZielFehler, + ermittleEmailConfig, + firmenSmtpZuConfig, + validateSmtpEingabe, + type BestehendSmtp, + type FirmenSmtpZeile, +} from "./smtp"; import { verschluessele } from "./smtp-crypto"; const KEY = Buffer.alloc(32, 3).toString("base64"); @@ -15,9 +25,16 @@ const EINGABE = { absenderName: "Firma B", }; +const BESTEHEND: BestehendSmtp = { + host: "smtp.firma.de", + port: 587, + benutzer: "mailer", + passwort_verschluesselt: "v1:x:y:z", +}; + describe("validateSmtpEingabe", () => { it("uebernimmt gueltige Werte", () => { - expect(validateSmtpEingabe(EINGABE, false)).toEqual({ + expect(validateSmtpEingabe(EINGABE, null)).toEqual({ valid: true, werte: { host: "smtp.firma.de", @@ -25,35 +42,62 @@ describe("validateSmtpEingabe", () => { secure: false, benutzer: "mailer", neuesPasswort: "geheim", + passwortBehalten: false, absender_adresse: "noreply@firma.de", absender_name: "Firma B", }, }); }); it("Host ist Pflicht", () => { - expect(validateSmtpEingabe({ ...EINGABE, host: " " }, false)).toEqual({ valid: false, error: "Bitte den SMTP-Server angeben." }); + expect(validateSmtpEingabe({ ...EINGABE, host: " " }, null)).toEqual({ valid: false, error: "Bitte den SMTP-Server angeben." }); }); - it("Port muss 1 bis 65535 sein", () => { - expect(validateSmtpEingabe({ ...EINGABE, port: "70000" }, false)).toEqual({ + it.each(["70000", "22", "80", "abc", "587.5", ""])("Port %s ist nicht erlaubt", (port) => { + expect(validateSmtpEingabe({ ...EINGABE, port }, null)).toEqual({ valid: false, - error: "Bitte einen gültigen Port (1–65535) angeben.", + error: "Bitte einen gültigen Port (25, 465, 587 oder 2525) angeben.", }); }); + it.each(["25", "465", "587", "2525"])("Port %s ist erlaubt", (port) => { + expect(validateSmtpEingabe({ ...EINGABE, port }, null).valid).toBe(true); + }); it("Absenderadresse muss eine E-Mail sein", () => { - expect(validateSmtpEingabe({ ...EINGABE, absenderAdresse: "kein mail" }, false)).toEqual({ + expect(validateSmtpEingabe({ ...EINGABE, absenderAdresse: "kein mail" }, null)).toEqual({ valid: false, error: "Bitte eine gültige Absenderadresse angeben.", }); }); it("Benutzer ohne neues und ohne gespeichertes Passwort scheitert", () => { - expect(validateSmtpEingabe({ ...EINGABE, passwort: "" }, false)).toEqual({ valid: false, error: "Bitte ein Passwort eingeben." }); + expect(validateSmtpEingabe({ ...EINGABE, passwort: "" }, null)).toEqual({ valid: false, error: "Bitte ein Passwort eingeben." }); }); - it("leeres Passwort mit gespeichertem Passwort bleibt unveraendert (null)", () => { - const e = validateSmtpEingabe({ ...EINGABE, passwort: "" }, true); + it("gleiches Ziel + leeres Passwort: gespeichertes Passwort bleibt", () => { + const e = validateSmtpEingabe({ ...EINGABE, passwort: "" }, BESTEHEND); expect(e.valid && e.werte.neuesPasswort).toBeNull(); + expect(e.valid && e.werte.passwortBehalten).toBe(true); + }); + it("geaenderter Host + leeres Passwort scheitert", () => { + expect(validateSmtpEingabe({ ...EINGABE, host: "evil.example.de", passwort: "" }, BESTEHEND)).toEqual({ + valid: false, + error: "Bitte ein Passwort eingeben.", + }); + }); + it("geaenderter Port + leeres Passwort scheitert", () => { + expect(validateSmtpEingabe({ ...EINGABE, port: "465", passwort: "" }, BESTEHEND).valid).toBe(false); + }); + it("geaenderter Benutzer + leeres Passwort scheitert", () => { + expect(validateSmtpEingabe({ ...EINGABE, benutzer: "anderer", passwort: "" }, BESTEHEND).valid).toBe(false); + }); + it("geaenderter Host mit neuem Passwort ist gueltig", () => { + const e = validateSmtpEingabe({ ...EINGABE, host: "neu.example.de", passwort: "neu" }, BESTEHEND); + expect(e.valid && e.werte.neuesPasswort).toBe("neu"); + expect(e.valid && e.werte.passwortBehalten).toBe(false); + }); + it("bestehende Zeile ohne gespeichertes Passwort zaehlt nicht", () => { + expect( + validateSmtpEingabe({ ...EINGABE, passwort: "" }, { ...BESTEHEND, passwort_verschluesselt: null }).valid + ).toBe(false); }); it("ohne Benutzer wird das Passwort ignoriert", () => { - const e = validateSmtpEingabe({ ...EINGABE, benutzer: "", passwort: "x" }, false); + const e = validateSmtpEingabe({ ...EINGABE, benutzer: "", passwort: "x" }, null); expect(e.valid && e.werte.benutzer).toBeNull(); expect(e.valid && e.werte.neuesPasswort).toBeNull(); }); @@ -63,6 +107,8 @@ describe("firmenSmtpZuConfig / ermittleEmailConfig", () => { const alt = process.env.SMTP_VERSCHLUESSELUNG_KEY; beforeEach(() => { process.env.SMTP_VERSCHLUESSELUNG_KEY = KEY; + (lookup as unknown as ReturnType).mockReset(); + (lookup as unknown as ReturnType).mockResolvedValue([{ address: "93.184.216.34", family: 4 }]); }); afterEach(() => { if (alt === undefined) { @@ -100,9 +146,21 @@ describe("firmenSmtpZuConfig / ermittleEmailConfig", () => { }); }); - it("nimmt den Firmen-SMTP vor dem Fallback", async () => { + it("nimmt den Firmen-SMTP vor dem Fallback und pinnt die geprueft aufgeloeste IP", async () => { const fallback = () => ({ host: "global", port: 25, secure: false, from: "g@x.de", auth: null }); - expect((await ermittleEmailConfig(fakeAdmin(zeile()), "f2", fallback))?.host).toBe("smtp.firma.de"); + const cfg = await ermittleEmailConfig(fakeAdmin(zeile()), "f2", fallback); + expect(cfg?.host).toBe("93.184.216.34"); + expect(cfg?.servername).toBe("smtp.firma.de"); + }); + + it("wirft SmtpZielFehler, wenn der Firmen-SMTP privat aufloest", async () => { + (lookup as unknown as ReturnType).mockResolvedValue([{ address: "10.0.0.5", family: 4 }]); + await expect(ermittleEmailConfig(fakeAdmin(zeile()), "f2", () => null)).rejects.toBeInstanceOf(SmtpZielFehler); + }); + + it("prueft den globalen Fallback nicht", async () => { + const fallback = () => ({ host: "127.0.0.1", port: 1025, secure: false, from: "g@x.de", auth: null }); + expect((await ermittleEmailConfig(fakeAdmin(null), "f2", fallback))?.host).toBe("127.0.0.1"); }); it("faellt ohne Firmen-SMTP auf den globalen zurueck", async () => { diff --git a/web/lib/firma/smtp.ts b/web/lib/firma/smtp.ts index 5d9809d..b57c3b4 100644 --- a/web/lib/firma/smtp.ts +++ b/web/lib/firma/smtp.ts @@ -1,6 +1,7 @@ import type { SupabaseClient } from "@supabase/supabase-js"; import { getEmailConfig, type EmailConfig } from "@/lib/notifications/email-config"; import { entschluessele } from "./smtp-crypto"; +import { pruefeSmtpZiel } from "./smtp-ziel"; export type FirmenSmtpZeile = { firma_id: string; @@ -21,10 +22,29 @@ export type SmtpWerte = { secure: boolean; benutzer: string | null; neuesPasswort: string | null; + // true: kein neues Passwort, das gespeicherte bleibt (Ziel und Benutzer unveraendert). + passwortBehalten: boolean; absender_adresse: string; absender_name: string | null; }; +export type BestehendSmtp = { + host: string; + port: number; + benutzer: string | null; + passwort_verschluesselt: string | null; +}; + +export const ERLAUBTE_SMTP_PORTS = [25, 465, 587, 2525]; +export const SMTP_ZIEL_NICHT_ERLAUBT = "SMTP-Ziel nicht erlaubt"; + +export class SmtpZielFehler extends Error { + constructor() { + super(SMTP_ZIEL_NICHT_ERLAUBT); + this.name = "SmtpZielFehler"; + } +} + type Eingabe = { host: unknown; port: unknown; @@ -41,14 +61,14 @@ function text(wert: unknown): string { export function validateSmtpEingabe( input: Eingabe, - passwortGespeichert: boolean + bestehend: BestehendSmtp | null ): { valid: true; werte: SmtpWerte } | { valid: false; error: string } { const host = text(input.host); if (!host) return { valid: false, error: "Bitte den SMTP-Server angeben." }; const port = Number(text(input.port)); - if (!Number.isInteger(port) || port < 1 || port > 65535) { - return { valid: false, error: "Bitte einen gültigen Port (1–65535) angeben." }; + if (!ERLAUBTE_SMTP_PORTS.includes(port)) { + return { valid: false, error: "Bitte einen gültigen Port (25, 465, 587 oder 2525) angeben." }; } const absender = text(input.absenderAdresse); @@ -59,7 +79,12 @@ export function validateSmtpEingabe( const benutzer = text(input.benutzer) || null; // Passwort nicht trimmen: Leerzeichen koennen Teil des Passworts sein. const passwort = typeof input.passwort === "string" && input.passwort !== "" ? input.passwort : null; - if (benutzer && !passwort && !passwortGespeichert) { + // Das gespeicherte Passwort gilt nur fuer genau dieses Ziel und diesen Benutzer; + // sonst koennte es an einen anderen Server geschickt werden. + const zielGleich = + bestehend !== null && bestehend.host === host && bestehend.port === port && bestehend.benutzer === benutzer; + const passwortBehalten = Boolean(benutzer && !passwort && zielGleich && bestehend?.passwort_verschluesselt); + if (benutzer && !passwort && !passwortBehalten) { return { valid: false, error: "Bitte ein Passwort eingeben." }; } @@ -71,6 +96,7 @@ export function validateSmtpEingabe( secure: input.secure, benutzer, neuesPasswort: benutzer ? passwort : null, + passwortBehalten, absender_adresse: absender, absender_name: text(input.absenderName) || null, }, @@ -100,6 +126,14 @@ export function firmenSmtpZuConfig(zeile: FirmenSmtpZeile): EmailConfig { }; } +// Prueft das Ziel und pinnt die Verbindung auf die geprueft aufgeloeste IP +// (verhindert DNS-Rebinding zwischen Pruefung und Verbindungsaufbau). +export async function pinneSmtpZiel(cfg: EmailConfig): Promise { + const ziel = await pruefeSmtpZiel(cfg.host); + if (!ziel.ok) throw new SmtpZielFehler(); + return { ...cfg, host: ziel.ip, servername: cfg.host }; +} + // Firmen-SMTP vor globalem Fallback (SMTP_* aus der .env); null = keiner vorhanden. export async function ermittleEmailConfig( admin: SupabaseClient, @@ -107,5 +141,6 @@ export async function ermittleEmailConfig( fallback: () => EmailConfig | null = getEmailConfig ): Promise { const zeile = await ladeFirmenSmtp(admin, firmaId); - return zeile ? firmenSmtpZuConfig(zeile) : fallback(); + // Nur der Firmen-SMTP wird geprueft; der globale Fallback kommt vom Betreiber (.env). + return zeile ? pinneSmtpZiel(firmenSmtpZuConfig(zeile)) : fallback(); } diff --git a/web/lib/notifications/email-config.ts b/web/lib/notifications/email-config.ts index 8a97226..450aa82 100644 --- a/web/lib/notifications/email-config.ts +++ b/web/lib/notifications/email-config.ts @@ -4,6 +4,9 @@ export type EmailConfig = { secure: boolean; from: string; auth: { user: string; pass: string } | null; + // Gesetzt, wenn host auf eine geprueft aufgeloeste IP gepinnt wurde: TLS prueft + // das Zertifikat dann gegen den urspruenglichen Namen. + servername?: string; }; // Liest die SMTP-Konfiguration aus den Umgebungsvariablen. null = kein globaler SMTP; diff --git a/web/lib/notifications/email.test.ts b/web/lib/notifications/email.test.ts index 66ade3f..3065f58 100644 --- a/web/lib/notifications/email.test.ts +++ b/web/lib/notifications/email.test.ts @@ -131,6 +131,21 @@ describe("sendeProtokollMail", () => { expect(createTransport.mock.calls[0][0]).toMatchObject({ requireTLS: true, auth: { user: "u", pass: "p" } }); }); + it("pinnt auf die IP und prueft das Zertifikat gegen den urspruenglichen Namen", async () => { + sendMail.mockResolvedValue({ messageId: "m" }); + await sendeProtokollMail({ ...cfg, host: "93.184.216.34", servername: "smtp.firma.de" }, mail); + expect(createTransport.mock.calls[0][0]).toMatchObject({ + host: "93.184.216.34", + tls: { servername: "smtp.firma.de" }, + }); + }); + + it("ohne servername keine tls-Option", async () => { + sendMail.mockResolvedValue({ messageId: "m" }); + await sendeProtokollMail(cfg, mail); + expect((createTransport.mock.calls[0][0] as { tls?: unknown }).tls).toBeUndefined(); + }); + it("ohne Auth: kein auth, kein requireTLS", async () => { sendMail.mockResolvedValue({ messageId: "m" }); await sendeProtokollMail({ ...cfg, auth: null }, mail); diff --git a/web/lib/notifications/email.ts b/web/lib/notifications/email.ts index ac036cb..508f7b5 100644 --- a/web/lib/notifications/email.ts +++ b/web/lib/notifications/email.ts @@ -60,6 +60,7 @@ export async function sendeProtokollMail(cfg: EmailConfig, mail: ProtokollMail): port: cfg.port, secure: cfg.secure, auth: cfg.auth ?? undefined, + tls: cfg.servername ? { servername: cfg.servername } : undefined, // Mit Zugangsdaten niemals im Klartext senden: STARTTLS erzwingen, sonst // koennte ein Angreifer STARTTLS entfernen und die Credentials mitlesen. requireTLS: cfg.auth !== null && !cfg.secure, diff --git a/web/lib/notifications/handler.test.ts b/web/lib/notifications/handler.test.ts index d80c5af..9038db0 100644 --- a/web/lib/notifications/handler.test.ts +++ b/web/lib/notifications/handler.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from "vitest"; import type { SupabaseClient } from "@supabase/supabase-js"; import { protokollMailHandler, whatsappHandler } from "./handler"; +import { SmtpZielFehler } from "@/lib/firma/smtp"; import type { OutboxRow } from "./dispatch"; import type { EmailConfig } from "./email-config"; import type { WhatsAppConfig } from "./config"; @@ -144,6 +145,20 @@ describe("whatsappHandler (Empfaenger pro Firma)", () => { }); }); +describe("protokollMailHandler mit geblocktem SMTP-Ziel", () => { + it("meldet nur den generischen Text und erzeugt kein PDF", async () => { + const erzeugePdf = vi.fn(); + const res = await protokollMailHandler({} as never, { + erzeugePdf, + ladeConfig: async () => { + throw new SmtpZielFehler(); + }, + })(row()); + expect(res).toEqual({ ok: false, fehler: "SMTP-Ziel nicht erlaubt" }); + expect(erzeugePdf).not.toHaveBeenCalled(); + }); +}); + describe("protokollMailHandler ohne SMTP", () => { it("meldet Kein SMTP konfiguriert (Retry, nicht endgueltig) und erzeugt kein PDF", async () => { const erzeugePdf = vi.fn(); diff --git a/web/lib/notifications/handler.ts b/web/lib/notifications/handler.ts index 9540348..ec22728 100644 --- a/web/lib/notifications/handler.ts +++ b/web/lib/notifications/handler.ts @@ -1,6 +1,6 @@ import type { SupabaseClient } from "@supabase/supabase-js"; import { erzeugeProtokollPdf } from "@/lib/auftraege/protokoll-pdf"; -import { ermittleEmailConfig } from "@/lib/firma/smtp"; +import { ermittleEmailConfig, SMTP_ZIEL_NICHT_ERLAUBT, SmtpZielFehler } from "@/lib/firma/smtp"; import type { WhatsAppConfig } from "./config"; import type { Handler } from "./dispatch"; import type { EmailConfig } from "./email-config"; @@ -49,6 +49,10 @@ export function protokollMailHandler( try { cfg = await ladeConfig(admin, row.firma_id); } catch (fehler) { + // Admins lesen notification_outbox: bei geblocktem Ziel kein Rohtext (kein Orakel). + if (fehler instanceof SmtpZielFehler) { + return { ok: false, fehler: SMTP_ZIEL_NICHT_ERLAUBT }; + } return { ok: false, fehler: `SMTP-Konfiguration fehlerhaft: ${fehler instanceof Error ? fehler.message : String(fehler)}`, From ba26d50e75f493e5400fe885095ac76b5d602c6f Mon Sep 17 00:00:00 2001 From: Jonny Date: Mon, 12 Oct 2026 14:34:47 +0200 Subject: [PATCH 16/16] fix: Logo-Pfad per Regex absichern, pgTAP fuer FIN pro Firma Co-Authored-By: Claude Sonnet 5.5 --- .../20261012090400_firmen_logo_pfad_regex.sql | 8 ++++ supabase/tests/firmen_logo_pfad_test.sql | 16 ++++++- supabase/tests/mandanten_struktur_test.sql | 44 ++++++++++++++++++- 3 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 supabase/migrations/20261012090400_firmen_logo_pfad_regex.sql diff --git a/supabase/migrations/20261012090400_firmen_logo_pfad_regex.sql b/supabase/migrations/20261012090400_firmen_logo_pfad_regex.sql new file mode 100644 index 0000000..590fb90 --- /dev/null +++ b/supabase/migrations/20261012090400_firmen_logo_pfad_regex.sql @@ -0,0 +1,8 @@ +-- Der LIKE-Check aus 20261012090300 liess "/..//logo-1.png" zu. +-- Der Pfad muss exakt dem Muster aus logoPfad() (web/lib/firma/logo.ts) entsprechen. +alter table public.firmen + drop constraint firmen_logo_pfad_eigener_ordner; + +alter table public.firmen + add constraint firmen_logo_pfad_eigener_ordner + check (logo_pfad is null or logo_pfad ~ ('^' || id::text || '/logo-[0-9]+\.(png|jpg|svg)$')); diff --git a/supabase/tests/firmen_logo_pfad_test.sql b/supabase/tests/firmen_logo_pfad_test.sql index 4cbf418..d98ac91 100644 --- a/supabase/tests/firmen_logo_pfad_test.sql +++ b/supabase/tests/firmen_logo_pfad_test.sql @@ -1,5 +1,5 @@ begin; -select plan(2); +select plan(4); insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f002', 'Firma B'); @@ -10,6 +10,20 @@ select throws_ok( 'Logo-Pfad im Ordner einer fremden Firma wird abgelehnt' ); +select throws_ok( + $$ update public.firmen set logo_pfad = '00000000-0000-0000-0000-00000000f002/../00000000-0000-0000-0000-00000000f001/logo-1.png' + where id = '00000000-0000-0000-0000-00000000f002' $$, + '23514', null, + 'Pfad mit ../ in den Ordner einer fremden Firma wird abgelehnt' +); + +select throws_ok( + $$ update public.firmen set logo_pfad = '00000000-0000-0000-0000-00000000f002/x.png' + where id = '00000000-0000-0000-0000-00000000f002' $$, + '23514', null, + 'Pfad im eigenen Ordner, aber nicht im Format logo-., wird abgelehnt' +); + select lives_ok( $$ update public.firmen set logo_pfad = '00000000-0000-0000-0000-00000000f002/logo-1.png' where id = '00000000-0000-0000-0000-00000000f002' $$, diff --git a/supabase/tests/mandanten_struktur_test.sql b/supabase/tests/mandanten_struktur_test.sql index 96fb37a..c9b03a1 100644 --- a/supabase/tests/mandanten_struktur_test.sql +++ b/supabase/tests/mandanten_struktur_test.sql @@ -1,5 +1,5 @@ begin; -select plan(16); +select plan(20); -- Firma B neben der Bestandsfirma Widmann (f001) insert into public.firmen (id, name) values ('00000000-0000-0000-0000-00000000f002', 'Firma B'); @@ -158,6 +158,48 @@ select is( 'Firma ohne WhatsApp-Empfaenger bekommt keine Outbox-Zeile' ); +-- 14a) FIN ist pro Firma eindeutig: gleiche FIN in f001 und f002 ist erlaubt +update public.fahrzeuge set fin = 'WVWZZZ1KZAW000002' where id = 'a0000000-0000-0000-0000-0000000000d1'; +select lives_ok( + $$ update public.fahrzeuge set fin = 'WVWZZZ1KZAW000002' where id = 'b0000000-0000-0000-0000-0000000000d1' $$, + 'Gleiche FIN in einer anderen Firma ist erlaubt' +); + +-- 14b) doppelte FIN in derselben Firma nicht +select throws_ok( + $$ insert into public.fahrzeuge (kennzeichen, fin, firma_id) + values ('MT-AB 9', 'WVWZZZ1KZAW000002', '00000000-0000-0000-0000-00000000f001') $$, + '23505', null, + 'Doppelte FIN in derselben Firma scheitert' +); + +-- 14c) fin_bei_fahrtbeginn sucht nur in der eigenen Firma: eine FIN, die nur in +-- Firma B existiert, wird in Firma A nachgetragen und nicht als abweichend gemeldet. +insert into public.fahrzeuge (id, kennzeichen, fin, firma_id) values + ('b0000000-0000-0000-0000-0000000000d2', 'MT-BB 2', 'WDB9066331S555555', '00000000-0000-0000-0000-00000000f002'); +insert into public.fahrzeuge (id, kennzeichen, firma_id) values + ('a0000000-0000-0000-0000-0000000000d2', 'MT-AB 2', '00000000-0000-0000-0000-00000000f001'); +insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, zugewiesen_an, status, firma_id) values + ('a0000000-0000-0000-0000-0000000000e2', 'a0000000-0000-0000-0000-0000000000c1', 'a0000000-0000-0000-0000-0000000000c1', + 'a0000000-0000-0000-0000-0000000000d2', 'a0000000-0000-0000-0000-0000000000a1', + 'a0000000-0000-0000-0000-0000000000a3', 'zugewiesen', '00000000-0000-0000-0000-00000000f001'); + +set local role authenticated; +set local request.jwt.claims to '{"sub": "a0000000-0000-0000-0000-0000000000a3", "role": "authenticated"}'; +select is( + public.fin_bei_fahrtbeginn('a0000000-0000-0000-0000-0000000000e2', 'WDB9066331S555555'), + 'nachgetragen'::public.app_fin_abgleich, + 'FIN-Abgleich ignoriert FINs fremder Firmen (nachgetragen statt abweichend)' +); +reset role; +reset request.jwt.claims; + +select is( + (select fin from public.fahrzeuge where id = 'a0000000-0000-0000-0000-0000000000d2'), + 'WDB9066331S555555', + 'FIN steht am Fahrzeug der eigenen Firma' +); + -- 15) Mit Nutzer-Session kann aktiv nicht geaendert werden. Nur Claims setzen, -- Rolle bleibt postgres: in Task 1 gibt es noch keine Policy auf firmen, der -- Trigger soll aber trotzdem greifen.