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

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

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

Synced Dec 3, 19:30 UTC

audit(phase1): preserve executed permission catalog checks and migration-risk findings

* docs(phase1): record owner request and read-only security audit scope * test(phase1): add production-safe read-only access catalog checks * docs(phase1): record production SQL audit results and inspect 21 public definer guards * docs(phase1): record validated 4-pass live permission checks and stale PR #58 hazard

davoodmehraban89 committed Oct 13, 2026 at 13:07 UTC 9d40b70be90172772d12eb9fa33915fe9c055c67
3 files changed +151
PROJECT_STATE.md
+12
@@ -158,6 +158,18 @@ The latest user message is the sole source of new instructions. Read AGENTS.md t
158 - **Next discriminator:** owner keeps **same computer and browser** and temporarily changes only Internet access to a phone mobile hotspot; clicks the same built-in connectivity test once more, returns only four status codes and optional login success/time. If Auth and REST respond on hotspot, investigate current ISP/DNS/routing/firewall/proxy. If both still time out, assess local device/browser/proxy or service edge via privacy-safe diagnostics before any code change. Do not request email/password/tokens/cookies/HAR. No Auth/RLS/schema/roles, financial history, invoice or OTP modifications. A bounded runtime fix, if proven necessary, needs independent Chromium/Golden/DB/Security gates and owner retest. Issue #106 OPEN.
159 - **Change boundary:** evidence-only documentation update and Issue #106 comment; rollback revert docs-only PR. No runtime change or customer production mutation.
160
161 +### 2026-10-13 Owner: pause Phase 0 login performance; progress independent Phase 1 security — EXECUTION STARTED
162 +- **Latest owner instruction:** defer sign-in/startup slowness, continue approved Finora execution phases. **Explicit boundary:** leave F0-01 / #106 OPEN; do not optimize login or claim Phase 0 complete. Per approved eight-phase roadmap, perform a **Phase 1 read-only security/data-integrity audit** in parallel with blocked owner-authenticated Phase 0 gates. No production Auth/RLS/schema/role, data, permissions, billing, or finance cutover changes authorized by this instruction.
163 +- **Verified beginning main:** `1fa5cf99be9eb790d1192b7597d2dbf65cc9d3fa`. Live Supabase `hcsixhqbyuhpshfwqpjx` ACTIVE_HEALTHY; **82 migrations** last `20261012075507`; existing open PR #58 contains a migration archive under a **different timestamp** (`20261007163500`) from the production-recorded `20261007165208`, and mixes old auth/frontend features; do **not** merge, rename blindly, reapply, or issue replacement SQL. Outstanding PR #6/#39/#40 also not accepted.
164 +- **Initial independently executed read-only catalog findings:** public tables **18/18 RLS**, private tables **3/10 RLS**, **zero anon/authenticated SELECT grants to all 10 private tables**; SECURITY DEFINER routines: public **27** (of which **21 authenticated EXECUTE**, **0 anon EXECUTE**, **27 configured search_path**); private **66** (of which **43 authenticated EXECUTE**, **0 anon EXECUTE**, **66 configured search_path**). Authenticated has USAGE on private schema, whereas anon does not; this requires reviewing actual API exposure and callable routine guards, **not** assuming no possible access or an exploitable vulnerability. The 21 public authenticated-callable warnings are review inputs. Six sampled public admin-license mutators explicitly call `public.is_admin()`; sampled organization invitation/workflow functions use `auth.uid()` and capability checks, but this is **source review, not authenticated adversarial execution proof**.
165 +- **This isolated slice:** deliver an executable **read-only permissions/assertion SQL audit** and a Phase 1 evidence memo with repeat procedure, expected invariants, unresolved negative tests and risk priority. Verify against live metadata with SELECT only, plus repo presence/readback; no DB or service changes, no test identities. Record exact output, SHA and outcome after the fact. This is a **Phase 1 verification slice**, not Phase 1 acceptance; additional two-user revocation, adversarial grants, backup/restore, advisor reviews and sign-off remain OPEN. Rollback revert docs/test-file PR.
166 +
167 +### 2026-10-13 Phase 1 permissions audit — LIVE SQL 4 PASS / 2 REVIEW / NO DATABASE MUTATION / PR CI PENDING
168 +- **Executable deliverables on isolated branch:** `supabase/tests/phase1_permissions_readonly.sql` (catalog-only SELECT audit) and `docs/FINORA_PHASE1_SECURITY_READONLY_AUDIT_2026-10-13.md` (repeat procedure, 21-function risk roster, historic migration discrepancy). SQL was **fetched back from GitHub** and executed read-only via production Supabase metadata access. Exact results: `PUBLIC_ALL_RLS` PASS **18/18**, `PRIVATE_NO_CLIENT_DIRECT_READ` PASS **0 of 10 exposed**, `PUBLIC_DEFINER_NO_ANON_EXEC` PASS **0 of 27**, `DEFINER_EXPLICIT_SEARCH_PATH` PASS **93/93**; `PUBLIC_AUTHENTICATED_DEFINER_REVIEW` REVIEW **21**, `PRIVATE_RLS_COVERAGE_REVIEW` REVIEW **3/10**. **4 PASS / 2 REVIEW / 0 FAIL**. The 21 live advisor warnings match exactly the 21 `public` authenticated-callable SECURITY DEFINER routines.
169 +- **Concrete regression hazard from independent production function review:** stale open PR #58 `20261007163500_phone_identity_profile.sql` defines `public.handle_new_user` with `organization_members` inserted **before** `licenses`. Current live function, after Oct-12 safeguard, deliberately inserts `licenses` **before** `organization_members` so the seat guard can evaluate capacity. **Do not reapply the stale old function or merge PR #58 as-is.** Mismatched old archive filename `20261007163500` vs live migration ledger `20261007165208` remains unresolved; exact executed SQL-body parity NOT VERIFIED.
170 +- **Source review of all 21 public authenticated-callable SECURITY DEFINER routines** completed using `pg_get_functiondef`, grouped into six admin license mutators (explicit `is_admin`), two read predicates, seven office, five organizational/invitation, one own-profile RPC. Static guard presence does **not** prove correct tenant isolation or absence of privilege escalation. Authenticated two-user revocation/adversarial parameter checks, private RPC exposure, leaked-password protection, backup/restore and migration parity remain OPEN and require appropriate approval/test identities.
171 +- **Boundaries:** Owner-directed deferral of F0-01 slowness persists; F0-01/Phase 0 OPEN. Phase 1 audit slice metadata verification PASS only; **Phase 1 owner acceptance NOT CLAIMED**. No JS runtime, production SQL DDL/DML, Auth/RLS/grant change, new identities, financial records, subscription payments or secrets touched. PR Quality/Security and any post-merge exact-SHA gates **PENDING at this checkpoint**; do not claim release until verified. Rollback revert documentation+read-only SQL check.
172 +
173 ## Current change ledger
174 | 2026-10-07 | Owner requested accounting/product usability refinement from live screenshots: automatic non-user-entered floating-detail codes, contextual in-product guides (especially accounting/chart/dimensions), remove duplicate product internal tax ID and use product code as internal item ID, strengthen in-control product/person search, introduce hierarchical product group/subgroup coding with deterministic 6-digit product codes, and keep sale/purchase commercial-document workspace layout stable while only semantic fields change. | **IMPLEMENTED / LOCAL VERIFICATION PASSED / CI PENDING** | Baseline main = `7e58c75f7d754f378d94ca3f356c1ae580aa7ee3`. Automatic dimension type/value codes, contextual guides, product-code-as-internal-ID, normalized multi-token search, and additive six-digit product coding implemented. Existing historical codes preserved. Commercial sale/purchase workspaces now share a stable `صدور سند تجاری` header/actions layout; duplicate purchase sidebar injection removed; the public selector is the single document-type selector and the legacy internal invoice-kind control is hidden. Local syntax/static/commerce/UX/accounting phases 2–6/Golden checks passed; protected-branch CI remains pending. |
175
docs/FINORA_PHASE1_SECURITY_READONLY_AUDIT_2026-10-13.md new
+71
@@ -0,0 +1,71 @@
1 +# Finora Phase 1 — Live permission and SECURITY DEFINER read-only audit
2 +**Observed:** 2026-10-13 · **Scope:** independent, metadata-only Phase 1 slice while owner defers F0-01 startup slowness. **Status:** READ-ONLY METADATA VERIFIED; AUTHENTICATED NEGATIVE TESTS OPEN; PHASE 1 NOT ACCEPTED.
3 +
4 +## Authority and version
5 +- Owner explicitly prioritizes continuing Finora phases now; Phase 0 login slowness remains open and deferred, **not accepted**.
6 +- Canonical protected main at audit start: `1fa5cf99be9eb790d1192b7597d2dbf65cc9d3fa`. GitHub same SHA Quality `38357143810`, Security `38357143834`, Release `38357450781`, gated Pages `38357495885` SUCCESS. Exact production user-login stability is unresolved and separate.
7 +- Production Supabase project `hcsixhqbyuhpshfwqpjx` was **ACTIVE_HEALTHY**, PostgreSQL 17.6.1.166, **82 migration ledger records**, last `20261012075507 fix_identity_bootstrap_license_before_membership`. This audit does not authorize schema changes or infer migration SQL equivalence.
8 +
9 +## Directly verified live catalog metadata
10 +| Control | Observed | Interpretation |
11 +|---|---|---|
12 +| Public tables with RLS enabled | **18/18** | All inspected public base tables use RLS; no assurance policy bodies cannot be bypassed |
13 +| Private tables with RLS enabled | **3/10** | Seven private tables do not enable RLS; needs threat-model/privilege review |
14 +| Direct SELECT on private tables by `anon` or `authenticated` | **0/10** | No direct table SELECT grants found for either role, regardless of RLS |
15 +| Private schema USAGE | `anon=false`, `authenticated=true` | Do not equate table-grant absence with all possible RPC/function paths being inaccessible |
16 +| Public SECURITY DEFINER functions | **27** total; **21** executable by `authenticated`, **0** by `anon` | Matches the 21 authenticated-callable function advisor warnings; these are review candidates, not 21 proven exploits |
17 +| Private SECURITY DEFINER functions | **66** total; **43** executable by `authenticated`, **0** by `anon` | Private helper execution policy and schemas require separate API exposure/capability review |
18 +| Explicit function search_path | **93/93** public+private SECURITY DEFINER | Fixed search_path is present, but not a sufficient authorization proof |
19 +
20 +This is a snapshot of catalog metadata from live queries, **not** an exhaustive adversarial user simulation. Count of `SECURITY DEFINER` includes trigger/helpers; only public `authenticated`-callable functions are the 21 directly reported API-exposure warnings.
21 +
22 +## Source-level sample (not an authorization penetration test)
23 +- Six `public.admin_*license*`/user-capacity mutators inspected via `pg_get_functiondef` enforce `public.is_admin()` and validate inputs. The checker itself relies on `auth.uid()` and `public.profiles.role='admin'`. A compromised global admin role or missing tenant constraints elsewhere is **not** ruled out by source review.
24 +- Sampled `public.organization_create_invitation`, `organization_accept_invitation` and `office_refer_correspondence_v2` include `auth.uid()`, organizational ownership/capability checks and membership checks. Real two-identity negative tests remain mandatory.
25 +- Supabase security advisor flags `rls_enabled_no_policy` for three private office-workflow tables and `auth_leaked_password_protection` as a separate warning. Warnings are actionable review inputs; enabling protection or changing RLS/Auth configuration requires explicit owner approval.
26 +
27 +## Executable repeatable read-only check
28 +File: `supabase/tests/phase1_permissions_readonly.sql`. It reads only `pg_catalog`, `has_table_privilege`, and `has_function_privilege`. Status `PASS` means the listed *metadata contract* holds, `FAIL` means drift/violation needing investigation, and `REVIEW` is intentionally not a failure or a vulnerability claim. It does not query real tenant tables, authenticate users, or mutate data.
29 +
30 +Expected initial run: `PUBLIC_ALL_RLS PASS (18/18)`; `PRIVATE_NO_CLIENT_DIRECT_READ PASS (0 of 10)`; `PUBLIC_DEFINER_NO_ANON_EXEC PASS (0 of 27)`; `DEFINER_EXPLICIT_SEARCH_PATH PASS (93/93)`; `PUBLIC_AUTHENTICATED_DEFINER_REVIEW REVIEW (21)`; `PRIVATE_RLS_COVERAGE_REVIEW REVIEW (3/10)`. Counts reflect this deployment and should not be hard-coded as invariants.
31 +
32 +## Production migration archive discrepancy, held for review
33 +- Live migration `20261007165208 phone_identity_profile` is recorded in Supabase.
34 +- Current `main` has **no** archived file for that operation; stale [PR #58](https://github.com/davoodmehraban89/Factor-easy/pull/58) includes `supabase/migrations/20261007163500_phone_identity_profile.sql`, a *different migration timestamp*, bundled with historical admin/frontend/Auth changes and presently unmerged. **No proof of SQL-body parity**, and **no authority** to rename, reapply or merge PR #58 unreviewed.
35 +- Required next audit: recover verified executed SQL text/metadata from appropriate production migration source and compare exact semantics/recorded ledger version to PR archive offline. Do not execute historical DDL against production.
36 +
37 +## Acceptance boundaries / next safely executable slices
38 +1. Independently check all 21 public authenticated-callable SECURITY DEFINER functions for authorization, organization ID spoofing, parameter validation and search_path; classify each with evidence.
39 +2. Build isolated two-user read-only/negative tests for tenant separation, offboarding/revocation and access to invitation/office/request functions; **requires separately authorized durable test users**. Never use live production financial rows for disposable tests.
40 +3. Verify recovery/backup in isolated approved scope and reconciliation of 82 live migrations against repository archives. Password-leak protection, Auth/RLS/role/schema changes and privileged probes require separate approval.
41 +4. Continue independent Phase 2 accounting invariant review after approved Phase 1 contracts; do not authorize historical cutover or financial writes yet.
42 +
43 +**No runtime change, database migration, Auth/RLS/grant change, new users, or financial record mutation in this slice.** Rollback of deliverables is a docs/test-file-only revert. F0-01, Phase 0 and overall Phase 1 acceptance remain OPEN.
44 +
45 +## Independently executed SQL fixture — observed results (same day)
46 +The repository SQL file `supabase/tests/phase1_permissions_readonly.sql` was **fetched back from the Phase 1 branch** and executed using the authorized production Supabase connector's read-only SQL operation. It returned **4 PASS, 2 REVIEW, 0 FAIL**:
47 +
48 +| Check ID | Result | Actual output |
49 +|---|---|---|
50 +| `PUBLIC_ALL_RLS` | PASS | 18/18 |
51 +| `PRIVATE_NO_CLIENT_DIRECT_READ` | PASS | 0 of 10 have direct client SELECT |
52 +| `PUBLIC_DEFINER_NO_ANON_EXEC` | PASS | 0 of 27 callable by anon |
53 +| `DEFINER_EXPLICIT_SEARCH_PATH` | PASS | 93/93 |
54 +| `PUBLIC_AUTHENTICATED_DEFINER_REVIEW` | REVIEW | 21 callable by authenticated |
55 +| `PRIVATE_RLS_COVERAGE_REVIEW` | REVIEW | 3/10 enabled |
56 +
57 +This audit does not inspect arbitrary RPC parameter exploitability, PostgREST exposed schema configuration, service-role access or real revoked-user session tokens. A healthy direct-privilege snapshot alone does not establish secure cross-tenant application behavior.
58 +
59 +### Review roster of 21 public authenticated-callable routines
60 +The live advisor's exact 21 names were matched against the live catalog's 21 public definer functions callable by `authenticated` and `pg_get_functiondef` was inspected **without executing any of them**.
61 +
62 +- **Six license/admin mutators:** `admin_cancel_license`, `admin_extend_license`, `admin_set_company_limit`, `admin_set_license`, `admin_set_license_modules`, `admin_set_user_limit`. Their SQL bodies explicitly check `public.is_admin()`; inspect global admin lifecycle/tenant-scoped targeting with authenticated negative tests before accepting.
63 +- **Two read predicates:** `has_active_license`, `is_admin`. The `is_admin` body binds to `auth.uid()`; `has_active_license` invokes private entitlement logic. These are not a proof that every downstream RPC rejects a revoked user.
64 +- **Seven office RPCs:** `office_act_on_referral`, `office_archive_search`, `office_classify_correspondence`, `office_link_correspondence`, `office_mark_correspondence_read`, `office_refer_correspondence_v2`, `office_referral_work_queue`. Each sampled source includes an organizational entitlement/capability check; select cases reference `auth.uid()`. An attacker-controlled organization ID still requires real cross-tenant negative testing.
65 +- **Five organizational/invitation RPCs:** `organization_accept_invitation`, `organization_capacity_summary`, `organization_create_invitation`, `organization_expire_invitations`, `organization_revoke_invitation`. Their definitions use private organization permission/entitlement predicates; the acceptance handler separately checks `auth.uid()` and token/email correspondence.
66 +- **One identity RPC:** `update_my_identity_profile`. Source checks `auth.uid()` and updates the caller's own profile; cross-user mutation and username collision need isolated negative tests.
67 +
68 +**Review outcome:** An explicit guard or search_path constraint was located in source paths, but **no routine is certified immune to parameter spoofing or privilege escalation** by this static exercise. These are **reviewed for source-level guard presence**, not safely pentested or resolved as warnings.
69 +
70 +### Concrete PR #58 signup ordering incompatibility
71 +The old PR #58 archive `supabase/migrations/20261007163500_phone_identity_profile.sql` defines `public.handle_new_user()` such that it inserts into `public.organization_members` **before** `public.licenses`. The **live production function**, independently read from `pg_get_functiondef('public.handle_new_user()'::regprocedure)`, inserts `public.licenses` **before** `public.organization_members` and explicitly documents the preceding seat-capacity trigger dependency. Therefore re-applying the old PR function as-is would risk undoing the 2026-10-12 signup safeguard. A fresh all-migrations replay may subsequently override the old function, but **order-specific correctness and historical migration parity are not demonstrated**. Do not merge/reapply old PR #58 as a blanket fix; extract and reconcile individual historical SQL bodies first under owner-approved migration procedure.
supabase/tests/phase1_permissions_readonly.sql new
+68
@@ -0,0 +1,68 @@
1 +-- Finora Phase 1 production-catalog access audit (READ-ONLY).
2 +-- SELECT metadata only. No customer rows, JWTs, passwords, mutation or auth bypass.
3 +-- Run with the authorized Supabase read-only SQL interface; do NOT run service changes.
4 +WITH
5 +pub AS (
6 + SELECT c.oid,c.relrowsecurity
7 + FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
8 + WHERE n.nspname='public' AND c.relkind IN ('r','p')
9 +),
10 +prv AS (
11 + SELECT c.oid,c.relrowsecurity
12 + FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace
13 + WHERE n.nspname='private' AND c.relkind IN ('r','p')
14 +),
15 +def AS (
16 + SELECT p.oid,n.nspname AS schema_name,coalesce(array_to_string(p.proconfig,','),'') AS config
17 + FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid=p.pronamespace
18 + WHERE p.prosecdef AND n.nspname IN ('public','private')
19 +),
20 +checks AS (
21 + SELECT 10 AS sort_order,'PUBLIC_ALL_RLS' AS check_id,
22 + CASE WHEN COUNT(*)>0 AND COUNT(*)=COUNT(*) FILTER (WHERE relrowsecurity)
23 + THEN 'PASS' ELSE 'FAIL' END AS status,
24 + (COUNT(*) FILTER (WHERE relrowsecurity))::text||'/'||COUNT(*)::text AS observed,
25 + 'Every public table has RLS enabled' AS requirement
26 + FROM pub
27 + UNION ALL
28 + SELECT 20,'PRIVATE_NO_CLIENT_DIRECT_READ',
29 + CASE WHEN COUNT(*)>0 AND COUNT(*) FILTER (WHERE
30 + pg_catalog.has_table_privilege('anon',oid,'SELECT')
31 + OR pg_catalog.has_table_privilege('authenticated',oid,'SELECT'))=0
32 + THEN 'PASS' ELSE 'FAIL' END,
33 + (COUNT(*) FILTER (WHERE
34 + pg_catalog.has_table_privilege('anon',oid,'SELECT')
35 + OR pg_catalog.has_table_privilege('authenticated',oid,'SELECT')))::text||' of '||COUNT(*)::text||' have direct client SELECT',
36 + 'No anon/authenticated direct SELECT grant on private tables'
37 + FROM prv
38 + UNION ALL
39 + SELECT 30,'PUBLIC_DEFINER_NO_ANON_EXEC',
40 + CASE WHEN COUNT(*)>0 AND COUNT(*) FILTER
41 + (WHERE pg_catalog.has_function_privilege('anon',oid,'EXECUTE'))=0
42 + THEN 'PASS' ELSE 'FAIL' END,
43 + (COUNT(*) FILTER (WHERE pg_catalog.has_function_privilege('anon',oid,'EXECUTE')))::text||' of '||COUNT(*)::text||' callable by anon',
44 + 'No exposed-schema SECURITY DEFINER functions callable by anon'
45 + FROM def WHERE schema_name='public'
46 + UNION ALL
47 + SELECT 40,'DEFINER_EXPLICIT_SEARCH_PATH',
48 + CASE WHEN COUNT(*)>0 AND COUNT(*)=COUNT(*) FILTER (WHERE config LIKE '%search_path=%')
49 + THEN 'PASS' ELSE 'FAIL' END,
50 + (COUNT(*) FILTER (WHERE config LIKE '%search_path=%'))::text||'/'||COUNT(*)::text AS observed,
51 + 'All inspected SECURITY DEFINER routines pin search_path'
52 + FROM def
53 + UNION ALL
54 + SELECT 50,'PUBLIC_AUTHENTICATED_DEFINER_REVIEW',
55 + 'REVIEW',
56 + (COUNT(*) FILTER (WHERE pg_catalog.has_function_privilege('authenticated',oid,'EXECUTE')))::text||
57 + ' publicly exposed SECURITY DEFINER functions callable by authenticated',
58 + 'Require per-function authorization/source review; not automatically a flaw'
59 + FROM def WHERE schema_name='public'
60 + UNION ALL
61 + SELECT 60,'PRIVATE_RLS_COVERAGE_REVIEW',
62 + 'REVIEW',
63 + (COUNT(*) FILTER (WHERE relrowsecurity))::text||'/'||COUNT(*)::text AS observed,
64 + 'Private tables without RLS need separate schema/grant/RPC-path analysis'
65 + FROM prv
66 +)
67 +SELECT check_id,status,observed,requirement
68 +FROM checks ORDER BY sort_order;