Metadata-Version: 2.5
Name: sfsec
Version: 0.3.1
Summary: Read-only Salesforce org security scanner
Author: sfsec contributors
License-Expression: MIT
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: click<9,>=8.1
Requires-Dist: defusedxml<1,>=0.7.1
Requires-Dist: httpx<1,>=0.27
Requires-Dist: jinja2<4,>=3.1
Requires-Dist: pydantic<3,>=2
Requires-Dist: pyyaml<7,>=6
Requires-Dist: rich<15,>=13
Provides-Extra: dev
Requires-Dist: bandit<2,>=1.8; extra == 'dev'
Requires-Dist: jsonschema<5,>=4.23; extra == 'dev'
Requires-Dist: mypy<2,>=1.13; extra == 'dev'
Requires-Dist: pip-audit<3,>=2.7; extra == 'dev'
Requires-Dist: pytest-cov<7,>=5; extra == 'dev'
Requires-Dist: pytest<10,>=9.0.3; extra == 'dev'
Requires-Dist: respx<1,>=0.21; extra == 'dev'
Requires-Dist: ruff<1,>=0.8; extra == 'dev'
Requires-Dist: types-defusedxml<1,>=0.7; extra == 'dev'
Description-Content-Type: text/markdown

# sfsec

`sfsec` is a read-only command-line scanner for Salesforce org security
configuration. It collects a snapshot from one org, then analyses that
snapshot offline. Rules do not receive an HTTP client and do not call the
network. The same snapshot and the same config produce the same JSON report,
except `generated_at`, which is the time the report was built. `duration_ms`
is always `0`. The analysis clock defaults to `meta.collected_at`.

Two modules run unless you narrow them:

- **security** is the org security catalogue. It owns the top-level score
  (0–100) and grade. An unsuppressed critical finding caps the score at 49.
  An unsuppressed high finding caps it at 69. Grades are A at 90, B at 80,
  C at 70, D at 60, and F below that. `NOT_EVALUATED` does not lower the
  score. It lowers coverage. Coverage below 70% adds a warning.
- **practices** is Platform Health. The console prints it as `health=`. It
  does not change the security grade. A practices-only run leaves the
  top-level JSON `score` null.

The catalogue is 142 rules: 92 security and 50 practices. The generated list,
including each rule's datasets, risk, remediation, and reference URL, is
[docs/RULES.md](docs/RULES.md). That file is produced by
`sfsec rules list --format md`. Do not edit it by hand.

