@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / ebc2a29
Fork 0

سامانه صدور فاکتور و حسابداری

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 4, 01:45 UTC

fix(finance): validate journal dimension type value integrity

davoodmehraban89 committed Nov 15, 2026 at 13:08 UTC ebc2a295e19457a6790b87038d3ebe83d099fcc1
5 files changed +142 -2
PROJECT_STATE.md
+6 -1
@@ -325,4 +325,9 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
325 ### 2026-11-15 — Independent SQL review: guard audit tenant scope
326 - Review found `private.finora_phase1a_log_guard(uuid,text,text,text)` is SECURITY DEFINER and EXECUTE-granted to authenticated, but previously trusted caller-supplied `p_org` without checking active membership. A tenant A member could forge guard_violation audit entries in tenant B. This is an audit-integrity / cross-tenant contamination risk, not direct financial-row write access.
327 - Added candidate migration `20261115130000_wp1_guard_audit_tenant_scope.sql`, conservative DOWN, and `wp1_guard_audit_tenant_scope.sql` regression. It requires active membership for `auth.uid()` before audit insertion and bounds input. Trigger logging for same-tenant operations remains permitted.
328 -- Patch has not yet passed CI. It is candidate-only; do not merge or deploy until the full exact-head WP1 workflow passes and SQL/ACL review is repeated.
\ No newline at end of file
328 +- Patch has not yet passed CI. It is candidate-only; do not merge or deploy until the full exact-head WP1 workflow passes and SQL/ACL review is repeated.
329 +
330 +### 2026-11-15 — Independent SQL review: dimension type/value consistency
331 +- Review found `private.finora_phase1a_validate_saved` checked that dimension type and value existed in the same company, but did not require `dimensionValues.dimensionTypeId` to equal the linked dimension type, nor require both entities active. A balanced journal could therefore carry a semantically invalid analytic dimension pair.
332 +- Added candidate migration `20261115140000_wp1_dimension_value_type_scope.sql`, conservative DOWN, and `wp1_dimension_value_type_scope.sql` regression. It rejects mismatched type/value, inactive dimensions, and wrong-company links; test verifies no partial draft survives and a valid pair still posts.
333 +- Account-specific required/optional dimension rules remain open. This patch has not passed CI and is not Production-authorized.
\ No newline at end of file
docs/audits/WP1_DB_ONLY_INTEGRATION_CANDIDATE_2026-11-15_FA.md
+9 -1
@@ -54,4 +54,12 @@ The read-through of the staged SQL found that `private.finora_phase1a_log_guard(
54
55 An additive candidate migration `20261115130000_wp1_guard_audit_tenant_scope.sql` now checks that `auth.uid()` is an active member of the supplied organization before writing and bounds audit input. A synthetic SQL regression `wp1_guard_audit_tenant_scope.sql` verifies that cross-tenant injection is denied while same-tenant trigger logging remains available. A conservative DOWN restores the prior logger body; it does not remove audit history.
56
57 -This is a code-review-driven patch, not yet validated. It is included in the disposable WP1 suite and must pass the next exact-head CI run. It does not change the audit/shadow default, enable enforcement, or authorize Production.
\ No newline at end of file
57 +This is a code-review-driven patch, not yet validated. It is included in the disposable WP1 suite and must pass the next exact-head CI run. It does not change the audit/shadow default, enable enforcement, or authorize Production.
58 +
59 +## Independent SQL review finding — dimension type/value integrity
60 +
61 +The current saved-journal validator verified that a dimension type and dimension value both belonged to the company, but did not verify that the selected value actually belonged to the selected type or that either entity was active. This allowed semantically invalid analytic tags to be attached to an otherwise balanced voucher.
62 +
63 +Candidate correction `20261115140000_wp1_dimension_value_type_scope.sql` now requires matching `dimensionValues.dimensionTypeId`, company scope, and active type/value state before accepting the journal graph. The regression `wp1_dimension_value_type_scope.sql` proves mismatched type/value and inactive values are rejected without leaving a partial draft, while a valid pair still posts. The DOWN restores the prior validator.
64 +
65 +This patch is candidate-only and awaits the full disposable CI run. Account-specific required/optional dimension rules remain unimplemented and are still an explicit blocker; this correction does not claim to complete entity-backed dimension policy.
\ No newline at end of file
supabase/migrations/20261115140000_wp1_dimension_value_type_scope.sql new
+42
@@ -0,0 +1,42 @@
1 +-- WP1 correction: dimension type/value links must be internally consistent.
2 +-- Reject wrong-company, mismatched type/value and inactive dimensions before draft/post.
3 +CREATE OR REPLACE FUNCTION private.finora_phase1a_validate_saved(
4 + p_org uuid,p_voucher text,p_company text)
5 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
6 +AS $fn$
7 +DECLARE x record; n integer:=0; debit_total numeric:=0;credit_total numeric:=0; v_year text;
8 +BEGIN
9 + SELECT data->>'fiscalYearId' INTO STRICT v_year FROM public.records
10 + WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_voucher;
11 + FOR x IN SELECT id,data FROM public.records
12 + WHERE organization_id=p_org AND collection='journalLines'
13 + AND data->>'voucherId'=p_voucher ORDER BY id LOOP
14 + IF x.data->>'companyId' IS DISTINCT FROM p_company
15 + OR x.data->>'fiscalYearId' IS DISTINCT FROM v_year THEN
16 + RAISE EXCEPTION 'FINORA_LINE_SCOPE_MISMATCH' USING ERRCODE='23514';
17 + END IF;
18 + PERFORM private.finora_phase1a_validate_line(p_org,p_company,x.data);
19 + IF EXISTS(SELECT 1 FROM public.records dim
20 + WHERE dim.organization_id=p_org AND dim.collection='journalLineDimensions'
21 + AND dim.data->>'voucherId'=p_voucher AND dim.data->>'journalLineId'=x.id
22 + AND (dim.data->>'companyId' IS DISTINCT FROM p_company
23 + OR NOT EXISTS(SELECT 1 FROM public.records t
24 + WHERE t.organization_id=p_org AND t.collection='dimensionTypes'
25 + AND t.id=dim.data->>'dimensionTypeId' AND t.data->>'companyId'=p_company
26 + AND coalesce(t.data->>'active','true')='true')
27 + OR NOT EXISTS(SELECT 1 FROM public.records v
28 + WHERE v.organization_id=p_org AND v.collection='dimensionValues'
29 + AND v.id=dim.data->>'dimensionValueId' AND v.data->>'companyId'=p_company
30 + AND v.data->>'dimensionTypeId'=dim.data->>'dimensionTypeId'
31 + AND coalesce(v.data->>'active','true')='true'))) THEN
32 + RAISE EXCEPTION 'FINORA_DIMENSION_OUT_OF_SCOPE' USING ERRCODE='23503';
33 + END IF;
34 + n:=n+1;
35 + debit_total:=debit_total+(x.data->>'debit')::numeric;
36 + credit_total:=credit_total+(x.data->>'credit')::numeric;
37 + END LOOP;
38 + IF n<2 OR debit_total<=0 OR debit_total<>credit_total THEN
39 + RAISE EXCEPTION 'FINORA_UNBALANCED_POSTED_JOURNAL count=% debit=% credit=%',
40 + n,debit_total,credit_total USING ERRCODE='23514';
41 + END IF;
42 +END $fn$;
supabase/rollback/20261115140000_wp1_dimension_value_type_scope.sql new
+31
@@ -0,0 +1,31 @@
1 +-- Conservative DOWN: restore prior dimension existence/company-only checks.
2 +CREATE OR REPLACE FUNCTION private.finora_phase1a_validate_saved(
3 + p_org uuid,p_voucher text,p_company text)
4 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
5 +AS $fn$
6 +DECLARE x record; n integer:=0; debit_total numeric:=0;credit_total numeric:=0; v_year text;
7 +BEGIN
8 + SELECT data->>'fiscalYearId' INTO STRICT v_year FROM public.records WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_voucher;
9 + FOR x IN SELECT id,data FROM public.records
10 + WHERE organization_id=p_org AND collection='journalLines'
11 + AND data->>'voucherId'=p_voucher ORDER BY id LOOP
12 + IF x.data->>'companyId' IS DISTINCT FROM p_company OR x.data->>'fiscalYearId' IS DISTINCT FROM v_year THEN RAISE EXCEPTION 'FINORA_LINE_SCOPE_MISMATCH' USING ERRCODE='23514'; END IF;
13 + PERFORM private.finora_phase1a_validate_line(p_org,p_company,x.data);
14 + IF EXISTS(SELECT 1 FROM public.records dim
15 + WHERE dim.organization_id=p_org AND dim.collection='journalLineDimensions'
16 + AND dim.data->>'voucherId'=p_voucher AND dim.data->>'journalLineId'=x.id
17 + AND (NOT EXISTS(SELECT 1 FROM public.records t WHERE t.organization_id=p_org
18 + AND t.collection='dimensionTypes' AND t.id=dim.data->>'dimensionTypeId'
19 + AND t.data->>'companyId'=p_company)
20 + OR NOT EXISTS(SELECT 1 FROM public.records v WHERE v.organization_id=p_org
21 + AND v.collection='dimensionValues' AND v.id=dim.data->>'dimensionValueId'
22 + AND v.data->>'companyId'=p_company))) THEN
23 + RAISE EXCEPTION 'FINORA_DIMENSION_OUT_OF_SCOPE' USING ERRCODE='23503';
24 + END IF;
25 + n:=n+1;debit_total:=debit_total+(x.data->>'debit')::numeric;
26 + credit_total:=credit_total+(x.data->>'credit')::numeric;
27 + END LOOP;
28 + IF n<2 OR debit_total<=0 OR debit_total<>credit_total THEN
29 + RAISE EXCEPTION 'FINORA_UNBALANCED_POSTED_JOURNAL count=% debit=% credit=%',n,debit_total,credit_total USING ERRCODE='23514';
30 + END IF;
31 +END $fn$;
supabase/tests/wp1_dimension_value_type_scope.sql new
+54
@@ -0,0 +1,54 @@
1 +-- Dimension type/value consistency, company scope and active-state negative tests.
2 +\set ON_ERROR_STOP on
3 +BEGIN;
4 +INSERT INTO auth.users(id,email,email_confirmed_at,raw_user_meta_data)
5 +VALUES('fb000000-0000-4000-8000-000000000001','wp1-dimension-scope@example.invalid',now(),'{}');
6 +SELECT set_config('wp1.dimension_org',(SELECT id::text FROM public.organizations
7 + WHERE owner_user_id='fb000000-0000-4000-8000-000000000001'),true);
8 +SELECT set_config('request.jwt.claim.sub','fb000000-0000-4000-8000-000000000001',true);
9 +INSERT INTO public.records(owner_id,organization_id,collection,id,data) VALUES
10 +(auth.uid(),current_setting('wp1.dimension_org')::uuid,'companies','DS_C','{"name":"Dimension scope"}'),
11 +(auth.uid(),current_setting('wp1.dimension_org')::uuid,'fiscalYears','DS_Y','{"companyId":"DS_C","startDate":"1405/01/01","endDate":"1405/12/29","status":"open"}'),
12 +(auth.uid(),current_setting('wp1.dimension_org')::uuid,'accounts','DS_A','{"companyId":"DS_C","active":true,"postingAllowed":true}'),
13 +(auth.uid(),current_setting('wp1.dimension_org')::uuid,'accounts','DS_B','{"companyId":"DS_C","active":true,"postingAllowed":true}'),
14 +(auth.uid(),current_setting('wp1.dimension_org')::uuid,'dimensionTypes','DS_TYPE_A','{"companyId":"DS_C","active":true}'),
15 +(auth.uid(),current_setting('wp1.dimension_org')::uuid,'dimensionTypes','DS_TYPE_B','{"companyId":"DS_C","active":true}'),
16 +(auth.uid(),current_setting('wp1.dimension_org')::uuid,'dimensionValues','DS_VALUE_A','{"companyId":"DS_C","dimensionTypeId":"DS_TYPE_A","active":true}'),
17 +(auth.uid(),current_setting('wp1.dimension_org')::uuid,'dimensionValues','DS_VALUE_B','{"companyId":"DS_C","dimensionTypeId":"DS_TYPE_B","active":true}'),
18 +(auth.uid(),current_setting('wp1.dimension_org')::uuid,'dimensionValues','DS_VALUE_INACTIVE','{"companyId":"DS_C","dimensionTypeId":"DS_TYPE_A","active":false}');
19 +INSERT INTO private.finora_phase1a_guard_modes(organization_id,mode)
20 +VALUES(current_setting('wp1.dimension_org')::uuid,'enforce');
21 +SET LOCAL ROLE authenticated;
22 +DO $test$
23 +DECLARE org uuid:=current_setting('wp1.dimension_org')::uuid; r jsonb; kind text;
24 +BEGIN
25 + FOREACH kind IN ARRAY ARRAY['mismatched_type','inactive_value'] LOOP
26 + BEGIN
27 + r:=public.finora_journal_create_draft(org,'DS_BAD_'||kind,
28 + '{"companyId":"DS_C","fiscalYearId":"DS_Y","date":"1405/07/24"}',
29 + jsonb_build_array(
30 + jsonb_build_object('id','DS_BAD_'||kind||'_A','accountId','DS_A','debit',100,'credit',0,
31 + 'dimensions',jsonb_build_array(jsonb_build_object('dimensionTypeId','DS_TYPE_A',
32 + 'dimensionValueId',CASE WHEN kind='mismatched_type' THEN 'DS_VALUE_B' ELSE 'DS_VALUE_INACTIVE' END))),
33 + jsonb_build_object('id','DS_BAD_'||kind||'_B','accountId','DS_B','debit',0,'credit',100)));
34 + RAISE EXCEPTION 'WP1_INVALID_DIMENSION_ACCEPTED: %',kind;
35 + EXCEPTION WHEN foreign_key_violation THEN
36 + IF SQLERRM<>'FINORA_DIMENSION_OUT_OF_SCOPE' THEN RAISE; END IF;
37 + END;
38 + IF EXISTS(SELECT FROM public.records WHERE organization_id=org
39 + AND collection='journalVouchers' AND id='DS_BAD_'||kind) THEN
40 + RAISE EXCEPTION 'WP1_INVALID_DIMENSION_LEFT_PARTIAL_DRAFT: %',kind;
41 + END IF;
42 + END LOOP;
43 + r:=public.finora_journal_create_draft(org,'DS_VALID',
44 + '{"companyId":"DS_C","fiscalYearId":"DS_Y","date":"1405/07/24"}',
45 + jsonb_build_array(
46 + jsonb_build_object('id','DS_VALID_A','accountId','DS_A','debit',100,'credit',0,
47 + 'dimensions',jsonb_build_array(jsonb_build_object('dimensionTypeId','DS_TYPE_A','dimensionValueId','DS_VALUE_A'))),
48 + jsonb_build_object('id','DS_VALID_B','accountId','DS_B','debit',0,'credit',100)));
49 + r:=public.finora_journal_post(org,'DS_VALID',(r#>>'{voucher,version}')::bigint);
50 + IF r#>>'{voucher,status}'<>'posted' THEN RAISE EXCEPTION 'WP1_VALID_DIMENSION_POST_FAILED'; END IF;
51 + SET CONSTRAINTS ALL IMMEDIATE;
52 + RAISE NOTICE 'WP1_DIMENSION_TYPE_VALUE_SCOPE_PASS: mismatch and inactive rejected; valid pair posts';
53 +END $test$;
54 +ROLLBACK;