strix-agent 0.1.18__py3-none-any.whl → 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of strix-agent might be problematic. Click here for more details.

Files changed (68) hide show
  1. strix/agents/StrixAgent/strix_agent.py +49 -39
  2. strix/agents/StrixAgent/system_prompt.jinja +23 -10
  3. strix/agents/base_agent.py +90 -10
  4. strix/agents/state.py +23 -2
  5. strix/interface/cli.py +171 -0
  6. strix/interface/main.py +482 -0
  7. strix/{cli → interface}/tool_components/base_renderer.py +2 -2
  8. strix/{cli → interface}/tool_components/reporting_renderer.py +2 -1
  9. strix/{cli → interface}/tool_components/scan_info_renderer.py +17 -12
  10. strix/{cli/app.py → interface/tui.py} +107 -31
  11. strix/interface/utils.py +435 -0
  12. strix/prompts/README.md +64 -0
  13. strix/prompts/__init__.py +1 -1
  14. strix/prompts/cloud/.gitkeep +0 -0
  15. strix/prompts/custom/.gitkeep +0 -0
  16. strix/prompts/frameworks/fastapi.jinja +142 -0
  17. strix/prompts/frameworks/nextjs.jinja +126 -0
  18. strix/prompts/protocols/graphql.jinja +215 -0
  19. strix/prompts/reconnaissance/.gitkeep +0 -0
  20. strix/prompts/technologies/firebase_firestore.jinja +177 -0
  21. strix/prompts/technologies/supabase.jinja +189 -0
  22. strix/prompts/vulnerabilities/authentication_jwt.jinja +133 -115
  23. strix/prompts/vulnerabilities/broken_function_level_authorization.jinja +146 -0
  24. strix/prompts/vulnerabilities/business_logic.jinja +146 -118
  25. strix/prompts/vulnerabilities/csrf.jinja +137 -131
  26. strix/prompts/vulnerabilities/idor.jinja +149 -118
  27. strix/prompts/vulnerabilities/insecure_file_uploads.jinja +188 -0
  28. strix/prompts/vulnerabilities/mass_assignment.jinja +141 -0
  29. strix/prompts/vulnerabilities/path_traversal_lfi_rfi.jinja +142 -0
  30. strix/prompts/vulnerabilities/race_conditions.jinja +135 -165
  31. strix/prompts/vulnerabilities/rce.jinja +128 -180
  32. strix/prompts/vulnerabilities/sql_injection.jinja +128 -192
  33. strix/prompts/vulnerabilities/ssrf.jinja +118 -151
  34. strix/prompts/vulnerabilities/xss.jinja +144 -196
  35. strix/prompts/vulnerabilities/xxe.jinja +151 -243
  36. strix/runtime/docker_runtime.py +28 -7
  37. strix/runtime/runtime.py +4 -1
  38. strix/telemetry/__init__.py +4 -0
  39. strix/{cli → telemetry}/tracer.py +21 -9
  40. strix/tools/agents_graph/agents_graph_actions.py +17 -12
  41. strix/tools/agents_graph/agents_graph_actions_schema.xml +10 -14
  42. strix/tools/executor.py +1 -1
  43. strix/tools/finish/finish_actions.py +1 -1
  44. strix/tools/registry.py +1 -1
  45. strix/tools/reporting/reporting_actions.py +1 -1
  46. {strix_agent-0.1.18.dist-info → strix_agent-0.3.1.dist-info}/METADATA +95 -15
  47. strix_agent-0.3.1.dist-info/RECORD +115 -0
  48. strix_agent-0.3.1.dist-info/entry_points.txt +3 -0
  49. strix/cli/main.py +0 -702
  50. strix_agent-0.1.18.dist-info/RECORD +0 -99
  51. strix_agent-0.1.18.dist-info/entry_points.txt +0 -3
  52. /strix/{cli → interface}/__init__.py +0 -0
  53. /strix/{cli/assets/cli.tcss → interface/assets/tui_styles.tcss} +0 -0
  54. /strix/{cli → interface}/tool_components/__init__.py +0 -0
  55. /strix/{cli → interface}/tool_components/agents_graph_renderer.py +0 -0
  56. /strix/{cli → interface}/tool_components/browser_renderer.py +0 -0
  57. /strix/{cli → interface}/tool_components/file_edit_renderer.py +0 -0
  58. /strix/{cli → interface}/tool_components/finish_renderer.py +0 -0
  59. /strix/{cli → interface}/tool_components/notes_renderer.py +0 -0
  60. /strix/{cli → interface}/tool_components/proxy_renderer.py +0 -0
  61. /strix/{cli → interface}/tool_components/python_renderer.py +0 -0
  62. /strix/{cli → interface}/tool_components/registry.py +0 -0
  63. /strix/{cli → interface}/tool_components/terminal_renderer.py +0 -0
  64. /strix/{cli → interface}/tool_components/thinking_renderer.py +0 -0
  65. /strix/{cli → interface}/tool_components/user_message_renderer.py +0 -0
  66. /strix/{cli → interface}/tool_components/web_search_renderer.py +0 -0
  67. {strix_agent-0.1.18.dist-info → strix_agent-0.3.1.dist-info}/LICENSE +0 -0
  68. {strix_agent-0.1.18.dist-info → strix_agent-0.3.1.dist-info}/WHEEL +0 -0