How the pieces fit together is [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
Choices that are not obvious from the code are
[docs/DECISIONS.md](docs/DECISIONS.md).

The tool does not phone home. After collection finishes, analysis and diff
do not use the network.

## Install

Python 3.10 or newer. The console script is `sfsec`. `python -m sfsec` is
the same entry point.

```bash
pipx install .
```

For development:

```bash
python3.12 -m venv .venv
.venv/bin/pip install -e '.[dev]'
```

Runtime libraries are `click`, `defusedxml`, `httpx`, `jinja2`, `pydantic`
v2, `pyyaml`, and `rich`. CI tests 3.10, 3.11, 3.12, 3.13, and 3.14.

## Quick start

Authenticate with the Salesforce CLI, then pass that alias on every command.
`sfsec` does not change the CLI's default org.

```bash
sf org login web --alias my-org
sfsec doctor --target-org my-org
sfsec scan --target-org my-org --fail-on high
```

`scan` writes `./sfsec-report-<orgid>-<timestamp>/` with `snapshot.json`,
`report.json`, and `report.html`, and prints the console summary. It then
opens `report.html` in the local browser. `--no-open` skips that. `--quiet`
prints one summary line and still opens the page.

To analyse a snapshot you already have:

```bash
sfsec analyze snapshot.json --fail-on high
sfsec diff previous.json current.json
```

`analyze` with no `--format` writes `report.json` and `report.html` in the
working directory (or under `--out`) and opens the HTML file.
`--format json` writes only JSON and does not open a browser.

## Commands

`--debug` and `--quiet` work on the top-level group and on `scan`,
`analyze`, `collect`, and `doctor`. `sfsec scan --quiet` and
`sfsec --quiet scan` both print one summary line. A usage error prints
Click's message and exits 2, with no traceback.

### `sfsec version`

Prints `sfsec` and the package version from `src/sfsec/version.py`.

### `sfsec doctor`

Checks connectivity, negotiates the API version, reads org limits, and
describes each dataset. It does not query rows. For every dataset the user
cannot read, it prints the missing permission or feature and the commands
that deploy `scanner-permset`. Exit 2 on auth or config failure. A describe
that Salesforce refuses is reported in the text. It is not a finding.

### `sfsec collect`

Writes one snapshot and nothing else. The client cannot send a write.

```bash
sfsec collect --target-org my-org --out snapshot.json
```

Flags:

- `--target-org`, `--instance-url`, `--access-token-stdin`, `--api-version`
  (default `62.0`), `--allow-custom-host`. See Authentication.
- `--concurrency` (default 4) and `--max-records` (default 50000). Both must
  be at least 1.
- `--force` skips the preflight that remaining daily API requests are at
  least 500. It does not raise the org's limit. If the limit is hit mid-run,
  datasets that have not finished are `error` with reason `api_limit`.
- `--no-source` skips Apex, Visualforce, Aura, and LWC bodies.
- `--redact-pii` replaces usernames, emails, names, and IP addresses before
  the snapshot is returned. See [docs/PRIVACY.md](docs/PRIVACY.md).
- `--deep` runs capped aggregate queries for ownership skew and account data
  skew. Those rules stay `NOT_EVALUATED` without it. The query cost is stored
  on the snapshot.
- `--strict` exits 3 when any dataset status is `error`. The snapshot is
  still written.
- `--out` is required and is a file path.

The summary line is `ok`, `unavailable`, `error`, `skipped`, and `api_calls`.

### `sfsec scan`

Collects a snapshot and analyses it. `--out` is always a directory. When it
is omitted, the directory is `./sfsec-report-<orgid>-<timestamp>/`, with the
org id and timestamp reduced to letters and digits. The default formats are
`console,json,html`, so the directory receives `snapshot.json` (unless
`--no-save-snapshot`), `report.json`, and `report.html`.

```bash
sfsec scan --target-org my-org --format json,html,sarif,csv,md --out ./sfsec-out
```

Flags shared with collect: auth, `--api-version`, `--allow-custom-host`,
`--concurrency`, `--max-records`, `--force`, `--no-source`, `--redact-pii`,
`--deep`, `--strict`. Additional flags:

- `--format` is a comma-separated list of `console`, `json`, `html`, `sarif`,
  `csv`, and `md`. Unknown names are an error. Duplicates are dropped.
- `--open` / `--no-open` (default open). When `html` is one of the formats,
  the command opens `report.html` in the local browser after the file is
  written. See the HTML section.
- `--save-snapshot` / `--no-save-snapshot` (default save).
- `--config` points at a YAML file. See Configuration.
- `--fail-on` is `critical`, `high`, `medium`, `low`, `info`, or `none`.
  It applies to security findings only. The flag overrides the config. When
  neither is set, the threshold is `high`. `none` does not fail the process
  on findings.
- `--fail-on-practices` is the same scale for Platform Health findings.
  Omitted means the process does not fail on practices findings.
- `--modules` is a comma-separated list of `security` and `practices`.
  Omitted means both. `--modules security,practices` is both. At least one
  name is required.
- `--only` and `--skip` take a rule id or a category, and can be repeated.
- `--baseline` is a previous report JSON file. `--fail-on-new` fails only
  findings that are new versus that baseline, at the same threshold. It
  requires `--baseline`. `none` does not fail on new findings either. A
  baseline from another org, or from another major version of sfsec, still
  produces the diff and adds a warning. The warning does not include the
  org id.
- `--overwrite` is required when `--out` already exists and is not empty.
  A symlink is refused.
- `--quiet` prints one line, for example
  `score=49 grade=F high=3 coverage=80% health=72`. A practices-only run
  starts with `health=` and has no `score=`.

A file path passed to `scan --out` is an error. Report files are written
inside the directory as `report.json`, `report.html`, `report.sarif`,
`report.csv`, and `report.md`.

### `sfsec analyze`

Reads a snapshot and writes reports. No network calls.

```bash
sfsec analyze snapshot.json --format json,html,sarif,csv,md --out ./sfsec-out
```

The default format is `console,json,html`. `--out` may be a single file when
its suffix is the only file format (`.json`, `.html`, `.htm`, `.sarif`,
`.csv`, `.md`, `.markdown`). A mix of formats needs a directory. Without
`--out`, files are `report.json` and `report.html` in the working directory.
`--overwrite` is required for a non-empty directory. `--max-snapshot-bytes`
defaults to 64 MiB and refuses a larger snapshot. The other analysis flags
match `scan`: `--config`, `--fail-on`, `--fail-on-practices`, `--modules`,
`--only`, `--skip`, `--baseline`, `--fail-on-new`, and `--open` / `--no-open`.
`--strict` is not on `analyze`. A dataset that was already `error` in the
snapshot stays a coverage gap or an empty input. It does not by itself exit 3.

### `sfsec rules`

```bash
sfsec rules list
sfsec rules list --format md
sfsec rules list --format json --module practices --category "Apex Quality"
sfsec rules show PRIV-001
```

`list` prints a table, JSON, or the markdown catalogue. `--module` is
`security` or `practices`. `--category` matches the rule's category,
case-insensitive. `show` prints one rule's module, category, severity,
required datasets, description, risk, remediation, and reference URLs.
An unknown id exits 2.

### `sfsec diff`

Compares two report JSON files by fingerprint. The first argument is the
baseline. The second is the current run.

```bash
sfsec diff previous.json current.json
sfsec diff previous.json current.json --format json
```

The console report is `new`, `resolved`, and `unchanged`. JSON is those same
three fields. This command does not write HTML and does not open a browser.
Suppressed findings are not part of the diff. The org and version warnings
described under `--baseline` are printed by `scan` and `analyze`, not by
`diff`.

## Authentication

There is no `--access-token` flag, so the token does not land in shell
history. `--target-org` and `--instance-url` together are a config error.
Resolution order:

1. `--target-org` runs `sf org display --target-org <alias> --json`.
   `sfdx force:org:display` is used only when the `sf` binary is missing.
   On Windows the `sf.cmd` shim is resolved with `which`.
2. `--instance-url` plus `SFSEC_ACCESS_TOKEN`, or `--access-token-stdin`.

A 401 retries once with a refreshed session when a target org can be
refreshed. The requested `--api-version` is then capped at the highest
version the org lists.

The instance URL must be https, without embedded credentials. The host must
match one of these suffixes, exactly or as a subdomain, unless
`--allow-custom-host` is set: `salesforce.com`, `force.com`,
`salesforce-setup.com`, `sfcrmproducts.cn`, `salesforce.mil`,
`cloudforce.com`, `crmforce.mil`. `salesforce.com` covers
`my.salesforce.com`, sandbox, scratch, and enhanced domains. Government
Cloud uses `salesforce.mil` and `crmforce.mil`.

TLS verification cannot be turned off. A corporate proxy is the standard
`HTTPS_PROXY` variable. Point `SSL_CERT_FILE` or `REQUESTS_CA_BUNDLE` at a
corporate CA bundle.

## What a scan checks

Each rule has a stable id, a category, a severity, the datasets it needs, a
description, a risk, a remediation that names a Setup path, and at least one
`https` reference. `sfsec rules show <id>` prints that record.
[docs/RULES.md](docs/RULES.md) is the full catalogue.

Missing permissions, missing fields, unlicensed features, and API errors do
not crash a scan. Dataset statuses are `ok`, `unavailable`, `error`, or
`skipped`. A rule whose dataset is missing becomes `NOT_EVALUATED` with the
dataset reason and, when it is known, the permission name. One rule that
raises becomes `ERROR`. The other rules still run.

### Security

The security module is the score you gate CI on.

| Category | What it looks at | Reference used by those rules |
| --- | --- | --- |
| Authentication | Users without MFA or SSO, administrators without an MFA method, privileged profiles without login IP ranges, SAML signature and version, auth providers, username-password API logins | [MFA](https://help.salesforce.com/s/articleView?id=sf.security_mfa.htm&type=5), [network access](https://help.salesforce.com/s/articleView?id=sf.security_networkaccess.htm&type=5), [SAML](https://help.salesforce.com/s/articleView?id=sf.sso_saml.htm&type=5), [auth providers](https://help.salesforce.com/s/articleView?id=sf.sso_provider_parent.htm&type=5), [OAuth flows](https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_flows.htm&type=5) |
| Privileged Access | Modify All Data and View All Data holders, powerful permission sets, integration users, Password Never Expires, who can edit access, profiles cloned from System Administrator, Export Reports, object-level view-all and modify-all, MFA bypass, assignment expiry | [User permissions](https://help.salesforce.com/s/articleView?id=sf.admin_userperms.htm&type=5), [permission sets](https://help.salesforce.com/s/articleView?id=sf.perm_sets_overview.htm&type=5) |
| User Hygiene | Stale logins, privileged users who have not logged in, never-logged-in users, frozen users, failed logins, legacy TLS, shared-looking interactive accounts | [Deactivate users](https://help.salesforce.com/s/articleView?id=sf.users_deactivate.htm&type=5), [freeze](https://help.salesforce.com/s/articleView?id=sf.users_freeze.htm&type=5), [login history](https://help.salesforce.com/s/articleView?id=sf.users_login_history.htm&type=5) |
| Session Security | Timeout, lock sessions to IP and domain, logout on timeout, clickjack, CSRF, HttpOnly, XSS and content sniffing, cache and autocomplete, email and IP enforcement, HTTPS and Login As | [Session settings](https://help.salesforce.com/s/articleView?id=sf.admin_sessions.htm&type=5) |
| Password Policy | Length, complexity, invalid attempts, lockout, history, obscured secret answer, expiration | [Password policies](https://help.salesforce.com/s/articleView?id=sf.security_overview_passwords.htm&type=5). Expiration `Never` is informational. The finding names NIST Special Publication 800-63B: forced rotation is not required when MFA is enforced. |
| Network | Org and profile trusted IP ranges, remote site settings, CSP trusted sites, CORS origins, named credentials that use `http://` | [Network access](https://help.salesforce.com/s/articleView?id=sf.security_networkaccess.htm&type=5), [remote sites](https://help.salesforce.com/s/articleView?id=sf.configuring_remoteproxy.htm&type=5), [CSP trusted sites](https://help.salesforce.com/s/articleView?id=sf.csp_trusted_sites.htm&type=5), [CORS](https://help.salesforce.com/s/articleView?id=sf.extend_code_cors.htm&type=5) |
| Sharing | External and internal org-wide defaults on sensitive objects, custom-object external access, unbounded guest sharing, criteria-based guest sharing on a sensitive object, portal and internal-edit rules | [Org-wide defaults](https://help.salesforce.com/s/articleView?id=sf.security_sharing_owd_about.htm&type=5), [sharing rules](https://help.salesforce.com/s/articleView?id=sf.security_about_sharing_rules.htm&type=5), [guest sharing rules](https://help.salesforce.com/s/articleView?id=platform.security_sharing_rules_guest.htm&type=5) |
| Guest Access | Active sites, guest object permissions scored against least privilege, API Enabled, view-all and name lookup, insecure Apex, field access on sensitive objects, guest settings, flows a guest can run | [Secure guest users](https://help.salesforce.com/s/articleView?id=sf.networks_secure_guest_users.htm&type=5), [guest record access](https://help.salesforce.com/s/articleView?id=platform.networks_guest_user_record_best_practices.htm&type=5), [guest sharing rules](https://help.salesforce.com/s/articleView?id=platform.security_sharing_rules_guest.htm&type=5) |
| Integrations | Connected-app self-authorization, unused OAuth tokens, refresh-token lifetime, Full scope with relaxed IP restrictions, PKCE and refresh secrets, certificates, installed packages, named-credential principals | [Connected apps](https://help.salesforce.com/s/articleView?id=sf.connected_app_overview.htm&type=5), [OAuth settings](https://help.salesforce.com/s/articleView?id=sf.connected_app_manage_oauth.htm&type=5), [certificates](https://help.salesforce.com/s/articleView?id=sf.security_keys_about.htm&type=5) |
| Custom Code | Sharing keywords, dynamic SOQL and SOSL, CRUD and FLS, hardcoded secrets and ids, Visualforce encoding, Aura and LWC DOM sinks, `http://` callouts, sensitive debug, weak hashes, open redirects, old API versions | [Sharing keywords](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_keywords_sharing.htm), [SOQL injection](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/pages_security_tips_soql_injection.htm), [enforcing CRUD and FLS](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_perms_enforcing.htm), [secure coding](https://developer.salesforce.com/docs/atlas.en-us.secure_coding_guide.meta/secure_coding_guide/secure_coding_guidelines.htm), [Visualforce XSS](https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_security_tips_xss.htm) |
| Monitoring | Risky setup changes in 90 days, Event Monitoring log files, Transaction Security policies, long-lived or guest trace flags, a scan that ran in a sandbox | [Setup audit trail](https://help.salesforce.com/s/articleView?id=sf.admin_monitorsetup.htm&type=5), [Event Monitoring](https://help.salesforce.com/s/articleView?id=sf.elf_event_monitoring.htm&type=5), [Transaction Security](https://help.salesforce.com/s/articleView?id=sf.enhanced_transaction_security_about.htm&type=5) |
| Data Exposure | Public file links without a password or expiry, externally available documents, Shield tenant secrets | [Content deliveries](https://help.salesforce.com/s/articleView?id=sf.content_delivery_about.htm&type=5), [Shield Platform Encryption](https://help.salesforce.com/s/articleView?id=sf.security_pe_overview.htm&type=5) |
| Health Check | The org Health Check score, and high, medium, and low risk settings | [Health Check](https://help.salesforce.com/s/articleView?id=sf.security_health_check.htm&type=5) |

Session and password rules are Health Check fallbacks. When
`health_check_risks` was collected, those fallbacks are `NOT_EVALUATED`
with reason `covered by Salesforce Health Check (HC-002/HC-003)` and they
are left out of the coverage denominator. `SESS-006` (CSRF on GET and POST)
is not a fallback. It still runs from `security_settings`. A missing key is
skipped. Only an explicit false value fails.

Code findings are heuristic. A safe pattern in a comment is ignored. A
method that enforces user mode anywhere in that method is treated as
enforcing it for the whole method. Managed-package source is not queried.
Guest checks read configuration. They do not open a site or log in as the
guest user. Shield and Event Monitoring are presence checks, not log-content
analysis.

### Guest users

A public Experience Cloud site or Salesforce Site has one guest user. Some
object access is expected. [Guest user security](https://help.salesforce.com/s/articleView?id=sf.networks_secure_guest_users.htm&type=5)
allows that profile Read and Create, and removes View All, Modify All, Edit,
and Delete. [Guest record access](https://help.salesforce.com/s/articleView?id=platform.networks_guest_user_record_best_practices.htm&type=5)
keeps guest org-wide defaults Private. Records are published only through a
[guest user sharing rule](https://help.salesforce.com/s/articleView?id=platform.security_sharing_rules_guest.htm&type=5),
which is criteria-based and Read only. The Spring '22 release note records
the same object-permission limit:
[read and create only](https://help.salesforce.com/s/articleView?id=release-notes.rn_experiences_guest_user_license_update.htm&language=en_US&release=236&type=5).

`GUEST-002` uses that split. Read on an object outside `sensitive_objects` is
not a finding. Create on such an object is not a finding. Read or Create on a
sensitive object (Account, Contact, Lead, Case, Opportunity, User, and the
rest of the default list) is medium. Edit or Delete is high. View All Records
or Modify All Records is critical. `SHARE-004` flags a guest sharing rule with
no criteria as critical, because it shares every record. A criteria-based Read
rule on a sensitive object is medium. A criteria-based Read rule on any other
object is not a finding. `GUEST-005` still fails `without sharing` as critical
and an `@AuraEnabled` or `@RemoteAction` method that declares neither
`with sharing` nor `inherited sharing` as high. `GUEST-009` covers the
Visualforce case those class grants miss: a page enabled for the guest whose
controller or extension is insecure. Salesforce does not require that
controller to be in Enabled Apex Class Access. Platform login and error pages
are ignored.

[AuraInspector](https://github.com/google/aura-inspector) is Mandiant's public
scanner for this exposure. Its write-up,
[Auditing Salesforce Aura for Data Exposure](https://cloud.google.com/blog/topics/threat-intelligence/auditing-salesforce-aura-data-exposure/),
shows a guest Aura request listing every record of an object when sharing and
object permissions allow it. The Aura methods are normal site traffic. The
misconfiguration is the guest profile and the guest sharing rule. `sfsec` scores
that configuration from the org. It does not call the Aura endpoint.

### Platform Health

Platform Health uses the same scoring formula and does not change the
security grade. The research notes for these rules are
[docs/BEST_PRACTICES_RESEARCH.md](docs/BEST_PRACTICES_RESEARCH.md).

| Category | Ids | What it looks at | Reference used by those rules |
| --- | --- | --- | --- |
| Apex Quality | BPA | SOQL or DML in loops, trigger shape, empty catch, `@future`, API version and size, tests, org and class coverage, debug statements | [Trigger best practices](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_bestpract.htm), [governor limits](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm), [testing](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_best_practices.htm) |
| Data Model | BPD | Ownership skew and account data skew (only with `--deep`), custom-field count, field descriptions, duplicate rules, inactive validation rules | [Ownership skew](https://developer.salesforce.com/docs/atlas.en-us.draes.meta/draes/draes_group_membership_data_skew.htm), [parent-child skew](https://developer.salesforce.com/docs/atlas.en-us.draes.meta/draes/draes_object_relationships_parent_child_data_skew.htm) |
| Automation | BPF | Active workflow rules, Process Builder, record-triggered flow order, DML or query inside a flow loop, fault paths, flow API version, inactive versions, objects that mix triggers, flows, and workflow | [Migrate to Flow](https://help.salesforce.com/s/articleView?id=sf.migrate_to_flow.htm&language=en_US), [Flow metadata](https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_visual_workflow.htm) |
| Limits | BPL | Data and file storage, daily API, async Apex, Bulk API, email, platform events, custom objects and fields near the edition cap | [Limits resource](https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_limits.htm), [edition limits](https://help.salesforce.com/s/articleView?id=xcloud.overview_limits_enterprise.htm&language=en_US&type=5) |
| Operations | BPO | Async job failure rate, failed batch and queueable jobs | [AsyncApexJob](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_asyncapexjob.htm) |
| Access Model | BPU | Custom profile count, empty permission sets, role depth, scheduled jobs owned by inactive users, integration users that look like named humans | [Permission set best practices](https://help.salesforce.com/s/articleView?id=sf.perm_sets_best_practices.htm&language=en_US&type=5), [profiles](https://help.salesforce.com/s/articleView?id=platform.admin_userprofiles.htm&language=en_US&type=5) |
| Experience | BPX | Users still on Salesforce Classic, old Visualforce API versions, Aura bundles with no LWC, Experience sites not on an enhanced domain | [Domain](https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_domain.htm) |

### Score

Each evaluated category starts at 100 and loses points for unsuppressed
`FAIL` findings. The deduction for one rule is capped at twice that rule's
weight. Weights are critical 15, high 8, medium 3, low 1, and info 0. The
overall score is the rounded mean of categories that had at least one pass
or fail, then capped: an unsuppressed critical finding limits it to 49, and
otherwise an unsuppressed high finding limits it to 69. The cap does not
raise a score that is already lower. When nothing was evaluated, the overall
score is 100. Coverage is evaluated rules divided by applicable rules.
Disabled rules, and Health Check fallbacks that did not run, are not in the
denominator. The formula is the same for both modules.
[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) records it.

### Suppressions and baselines

A suppression matches a rule, or a rule plus an entity id. `expires` is
inclusive. An expired suppression is ignored and warned. Suppressed findings
do not change the score, do not fail CI, and are not part of the baseline
diff. The fingerprint is the first 16 hex characters of
`sha256(rule_id + '|' + sorted affected ids)`. The hash uses the full id
list, not the list capped for display.

## Reports

JSON is the canonical model: sorted keys and a stable result order. Console,
HTML, SARIF, CSV, and Markdown are derived from that model. They are not a
second analysis.

### Console

Prints the org, edition, sandbox or production, the scanning user, the
security score and coverage when security ran, Platform Health when that
module ran, finding counts, the top findings, rules that were not evaluated,
rule errors, warnings, and the baseline diff. Org-controlled text is stripped
of ANSI and Rich markup before it is printed. `--quiet` is the single line
described under `scan`.

### JSON

`report.json` is the file other tools should parse. `score` and `summary`
are the security module, or null when security did not run. `modules.security`
and `modules.practices` are present only for modules that ran. Each result is
`PASS`, `FAIL`, `NOT_EVALUATED`, or `ERROR`, with `duration_ms` of 0.

### HTML

`report.html` is one self-contained file. The stylesheet and one script are
inline. Jinja autoescape is on. The content-security policy allows no
network (`connect-src 'none'`), no external script or font, and no
`unsafe-inline`. The stylesheet and the script are hashed, and those hashes
are the policy. Reference links are rendered only for `https` URLs that have
a host and no username or password. A `javascript:` URL, an `http:` URL, and
a URL with embedded credentials are not links.

The page is a review of the run:

- The header is the org, edition, sandbox or production, score, Platform
  Health, coverage, finding counts, and how many rules passed. Click a
  severity in the legend to filter to it. Click it again to clear.
- **Findings**, **Gaps**, **Errors**, **Suppressed**, and **All** switch the
  list. Gaps are rules that returned `NOT_EVALUATED`. Errors are rules that
  raised. Suppressed findings stay out of the score.
- The list is sorted by that status, then severity, then rule id, then
  fingerprint. Search, category, module, and status narrow it further.
- The selected row shows the gap (the reason the check did not run, for a
  gap or an error), the severity, the evidence, and the feedback. Feedback
  is the rule's remediation. An empty remediation says "No feedback." A gap
  has no org evidence. The page says that, and names the datasets the rule
  requires when the rule is registered. Evidence for a finding is the
  finding's evidence object, with keys sorted.
- Up and Down, or `j` and `k`, move between visible rows. Home and End jump.
  Slash focuses search. Escape clears it. The same detail is in each row's
  disclosure, so the page still reads with scripting off and when printed.
- Security category scores and Platform Health cards show a number and a
  letter. The number is that category's score, from 0 to 100. The letter is
  the grade: A 90+, B 80+, C 70+, D 60+, F below 60. The same scale is on
  the page, above each grid. Grades come from
  [src/sfsec/engine/scoring.py](src/sfsec/engine/scoring.py). The formula is
  in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).

`scan` and `analyze` open this file after it is written. The address passed
to the browser is a `file:` URI of that path. The access token is not in the
file and not in the URI. `--no-open` does not call the browser. If no
browser can open the file, the command prints `warning: could not open …`
on stderr and keeps the exit code the findings would have produced. The file
mode is `0600`, in a directory of mode `0700`.

### SARIF

SARIF 2.1.0. The `$schema` written into the file is
`https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json`.
One driver rule per rule id, one result per `FAIL` finding.
`security-severity` is a string score (critical 9.5, high 8.0, medium 5.5,
low 3.0, info 0.0). `CODE-*` findings get an SFDX `physicalLocation` under
`force-app/main/default/...` and a line number, so GitHub code scanning can
annotate a repository. Tests validate the document against the vendored
2.1.0 schema.

### CSV

One row per affected item. A cell that a spreadsheet would treat as a formula
(`=`, `+`, `-`, `@`, the full-width forms of those characters, a full-width
space before them, or a leading tab, CR, or LF) is prefixed with a quote.
`module` is the last column.

### Markdown

A summary plus findings grouped by severity, including a diff section when a
baseline was supplied. Org-controlled text is escaped so a pull-request
renderer cannot gain a link, image, HTML tag, heading, table cell, or
mention from a class name or an org name.

## Configuration

Copy `sfsec.example.yaml` to `sfsec.yaml` and pass `--config`. Every key is
optional. Unknown keys are an error.

- `fail_on` — `critical`, `high`, `medium`, `low`, `info`, or `none`.
  Omitted means `high`. `none` does not fail the process on security findings.
- `fail_on_practices` — the same values for Platform Health. Omitted, null,
  or `none` means the process does not fail on practices findings.
- `modules` — a list of `security` and `practices`. Omitted means both.
- `rules.disable` — rule ids that become `NOT_EVALUATED`.
- `rules.severity_overrides` — replace a rule's severity.
- `thresholds` — numeric limits. Defaults are
  `max_modify_all_data_users` 3, `max_view_all_data_users` 5,
  `inactive_days` 90, `privileged_inactive_days` 30,
  `oauth_token_unused_days` 90, `cert_expiry_warning_days` 30,
  `failed_login_threshold` 10, `session_timeout_max_minutes` 120,
  `min_password_length` 12, `max_system_debug` 10, `limits_warn_percent` 75,
  `limits_high_percent` 90, `apex_chars_warn_percent` 80,
  `apex_chars_high_percent` 90, `min_apex_coverage` 75,
  `max_custom_profiles` 20, `max_role_depth` 10,
  `max_inactive_validation_rules` 10, `many_custom_fields` 100,
  `field_doc_min_fields` 10, `obsolete_flow_versions` 10,
  `async_failure_min_jobs` 5, `old_api_version` 45.0.
  `sensitive_objects` defaults to Account, Contact, Lead, Case, Opportunity,
  User, Contract, Order, Asset, and Quote.
- `suppressions` — `rule`, optional `entity`, `reason`, and `expires`.

## Permissions

Minimum access so a scan finishes is **API Enabled** and **View Setup and
Configuration**. Datasets the user cannot read become `NOT_EVALUATED`. The
scan still finishes.

Full coverage also needs the permissions in
[docs/PERMISSIONS.md](docs/PERMISSIONS.md), including Modify All Data for
Health Check, Manage Multi-Factor Authentication in API, View All Users, and
Author Apex. The permission set in `scanner-permset` grants that list. It
does not grant `TwoFactorApi`. That permission requires MFA on API logins and
does not make `TwoFactorMethodsInfo` visible. Salesforce will not save Author
Apex, Customize Application, Modify All Data, or Manage Multi-Factor
Authentication in API by themselves, so the permission set includes the
dependencies those four require. The scanner still only sends read requests.

```bash
sf project deploy start -d scanner-permset --target-org X
sf org assign permset -n SFSEC_Scanner --target-org X
```

## Exit codes and CI

| Code | Meaning |
| --- | --- |
| 0 | No unsuppressed finding at or above the fail threshold. |
| 1 | A finding at or above the threshold, or a new one with `--fail-on-new`. |
| 2 | Usage, authentication, configuration, or a snapshot or report that cannot be read. |
| 3 | `scan --strict` or `collect --strict`, and at least one dataset status is `error`. The report or snapshot is still written. |
| 130 | Interrupted. Output files are not left half-written. |

`--fail-on` reads security findings. `--fail-on-practices` reads Platform
Health and defaults to off. In CI, prefer a dedicated user and the JWT bearer
flow. Do not print `sf org display` and do not commit the key. Pass
`--no-open` so a headless runner does not try to launch a browser. The
example uploads nothing by itself. The workflow in this repo uploads SARIF
only on a push to `main`.

```yaml
- name: Authenticate
  env:
    SFDX_AUTH_URL: ${{ secrets.SFDX_AUTH_URL }}
  run: echo "$SFDX_AUTH_URL" | sf org login sfdx-url --sfdx-url-stdin --alias ci-org
- name: Scan
  run: sfsec scan --target-org ci-org --fail-on high --no-open --format sarif --out sfsec-report
```

The SARIF file is `sfsec-report/report.sarif`.

```bash
sf org login jwt \
  --client-id "$SF_CONSUMER_KEY" \
  --jwt-key-file "$SF_JWT_KEY_FILE" \
  --username "$SF_USERNAME" \
  --instance-url https://login.salesforce.com \
  --alias ci-org
sfsec scan --target-org ci-org --fail-on high --no-open --format sarif,json --out sfsec-report
```

## Production

Use a dedicated user. Do not scan with a shared administrator login. The
client still refuses every write. The permissions are what Salesforce
requires before it returns each dataset.

Reports and the snapshot are mode `0600` in a directory mode `0700`. Pass
`--redact-pii` before a report leaves the machine. Login-history addresses
are stored as an IPv4 `/24` or an IPv6 `/64` either way. Content-distribution
URLs keep the scheme and host only. Hardcoded secrets in source are masked
(the first four characters, then `***`) before the snapshot is written.
`consumerSecret` is stripped from connected-app metadata. See
[docs/PRIVACY.md](docs/PRIVACY.md) and
[docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).

## Read-only client

The client raises before sending anything other than `GET`, or a SOAP POST
whose Body is exactly one of `listMetadata`, `readMetadata`, or
`describeMetadata` on `/services/Soap/m/<version>`. A Body with zero or
several children is refused. Redirects are not followed. An absolute URL is
sent only when it is https and its host and port are the instance URL, so
the access token is never sent to another host. Public `get()` is limited to
versions, limits, sObject describes, and the queries the collectors use.

SOAP is parsed with `defusedxml`. `<!DOCTYPE` and `<!ENTITY` are rejected,
and the body is capped. Access tokens live in a secret string. They are
scrubbed from logs, exceptions, snapshots, and reports. `--debug` tracebacks
set `show_locals` off. Output is written by atomic replace. A symlink
destination is refused.

## Troubleshooting

- `sf` is missing. Install the Salesforce CLI, or pass `--instance-url` and
  `SFSEC_ACCESS_TOKEN`.
- The instance host is rejected. It must be https and one of the suffixes
  under Authentication. `--allow-custom-host` is the explicit exception.
  Credentials in the URL are rejected.
- Daily API limit during the scan. Remaining datasets are `error` with
  reason `api_limit`, and the report is still written. `--strict` then
  exits 3. `--force` only skips the preflight check of 500 remaining
  requests.
- A rule is `NOT_EVALUATED`. The reason names the missing dataset, permission,
  or licence (Experience Cloud, Sites, Shield, Event Monitoring, Health
  Check, MFA). That is not a scan error. Open the HTML report and choose
  Gaps to read the reason and the remediation.
- Connected-app metadata can return `UNKNOWN_EXCEPTION` for one name, often
  a managed package. Those names are recorded as `fullName:ERROR_CODE`. The
  dataset stays `ok` when another name was read. A rule does not pass while
  any name failed. External client apps are collected the same way, without
  consumer keys or secrets.
- The output directory is not empty. Pass `--overwrite`. A symlink is refused.
- The browser did not open. The HTML file is still on disk. Reopen
  `report.html` locally, or pass `--no-open` on a machine with no display.
  The warning does not change the exit code.
- `--debug` logs at DEBUG. The access token is scrubbed from log lines and
  exception text.

## Limitations

- No write-back and no auto-remediation.
- No hosted web application. The review page is a file on the machine that
  ran the scan.
- No unauthenticated probing of Experience Cloud. Guest checks read
  configuration.
- No Shield or Event Monitoring log-content analysis beyond presence checks.
- Managed-package source is not scanned.
- Code findings are heuristic.
- A scratch-org run is recorded in
  [docs/LIVE_VALIDATION.md](docs/LIVE_VALIDATION.md) and
  [docs/LIVE_TESTING_GUIDE.md](docs/LIVE_TESTING_GUIDE.md). Counts there are
  from those orgs, not a guarantee for every org. `testorg/` seeds an
  intentionally insecure scratch org.

## Development

Tests must not call the network and must not use a real org. Client and
collector tests use `respx` against `https://example.test`. Fixtures under
`tests/fixtures/snapshots/` are synthetic. Do not commit tokens, usernames,
emails, or real org ids. Do not commit `reports/`, `sfsec-report-*/`, or
`*.snapshot.json`.

```bash
.venv/bin/ruff check .
.venv/bin/ruff format --check .
.venv/bin/mypy src/sfsec
.venv/bin/pytest -q --cov=sfsec
.venv/bin/pip-audit --skip-editable
.venv/bin/bandit -r src -ll
```

Coverage fails under 90%. mypy is strict. The pytest dev dependency is 9.0.3
or newer. CI runs those checks. The `package` job builds a wheel and smokes
`sfsec version` plus `sfsec analyze` on
`tests/fixtures/snapshots/insecure_org.json`. SARIF from that fixture is
uploaded only on a push to `main`. A tag `vX.Y.Z` that matches `sfsec version`
publishes that same wheel. How to open a pull request, what review `main`
requires, and how to cut that tag are in [CONTRIBUTING.md](CONTRIBUTING.md).
Report a vulnerability through GitHub private security advisories, as
[SECURITY.md](SECURITY.md) describes. Do not open a public issue that
contains a snapshot, a report, a token, a session id, a username, or an org id.

## Further reading

- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) — commands, client, snapshot, scoring, reports
- [docs/DECISIONS.md](docs/DECISIONS.md) — choices the code alone does not explain
- [docs/RULES.md](docs/RULES.md) — generated catalogue, one section per rule
- [docs/PERMISSIONS.md](docs/PERMISSIONS.md) — what the scanning user must be able to read
- [docs/PRIVACY.md](docs/PRIVACY.md) — what a snapshot keeps and how to share it
- [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) — what the tool is defending against
- [docs/AUDIT.md](docs/AUDIT.md) — review findings and how they were closed
- [docs/BEST_PRACTICES_RESEARCH.md](docs/BEST_PRACTICES_RESEARCH.md) — sources for Platform Health
- [CHANGELOG.md](CHANGELOG.md) — what each version shipped
