Apex Inherited Sharing

Introduction

Salesforce apex with sharing or without sharing keywords on a class to specify whether sharing rules must be enforced. Use the inherited sharing keyword on an Apex class to run the class in the sharing mode of the class that called it. Apex without a sharing declaration is insecure by default. Designing Apex classes that can run in either with sharing or without sharing mode at runtime is an advanced technique. Such a technique can be difficult to distinguish from one where a specific sharing declaration is accidentally omitted. An explicit inherited sharing declaration makes the intent clear, avoiding ambiguity arising from an omitted declaration or false positives from security analysis tooling.

Using inherited sharing enables you to pass AppExchange Security Review and ensure that your privileged Apex code is not used in unexpected or insecure ways. An Apex class with inherited sharing runs as with sharing when used as a Lightning component controller, a Visualforce controller, an Apex REST service, or any other entry point to an Apex transaction.

There is a distinct difference between an Apex class that is marked with inherited sharing and one with an omitted sharing declaration. If the class is used as the entry point to an Apex transaction, an omitted sharing declaration runs as without sharing. However, inherited sharing ensures that the default is to run as with sharing. A class declared as inherited sharing runs as without sharing only when explicitly called from an already established without sharing context.

This example declares an Apex class with inherited sharing and a Visualforce invocation of that Apex code. Because of the inherited sharing declaration, only contacts for which the running user has sharing access are displayed. If the declaration is omitted, even contacts that the user has no rights to view are displayed due to the insecure default behavior of omitting the declaration.

 

 

Apex Crypto Example

Salesforce Crypto Provides methods for creating digests, message authentication codes, and signatures, as well as encrypting and decrypting information.
The methods in the Crypto class can be used for securing content in Lightning Platform, or for integrating with external services such as Google or Amazon Webservices (AWS).The cryptographic capabilities of the Crypto class are normally used in the following scenarios:
  • Confidentiality – the protection of data either at rest or in transit from unauthorized parties
  • Integrity – the data is complete and correct
  • Authenticity – proof of the authenticity of the sender or receiver of the message

Encryption and Decryption

Salesforce supports encrypt and decrypt information using AES128, AES192, and AES256 algorithms. Currently, only symmetric private key encryption using the AES algorithm is supported. The length of privateKey must match the specified algorithm: 128 bits, 192 bits, or 256 bits, which is 16, 24, or 32 bytes, respectively. You can use a third-party application or the generateAesKey method to generate this key for you.Here is the example that will show encryption and decryption.

AES128 algorithms

AES192 algorithms

AES256 algorithms

Encrypt Decrypt With ManagedIV

Decrypts the Blob IVAndCipherText using the specified algorithm and private key. Use this method to decrypt blobs encrypted using a third party application or the encryptWithManagedIV method. These are all industry standard Advanced Encryption Standard (AES) algorithms with different size keys. They use cipher block chaining (CBC) and PKCS5 padding.The length of privateKey must match the specified algorithm: 128 bits, 192 bits, or 256 bits, which is 16, 24, or 32 bytes, respectively. You can use a third-party application or the generateAesKey method to generate this key for you.
AES128 algorithms

AES192 algorithms

AES256 algorithms

 

Digital signature 

Computes a unique digital signature for the input string, using the specified algorithm and the supplied private key.The algorithm name. The valid values for algorithmName are RSA-SHA1RSA-SHA256, or RSA.RSA-SHA1 is an RSA signature (with an asymmetric key pair) of a SHA1 hash.

You can use Salesforce Certificate to use for signing as shown below.The Unique Name for a certificate stored in the Salesforce organization’s Certificate and Key Management page to use for signing.

 

 

Apex Callouts in Read-Only Mode

let’s understand how to handler the apex callouts during the salesforce read-only mode.During read-only mode, Apex callouts to external services execute and aren’t blocked by the system. Typically, you might execute some follow-up operations in the same transaction after receiving a response from a callout. For example, you might make a DML call to update a Salesforce record. But write operations in Salesforce, such as record updates, are blocked during read-only mode. Instance refreshes result in periods of read-only mode to facilitate infrastructure upgrades. Another is site switches. Continuous site switching enables Salesforce to improve our operations and infrastructure and meet the compliance requirement of many of our customers. Planned instance refreshes and site switches will put your Salesforce org in read-only mode for a portion of your preferred maintenance windows. To check whether the org is in read-only mode, call  System.getApplicationReadWriteMode(). The following example checks the return value of System.getApplicationReadWriteMode(). If the return value is equal to ApplicationReadWriteMode.READ_ONLY enum value, the org is in read-only mode and the callout is skipped. Otherwise (ApplicationReadWriteMode.DEFAULT value), the callout is performed.