@@ -0,0 +1,177 @@
1
+ <firebase_firestore_security_guide>
2
+ <title>FIREBASE / FIRESTORE — ADVERSARIAL TESTING AND EXPLOITATION</title>
3
+
4
+ <critical>Most impactful findings in Firebase apps arise from weak Firestore/Realtime Database rules, Cloud Storage exposure, callable/onRequest Functions trusting client input, incorrect ID token validation, and over-trusted App Check. Treat every client-supplied field and token as untrusted. Bind subject/tenant on the server, not in the client.</critical>
5
+
6
+ <scope>
7
+ - Firestore (documents/collections, rules, REST/SDK)
8
+ - Realtime Database (JSON tree, rules)
9
+ - Cloud Storage (rules, signed URLs)
10
+ - Auth (ID tokens, custom claims, anonymous/sign-in providers)
11
+ - Cloud Functions (onCall/onRequest, triggers)
12
+ - Hosting rewrites, CDN/caching, CORS
13
+ - App Check (attestation) and its limits
14
+ </scope>
15
+
16
+ <methodology>
17
+ 1. Extract project config from client (apiKey, authDomain, projectId, appId, storageBucket, messagingSenderId). Identify all used Firebase products.
18
+ 2. Obtain multiple principals: unauth, anonymous (if enabled), basic user A, user B, and any staff/admin if available. Capture their ID tokens.
19
+ 3. Build Resource × Action × Principal matrix across Firestore/Realtime/Storage/Functions. Exercise every action via SDK and raw REST (googleapis) to detect parity gaps.
20
+ 4. Start from list/query paths (where allowed) to seed IDs; then swap document paths, tenants, and user IDs across principals and transports.
21
+ </methodology>
22
+
23
+ <architecture>
24
+ - Firestore REST: https://firestore.googleapis.com/v1/projects/<project>/databases/(default)/documents/<path>
25
+ - Storage REST: https://storage.googleapis.com/storage/v1/b/<bucket>
26
+ - Auth: Google-signed ID tokens (iss accounts.google.com/securetoken.google.com/<project>), aud <project/app-id>; identity is in sub/uid.
27
+ - Rules engines: separate for Firestore, Realtime DB, and Storage; Functions bypass rules when using Admin SDK.
28
+ </architecture>
29
+
30
+ <auth_and_tokens>
31
+ - ID token verification must enforce issuer, audience (project), signature (Google JWKS), expiration, and optionally App Check binding when used.
32
+ - Custom claims are appended by Admin SDK; client-supplied claims are ignored by Auth but may be trusted by app code if copied into docs.
33
+ - Pitfalls:
34
+ - Accepting any JWT with valid signature but wrong audience/project.
35
+ - Trusting uid/account IDs from request body instead of context.auth.uid in Functions.
36
+ - Mixing session cookies and ID tokens without verifying both paths equivalently.
37
+ - Tests:
38
+ - Replay tokens across environments/projects; expect strict aud/iss rejection server-side.
39
+ - Call Functions with and without Authorization; verify identical checks on both onCall and onRequest variants.
40
+ </auth_and_tokens>
41
+
42
+ <firestore_rules>
43
+ - Rules are not filters: a query must include constraints that make the rule true for all returned documents; otherwise reads fail. Do not rely on client to include where clauses correctly.
44
+ - Prefer ownership derived from request.auth.uid and server data, not from client payload fields.
45
+ - Common gaps:
46
+ - allow read: if request.auth != null (any user reads all data)
47
+ - allow write: if request.auth != null (mass write)
48
+ - Missing per-field validation (adds isAdmin/role/tenantId fields).
49
+ - Using client-supplied ownerId/orgId instead of enforcing doc.ownerId == request.auth.uid or membership in org.
50
+ - Over-broad list rules on root collections; per-doc checks exist but list still leaks via queries.
51
+ - Validation patterns:
52
+ - Restrict writes: request.resource.data.keys().hasOnly([...]) and forbid privilege fields.
53
+ - Enforce ownership: resource.data.ownerId == request.auth.uid && request.resource.data.ownerId == request.auth.uid
54
+ - Org membership: exists(/databases/(default)/documents/orgs/$(org)/members/$(request.auth.uid))
55
+ - Tests:
56
+ - Compare results for users A/B on identical queries; diff counts and IDs.
57
+ - Attempt cross-tenant reads: where orgId == otherOrg; try queries without org filter to confirm denial.
58
+ - Write-path: set/patch with foreign ownerId/orgId; attempt to flip privilege flags.
59
+ </firestore_rules>
60
+
61
+ <firestore_queries>
62
+ - Enumerate via REST to avoid SDK client-side constraints; try structured and REST filters.
63
+ - Probe composite index requirements: UI-driven queries may hide missing rule coverage when indexes are enabled but rules are broad.
64
+ - Explore collection group queries (collectionGroup) that may bypass per-collection rules if not mirrored.
65
+ - Use startAt/endAt/in/array-contains to probe rule edges and pagination cursors for cross-tenant bleed.
66
+ </firestore_queries>
67
+
68
+ <realtime_database>
69
+ - Misconfigured rules frequently expose entire JSON trees. Probe https://<project>.firebaseio.com/.json with and without auth.
70
+ - Confirm rules for read/write use auth.uid and granular path checks; avoid .read/.write: true or auth != null at high-level nodes.
71
+ - Attempt to write privilege-bearing nodes (roles, org membership) and observe downstream effects (e.g., Cloud Functions triggers).
72
+ </realtime_database>
73
+
74
+ <cloud_storage>
75
+ - Rules parallel Firestore but apply to object paths. Common issues:
76
+ - Public reads on sensitive buckets/paths.
77
+ - Signed URLs with long TTL, no content-disposition controls; replayable across tenants.
78
+ - List operations exposed: /o?prefix= enumerates object keys.
79
+ - Tests:
80
+ - GET gs:// paths via https endpoints without auth; verify content-type and Content-Disposition: attachment.
81
+ - Generate and reuse signed URLs across accounts and paths; try case/URL-encoding variants.
82
+ - Upload HTML/SVG and verify X-Content-Type-Options: nosniff; check for script execution.
83
+ </cloud_storage>
84
+
85
+ <cloud_functions>
86
+ - onCall provides context.auth automatically; onRequest must verify ID tokens explicitly. Admin SDK bypasses rules; all ownership/tenant checks must be enforced in code.
87
+ - Common gaps:
88
+ - Trusting client uid/orgId from request body instead of context.auth.
89
+ - Missing aud/iss verification when manually parsing tokens.
90
+ - Over-broad CORS allowing credentialed cross-origin requests; echoing Authorization in responses.
91
+ - Triggers (onCreate/onWrite) granting roles or issuing signed URLs solely based on document content controlled by the client.
92
+ - Tests:
93
+ - Call both onCall and equivalent onRequest endpoints with varied tokens and bodies; expect identical decisions.
94
+ - Create crafted docs to trigger privilege-granting functions; verify that server re-derives subject/tenant before acting.
95
+ - Attempt internal fetches (SSRF) via Functions to project/metadata endpoints.
96
+ </cloud_functions>
97
+
98
+ <app_check>
99
+ - App Check is not a substitute for authorization. Many apps enable App Check enforcement on client SDKs but do not verify on custom backends.
100
+ - Bypasses:
101
+ - Unenforced paths: REST calls directly to googleapis endpoints with ID token succeed regardless of App Check.
102
+ - Mobile reverse engineering: hook client and reuse ID token flows without attestation.
103
+ - Tests:
104
+ - Compare SDK vs REST behavior with/without App Check headers; confirm no elevated authorization via App Check alone.
105
+ </app_check>
106
+
107
+ <tenant_isolation>
108
+ - Apps often implement multi-tenant data models (orgs/<orgId>/...). Bind tenant from server context (membership doc or custom claim), not from client payload.
109
+ - Tests:
110
+ - Vary org header/subdomain/query while keeping token fixed; verify server denies cross-tenant access.
111
+ - Export/report Functions: ensure queries execute under caller scope; signed outputs must encode tenant and short TTL.
112
+ </tenant_isolation>
113
+
114
+ <bypass_techniques>
115
+ - Content-type switching: JSON vs form vs multipart to hit alternate code paths in onRequest Functions.
116
+ - Parameter/field pollution: duplicate JSON keys; last-one-wins in many parsers; attempt to sneak privilege fields.
117
+ - Caching/CDN: Hosting rewrites or proxies that key responses without Authorization or tenant headers.
118
+ - Race windows: write then read before background enforcements (e.g., post-write claim synchronizations) complete.
119
+ </bypass_techniques>
120
+
121
+ <blind_channels>
122
+ - Firestore: use error shape, document count, and ETag/length to infer existence under partial denial.
123
+ - Storage: length/timing differences on signed URL attempts leak validity.
124
+ - Functions: constant-time comparisons vs variable messages reveal authorization branches.
125
+ </blind_channels>
126
+
127
+ <tooling_and_automation>
128
+ - SDK + REST: httpie/curl + jq for REST; Firebase emulator and Rules Playground for rapid iteration.
129
+ - Mobile: apktool/objection/frida to extract config and hook SDK calls; inspect network logs for endpoints and tokens.
130
+ - Rules analysis: script rule probes for common patterns (auth != null, missing field validation, list vs get parity).
131
+ - Functions: fuzz onRequest endpoints with varied content-types and missing/forged Authorization; verify CORS and token handling.
132
+ - Storage: enumerate prefixes; test signed URL generation and reuse patterns.
133
+ </tooling_and_automation>
134
+
135
+ <reviewer_checklist>
136
+ - Do Firestore/Realtime/Storage rules derive subject and tenant from auth, not client fields?
137
+ - Are list/query rules aligned with per-doc checks (no broad list leaks)?
138
+ - Are privilege-bearing fields immutable or server-only (forbidden in writes)?
139
+ - Do Functions verify ID tokens (iss/aud/exp/signature) and re-derive identity before acting?
140
+ - Are Admin SDK operations scoped by server-side checks (ownership/tenant)?
141
+ - Is App Check treated as advisory, not authorization, across all paths?
142
+ - Are Hosting/CDN cache keys bound to Authorization/tenant to prevent leaks?
143
+ </reviewer_checklist>
144
+
145
+ <validation>
146
+ 1. Provide owner vs non-owner Firestore queries showing unauthorized access or metadata leak.
147
+ 2. Demonstrate Cloud Storage read/write beyond intended scope (public object, signed URL reuse, or list exposure).
148
+ 3. Show a Function accepting forged/foreign identity (wrong aud/iss) or trusting client uid/orgId.
149
+ 4. Document minimal reproducible requests with roles/tokens used and observed deltas.
150
+ </validation>
151
+
152
+ <false_positives>
153
+ - Public collections/objects documented and intended.
154
+ - Rules that correctly enforce per-doc checks with matching query constraints.
155
+ - Functions verifying tokens and ignoring client-supplied identifiers.
156
+ - App Check enforced but not relied upon for authorization.
157
+ </false_positives>
158
+
159
+ <impact>
160
+ - Cross-account and cross-tenant data exposure.
161
+ - Unauthorized state changes via Functions or direct writes.
162
+ - Exfiltration of PII/PHI and private files from Storage.
163
+ - Durable privilege escalation via misused custom claims or triggers.
164
+ </impact>
165
+
166
+ <pro_tips>
167
+ 1. Treat apiKey as project identifier only; identity must come from verified ID tokens.
168
+ 2. Start from rules: read them, then prove gaps with diffed owner/non-owner requests.
169
+ 3. Prefer REST for parity checks; SDKs can mask errors via client-side filters.
170
+ 4. Hunt privilege fields in docs and forbid them via rules; verify immutability.
171
+ 5. Probe collectionGroup queries and list rules; many leaks live there.
172
+ 6. Functions are the authority boundary—enforce subject/tenant there even if rules exist.
173
+ 7. Keep concise PoCs: one owner vs non-owner request per surface that clearly demonstrates the unauthorized delta.
174
+ </pro_tips>
175
+
176
+ <remember>Authorization must hold at every layer: rules, Functions, and Storage. Bind subject and tenant from verified tokens and server data, never from client payload or UI assumptions. Any gap becomes a cross-account or cross-tenant vulnerability.</remember>
177
+ </firebase_firestore_security_guide>
@@ -0,0 +1,189 @@
1
+ <supabase_security_guide>
2
+ <title>SUPABASE — ADVERSARIAL TESTING AND EXPLOITATION</title>
3
+
4
+ <critical>Supabase exposes Postgres through PostgREST, Realtime, GraphQL, Storage, Auth (GoTrue), and Edge Functions. Most impactful findings come from mis-scoped Row Level Security (RLS), unsafe RPCs, leaked service_role keys, lax Storage policies, GraphQL overfetching, and Edge Functions trusting headers or tokens without binding to issuer/audience/tenant.</critical>
5
+
6
+ <scope>
7
+ - PostgREST: table CRUD, filters, embeddings, RPC (remote functions)
8
+ - RLS: row ownership/tenant isolation via policies and auth.uid()
9
+ - Storage: buckets, objects, signed URLs, public/private policies
10
+ - Realtime: replication subscriptions, broadcast/presence channels
11
+ - GraphQL: pg_graphql over Postgres schema with RLS interaction
12
+ - Auth (GoTrue): JWTs, cookie/session, magic links, OAuth flows
13
+ - Edge Functions (Deno): server-side code calling Supabase with secrets
14
+ </scope>
15
+
16
+ <methodology>
17
+ 1. Inventory surfaces: REST /rest/v1, Storage /storage/v1, GraphQL /graphql/v1, Realtime wss, Auth /auth/v1, Functions https://<project>.functions.supabase.co/.
18
+ 2. Obtain tokens for: unauth (anon), basic user, other user, and (if disclosed) admin/staff; enumerate anon key exposure and verify if service_role leaked anywhere.
19
+ 3. Build a Resource × Action × Principal matrix and test each via REST and GraphQL. Confirm parity across channels and content-types (json/form/multipart).
20
+ 4. Start with list/search/export endpoints to gather IDs, then attempt direct reads/writes across principals, tenants, and transports. Validate RLS and function guards.
21
+ </methodology>
22
+
23
+ <architecture>
24
+ - Project endpoints: https://<ref>.supabase.co; REST at /rest/v1/<table>, RPC at /rest/v1/rpc/<fn>.
25
+ - Headers: apikey: <anon-or-service>, Authorization: Bearer <JWT>. Anon key only identifies the project; JWT binds user context.
26
+ - Roles: anon, authenticated; service_role bypasses RLS and must never be client-exposed.
27
+ - auth.uid(): current user UUID claim; policies must never trust client-supplied IDs over server context.
28
+ </architecture>
29
+
30
+ <rls>
31
+ - Enable RLS on every non-public table; absence or “permit-all” policies → bulk exposure.
32
+ - Common gaps:
33
+ - Policies check auth.uid() for read but forget UPDATE/DELETE/INSERT.
34
+ - Missing tenant constraints (org_id/tenant_id) allow cross-tenant reads/writes.
35
+ - Policies rely on client-provided columns (user_id in payload) instead of deriving from JWT.
36
+ - Complex joins where the effective policy is applied after filters, enabling inference via counts or projections.
37
+ - Tests:
38
+ - Compare results for two users: GET /rest/v1/<table>?select=*&Prefer=count=exact; diff row counts and IDs.
39
+ - Try cross-tenant: add &org_id=eq.<other_org> or use or=(org_id.eq.other,org_id.is.null).
40
+ - Write-path: PATCH/DELETE single row with foreign id; INSERT with foreign owner_id then read.
41
+ </rls>
42
+
43
+ <postgrest_and_rest>
44
+ - Filters: eq, neq, lt, gt, ilike, or, is, in; embed relations with select=*,profile(*); exploit embeddings to overfetch linked rows if resolvers skip per-row checks.
45
+ - Headers to know: Prefer: return=representation (echo writes), Prefer: count=exact (exposure via counts), Accept-Profile/Content-Profile to select schema.
46
+ - IDOR patterns: /rest/v1/<table>?select=*&id=eq.<other_id>; query alternative keys (slug, email) and composite keys.
47
+ - Search leaks: generous LIKE/ILIKE filters + lack of RLS → mass disclosure.
48
+ - Mass assignment: if RPC not used, PATCH can update unintended columns; verify restricted columns via database permissions/policies.
49
+ </postgrest_and_rest>
50
+
51
+ <rpc_functions>
52
+ - RPC endpoints map to SQL functions. SECURITY DEFINER bypasses RLS unless carefully coded; SECURITY INVOKER respects caller.
53
+ - Anti-patterns:
54
+ - SECURITY DEFINER + missing owner checks → vertical/horizontal bypass.
55
+ - set search_path left to public; function resolves unsafe objects.
56
+ - Trusting client-supplied user_id/tenant_id rather than auth.uid().
57
+ - Tests:
58
+ - Call /rest/v1/rpc/<fn> as different users with foreign ids in body.
59
+ - Remove or alter JWT entirely (Authorization: Bearer <anon>) to see if function still executes.
60
+ - Validate that functions perform explicit ownership/tenant checks inside SQL, not only in docs.
61
+ </rpc_functions>
62
+
63
+ <storage>
64
+ - Buckets: public vs private; objects live in storage.objects with RLS-like policies.
65
+ - Find misconfigs:
66
+ - Public buckets holding sensitive data: GET https://<ref>.supabase.co/storage/v1/object/public/<bucket>/<path>
67
+ - Signed URLs with long TTL and no audience binding; reuse/guess tokens across tenants/paths.
68
+ - Listing prefixes without auth: /storage/v1/object/list/<bucket>?prefix=
69
+ - Path confusion: mixed case, URL-encoding, “..” segments rejected at UI but accepted by API.
70
+ - Abuse vectors:
71
+ - Content-type/XSS: upload HTML/SVG served as text/html or image/svg+xml; confirm X-Content-Type-Options: nosniff and Content-Disposition: attachment.
72
+ - Signed URL replay across accounts/buckets if validation is lax.
73
+ </storage>
74
+
75
+ <realtime>
76
+ - Endpoint: wss://<ref>.supabase.co/realtime/v1. Join channels with apikey + Authorization.
77
+ - Risks:
78
+ - Channel names derived from table/schema/filters leaking other users’ updates when RLS or channel guards are weak.
79
+ - Broadcast/presence channels allowing cross-room join/publish without auth checks.
80
+ - Tests:
81
+ - Subscribe to public:realtime changes on protected tables; confirm row data visibility aligns with RLS.
82
+ - Attempt joining other users’ presence/broadcast channels (e.g., room:<user_id>, org:<id>).
83
+ </realtime>
84
+
85
+ <graphql>
86
+ - Endpoint: /graphql/v1 using pg_graphql with RLS. Risks:
87
+ - Introspection reveals schema relations; ensure it’s intentional.
88
+ - Overfetch via nested relations where field resolvers fail to re-check ownership/tenant.
89
+ - Global node IDs (if implemented) leaked and reusable via different viewers.
90
+ - Tests:
91
+ - Compare REST vs GraphQL responses for the same principal and query shape.
92
+ - Query deep nested fields and connections; verify RLS holds at each edge.
93
+ </graphql>
94
+
95
+ <auth_and_tokens>
96
+ - GoTrue issues JWTs with claims (sub=uid, role, aud=authenticated). Validate on server: issuer, audience, exp, signature, and tenant context.
97
+ - Pitfalls:
98
+ - Storing tokens in localStorage → XSS exfiltration; refresh mismanagement leading to long-lived sessions.
99
+ - Treating apikey as identity; it is project-scoped, not user identity.
100
+ - Exposing service_role key in client bundle or Edge Function responses.
101
+ - Tests:
102
+ - Replay tokens across services; check audience/issuer pinning.
103
+ - Try downgraded tokens (expired/other audience) against custom endpoints.
104
+ </auth_and_tokens>
105
+
106
+ <edge_functions>
107
+ - Deno-based functions often initialize server-side Supabase client with service_role. Risks:
108
+ - Trusting Authorization/apikey headers without verifying JWT against issuer/audience.
109
+ - CORS: wildcard origins with credentials; reflected Authorization in responses.
110
+ - SSRF via fetch; secrets exposed via error traces or logs.
111
+ - Tests:
112
+ - Call functions with and without Authorization; compare behavior.
113
+ - Try foreign resource IDs in function payloads; verify server re-derives user/tenant from JWT.
114
+ - Attempt to reach internal endpoints (metadata services, project endpoints) via function fetch.
115
+ </edge_functions>
116
+
117
+ <tenant_isolation>
118
+ - Ensure every query joins or filters by tenant_id/org_id derived from JWT context, not client input.
119
+ - Tests:
120
+ - Change subdomain/header/path tenant selectors while keeping JWT tenant constant; look for cross-tenant data.
121
+ - Export/report endpoints: confirm queries execute under caller scope; signed outputs must encode tenant and short TTL.
122
+ </tenant_isolation>
123
+
124
+ <bypass_techniques>
125
+ - Content-type switching: application/json ↔ application/x-www-form-urlencoded ↔ multipart/form-data to hit different code paths.
126
+ - Parameter pollution: duplicate keys in JSON/query; PostgREST chooses last/first depending on parser.
127
+ - GraphQL+REST parity probing: protections often drift; fetch via the weaker path.
128
+ - Race windows: parallel writes to bypass post-insert ownership updates.
129
+ </bypass_techniques>
130
+
131
+ <blind_channels>
132
+ - Use Prefer: count=exact and ETag/length diffs to infer unauthorized rows.
133
+ - Conditional requests (If-None-Match) to detect object existence without content exposure.
134
+ - Storage signed URLs: timing/length deltas to map valid vs invalid tokens.
135
+ </blind_channels>
136
+
137
+ <tooling_and_automation>
138
+ - PostgREST: httpie/curl + jq; enumerate tables with known names; fuzz filters (or=, ilike, neq, is.null).
139
+ - GraphQL: graphql-inspector, voyager; build deep queries to test field-level enforcement; complexity/batching tests.
140
+ - Realtime: custom ws client; subscribe to suspicious channels/tables; diff payloads per principal.
141
+ - Storage: enumerate bucket listing APIs; script signed URL generation/use patterns.
142
+ - Auth/JWT: jwt-cli/jose to validate audience/issuer; replay against Edge Functions.
143
+ - Policy diffing: maintain request sets per role and compare results across releases.
144
+ </tooling_and_automation>
145
+
146
+ <reviewer_checklist>
147
+ - Are all non-public tables RLS-enabled with explicit SELECT/INSERT/UPDATE/DELETE policies?
148
+ - Do policies derive subject/tenant from JWT (auth.uid(), tenant claim) rather than client payload?
149
+ - Do RPC functions run as SECURITY INVOKER, or if DEFINER, do they enforce ownership/tenant inside?
150
+ - Are Storage buckets private by default, with short-lived signed URLs bound to tenant/context?
151
+ - Does Realtime enforce RLS-equivalent filtering for subscriptions and block cross-room joins?
152
+ - Is GraphQL parity verified with REST; are nested resolvers guarded per field?
153
+ - Are Edge Functions verifying JWT (issuer/audience) and never exposing service_role to clients?
154
+ - Are CDN/cache keys bound to Authorization/tenant to prevent cache leaks?
155
+ </reviewer_checklist>
156
+
157
+ <validation>
158
+ 1. Provide owner vs non-owner requests for REST/GraphQL showing unauthorized access (content or metadata).
159
+ 2. Demonstrate a mis-scoped RPC or Storage signed URL usable by another user/tenant.
160
+ 3. Confirm Realtime or GraphQL exposure matches missing policy checks.
161
+ 4. Document minimal reproducible requests and role contexts used.
162
+ </validation>
163
+
164
+ <false_positives>
165
+ - Tables intentionally public (documented) with non-sensitive content.
166
+ - RLS-enabled tables returning only caller-owned rows; mismatched UI not backed by API responses.
167
+ - Signed URLs with very short TTL and audience binding.
168
+ - Edge Functions verifying tokens and re-deriving context before acting.
169
+ </false_positives>
170
+
171
+ <impact>
172
+ - Cross-account/tenant data exposure and unauthorized state changes.
173
+ - Exfiltration of PII/PHI/PCI, financial and billing artifacts, private files.
174
+ - Privilege escalation via RPC and Edge Functions; durable access via long-lived tokens.
175
+ - Regulatory and contractual violations stemming from tenant isolation failures.
176
+ </impact>
177
+
178
+ <pro_tips>
179
+ 1. Start with /rest/v1 list/search; counts and embeddings reveal policy drift fast.
180
+ 2. Treat UUIDs and signed URLs as untrusted; validate binding to subject/tenant and TTL.
181
+ 3. Focus on RPC and Edge Functions—they often centralize business logic and skip RLS.
182
+ 4. Test GraphQL and Realtime parity with REST; differences are where vulnerabilities hide.
183
+ 5. Keep role-separated request corpora and diff responses across deployments.
184
+ 6. Never assume apikey == identity; only JWT binds subject. Prove it.
185
+ 7. Prefer concise PoCs: one request per role that clearly shows the unauthorized delta.
186
+ </pro_tips>
187
+
188
+ <remember>RLS must bind subject and tenant on every path, and server-side code (RPC/Edge) must re-derive identity from a verified token. Any gap in binding, audience/issuer verification, or per-field enforcement becomes a cross-account or cross-tenant vulnerability.</remember>
189
+ </supabase_security_guide>
@@ -1,129 +1,147 @@
1
1
  <authentication_jwt_guide>
