Absolute Salesforce org URL written as a literal
ID |
apex.maintainability.hardcoded_salesforce_url |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Api Usage |
Language |
Apex |
Description
Reports a string literal holding an absolute Salesforce URL - a my.salesforce.com, force.com, lightning.force.com or visual.force.com host.
Rationale
The host name of an org is not stable: it changes when My Domain is enabled or renamed, it is different in every sandbox, and it is different again in a scratch org or a subscriber org. A link built on a literal host therefore points at the wrong org, which is worse than pointing nowhere - a sandbox email can send a user to production, where they act on real data believing they are in a test environment. A cross-org link also fails the session check and drops the user at a login page with no explanation.
The following code illustrates the pattern detected by this rule:
public class PortalLinks {
public String recordLink(Id recordId) {
// FLAGGED: Absolute Salesforce org URL written as a literal
return 'https://acme.my.salesforce.com/' + recordId;
}
public String communityLink(Id recordId) {
// FLAGGED: Absolute Salesforce org URL written as a literal
return 'https://acme.force.com/customers/s/case/' + recordId;
}
public String relativeLink(Id recordId) {
return '/' + recordId;
}
public String orgLink(Id recordId) {
return Url.getOrgDomainUrl().toExternalForm() + '/' + recordId;
}
public String externalApi() {
return 'callout:Billing_API/invoices';
}
}
Remediation
Use a relative URL ('/' + recordId) for anything inside the org, which the browser resolves against whatever host the user is on. Where an absolute URL is needed - an email body, an outbound payload - build it from Url.getOrgDomainUrl(), which returns the host the code is actually running on.