To test read-only mode in the sandbox, contact Salesforce to enable the read-only mode test option. Once the test option is enabled, you can toggle read-only mode on and verify your apps. Here is the  code

 

 

Chatter Private Messages Trigger

Write a trigger for ChatterMessage to automate the moderation of private messages in an organization or community. Use triggers to ensure that messages conform to your company’s messaging policies and don’t contain blacklisted words.Although you can create an after insert trigger, ChatterMessage is not updatable, and consequently, any after insert trigger that modifies ChatterMessage will fail at runtime with an appropriate error message.Here the trigger

This example shows a before insert trigger on ChatterMessage that is used to review each new message. This trigger calls a class method, moderator.review(), to review each new message before it is inserted. If a message violates your policy, for example when the message body contains blacklisted words, you can prevent the message from being sent by calling the Apex addError method. You can call addError to add a custom error message on a field or on the entire message. The following snippet shows a portion of the review content method that adds an error to the message Body field.

 

The below image show when you are trying to send the chatter message with the body that contains blacklisted words then it will through an error message.

Salesforce Apex Scheduler

Introduction:-

In this blog post, we are going to see how to use salesforce apex scheduling capabilities which support invoking the Apex class at specific times like daily or weekly or even every minute. To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the schedule using either the Schedule Apex page in the Salesforce user interface or the System.schedule method.

Apex Syntax

To schedule an Apex class to run at regular intervals, first, write an Apex class that implements the Salesforce-provided interface Schedulable.The schedulable interface is having the only execute method.

execute method will take the SchedulableContext object as an argument which will help to track the scheduled job once it’s scheduled. The SchedulableContext getTriggerID method returns the ID of the CronTrigger object associated with this scheduled job as a string. You can query CronTrigger to track the progress of the scheduled job.To stop the execution of a job that was scheduled, use the System.abortJob method with the ID returned by the getTriggerID method.Here is the sample code

Scheduling Apex

You can schedule the salesforce apex by using System.Schedule method or by using Salesforce UI. The main difference is Salesforce UI won’t support the Schedule job in Seconds and minutes which can be done with System.Schedule.The System.Schedule method uses the user’s timezone on the basis of all schedules, but runs in system mode—all classes are executed, whether or not the user has permission to execute the class.The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and the name of the class. This expression has the following syntax:

The following are some examples of how to use the expression.

Expression Description
0 0 13 * * ? Class runs every day at 1 PM.
0 0 22 ? * 6L Class runs the last Friday of every month at 10 PM.
0 0 10 ? * MON-FRI Class runs Monday through Friday at 10 AM.
0 0 20 * * ? 2010 Class runs every day at 8 PM during the year 2010.

Below code shows how to schedule apex by using the system.schedule which will run every day at 1 PM.Run this code from execute anonymous window.

Scheduling a Job from the UI

 You can also schedule a class using the user interface.

  1. Go to Apex Classes.
  2. Click Schedule Apex 
  3. Click Save.
 

Monitoring 

After the Apex job has been scheduled you can track the schedule details from the Salesforce UI or by running a SOQL query on CronTrigger as shown below.

The jobID variable holding the ID of the job. The System.schedule method returns the job ID. If you’re performing this query inside the execute method of your schedulable class, you can obtain the ID of the current job by calling getTriggerId on the SchedulableContext argument variable. Assuming this variable name is sc, the modified example becomes:


 

You can also get the job’s name and the job’s type from the CronJobDetail record associated with the CronTrigger record. To do so, use the CronJobDetail relationship when performing a query on CronTrigger. This example retrieves the most recent CronTrigger record with the job name and type from CronJobDetail.

Test Class

 

Things to Remember

  1. Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability.
  2. You can only have 100 scheduled Apex jobs at one time
  3. Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger won’t add more scheduled classes than the limit.
  4. If there are one or more active scheduled jobs for an Apex class, you cannot update the class or any classes referenced by this class through the Salesforce user interface. However, you can enable deployments to update the class with active scheduled jobs by using the Metadata API (for example, when using the Force.com IDE
  5. Synchronous Web service callouts are not supported from scheduled Apex.
  6. The maximum number of scheduled Apex executions per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater. This limit is for your entire org and is shared with all asynchronous Apex: Batch Apex, Queueable Apex, scheduled Apex, and future methods.
  7. Apex jobs scheduled to run during a Salesforce service maintenance downtime will be scheduled to run after the service comes back up, when system resources become available. If a scheduled Apex job was running when downtime occurred, the job is rolled back and scheduled again after the service comes back up.

 

 

%d bloggers like this: