Skip to content

Add Security rules for Appwrite PHP conventions - #14062

Merged
abnegate merged 24 commits into
mainfrom
cursor/semgrep-static-rules-eb3f
Oct 7, 2026
Merged

abnegate merged 24 commits into
mainfrom
cursor/semgrep-static-rules-eb3f

Conversation

@abnegate

@abnegate abnegate commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Adds Security rules under .semgrep/ for Appwrite PHP coding conventions and wires them into CI. Rules are written as general pattern classes with allowlists, not lists of files or collections. CI changes only; no product code changes.

  • New ERROR findings fail Checks / Rules (and the scheduled Scan Rules job).
  • New WARNING findings do not fail the job. They are posted as one sticky PR comment (<!-- semgrep-rules-comment -->) that is updated in place. Findings are grouped by rule. Each one has:
    • a file:line link to the scanned commit;
    • where it is: method + path + scope for routes, the hook and its groups, Class::method(), or the init resource;
    • a short What's wrong and How to fix built from the matched code.
  • Baselined findings (.semgrep/baseline.json) neither fail the job nor appear in detail on the comment. The comment shows them only as per-rule counts in a collapsed block. They are still written to SARIF.
  • Incomplete scans. The comment step runs under always(). If semgrep.json is missing or unreadable (because the install, fixtures, proofs, or scan failed), the sticky comment says the scan did not complete and links the run. It does not post an all-clear.

Baseline. Merging this PR does not change the result for other PRs. .semgrep/baseline.json records the 32 findings on the current tree, which is main merged into this branch. Semgrep OSS only supports a commit-diff baseline, so .semgrep/baseline.js filters the JSON scan itself:

  • check prints totals, lists new findings and stale entries, and exits 1 on any new ERROR.
  • update regenerates the file.

Entries are keyed on rule id, path, and the whitespace-collapsed matched text, so line shifts elsewhere in a file do not resurface them. When the match spans a module route chain, the ->setHttpPath(…) line is part of the key. A route is therefore identified by both method and path, and replacing a baselined route with a different one surfaces as new. The regeneration steps are in .semgrep/README.md.

ERROR classes (23). These have 0 findings on the current tree.

Area Rules
Route declarations route-without-scope (every /v1 route declares a scope), route-without-api-group (non-public routes run the shared api hooks), redirect-param-without-validator
Authorization skip-ungated-load, global-authorization-disable, related-permissions-helper
Credential responses account-token-secret-scope-gate (now covers module action() methods and Key in any position), show-sensitive-outside-payload, insecure-cookie-flags
Guest-reachable input guest-url-without-publicurl (any URL-like param name, URL() or Text()), unbounded-map-to-outbound (any Assoc param name; a class-level ALLOWED_* constant counts as filtered), header-blocklist-filter
Request metadata client-ip-header (all forwarding headers and accessors, including host and proto)
Secrets and randomness default-secret-placeholder (a class of placeholder literals), insecure-random
Outbound clients tls-verification-disabled
Request-serving code unsafe-dynamic-code, shell-exec-in-handler, superglobal-in-handler, debug-output-in-handler, raw-sql-interpolation, xml-external-entities, request-path-to-filesystem (taint from request getters or string action params; realpath() alone does not sanitize, only a base-directory containment guard does)

WARNING classes (5). These have 32 findings on the current tree, all in the baseline. A class can be promoted to ERROR once its entries are cleared.

Rule Findings
guest-write-without-abuse-limit 17
permissive-write-permission 8
secret-compare-timing 5
weak-secret-env-default 2
Notes for rule authors (also in .semgrep/README.md):
  • Builtins need both spellings, for example unserialize(...) and \unserialize(...).
  • Route-level conditions match the whole method chain. Positive conditions go in metavariable-regex so that negative conditions can still see the full chain.
  • New rules add an entry to explainers in .github/workflows/semgrep-comment.js.