2
- <title>AUTHENTICATION & JWT VULNERABILITIES</title>
3
-
4
- <critical>Authentication flaws lead to complete account takeover. JWT misconfigurations are everywhere.</critical>
5
-
6
- <jwt_structure>
7
- header.payload.signature
8
- - Header: {% raw %}{"alg":"HS256","typ":"JWT"}{% endraw %}
9
- - Payload: {% raw %}{"sub":"1234","name":"John","iat":1516239022}{% endraw %}
10
- - Signature: HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
11
- </jwt_structure>
12
-
13
- <common_attacks>
14
- <algorithm_confusion>
15
- RS256 to HS256:
16
- - Change RS256 to HS256 in header
17
- - Use public key as HMAC secret
18
- - Sign token with public key (often in /jwks.json or /.well-known/)
19
- </algorithm_confusion>
20
-
21
- <none_algorithm>
22
- - Set {% raw %}"alg": "none"{% endraw %} in header
23
- - Remove signature completely (keep the trailing dot)
24
- </none_algorithm>
25
-
26
- <weak_secrets>
27
- Common secrets: 'secret', 'password', '123456', 'key', 'jwt_secret', 'your-256-bit-secret'
28
- </weak_secrets>
29
-
30
- <kid_manipulation>
31
- - SQL Injection: {% raw %}"kid": "key' UNION SELECT 'secret'--"{% endraw %}
32
- - Command injection: {% raw %}"kid": "|sleep 10"{% endraw %}
33
- - Path traversal: {% raw %}"kid": "../../../../../../dev/null"{% endraw %}
34
- </kid_manipulation>
35
- </common_attacks>
2
+ <title>AUTHENTICATION AND JWT/OIDC</title>
3
+
4
+ <critical>JWT/OIDC failures often enable token forgery, token confusion, cross-service acceptance, and durable account takeover. Do not trust headers, claims, or token opacity without strict validation bound to issuer, audience, key, and context.</critical>
5
+
6
+ <scope>
7
+ - Web/mobile/API authentication using JWT (JWS/JWE) and OIDC/OAuth2
8
+ - Access vs ID tokens, refresh tokens, device/PKCE/Backchannel flows
9
+ - First-party and microservices verification, gateways, and JWKS distribution
10
+ </scope>
11
+
12
+ <methodology>
13
+ 1. Inventory issuers and consumers: identity providers, API gateways, services, mobile/web clients.
14
+ 2. Capture real tokens (access and ID) for multiple roles. Note header, claims, signature, and verification endpoints (/.well-known, /jwks.json).
15
+ 3. Build a matrix: Token Type × Audience × Service; attempt cross-use (wrong audience/issuer/service) and observe acceptance.
16
+ 4. Mutate headers (alg, kid, jku/x5u/jwk, typ/cty/crit), claims (iss/aud/azp/sub/nbf/iat/exp/scope/nonce), and signatures; verify what is actually enforced.
17
+ </methodology>
18
+
19
+ <discovery_techniques>
20
+ <endpoints>
21
+ - Well-known: /.well-known/openid-configuration, /oauth2/.well-known/openid-configuration
22
+ - Keys: /jwks.json, rotating key endpoints, tenant-specific JWKS
23
+ - Auth: /authorize, /token, /introspect, /revoke, /logout, device code endpoints
24
+ - App: /login, /callback, /refresh, /me, /session, /impersonate
25
+ </endpoints>
26
+
27
+ <token_features>
28
+ - Headers: {% raw %}{"alg":"RS256","kid":"...","typ":"JWT","jku":"...","x5u":"...","jwk":{...}}{% endraw %}
29
+ - Claims: {% raw %}{"iss":"...","aud":"...","azp":"...","sub":"user","scope":"...","exp":...,"nbf":...,"iat":...}{% endraw %}
30
+ - Formats: JWS (signed), JWE (encrypted). Note unencoded payload option ("b64":false) and critical headers ("crit").
31
+ </token_features>
32
+ </discovery_techniques>
33
+
34
+ <exploitation_techniques>
35
+ <signature_verification>
36
+ - RS256→HS256 confusion: change alg to HS256 and use the RSA public key as HMAC secret if algorithm is not pinned
37
+ - "none" algorithm acceptance: set {% raw %}"alg":"none"{% endraw %} and drop the signature if libraries accept it
38
+ - ECDSA malleability/misuse: weak verification settings accepting non-canonical signatures
39
+ </signature_verification>
40
+
41
+ <header_manipulation>
42
+ - kid injection: path traversal {% raw %}../../../../keys/prod.key{% endraw %}, SQL/command/template injection in key lookup, or pointing to world-readable files
43
+ - jku/x5u abuse: host attacker-controlled JWKS/X509 chain; if not pinned/whitelisted, server fetches and trusts attacker keys
44
+ - jwk header injection: embed attacker JWK in header; some libraries prefer inline JWK over server-configured keys
45
+ - SSRF via remote key fetch: exploit JWKS URL fetching to reach internal hosts
46
+ </header_manipulation>
47
+
48
+ <key_and_cache_issues>
49
+ - JWKS caching TTL and key rollover: accept obsolete keys; race rotation windows; missing kid pinning → accept any matching kty/alg
50
+ - Mixed environments: same secrets across dev/stage/prod; key reuse across tenants or services
51
+ - Fallbacks: verification succeeds when kid not found by trying all keys or no keys (implementation bugs)
52
+ </key_and_cache_issues>
53
+
54
+ <claims_validation_gaps>
55
+ - iss/aud/azp not enforced: cross-service token reuse; accept tokens from any issuer or wrong audience
56
+ - scope/roles fully trusted from token: server does not re-derive authorization; privilege inflation via claim edits when signature checks are weak
57
+ - exp/nbf/iat not enforced or large clock skew tolerance; accept long-expired or not-yet-valid tokens
58
+ - typ/cty not enforced: accept ID token where access token required (token confusion)
59
+ </claims_validation_gaps>
60
+
61
+ <token_confusion_and_oidc>
62
+ - Access vs ID token swap: use ID token against APIs when they only verify signature but not audience/typ
63
+ - OIDC mix-up: redirect_uri and client mix-ups causing tokens for Client A to be redeemed at Client B
64
+ - PKCE downgrades: missing S256 requirement; accept plain or absent code_verifier
65
+ - State/nonce weaknesses: predictable or missing → CSRF/logical interception of login\n- Device/Backchannel flows: codes and tokens accepted by unintended clients or services
66
+ </token_confusion_and_oidc>
67
+
68
+ <refresh_and_session>
69
+ - Refresh token rotation not enforced: reuse old refresh token indefinitely; no reuse detection
70
+ - Long-lived JWTs with no revocation: persistent access post-logout
71
+ - Session fixation: bind new tokens to attacker-controlled session identifiers or cookies
72
+ </refresh_and_session>
73
+
74
+ <transport_and_storage>
75
+ - Token in localStorage/sessionStorage: susceptible to XSS exfiltration; cookie vs header trade-offs with SameSite/CSRF
76
+ - Insecure CORS: wildcard origins with credentialed requests expose tokens and protected responses
77
+ - TLS and cookie flags: missing Secure/HttpOnly; lack of mTLS or DPoP/"cnf" binding permits replay from another device
78
+ </transport_and_storage>
79
+ </exploitation_techniques>
36
80
 
37
81
  <advanced_techniques>
38
- <jwk_injection>
39
- Embed public key in token header:
40
- {% raw %}{"jwk": {"kty": "RSA", "n": "your-public-key-n", "e": "AQAB"}}{% endraw %}
41
- </jwk_injection>
42
-
43
- <jku_manipulation>
44
- Set jku/x5u to attacker-controlled URL hosting malicious JWKS
45
- </jku_manipulation>
46
-
47
- <timing_attacks>
48
- Extract signature byte-by-byte using verification timing differences
49
- </timing_attacks>
50
- </advanced_techniques>
51
-
52
- <oauth_vulnerabilities>
53
- <authorization_code_theft>
54
- - Exploit redirect_uri with open redirects, subdomain takeover, parameter pollution
55
- - Missing/predictable state parameter = CSRF
56
- - PKCE downgrade: remove code_challenge parameter
57
- </authorization_code_theft>
58
- </oauth_vulnerabilities>
59
-
60
- <saml_attacks>
61
- - Signature exclusion: remove signature element
62
- - Signature wrapping: inject assertions
63
- - XXE in SAML responses
64
- </saml_attacks>
65
-
66
- <session_attacks>
67
- - Session fixation: force known session ID
68
- - Session puzzling: mix different session objects
69
- - Race conditions in session generation
70
- </session_attacks>
71
-
72
- <password_reset_flaws>
73
- - Predictable tokens: MD5(timestamp), sequential numbers
74
- - Host header injection for reset link poisoning
75
- - Race condition resets
76
- </password_reset_flaws>
77
-
78
- <mfa_bypass>
79
- - Response manipulation: change success:false to true
80
- - Status code manipulation: 403 to 200
81
- - Brute force with no rate limiting
82
- - Backup code abuse
83
- </mfa_bypass>
84
-
85
- <advanced_bypasses>
86
- <unicode_normalization>
87
- Different representations: admin@example.com (fullwidth), аdmin@example.com (Cyrillic)
88
- </unicode_normalization>
89
-
90
- <authentication_chaining>
91
- - JWT + SQLi: kid parameter with SQL injection
92
- - OAuth + XSS: steal tokens via XSS
93
- - SAML + XXE + SSRF: chain for internal access
94
- </authentication_chaining>
95
- </advanced_bypasses>
96
-
97
- <tools>
98
- - jwt_tool: Comprehensive JWT testing
99
- - Check endpoints: /login, /oauth/authorize, /saml/login, /.well-known/openid-configuration, /jwks.json
100
- </tools>
82
+ <microservices_and_gateways>
83
+ - Audience mismatch: internal services verify signature but ignore aud → accept tokens for other services
84
+ - Header trust: edge or gateway injects X-User-Id; backend trusts it over token claims
85
+ - Asynchronous consumers: workers process messages with bearer tokens but skip verification on replay
86
+ </microservices_and_gateways>
87
+
88
+ <jws_edge_cases>
89
+ - Unencoded payload (b64=false) with crit header: libraries mishandle verification paths
90
+ - Nested JWT (JWT-in-JWT) verification order errors; outer token accepted while inner claims ignored
91
+ </jws_edge_cases>
92
+
93
+ <special_contexts>
94
+ <mobile>
95
+ - Deep-link/redirect handling bugs leak codes/tokens; insecure WebView bridges exposing tokens
96
+ - Token storage in plaintext files/SQLite/Keychain/SharedPrefs; backup/adb accessible
97
+ </mobile>
98
+
99
+ <sso_federation>
100
+ - Misconfigured trust between multiple IdPs/SPs, mixed metadata, or stale keys lead to acceptance of foreign tokens
101
+ </sso_federation>
102
+ </special_contexts>
103
+
104
+ <chaining_attacks>
105
+ - XSS token theft → replay across services with weak audience checks
106
+ - SSRF fetch private JWKS → sign tokens accepted by internal services
107
+ - Host header poisoning → OIDC redirect_uri poisoning → code capture
108
+ - IDOR in sessions/impersonation endpoints → mint tokens for other users
109
+ </chaining_attacks>
101
110
 
