# Fast Start - Security

**Framework:** KernDX | **Total time:** ~30 minutes

- **What this is:** a way to have every database read and write automatically respect the running user's
  permissions, so you never hand-write a security check.
- **Why it matters:** forgetting one of those checks is how data quietly leaks to someone who should not see it.
  KernDX makes the safe behaviour the default, so the gap can't happen by accident.
- **Who should follow this:** developers writing Apex that touches data, plus the architects and tech leads who set
  security standards for a team.
- **When to use it:** any time your code queries or saves records, which is nearly always.
- **What you'll build:** a service class that reads and writes records through the framework. It gets object
  create/read/update/delete permissions (CRUD) and field-level security (FLS) enforced against the running user by
  default, all without writing a single `Security.stripInaccessible()` call or `WITH USER_MODE` clause.
- **Along the way:** you also see how to get the rows back without the fields the user can't see, instead of an error.
- **Success looks like:** your queries and DML respect the running user's permissions automatically, a
  lower-permission user can't read or write fields they lack access to, and your test class has 100% coverage.
- **In one line:** every `kern.QRY_Builder` query and `kern.DML_Builder` transaction runs in
  `AccessLevel.USER_MODE` by default, so CRUD, field-level security, and sharing are enforced against the running
  user with no extra code.

> **Namespaces in code samples:** `kern.` on a class and `kern__` on an object, field, or metadata type mark the managed package's namespace.
> On the managed package, framework references need those prefixes even where a sample omits them; repackaged under your own namespace, replace `kern`/`kern__`
> with your prefix; on an unmanaged deploy, drop them. See [How to read the code samples](/installation#how-to-read-the-code-samples).

## Before you start

- Open your terminal in your project's top folder, the one that holds `sfdx-project.json`. On Windows that terminal is
  Command Prompt.
- Run the four-line check on [Set Up Your Computer](/set-up-your-computer#check-you-are-ready) once: it proves
  your terminal, the CLI, your login and the KernDX package, and answers what goes wrong. Done that today? Carry on.
- Work in a sandbox or a scratch org, never production.
- Every command below writes `YourOrgAlias` where your org's alias goes: the name you gave it when you logged in.

---

## Tier 1: See It Work (~2 minutes)

KernDX queries and DML are secure by default. You don't add a security call: you get one for free on every
`kern.QRY_Builder` and `kern.DML_Builder` call.

The tries below build each query in place, so that each runs on its own in one window. In your own classes, chain the
same calls on a selector's `query`, as the [Tier 2](#tier-2-build-your-own-20-minutes) service does.

### Secure Query by Default

**In Salesforce**, open the Developer Console (the gear icon, then Developer Console), then Debug, then Open Execute
Anonymous Window, and run:

```apex
// No security method chained — this still runs in USER_MODE.
// CRUD, FLS, and sharing are enforced against YOU, the running user.
List<Account> accounts = kern.QRY_Builder.selectFrom(Account.SObjectType)
		.fields(new List<SObjectField> {Account.Name, Account.AnnualRevenue})
		.withLimit(5)
		.toList();

System.debug('Rows returned: ' + accounts.size());
```

You should see this line in the log; the number is how many Accounts came back, up to five, so yours may be lower:

```text
Rows returned: 5
```

As a system administrator you see every field and every row, so this looks unremarkable. The difference shows
up for a lower-permission user:

- If that user lacks read access on `AnnualRevenue`, the query throws a `System.QueryException` instead of silently
  leaking the value. That is USER_MODE doing its job.
- **USER_MODE** means the query runs with the current user's read and write permissions and record sharing enforced.
- **SYSTEM_MODE** skips the object and field permission checks only. Record sharing keeps following the calling class.

> **Want to prove it?** USER_MODE and SYSTEM_MODE behave identically for an admin (you hold every
> permission). The gap only appears when running as a lower-permission user, which is exactly what the
> `System.runAs()` test in [Tier 2](#step-3-write-tests) demonstrates.

Something went wrong? See [Common Issues, Secure Query by Default](#secure-query-by-default-1).

### Secure DML by Default

Writes are secured the same way. A plain `kern.DML_Builder` transaction runs in USER_MODE.

**In Salesforce**, in the same Execute Anonymous window, run:

```apex
Account account = new Account(Name = 'Secure Test', Phone = '555-0100');

// No .withUserMode() needed — USER_MODE is the default. Insert is checked
// against the running user's create permission on Account and its fields.
kern.DML_Builder.TransactionResult result = kern.DML_Builder.newTransaction()
		.doInsert(account)
		.execute();

System.debug('Insert success: ' + result.isSuccess());
System.debug('Account Id: ' + account.Id);
```

You should see these lines in the log, with your record's Id in place of `001...`:

```text
Insert success: true
Account Id: 001...
```

If the running user lacked create access on `Account`, or write access on a field you set, the insert would
fail with a security error rather than writing data the user was never allowed to touch.

Something went wrong? See [Common Issues, Secure DML by Default](#secure-dml-by-default-1).

### Strip Inaccessible Fields

USER_MODE throws when a query touches a field the user can't read. Sometimes you'd rather **drop** the
unreadable fields and keep going, for example when you query a generous field list but only need whatever the
user is actually allowed to see. Chain `.stripInaccessible()`.

The strip runs after the query returns, so the query itself must not be refused first. In USER_MODE, the platform
refuses the query before the strip can run. So this read:

- uses `.withSystemMode()` to run in SYSTEM_MODE;
- uses `.withSharing()` to keep record sharing.

SYSTEM_MODE does not check the object permission, so use this form only for an object the user may read.

**In Salesforce**, in the same Execute Anonymous window, run:

```apex
// Returns rows with inaccessible fields removed (set to null) instead of throwing.
List<Account> stripped = kern.QRY_Builder.selectFrom(Account.SObjectType)
		.fields(new List<SObjectField> {Account.Name, Account.AnnualRevenue})
		.withSystemMode()
		.withSharing()
		.stripInaccessible()
		.withLimit(5)
		.toList();

System.debug('Rows returned: ' + stripped.size());
```

You should see this line in the log; the number is how many Accounts came back, up to five, so yours may be lower:

```text
Rows returned: 5
```

Under the hood the framework runs `Security.stripInaccessible(AccessType.READABLE, records)` on the result set
after the query returns, so any field the running user can't read is removed from the records you get back.

> **When to move to Tier 2:** When you want to encapsulate secure reads and writes in a reusable service class
> and verify the enforcement with a `System.runAs()` test.

---

## Tier 2: Build Your Own (~20 minutes)

> **No local project?** You can create classes directly in the Developer Console (Gear Icon > Developer
> Console > File > New > Apex Class) and run tests from there too (Test > New Run). Paste the code, save,
> and skip the terminal commands.

Build a small contact-directory service that reads Contacts through the framework and creates new ones. Both
the read and the write inherit USER_MODE, so the service automatically respects whatever the calling user is
allowed to see and do.

### Step 1: Create the Service Class

The service is one class with a method that reads Contacts and a method that creates one. You create an empty class
with one command, paste the code into it, then send it to your org.

**1. In the terminal**, from your project's top folder, create the empty class:

```shell
sf apex generate class --name SVC_ContactDirectory --output-dir force-app/main/default/classes
```

You should see two files created in `force-app/main/default/classes`: `SVC_ContactDirectory.cls` and its companion of
the same name ending in `.cls-meta.xml`.

The second file tells Salesforce which API version the class uses. You never edit it, but a deploy fails without it.

**2. In your editor**, open this file, delete what is there, paste the code below in, and save. Paste it exactly as
it is: keep the class name.

```text
force-app/main/default/classes/SVC_ContactDirectory.cls
```

> **Why `public`?** Unlike triggers and APIs, service classes are called directly by your code. The
> framework doesn't need to resolve them by name, so `global` is not required.

> **Why `with sharing`?** Declaring the service `with sharing` makes the class's record-visibility intent
> explicit. CRUD and FLS already come from USER_MODE, and `with sharing` documents that this class enforces
> record-level sharing too.

```apex
/**
 * @description Contact directory service. Reads and creates Contacts through the framework,
 * inheriting USER_MODE so CRUD and field-level security are enforced against the running user.
 *
 * @see SVC_ContactDirectory_TEST
 *
 * @author your.name@company.com
 *
 * @group Services
 *
 * @date February 2026, November 2026
 */
public with sharing class SVC_ContactDirectory
{
	/**
	 * @description Returns Contacts whose last name matches. Runs in USER_MODE by default, so a user
	 * who cannot read Contacts, or one of the selected fields, gets a QueryException.
	 *
	 * @param lastName The last name to filter by.
	 *
	 * @return Contacts the running user is allowed to see.
	 */
	public List<Contact> findByLastName(String lastName)
	{
		return new SEL_Contacts().query
				.condition(Contact.LastName).equals(lastName)
				.toList();
	}

	/**
	 * @description Creates a Contact. Runs in USER_MODE by default, so the create is checked
	 * against the running user's create access on Contact and on each field set.
	 *
	 * @param firstName The Contact's first name.
	 * @param lastName The Contact's last name.
	 *
	 * @return The result of the insert transaction.
	 */
	public kern.DML_Builder.TransactionResult createContact(String firstName, String lastName)
	{
		Contact newContact = new Contact(FirstName = firstName, LastName = lastName);

		return kern.DML_Builder.newTransaction()
				.doInsert(newContact)
				.execute();
	}

	/**
	 * @description Reads Contacts with the fields this service returns. Every read goes through a selector, so the
	 * fields live in one place and the read gets the framework's security, caching, logging and test mocks.
	 */
	private with sharing class SEL_Contacts extends kern.SEL_Base
	{
		/**
		 * @description Creates the selector for Contacts.
		 */
		public SEL_Contacts()
		{
			super(Contact.SObjectType);
		}

		/**
		 * @description The fields every read returns.
		 *
		 * @return First name, last name and email.
		 */
		public override List<SObjectField> getFields()
		{
			return new List<SObjectField> {Contact.FirstName, Contact.LastName, Contact.Email};
		}
	}
}
```

**3. In the terminal**, send the class to your org:

```shell
sf project deploy start -o YourOrgAlias -m "ApexClass:SVC_ContactDirectory"
```

You should see `Status: Succeeded`, with `SVC_ContactDirectory` listed as created.

Something went wrong? See [Common Issues, Step 1](#step-1-create-the-service-class-1).

### Step 2: Execute

Try the service from anonymous Apex. The code creates a Contact through the service, then reads it back; run it as
one piece, since the read depends on the create.

**In Salesforce**, open the Developer Console (the gear icon, then Developer Console), then Debug, then Open Execute
Anonymous Window, and run:

```apex
kern.DML_Builder.TransactionResult result =
		new SVC_ContactDirectory().createContact('Jane', 'Directory');

System.debug('Create success: ' + result.isSuccess());

List<Contact> found = new SVC_ContactDirectory().findByLastName('Directory');
System.debug('Found: ' + found.size());

for(Contact each : found)
{
	System.debug(each.FirstName + ' ' + each.LastName);
}
```

You should see these lines in the log. `Found` counts every Contact with the last name Directory that you can see, so it may be
higher than 1:

```text
Create success: true
Found: 1
Jane Directory
```

**Why it works, the key patterns:**

- **`new SEL_Contacts().query`**: the read goes through a selector that extends `kern.SEL_Base`, so its fields live in
  one place. The query runs in USER_MODE by default, so CRUD, FLS, and sharing are enforced against the running user
  with no extra method call.
- **A field the user can't read**: the query throws a `QueryException` rather than return it. If you would
  rather get the rows back without that field, see [Strip Inaccessible Fields](#strip-inaccessible-fields).
- **`kern.DML_Builder.newTransaction()...execute()`**: the insert runs in USER_MODE by default, so the create
  is checked against the user's object and field permissions.
- **No security boilerplate**: you never wrote `WITH USER_MODE`, `Security.stripInaccessible(...)`, or a
  manual `Schema.sObjectType.Contact.isCreateable()` check. The framework supplied all of it.

### Step 3: Write Tests

The test class checks the create and the read, and its third test uses `System.runAs()` with a minimum-access user to
prove the enforcement is real, and not just the admin's all-permissions view. You create the empty class with one
command, paste the code into it, send it to your org, then run it.

**1. In the terminal**, from your project's top folder, create the empty test class:

```shell
sf apex generate class --name SVC_ContactDirectory_TEST --output-dir force-app/main/default/classes
```

You should see two files created in `force-app/main/default/classes`: `SVC_ContactDirectory_TEST.cls` and its
companion of the same name ending in `.cls-meta.xml`.

**2. In your editor**, open this file, delete what is there, paste the code below in exactly as it is, and save:

```text
force-app/main/default/classes/SVC_ContactDirectory_TEST.cls
```

```apex
/**
 * @description Unit tests for SVC_ContactDirectory.
 *
 * @see SVC_ContactDirectory
 *
 * @author your.name@company.com
 *
 * @group Services
 *
 * @date February 2026, November 2026
 */
@IsTest(isParallel=false)
private class SVC_ContactDirectory_TEST
{
	/** @description Tests that createContact inserts a Contact in USER_MODE. */
	@IsTest
	private static void shouldCreateContact()
	{
		kern.DML_Builder.TransactionResult result =
				new SVC_ContactDirectory().createContact('Test', 'Person');

		Assert.isTrue(result.isSuccess(), 'Create should succeed for an admin running the test');
		Assert.areEqual(1, result.getSuccessCount(), 'Should insert exactly one Contact');
	}

	/** @description Tests that findByLastName returns matching Contacts. */
	@IsTest
	private static void shouldFindContactsByLastName()
	{
		kern.TST_Builder.of(Contact.SObjectType)
				.withOverride(Contact.FirstName, 'Find')
				.withOverride(Contact.LastName, 'Target')
				.build();

		List<Contact> found = new SVC_ContactDirectory().findByLastName('Target');

		Assert.areEqual(1, found.size(), 'Should return the matching Contact');
		Assert.areEqual('Find', found[0].FirstName, 'Should return the correct Contact');
	}

	/**
	 * @description Proves USER_MODE enforces the *running user's* permissions. A minimum-access user
	 * with no Contact access is rejected by the secure read — the admin running the test would have
	 * sailed straight through, which is exactly the trap USER_MODE closes.
	 */
	@IsTest
	private static void shouldEnforceRunningUserPermissionsOnRead()
	{
		kern.TST_Builder.of(Contact.SObjectType)
				.withOverride(Contact.FirstName, 'Scoped')
				.withOverride(Contact.LastName, 'Reader')
				.build();

		User minimumAccessUser = buildMinimumAccessUser();

		System.runAs(minimumAccessUser)
		{
			try
			{
				new SVC_ContactDirectory().findByLastName('Reader');
				Assert.fail('USER_MODE must reject a user without Contact access');
			}
			catch(Exception error)
			{
				Assert.isInstanceOfType(error, QueryException.class,
						'USER_MODE must reject a user without Contact access, proving the framework enforces '
						+ 'the running user\'s permissions, not the admin\'s');
			}
		}
	}

	/**
	 * @description Builds a minimum-access user for running-user enforcement tests.
	 *
	 * @return A User assigned the Minimum Access profile.
	 */
	private static User buildMinimumAccessUser()
	{
		Profile minimumAccess = new kern.SEL_Profile().findByName('Minimum Access - Salesforce');

		return (User)kern.TST_Builder.of(User.SObjectType)
				.withOverride(User.ProfileId, minimumAccess.Id)
				.withOverride(User.LastName, 'Scoped')
				.withOverride(User.Alias, 'scoped')
				.withOverride(User.Email, 'scoped.reader@example.com')
				.withOverride(User.Username, 'scoped.reader.' + DateTime.now().getTime() + '@example.com')
				.withOverride(User.EmailEncodingKey, 'UTF-8')
				.withOverride(User.LanguageLocaleKey, 'en_US')
				.withOverride(User.LocaleSidKey, 'en_US')
				.withOverride(User.TimeZoneSidKey, 'America/Los_Angeles')
				.build();
	}
}
```

**3. In the terminal**, send the test class to your org:

```shell
sf project deploy start -o YourOrgAlias -m "ApexClass:SVC_ContactDirectory_TEST"
```

You should see `Status: Succeeded`, with `SVC_ContactDirectory_TEST` listed as created.

**4. In the terminal**, run the test:

```shell
sf apex run test -o YourOrgAlias -t SVC_ContactDirectory_TEST --code-coverage --synchronous --result-format human
```

You should see 3 tests passing and 100% coverage on `SVC_ContactDirectory`: all three tests show `Pass`, the summary
line `Outcome` reads `Passed`, and the coverage table shows `SVC_ContactDirectory` at `100%`.

> **About the annotations:**
>
> - This class uses `@IsTest(isParallel=false)` because `buildMinimumAccessUser()` inserts a `User`, and Salesforce
>   blocks DML on setup objects like `User` inside *parallel* test runs.
> - Most test classes should prefer `@IsTest(isParallel=true)` for faster runs. Use `isParallel=false` only when a test
>   does setup-object DML, as this one does.
> - `SeeAllData` defaults to `false`, so we omit it.
> - The `System.runAs()` block in the third test is the right habit for security code: it verifies the framework
>   enforces the *running user's* permissions, which is the entire point of USER_MODE.
> - The `Minimum Access - Salesforce` profile must exist in your org; it ships with every org by default.

Something went wrong? See [Common Issues, Step 3](#step-3-write-tests-1).

---

## Tier 3: Production Patterns (~5 minutes)

### Query Security Methods

`kern.QRY_Builder` gives you independent security options you can combine. In your own classes, chain them on a
selector's `query`, as the [Tier 2](#tier-2-build-your-own-20-minutes) service does.

**In Salesforce**, run these in an Execute Anonymous window; each runs without an error:

```apex
// Default — USER_MODE (CRUD + FLS + sharing enforced against the running user)
List<Account> defaultQuery = kern.QRY_Builder.selectFrom(Account.SObjectType)
		.fields(new List<SObjectField> {Account.Name})
		.withLimit(5)
		.toList();

// Explicit USER_MODE — redundant under the default, useful as belt-and-braces
// (it overrides the org-wide kill switch even if that has been flipped off)
List<Account> userMode = kern.QRY_Builder.selectFrom(Account.SObjectType)
		.fields(new List<SObjectField> {Account.Name})
		.withUserMode()
		.withLimit(5)
		.toList();

// Strip inaccessible fields from the results instead of throwing
// (SYSTEM_MODE with sharing kept: in USER_MODE a hidden field refuses the query)
List<Account> stripped = kern.QRY_Builder.selectFrom(Account.SObjectType)
		.fields(new List<SObjectField> {Account.Name, Account.AnnualRevenue})
		.withSystemMode()
		.withSharing()
		.stripInaccessible()
		.withLimit(5)
		.toList();

// Read records whatever their sharing; the user's object and field permissions still apply
List<Account> everyAccount = kern.QRY_Builder.selectFrom(Account.SObjectType)
		.fields(new List<SObjectField> {Account.Name, Account.AnnualRevenue})
		.bypassSharing()
		.withLimit(5)
		.toList();
```

The full menu of query security methods:

| Method                 | Effect                                                                                              | When to Use                                                      |
|------------------------|-----------------------------------------------------------------------------------------------------|------------------------------------------------------------------|
| *(none, the default)*  | USER_MODE: CRUD, FLS, and sharing enforced against the running user                                 | Every query your users reach                                     |
| `.withUserMode()`      | Forces USER_MODE even if the org-wide kill switch has been flipped off                              | Belt-and-braces enforcement on a critical user-facing read       |
| `.stripInaccessible()` | Removes fields the user can't read from results (post-query) instead of throwing, in SYSTEM_MODE. In USER_MODE a selected field the user can't read still makes the query fail | When you'd rather drop unreadable fields than fail the query (with `.withSystemMode()`) |
| `.withSystemMode()`    | Forces SYSTEM_MODE: bypasses CRUD/FLS for this query only                                           | Framework-internal reads (configuration, framework-owned tables) |
| `.withSharing()`       | Uses a `with sharing` proxy (only has effect in SYSTEM_MODE: USER_MODE enforces sharing anyway)     | Enforce sharing on a SYSTEM_MODE query                           |
| `.bypassSharing()`     | Uses a `without sharing` proxy. In USER_MODE the user's object and field permissions still apply: fields the user can't read are removed from the rows | Read records whatever their sharing (use with caution) |
| `.withoutSecurity()`   | Waives object and field checks and record sharing in one call (SYSTEM_MODE plus the sharing bypass) | System-level reads that must span every record                   |

> **What the sharing methods do in USER_MODE.**
>
> - **`.withSharing()`:** USER_MODE always enforces sharing, so it changes nothing there on its own. After
>   `.bypassSharing()`, it cancels the bypass. Otherwise it matters only in SYSTEM_MODE.
> - **`.bypassSharing()`:** ignores sharing in both modes. In USER_MODE it keeps the user's object and field
>   permissions, and refuses these reads:
>   - a read by a user who can't read the object;
>   - a filter or sort you build on a field the user can't read;
>   - a selected field or a child query through a lookup field or a parent object the user can't read;
>   - selected text KernDX can't check, such as a child query written as text;
>   - `toQueryLocator()`, `toCursor()` and reads of totals or groups, because KernDX can't remove hidden fields from
>     them.
> - **For such a read, add `.withSystemMode()`.** Note that this also turns off the object and field checks.
>
> The [Security Guide](/security-guide#user-mode-vs-sharing-proxy) lists every rule.

Something went wrong? See [Common Issues, Query Security Methods](#query-security-methods-1).

### DML Security Methods

`kern.DML_Builder` follows the same secure-by-default rule. Here are the access-mode and sharing controls:

| Method              | Effect                                                                 | When to Use                                                 |
|---------------------|------------------------------------------------------------------------|-------------------------------------------------------------|
| *(none, the default)* | USER_MODE: object permissions, field-level security, and record sharing all enforced against the running user | Every write your users reach                                |
| `.withUserMode()`   | Forces USER_MODE even if the org-wide kill switch has been flipped off | Belt-and-braces enforcement on a critical user-facing write |
| `.withSystemMode()` | Forces SYSTEM_MODE: bypasses CRUD/FLS for this transaction only        | Framework-owned writes (logs, orchestration rows)           |
| `.bypassSharing()`  | Routes through a `without sharing` proxy (sharing only; not CRUD/FLS). In USER_MODE, fields the user can't create or edit are left out of the save | Isolated calculations that must ignore record-level sharing |

**In your editor**, in your own Apex, where `accountFromUi` and `orchestrationRecord` are the records you are saving:

```apex
// User-facing write: enforce CRUD + FLS (USER_MODE is already the default;
// .withUserMode() makes the intent explicit and survives the kill switch)
kern.DML_Builder.newTransaction()
		.doInsert(accountFromUi)
		.withUserMode()
		.execute();

// Framework-owned write that must run as system (bypass CRUD/FLS)
kern.DML_Builder.newTransaction()
		.doInsert(orchestrationRecord)
		.withSystemMode()
		.execute();
```

> **There is no write-side `stripInaccessible()`.** Stripping inaccessible fields is a read concept.
>
> - **To make an untrusted write respect the user's field permissions,** rely on the USER_MODE default (or
>   `.withUserMode()`). It rejects writes to fields the running user can't update, which is the correct behaviour for a
>   write.
> - **`.bypassSharing()` affects sharing only;** it does **not** turn off USER_MODE's CRUD/FLS enforcement. With it, if
>   the user can't create or edit a field, the save leaves that field out without an error, and one warning in the log
>   names the field.
> - **If the user lacks the object permission this save needs** (create, edit, delete or undelete), the save is still
>   refused.

Something went wrong? See [Common Issues, DML Security Methods](#dml-security-methods-1).

### When to Opt Out of USER_MODE

SYSTEM_MODE is for framework-internal reads and writes: configuration that the running user has no permission
on by design (custom metadata, framework-owned objects, system-schema lookups). Your application code should
almost never need it. When you do, prefer keeping the opt-out local:

- **One query or one transaction:** chain `.withSystemMode()` on that single call.
- **A whole selector that always reads framework-internal data:** subclass `kern.SEL_Base` and override
  `systemModeRequired()` to return `true`. Every query through that selector then runs in SYSTEM_MODE, keeping
  the opt-out in one place instead of scattered across call sites.

**In your editor**, in a new class:

```apex
public with sharing class SEL_MyInternalSetting extends kern.SEL_Base
{
	public SEL_MyInternalSetting()
	{
		// MyInternalSetting__mdt is a stand-in — replace it with your own object or custom metadata type.
		super(MyInternalSetting__mdt.SObjectType);
	}

	public override Boolean systemModeRequired()
	{
		return true;
	}
}
```

### The Org-Wide Kill Switch

If a code change suddenly breaks security enforcement in production, you need a way to turn the secure default
off org-wide without waiting for a deployment. That master off-switch you can flip in an incident is the
kill-switch. Two custom metadata records hold it, and each controls the secure-by-default behaviour across the
whole org:

- `kern__FeatureFlag.UserModeQueries_Enabled` controls the default for every `kern.QRY_Builder` query.
- `kern__FeatureFlag.UserModeDml_Enabled` controls the default for every `kern.DML_Builder` transaction.

Both ship enabled (`IsEnabledByDefault__c = true`).

- **To fall back to SYSTEM_MODE framework-wide for a while,** set the relevant flag's `IsEnabledByDefault__c` to `false` in
  **Setup > Custom Metadata Types > FeatureFlag**. Do this **for emergency rollback only, while offending code is
  fixed**. The next transaction picks it up, and no deploy is required.
- **Do not flip these as a routine configuration lever:** doing so weakens the security posture of every query or
  write your users reach.
- **A call that chained `.withUserMode()` keeps enforcing USER_MODE even with the flag off,** which is why critical
  user-facing paths should opt in explicitly.

Something went wrong? See [Common Issues, The Org-Wide Kill Switch](#the-org-wide-kill-switch-1).

### Field Encryption

Sometimes you need to encrypt a short-lived, session-scoped value, such as a temporary token or wizard state,
without managing keys yourself. For that case, with automatic key management, see the
[Security Guide: Data Encryption](/security-guide#data-encryption-decryption-util-sessionencryption).
For long-term encrypted storage, use Salesforce Shield Platform Encryption.

### Clean up

If you built this example only to try the framework, run this command when you have finished the guide. The
`Secure Test` Account from Tier 1 and the `Jane Directory` Contact from Step 2 stay; delete them in the app, or leave
them.

**In the terminal**, delete the service and its test class:

```shell
sf project delete source -o YourOrgAlias -m "ApexClass:SVC_ContactDirectory_TEST" -m "ApexClass:SVC_ContactDirectory" --no-prompt
```

You should see `Status: Succeeded`, then a `Deleted Source` table listing the two classes.

The command deletes the files from your project too.

Something went wrong? See [Common Issues](#clean-up-1).

---

## Common Issues

Trouble with your computer rather than this guide (`sf` is not recognised, scripts are disabled, you are not logged
in, the wrong folder)? Those are answered once, in
[Set Up Your Computer](/set-up-your-computer#if-something-went-wrong).

### Secure Query by Default

#### A lower-permission user's query fails on a field they cannot read

This is USER_MODE, the default, doing its job: it enforces field-level security (FLS) and stops the query rather than
return a field the user may not read. Chain `.withSystemMode()`, `.withSharing()` and `.stripInaccessible()` to drop
the field instead of failing (see [Strip Inaccessible Fields](#strip-inaccessible-fields)), or grant the user read
access to the field.

### Secure DML by Default

#### An insert or update fails for a lower-permission user

USER_MODE, the default, checks the write against the user's object permissions (CRUD) and field-level security (FLS).
Grant the user the object or field permission they need. Use `.withSystemMode()` only for a framework-owned write,
never to get a user's own write through.

### Step 1: Create the Service Class

#### The deploy says there is nothing to deploy

The deploy stops with `No source-backed components present in the package.` The command ran inside another project's
folder, so the CLI looked for the class there and found nothing. Open the terminal in your own project's top folder,
the one that holds `sfdx-project.json`, and run the command again.

### Step 3: Write Tests

#### The deploy fails

The test class's deploy fails for the same reasons as the service's; see the entries under
[Step 1](#step-1-create-the-service-class-1).

#### Your tests pass, but your users see errors

The tests ran as you, and an admin holds every permission, which hides the enforcement. Add a `System.runAs()` test
with a `Minimum Access - Salesforce` user, as the third test in Step 3 does.

### Query Security Methods

#### `.withSharing()` or `.bypassSharing()` seems to do nothing on a query

- **`.withSharing()`:** USER_MODE already enforces sharing, so it changes nothing there on its own. (After
  `.bypassSharing()`, it cancels the bypass.) Otherwise it takes effect only after `.withSystemMode()`.
- **`.bypassSharing()`:** works in USER_MODE too, but the user's object and field permissions still apply: a field the
  user can't read is removed from the rows. If the code must read that field, add `.withSystemMode()`, which also
  turns off the object and field checks.

### DML Security Methods

#### `DML_Builder` has no `.stripInaccessible()`

Stripping inaccessible fields is a read-side idea, so `kern.DML_Builder` does not offer it. For untrusted writes, use
the USER_MODE default (or `.withUserMode()`), which rejects fields the user cannot write.

### The Org-Wide Kill Switch

#### Every query suddenly runs in SYSTEM_MODE

Someone switched off the `UserModeQueries_Enabled` flag. Set `IsEnabledByDefault__c = true` on the flag, or chain
`.withUserMode()` on critical calls so they keep enforcing USER_MODE either way.

### Clean up

#### `No ApexClass named: SVC_ContactDirectory found`

The command shows `Status: Failed` and a `Component Failures` table with this line, and the same for
`SVC_ContactDirectory_TEST`. The org no longer holds the classes: the clean-up already ran, or they were deleted
another way. There is nothing left to delete.

Still stuck? [Tell us](https://github.com/JVB-Consulting/kerndx/issues/new?template=bug_report.md&title=%5Bdocs%5D%20Security) which step and what you saw.


## What You Now Know

After completing this guide, you understand **secure-by-default data access** in KernDX:

| Concept                    | What It Does                                                                          |
|----------------------------|---------------------------------------------------------------------------------------|
| **USER_MODE default**      | Every `kern.QRY_Builder` query and `kern.DML_Builder` write enforces CRUD/FLS/sharing |
| **`.stripInaccessible()`** | Removes fields the user can't read from query results instead of throwing, in SYSTEM_MODE |
| **`.withSystemMode()`**    | Per-call opt-out for framework-internal reads/writes (bypasses CRUD/FLS)              |
| **`systemModeRequired()`** | Per-selector opt-out so framework-internal selectors always run SYSTEM_MODE           |
| **Kill-switch flags**      | `UserModeQueries_Enabled` and `UserModeDml_Enabled`, for emergency org-wide rollback only |

**Key patterns:**

- **Write nothing for the common case:** USER_MODE is the default, so secure reads and writes need no extra code.
- **`.stripInaccessible()` for graceful reads:** with `.withSystemMode()`, drop unreadable fields instead of failing
  the query.
- **`System.runAs()` in tests:** prove enforcement with a lower-permission user, because admins mask it.
- **Opt out locally, not globally:** `.withSystemMode()` per call or `systemModeRequired()` per selector, and
  reserve the kill-switch flags for emergencies.
- **There is no write-side strip:** for untrusted writes, USER_MODE rejects fields the user can't update.

---

## Next Steps

- [Selectors (secure query patterns)](/fast-start-selectors)
- [DML Builder (secure writes)](/fast-start-dml)
- [Test Data Patterns](/fast-start-test-data)
- [Code Scanning (catch security anti-patterns)](/fast-start-code-scanning)
- [Complete Security Guide](/security-guide)
- [QRY_Builder Reference](/reference/apex/qry-builder)
- [DML_Builder Reference](/reference/apex/dml-builder)