Test Plan

  • semgrep test .semgrep passes 28/28. Every rule has a sibling .php fixture with ruleid and ok cases. semgrep --validate reports 28 rules and 0 errors with baseline.js / baseline.json present.
  • request-path-to-filesystem fixture:
    • An unchecked file_get_contents(realpath($base . '/' . $request->getParam('path'))) is flagged.
    • A realpath() result read without a check is flagged.
    • A realpath() result whose failed str_starts_with check only logs is flagged.
    • It stays clean after an exiting str_starts_with or substr + strlen guard, and inside a positive str_starts_with branch.
    • On the tree, the ACME challenge route in app/controllers/general.php, which uses the substr guard, stays clean.
  • bash .semgrep/prove.sh:
    • Runs an ERROR-only scan (no baseline) on one known-bad snippet per ERROR rule and asserts that the scan fails with that rule id.
    • Asserts that a file of house patterns produces no ERROR findings. The patterns include gated skips, PublicURL, redirectValidator, ALLOWED_HEADERS, getIP(), random_bytes, bound SQL, basename, httponly cookies, and event-payload showSensitive. A second clean file mirrors EncryptionKey (a PLACEHOLDER constant, comparisons against it, and a Console::warning naming it).
  • CI-equivalent scan on src/Appwrite app/controllers app/init:
    • Without a baseline: 32 findings (0 ERROR).
    • With the baseline: baseline.js check reports 32 baselined, 0 new ERROR, 0 new WARNING, and exits 0.
  • Baseline behaviour:
    • Inserting lines at the top of a baselined file keeps its finding matched.
    • Adding Permission::write(Role::any()) next to baselined lines gives 2 new WARNINGs (exit 0).
    • An injected eval($request->getParam(...)) file gives 1 new ERROR (exit 1).
    • Changing the setHttpPath of a baselined guest-write route (same method, still no abuse limit) gives 1 new WARNING and 1 stale entry.
  • Comment rendering:
    • The current tree renders the all-clear plus a collapsed per-rule summary of the 32 baselined findings.
    • A missing semgrep.json and a truncated one each replace the sticky comment with the "Scan did not complete" notice and a run link. This was checked against a stubbed GitHub client.
    • With a partial baseline, only the unbaselined findings are listed in detail, each with a link, location, What's wrong, and How to fix.
    • Without a baseline, the full 32 findings render to about 21k characters.
  • Formatter stress test: all 130 fixture findings, copied into one module directory, get an explanation. The comment stops at 59.5k characters with an "omitted" note.

Related PRs and Issues

  • None.

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs? (N/A: no API changes.)
Open in Web Open in Cursor 

Wire a Checks / Rules job into PR CI and the scheduled security scan so
common skip, token-response, outbound-map, header-filter, and nested
permission patterns fail the build instead of waiting on review.

Co-authored-by: Jake Barnby <[email protected]>
@github-advanced-security

Copy link
Copy Markdown

You are seeing this message because GitHub Code Scanning has recently been set up for this repository, or this pull request contains the workflow file for the Code Scanning tool.

What Enabling Code Scanning Means:

  • The 'Security' tab will display more code scanning analysis results (e.g., for the default branch).
  • Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results.
  • You will be able to see the analysis results for the pull request's branch on this overview once the scans have completed and the checks have passed.

For more information about GitHub Code Scanning, check out the documentation.

cursoragent and others added 2 commits October 2, 2026 03:00
Expand skip and token-response matching, drop screenshots path excludes
in favor of WARNING review signal, and add client-IP and placeholder-secret
checks. ERROR scan on current main stays clean.

Co-authored-by: Jake Barnby <[email protected]>
Replace the userdata skip list with an allowlisted skip+load class, cover
token/JWT output, related-permission name families, guest ROLE_GUESTS
scopes, and guest URL params without PublicURL. Leave known screenshots
sites as WARNING instead of path excludes.

Co-authored-by: Jake Barnby <[email protected]>
@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → cursor/semgrep-static-rules-eb3f (after).