102
111
  <validation>
103
- To confirm authentication flaw:
104
- 1. Demonstrate account access without credentials
105
- 2. Show privilege escalation
106
- 3. Prove token forgery works
107
- 4. Bypass authentication/2FA requirements
108
- 5. Maintain persistent access
112
+ 1. Show forged or cross-context token acceptance (wrong alg, wrong audience/issuer, or attacker-signed JWKS).
113
+ 2. Demonstrate access token vs ID token confusion at an API.
114
+ 3. Prove refresh token reuse without rotation detection or revocation.
115
+ 4. Confirm header abuse (kid/jku/x5u/jwk) leading to key selection under attacker control.
116
+ 5. Provide owner vs non-owner evidence with identical requests differing only in token context.
109
117
  </validation>
110
118
 
111
119
  <false_positives>
112
- NOT a vulnerability if:
113
- - Requires valid credentials
114
- - Only affects own session
115
- - Proper signature validation
116
- - Token expiration enforced
117
- - Rate limiting prevents brute force
120
+ - Token rejected due to strict audience/issuer enforcement
121
+ - Key pinning with JWKS whitelist and TLS validation
122
+ - Short-lived tokens with rotation and revocation on logout
123
+ - ID token not accepted by APIs that require access tokens
118
124
  </false_positives>
119
125
 
120
126
  <impact>
121
- - Account takeover: access other users' accounts
122
- - Privilege escalation: user to admin
123
- - Token forgery: create valid tokens
124
- - Bypass mechanisms: skip auth/2FA
125
- - Persistent access: survives logout
127
+ - Account takeover and durable session persistence
128
+ - Privilege escalation via claim manipulation or cross-service acceptance
129
+ - Cross-tenant or cross-application data access
130
+ - Token minting by attacker-controlled keys or endpoints
126
131
  </impact>
127
132
 
128
- <remember>Focus on RS256->HS256, weak secrets, and none algorithm first. Modern apps use multiple auth methods simultaneously - find gaps in integration.</remember>
133
+ <pro_tips>
134
+ 1. Pin verification to issuer and audience; log and diff claim sets across services.
135
+ 2. Attempt RS256→HS256 and "none" first only if algorithm pinning is unclear; otherwise focus on header key control (kid/jku/x5u/jwk).
136
+ 3. Test token reuse across all services; many backends only check signature, not audience/typ.
137
+ 4. Exploit JWKS caching and rotation races; try retired keys and missing kid fallbacks.
138
+ 5. Exercise OIDC flows with PKCE/state/nonce variants and mixed clients; look for mix-up.
139
+ 6. Try DPoP/mTLS absence to replay tokens from different devices.
140
+ 7. Treat refresh as its own surface: rotation, reuse detection, and audience scoping.
141
+ 8. Validate every acceptance path: gateway, service, worker, WebSocket, and gRPC.
142
+ 9. Favor minimal PoCs that clearly show cross-context acceptance and durable access.
143
+ 10. When in doubt, assume verification differs per stack (mobile vs web vs gateway) and test each.
144
+ </pro_tips>
145
+
146
+ <remember>Verification must bind the token to the correct issuer, audience, key, and client context on every acceptance path. Any missing binding enables forgery or confusion.</remember>
129
147
  </authentication_jwt_guide>