Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,345 @@
-- Billing storage capacity enforcement.
--
-- Storage is one tenant-wide pool: base-plan storage + extra-seat storage +
-- active recurring storage add-ons. Both the core app and customer portal use
-- advisory-lock namespace 26026 before creating an upload reservation.
--
-- Inverse SQL (manual coordinated rollback only):
-- BEGIN;
-- Recreate public.hivegrid_portal_reserve_upload(...) from
-- 20260725223700_admin_sales_portal_rls/migration.sql, then:
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_tenant_storage_capacity_bytes(text);
-- REVOKE SELECT ON public."TenantSubscriptionProduct" FROM hivegrid_rls_definer;
-- COMMIT;
BEGIN;
GRANT CREATE ON SCHEMA public TO hivegrid_rls_definer;
GRANT SELECT ON public."TenantSubscriptionProduct" TO hivegrid_rls_definer;
SET LOCAL ROLE hivegrid_rls_definer;
CREATE OR REPLACE FUNCTION public.hivegrid_portal_tenant_storage_capacity_bytes(p_tenant_id text)
RETURNS bigint
LANGUAGE plpgsql
STABLE
SECURITY DEFINER
SET search_path = pg_catalog, public
SET row_security = off
AS $function$
DECLARE
subscription_record record;
base_product_record record;
normalized_plan_code text;
office_seats integer;
field_seats integer;
included_office_seats integer;
included_field_seats integer;
included_storage_gb bigint;
storage_add_on_gb bigint;
unknown_storage_add_on_count integer;
BEGIN
IF session_user NOT IN ('hivegrid_app', 'hivegrid_worker', 'hivegrid_portal')
OR NULLIF(btrim(p_tenant_id), '') IS NULL THEN
RETURN 0;
END IF;
SELECT subscription.* INTO subscription_record
FROM public."TenantSubscription" AS subscription
WHERE subscription."tenantId" = p_tenant_id;
IF NOT FOUND
OR subscription_record."cancelledAt" IS NOT NULL
OR subscription_record."frozenAt" IS NOT NULL
OR subscription_record."status" NOT IN ('active', 'trial')
OR (
subscription_record."status" = 'trial'
AND subscription_record."trialEndsAt" IS NOT NULL
AND subscription_record."trialEndsAt" <= CURRENT_TIMESTAMP
) THEN
RETURN 0;
END IF;
SELECT
tenant_product."planCode",
tenant_product."seatQuantity",
tenant_product."officeSeatQuantity",
tenant_product."fieldSeatQuantity",
tenant_product."storageAddOnCodes",
tenant_product."quantity",
product."code",
product."lagoPlanCode"
INTO base_product_record
FROM public."TenantSubscriptionProduct" AS tenant_product
JOIN public."SubscriptionProduct" AS product
ON product."id" = tenant_product."subscriptionProductId"
WHERE tenant_product."tenantSubscriptionId" = subscription_record."id"
AND product."kind" = 'base_plan'
AND tenant_product."cancelledAt" IS NULL
AND (tenant_product."currentPeriodStart" IS NULL OR tenant_product."currentPeriodStart" <= CURRENT_TIMESTAMP)
AND (tenant_product."endsAt" IS NULL OR tenant_product."endsAt" > CURRENT_TIMESTAMP)
ORDER BY
(
COALESCE(tenant_product."planCode", product."code", product."lagoPlanCode")
= subscription_record."planCode"
) DESC,
tenant_product."createdAt" DESC
LIMIT 1;
IF NOT FOUND THEN
RETURN 0;
END IF;
normalized_plan_code := COALESCE(
base_product_record."planCode",
base_product_record."code",
base_product_record."lagoPlanCode",
subscription_record."planCode"
);
IF normalized_plan_code = 'starter' THEN
included_office_seats := 2;
included_field_seats := 5;
included_storage_gb := 100;
ELSIF normalized_plan_code = 'pro' THEN
included_office_seats := 5;
included_field_seats := 15;
included_storage_gb := 250;
ELSIF normalized_plan_code = 'business' THEN
included_office_seats := 10;
included_field_seats := 30;
included_storage_gb := 500;
ELSE
RETURN 0;
END IF;
office_seats := COALESCE(base_product_record."officeSeatQuantity", subscription_record."officeSeatQuantity", 0);
field_seats := COALESCE(base_product_record."fieldSeatQuantity", subscription_record."fieldSeatQuantity", 0);
IF office_seats = 0 AND field_seats = 0 THEN
office_seats := GREATEST(
1,
COALESCE(base_product_record."seatQuantity", base_product_record."quantity", subscription_record."seatQuantity", 1)
);
END IF;
IF office_seats < 0 OR field_seats < 0 OR office_seats > 10000 OR field_seats > 10000 THEN
RETURN 0;
END IF;
WITH storage_codes AS (
SELECT DISTINCT code
FROM unnest(
COALESCE(subscription_record."storageAddOnCodes", ARRAY[]::text[])
|| COALESCE(base_product_record."storageAddOnCodes", ARRAY[]::text[])
|| COALESCE(ARRAY(
SELECT product."code"
FROM public."TenantSubscriptionProduct" AS tenant_product
JOIN public."SubscriptionProduct" AS product
ON product."id" = tenant_product."subscriptionProductId"
WHERE tenant_product."tenantSubscriptionId" = subscription_record."id"
AND product."kind" = 'recurring_add_on'
AND product."code" LIKE 'storage\_%' ESCAPE '\'
AND tenant_product."cancelledAt" IS NULL
AND (tenant_product."currentPeriodStart" IS NULL OR tenant_product."currentPeriodStart" <= CURRENT_TIMESTAMP)
AND (tenant_product."endsAt" IS NULL OR tenant_product."endsAt" > CURRENT_TIMESTAMP)
), ARRAY[]::text[])
) AS code
)
SELECT
COALESCE(sum(CASE code
WHEN 'storage_100gb' THEN 100
WHEN 'storage_500gb' THEN 500
WHEN 'storage_1tb' THEN 1000
WHEN 'storage_5tb' THEN 5000
ELSE 0
END), 0),
count(*) FILTER (WHERE code NOT IN ('storage_100gb', 'storage_500gb', 'storage_1tb', 'storage_5tb'))
INTO storage_add_on_gb, unknown_storage_add_on_count
FROM storage_codes;
IF unknown_storage_add_on_count > 0 THEN
RETURN 0;
END IF;
RETURN (
included_storage_gb
+ GREATEST(0, office_seats - included_office_seats) * 20
+ GREATEST(0, field_seats - included_field_seats) * 10
+ storage_add_on_gb
) * 1073741824;
END
$function$;
ALTER FUNCTION public.hivegrid_portal_tenant_storage_capacity_bytes(text) OWNER TO hivegrid_rls_definer;
REVOKE ALL ON FUNCTION public.hivegrid_portal_tenant_storage_capacity_bytes(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_portal, hivegrid_authentik_jit;
CREATE OR REPLACE FUNCTION public.hivegrid_portal_reserve_upload(
p_upload_id text,
p_file_upload_id text,
p_file_id text,
p_file_entity_link_id text,
p_project_id text,
p_filename text,
p_mime_type text,
p_size_bytes bigint,
p_checksum_sha256 text,
p_idempotency_key text,
p_quota_limit_bytes bigint
)
RETURNS TABLE (
"uploadId" text,
"fileUploadId" text,
"fileId" text,
"fileEntityLinkId" text,
"projectLeaderUserId" text,
"alreadyCompleted" boolean,
"effectsCompleted" boolean
)
LANGUAGE plpgsql
VOLATILE
SECURITY DEFINER
SET search_path = pg_catalog, public
SET row_security = off
AS $function$
DECLARE
access_record record;
normalized_mime text := lower(btrim(p_mime_type));
normalized_key text := NULLIF(btrim(p_idempotency_key), '');
key_prefix text;
configured_max_files integer;
configured_max_bytes integer;
used_and_reserved_bytes bigint;
commercial_quota_limit_bytes bigint;
existing_record record;
BEGIN
SELECT * INTO access_record
FROM public.hivegrid_portal_require_project_access(p_project_id, true, true, false);
IF p_upload_id !~ '^[A-Za-z0-9_-]{1,191}$'
OR p_file_upload_id !~ '^[A-Za-z0-9_-]{1,191}$'
OR p_file_id !~ '^[A-Za-z0-9_-]{1,191}$'
OR p_file_entity_link_id !~ '^[A-Za-z0-9_-]{1,191}$'
OR normalized_key IS NULL
OR normalized_key !~ '^[A-Za-z0-9._:-]{1,128}$'
OR NULLIF(btrim(p_filename), '') IS NULL
OR length(p_filename) > 255
OR p_filename ~ '[[:cntrl:]]'
OR p_filename ~ '\.\.[/\\]'
OR p_size_bytes < 1
OR p_size_bytes > 104857600
OR p_checksum_sha256 !~ '^[0-9a-f]{64}$'
OR p_quota_limit_bytes < p_size_bytes
OR p_quota_limit_bytes > 1125899906842624 THEN
RAISE EXCEPTION 'Invalid portal upload reservation' USING ERRCODE = '22023';
END IF;
IF normalized_mime NOT IN (
'image/png', 'image/jpeg', 'image/webp', 'image/heic', 'image/heif', 'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'audio/mpeg', 'audio/wav', 'audio/x-wav', 'audio/ogg', 'audio/mp4', 'audio/aac', 'audio/flac'
) THEN
RAISE EXCEPTION 'Unsupported portal upload type' USING ERRCODE = '22023';
END IF;
SELECT configuration."uploadMaxFiles", configuration."uploadMaxFileSizeBytes"
INTO configured_max_files, configured_max_bytes
FROM public."PortalConfiguration" AS configuration
WHERE configuration."tenantId" = access_record."tenantId"
AND configuration."portalId" = access_record."portalId";
IF configured_max_files < 1 OR configured_max_files > 10
OR configured_max_bytes < 1 OR configured_max_bytes > 104857600
OR p_size_bytes > configured_max_bytes THEN
RAISE EXCEPTION 'Portal upload exceeds configured limits' USING ERRCODE = '22023';
END IF;
PERFORM pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended(access_record."tenantId", 26026));
commercial_quota_limit_bytes := public.hivegrid_portal_tenant_storage_capacity_bytes(access_record."tenantId");
IF commercial_quota_limit_bytes < p_size_bytes THEN
RAISE EXCEPTION 'Portal upload quota exceeded' USING ERRCODE = '22023';
END IF;
SELECT upload."id", upload."fileUploadId", upload."fileId", upload."fileEntityLinkId", upload."projectId", upload."portalUserId",
upload."quotaBytes", upload."requestChecksumSha256", upload."status", upload."completedAt", upload."effectsCompletedAt",
file_upload."createdByUserId", file_upload."createdByPortalUserId",
file_upload."originalFilename", file_upload."mimeType", file_upload."totalSizeBytes"
INTO existing_record
FROM public."PortalUpload" AS upload
LEFT JOIN public."FileUpload" AS file_upload
ON file_upload."id" = upload."fileUploadId"
AND file_upload."tenantId" = upload."tenantId"
WHERE upload."tenantId" = access_record."tenantId"
AND upload."idempotencyKey" = normalized_key;
IF FOUND THEN
IF existing_record."portalUserId" <> access_record."portalUserId"
OR existing_record."projectId" <> p_project_id
OR existing_record."quotaBytes" <> p_size_bytes
OR existing_record."requestChecksumSha256" IS DISTINCT FROM p_checksum_sha256
OR existing_record."createdByUserId" IS NOT NULL
OR existing_record."createdByPortalUserId" <> access_record."portalUserId"
OR existing_record."originalFilename" <> btrim(p_filename)
OR lower(existing_record."mimeType") <> normalized_mime
OR existing_record."totalSizeBytes" <> p_size_bytes
OR existing_record."fileUploadId" IS NULL OR existing_record."fileId" IS NULL OR existing_record."fileEntityLinkId" IS NULL
OR existing_record."status" NOT IN ('reserved', 'uploading', 'scanning', 'clean')
OR (existing_record."status" = 'clean' AND existing_record."completedAt" IS NULL) THEN
RAISE EXCEPTION 'Portal upload idempotency collision' USING ERRCODE = '23505';
END IF;
RETURN QUERY SELECT existing_record."id", existing_record."fileUploadId", existing_record."fileId",
existing_record."fileEntityLinkId", access_record."projectLeaderUserId", existing_record."status" = 'clean',
existing_record."effectsCompletedAt" IS NOT NULL;
RETURN;
END IF;
key_prefix := regexp_replace(normalized_key, ':[0-9]+$', '');
IF normalized_key ~ ':[0-9]+$'
AND split_part(normalized_key, ':', array_length(string_to_array(normalized_key, ':'), 1))::integer >= configured_max_files THEN
RAISE EXCEPTION 'Portal upload file-count limit exceeded' USING ERRCODE = '22023';
END IF;
IF (
SELECT count(*)
FROM public."PortalUpload" AS upload
WHERE upload."tenantId" = access_record."tenantId"
AND upload."portalUserId" = access_record."portalUserId"
AND regexp_replace(upload."idempotencyKey", ':[0-9]+$', '') = key_prefix
) >= configured_max_files THEN
RAISE EXCEPTION 'Portal upload file-count limit exceeded' USING ERRCODE = '22023';
END IF;
SELECT
COALESCE((
SELECT sum(file."sizeBytes"::bigint)
FROM public."File" AS file
WHERE file."tenantId" = access_record."tenantId"
), 0)
+ COALESCE((
SELECT sum(file_upload."totalSizeBytes"::bigint)
FROM public."FileUpload" AS file_upload
WHERE file_upload."tenantId" = access_record."tenantId"
AND file_upload."status" = 'in_progress'
AND file_upload."expiresAt" > CURRENT_TIMESTAMP
), 0)
INTO used_and_reserved_bytes;
IF used_and_reserved_bytes + p_size_bytes > LEAST(p_quota_limit_bytes, commercial_quota_limit_bytes) THEN
RAISE EXCEPTION 'Portal upload quota exceeded' USING ERRCODE = '22023';
END IF;
INSERT INTO public."FileUpload" (
"id", "createdAt", "updatedAt", "tenantId", "createdByUserId", "createdByPortalUserId",
"originalFilename", "totalSizeBytes", "mimeType", "totalChunks", "receivedChunks", "status", "targetFileId", "expiresAt"
) VALUES (
p_file_upload_id, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, access_record."tenantId", NULL, access_record."portalUserId",
btrim(p_filename), p_size_bytes::integer, normalized_mime, 1, 0, 'in_progress', p_file_id, CURRENT_TIMESTAMP + INTERVAL '24 hours'
);
INSERT INTO public."PortalUpload" (
"id", "createdAt", "updatedAt", "tenantId", "portalId", "portalUserId", "projectId", "fileUploadId", "fileId",
"fileEntityLinkId", "category", "status", "quotaBytes", "requestChecksumSha256", "idempotencyKey"
) VALUES (
p_upload_id, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, access_record."tenantId", access_record."portalId", access_record."portalUserId",
p_project_id, p_file_upload_id, p_file_id, p_file_entity_link_id, 'attachment', 'reserved', p_size_bytes::integer, p_checksum_sha256, normalized_key
);
RETURN QUERY SELECT p_upload_id, p_file_upload_id, p_file_id, p_file_entity_link_id, access_record."projectLeaderUserId", false, false;
END
$function$;
ALTER FUNCTION public.hivegrid_portal_reserve_upload(text,text,text,text,text,text,text,bigint,text,text,bigint) OWNER TO hivegrid_rls_definer;
REVOKE ALL ON FUNCTION public.hivegrid_portal_reserve_upload(text,text,text,text,text,text,text,bigint,text,text,bigint) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_reserve_upload(text,text,text,text,text,text,text,bigint,text,text,bigint) TO hivegrid_portal;
RESET ROLE;
REVOKE CREATE ON SCHEMA public FROM hivegrid_rls_definer;
COMMIT;