Metric Before After Change
🚀 Requests/sec 191.43 198.49 ⚪ +3.7%
⏱️ Latency P50 88.24 ms 87.68 ms ⚪ -0.6%
⏱️ Latency P95 214.77 ms 204.29 ms ⚪ -4.9%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 87.68 204.29 12,597 198.49 -10.49
Account 163.68 312.19 663 11.03 -59.17
TablesDB 84.53 156.68 6,851 110.3 -18
Storage 80.27 180.31 3,315 55.05 +3.84
Functions 124.17 256.07 1,768 29.96 +16.68

Top API waits (after)

API request Max wait (ms)
account.prefs.update 556.53
functions.variables.update 442.98
account.name.update 433.88
functions.delete 417.52
storage.buckets.create 384.96

cursoragent and others added 3 commits October 2, 2026 03:33
…on PRs.

Drop the named-collection ERROR leftover. Ungated skip+load of any
non-allowlisted collection now fails CI; fixtures and prove.sh show a
known-bad snippet fails and a gated skip does not. Checks / Rules upserts
one sticky PR comment for WARNING (and ERROR) findings.

Co-authored-by: Jake Barnby <[email protected]>
Rename `static-  rules` to `static-rules`. GitHub job ids cannot contain spaces, which left Checks / Rules (and the rest of CI) unscheduled.

Co-authored-by: Jake Barnby <[email protected]>
@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

32 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (17)
  • php.appwrite.permissive-write-permission (8)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

cursoragent and others added 6 commits October 2, 2026 04:03
Replace the three-column table (160-char mid-sentence clip) with a bullet
list of file:line, rule id, and the complete rule message. Drop whole
findings only when the comment would exceed GitHub's size limit.

Co-authored-by: Jake Barnby <[email protected]>
client-ip-header covers every forwarding header and accessor; the
placeholder rule matches a literal class; guest URL and Assoc rules match
any URL-like / map param on ROLE_GUESTS scopes and honour class ALLOWED_*
allowlists; the token gate covers module action() methods and Key in any
position; header-blocklist-filter is ERROR now that main is clean.

Co-authored-by: Jake Barnby <[email protected]>
Every /v1 route needs a scope label, non-public routes need the api hook
group, redirect-target params need redirectValidator, and guest-scoped
writes without an abuse limit are surfaced as WARNING.

Co-authored-by: Jake Barnby <[email protected]>
Dynamic code, process execution, disabled TLS verification, superglobals,
request-wide authorization disable, showSensitive outside event payloads,
non-cryptographic randomness, libxml entity loading, interpolated SQL,
non-httponly cookies, debug output, and request-derived filesystem paths.

Co-authored-by: Jake Barnby <[email protected]>
Secret env defaults, non-constant-time secret comparisons, any/guests
write permissions, and outbound clients that follow redirects. Each has
live findings on main and is listed on the sticky PR comment.

Co-authored-by: Jake Barnby <[email protected]>
prove.sh runs the real ERROR scan on one known-bad snippet per ERROR rule,
asserts the expected rule id, and checks a file of house patterns stays
clean. README gains a full trigger matrix and rule-writing notes.

Co-authored-by: Jake Barnby <[email protected]>
@cursor cursor Bot changed the title Add custom Semgrep rules for authorization and data-handling review Add in-repo Semgrep rule classes for Appwrite PHP conventions Oct 2, 2026
cursoragent and others added 7 commits October 2, 2026 05:45
EncryptionKey on main declares the public default as a PLACEHOLDER
constant and compares against it; constant propagation made every use
an ERROR. Comparisons, warning/exception messages and a PLACEHOLDER
constant are now ok, while another class's PLACEHOLDER as a getEnv
default is caught explicitly.

Co-authored-by: Jake Barnby <[email protected]>
…mment.

The formatter reads each matched file from the checkout to resolve the
HTTP method, path and scope (or hook, Class::method, init resource), then
prints a per-rule What's wrong / How to fix built from the matched code,
with a link to the scanned commit. Findings are grouped by rule so the
full rule message appears once per group.

