Wednesday, 24 July 2019

escape single quotes to the query

Before escape single quotes to field

            
String detailQuery = 'select ' + fieldName + ' from ' + objectName + ' where id = \'' + auditParentId + '\'';

After escape single quotes to the field :


String detailQuery = String.format('select {0} from {1} where {2}', new List<String>{String.escapeSingleQuotes(fieldName), objectName, 'id =:auditParentID'});




Test class : 

 @IsTest
    private static void formatRecordDetailValueShouldThrowExceptionIfSOQLInjectionIsAttemptedOnFieldNameParameter() {
        TestUtil util = new TestUtil();
        User adminUser = util.generateSystemAdminForTest();
        CMPL123__Device__c testDevice = new CMPL123__Device__c (name = 'TestDevice');
        SObjectType sObjectType = CMPL123__Device__c.getSObjectType();
        Insert testDevice;

        String result;
        Boolean exceptionThrown;

        System.runAs(adminUser){
            Test.startTest();
            try {
                result = MDC_Utility.formatRecordDetailValue(testDevice.Id, 'CMPL123__Device__c', 'Name WHERE Name = \'TestDevice\' --');
            } catch (AccessViolationException ave) {
                exceptionThrown = true;
                System.assertEquals(sObjectType, ave.getSObjectType(), 'Exception not caused by ' + String.valueOf(sObjectType));
            }
            Test.stopTest();
        }

        System.assert(exceptionThrown);
        System.assertEquals(null, result, 'result is not null.  value: ' + result);
    
    }

    @IsTest
    private static void formatRecordDetailValueShouldThrowExceptionIfSOQLInjectionIsAttemptedOnObjectNameParameter() {
        TestUtil util = new TestUtil();
        User adminUser = util.generateSystemAdminForTest();
        CMPL123__Device__c testDevice = new CMPL123__Device__c (name = 'TestDevice');
        SObjectType sObjectType = CMPL123__Device__c.getSObjectType();
        Insert testDevice;

        String result;
        Boolean exceptionThrown;

        System.runAs(adminUser){
            Test.startTest();
            try {
                result = MDC_Utility.formatRecordDetailValue(testDevice.Id, 'CMPL123__Device__c WHERE Name = \'TestDevice\' --', 'Name');
            } catch (NullPointerException npe) {
                exceptionThrown = true;
            }
            Test.stopTest();
        }

        System.assert(exceptionThrown);
        System.assertEquals(null, result, 'result is not null.  value: ' + result);
    
    }
}

No comments:

Post a Comment