Co-authored-by: Jake Barnby <[email protected]>
@cursor cursor Bot changed the title Add in-repo Semgrep rule classes for Appwrite PHP conventions Add Security rules for Appwrite PHP conventions Oct 2, 2026
@abnegate
abnegate marked this pull request as ready for review October 2, 2026 08:45
@ghost

ghost commented Oct 2, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

No concrete defects were found in the incremental changes after checking surrounding code, database resolution, authorization, and existing concurrent-commit coverage.

Adds 28 custom Semgrep security rules with PHP fixtures, scratch proofs, baseline enforcement, SARIF uploads, and sticky PR comments. The refreshed baseline records 32 existing warnings. The PR also adds native-crash checks to E2E CI jobs and updates transaction commits to resolve the target database, reject cross-instance operations, and claim commits under a lock with authorization-aware access.

Latest changes: The newest commits add E2E native-crash checks, refresh the baseline, extend nested transaction-load fixtures, and update database resolution and atomic commit claiming.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 9
File Change
.github/workflows/ci.yml Adds security-rule validation and reporting, plus native-crash checks for E2E jobs.
.github/workflows/security-scan.yml Adds scheduled security-rule scanning and baseline enforcement.
.github/workflows/semgrep-comment.js Renders grouped findings and maintains a sticky PR comment, including incomplete-scan notices.
.gitignore Ignores temporary scratch-proof files.
.semgrep/README.md Documents rules, baseline maintenance, local validation, and PR reporting.
.semgrep/baseline.js, .semgrep/baseline.json Filters known findings using source-based keys and records 32 existing warnings.
.semgrep/*.yml, .semgrep/*.php Adds 28 security rules and fixtures, including nested transaction-load cases.
.semgrep/prove.sh Checks that known-bad snippets trigger ERROR rules and approved house patterns remain clean.
src/Appwrite/Platform/Modules/Databases/Http/Databases/Transactions/Update.php Resolves physical collections through the target database, rejects cross-instance transactions, and atomically claims commits with caller-specific authorization.

Reviewed the commits since 2d1b260 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

Comment thread .semgrep/request-path-to-filesystem.yml Resolved
Comment thread .github/workflows/semgrep-comment.js Resolved
Comment thread .semgrep/baseline.js Resolved
cursoragent and others added 3 commits October 4, 2026 00:18
…ard in request-path-to-filesystem.

Co-authored-by: Jake Barnby <[email protected]>
… all-clear when semgrep.json is missing.

Co-authored-by: Jake Barnby <[email protected]>
…ute at the same method is not baselined.

Co-authored-by: Jake Barnby <[email protected]>

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

The atomic claim loads transactions inside an unconditional Authorization
skip, which skip-ungated-load flags as ERROR. Gate it the same way as the
first load so session users go through document ACL and only API keys or
privileged callers skip.

Drop the retired Assistant from the security-rules baseline after merging
main, and cover the withTransaction skip shape in the fixture.
@abnegate

abnegate commented Oct 7, 2026

Copy link
Copy Markdown
Member Author

Follow-up after the last run:

  • Antivirus (dedicated) failed on a GCR image-pull timeout (timeout awaiting response headers) before any tests ran. That job is a flake; it will re-run on this push.
  • Branch was 167 commits behind main, including the Assistant removal and the atomic transaction-commit claim (425653ae8a). Merged main.
  • New ERROR on current main: skip-ungated-load on the commit lock in Transactions/Update.php (getDocument('transactions') inside an unconditional skip). Gated that skip on API-key / privileged callers, same as the first load, and added a withTransaction fixture case.
  • Baseline now 32 WARNINGs (dropped the retired Assistant outbound-follow-redirects site). 0 new ERROR, 0 new WARNING.

Local: semgrep test .semgrep 28/28, prove.sh clean, scan 32/32 baselined.

@abnegate
abnegate merged commit fc5a6c1 into main Oct 7, 2026
96 checks passed
@abnegate
abnegate deleted the cursor/semgrep-static-rules-eb3f branch October 7, 2026 05:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants