Skip to content

Commit

Permalink
feat(ec513) : ported location leakage rule EC513 to swift (#29)
Browse files Browse the repository at this point in the history
* feat(test): added first test for porting rule ec513 to swift

* feat(EC513) : add code check rule

* feat(test): added compliant test case for ec513 rule port to swift

* feat(ec513): integrated rule html and json

* feat(rules): updated rule list

---------

Co-authored-by: AhmedBAHRI <[email protected]>
  • Loading branch information
rgoussu-exalt and ahmedcove1 authored May 29, 2024
1 parent 3992707 commit daea639
Show file tree
Hide file tree
Showing 8 changed files with 227 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* ecoCode iOS plugin - Help the earth, adopt this green plugin for your applications
* Copyright © 2023 green-code-initiative (https://www.ecocode.io/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.ecocode.ios.swift.checks.sobriety;

import io.ecocode.ios.swift.SwiftRuleCheck;
import io.ecocode.ios.swift.antlr.generated.Swift5Parser;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNodeImpl;
import org.sonar.check.Rule;


@Rule(key = "EC513")
public class LocationLeakCheck extends SwiftRuleCheck {
private static final String DEFAULT_ISSUE_MESSAGE = "calls must be carefully paired: CLLocationManager.startUpdatingLocation() and CLLocationManager.stopUpdatingLocation()";
protected boolean firstCallExist = false;
protected boolean secondCallExist = false;
protected Swift5Parser.ExpressionContext id;

@Override
public void apply(ParseTree tree) {


if (tree instanceof Swift5Parser.ExpressionContext && (tree.getText().contains(".startUpdatingLocation()"))) {
firstCallExist = true;
id = (Swift5Parser.ExpressionContext) tree;
}

if (tree instanceof Swift5Parser.ExpressionContext && (tree.getText().contains(".stopUpdatingLocation()"))) {
secondCallExist = true;
}

if (tree instanceof TerminalNodeImpl && tree.getText().equals("<EOF>")) {
if (firstCallExist && !secondCallExist) {
this.recordIssue(id.getStart().getStartIndex(), DEFAULT_ISSUE_MESSAGE);
}
firstCallExist = false;
secondCallExist = false;
}
}
}
17 changes: 8 additions & 9 deletions swift-lang/src/main/resources/ecocode_swift_profile.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
"name": "ecoCode",
"ruleKeys": [
"EC505",
"EC506",
"EC602",
"EC543",
"EC521",
"EC509",
"EC512",
"EC513",
"EC520",
"EC522",
"EC547",
"EC523",
"EC503",
"EC603",
"EC512"
"EC524",
"EC530",
"EC533",
"EC603"
]
}
49 changes: 49 additions & 0 deletions swift-lang/src/main/resources/io/ecocode/rules/swift/EC513.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<p>Most Android-powered devices have built-in sensors that measure motion, orientation, and various environmental conditions.
In addition to these are the image sensor (a.k.a Camera) and the geopositioning sensor (a.k.a GPS).</p>
<br>The common point of all these sensors is that they are expensive while in use. Their common bug is to let the sensor
unnecessarily process data when the app enters an idle state, typically when paused or stopped.</br>
Consequently, calls must be carefully pairwised: <code>CLLocationManager.startUpdatingLocation() and CLLocationManager.stopUpdatingLocation()</code>.</br>
Failing to do so can drain the battery in just a few hours.</p>
<h2>Noncompliant Code Example</h2>
<pre>
import CoreLocation

class LocationTracker: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager?

override init() {
super.init()
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestAlwaysAuthorization() // Request appropriate authorization
locationManager?.startUpdatingLocation() // Start location updates
}

// LocationManager Delegate Methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Process new locations
}
}
</pre>
<br>
<h2>Compliant Code Example</h2>
<pre>
class LocationTracker: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager?

override init() {
super.init()
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestAlwaysAuthorization() // Request appropriate authorization
locationManager?.startUpdatingLocation() // Start location updates only when needed
}

// LocationManager Delegate Methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Process new locations
// Possibly stop updates if they are no longer needed
locationManager?.stopUpdatingLocation()
}
}
</pre>
19 changes: 19 additions & 0 deletions swift-lang/src/main/resources/io/ecocode/rules/swift/EC513.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"key": "EC513",
"title": "Leakage: Location Leak",
"defaultSeverity": "Major",
"description": "Most iOS devices come equipped with a variety of sensors that measure motion, orientation, and various environmental conditions. In addition to these, the devices include advanced sensors such as the image sensor (commonly referred to as the Camera) and the geo-positioning sensor (commonly referred to as GPS).\n\nThe common point of all these sensors is that they are power-intensive while in use. A typical issue arises when these sensors continue to process data unnecessarily after the application enters an idle state, typically when paused or when the user stops interacting with it.\n\nConsequently, calls must be carefully paired: CLLocationManager.startUpdatingLocation() and CLLocationManager.stopUpdatingLocation(). Failing to do so can drain the battery in just a few hours.",
"status": "ready",
"remediation": {
"func": "Constant/Issue",
"constantCost": "20min"
},
"tags": [
"sobriety",
"environment",
"ecocode",
"eco-design"
],
"type": "CODE_SMELL"
}

Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public void testMetadata() {

@Test
public void testRegistredRules() {
assertThat(repository.rules()).hasSize(11);
assertThat(repository.rules()).hasSize(12);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* ecoCode iOS plugin - Help the earth, adopt this green plugin for your applications
* Copyright © 2023 green-code-initiative (https://www.ecocode.io/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package io.ecocode.ios.swift.checks.sobriety;

import io.ecocode.ios.swift.checks.CheckTestHelper;
import org.assertj.core.api.ObjectAssert;
import org.junit.Test;
import org.sonar.api.batch.fs.TextPointer;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.batch.sensor.issue.Issue;
import org.sonar.api.batch.sensor.issue.IssueLocation;
import org.sonar.api.rule.RuleKey;

import static org.assertj.core.api.Assertions.assertThat;

public class LocationLeakCheckTest {

private static final String TEST_CASE_MISSING_RELEASE_CALL = "checks/sobriety/LocationLeakCheck_missing_release_trigger.swift";
private static final String TEST_CASE_COMPLIANT = "checks/sobriety/LocationLeakCheck_compliant_no_trigger.swift";
@Test
public void locationLeakCheck_missing_release_trigger(){
SensorContextTester context = CheckTestHelper.analyzeTestFile(TEST_CASE_MISSING_RELEASE_CALL);
ObjectAssert<Issue> issue = assertThat(context.allIssues()).hasSize(1)
.first();
issue.extracting(Issue::ruleKey).extracting(RuleKey::rule).isEqualTo("EC513");
issue.extracting(Issue::ruleKey).extracting(RuleKey::repository)
.isEqualTo("ecoCode-swift");
issue.extracting(Issue::primaryLocation)
.extracting(IssueLocation::textRange)
.extracting(TextRange::start)
.extracting(TextPointer::line)
.isEqualTo(11);
}

@Test
public void locationLeakCheck_compliant_no_trigger(){
SensorContextTester context = CheckTestHelper.analyzeTestFile(TEST_CASE_COMPLIANT);
assertThat(context.allIssues()).isEmpty();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import CoreLocation

class LocationTracker: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager?

override init() {
super.init()
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestAlwaysAuthorization() // Request appropriate authorization
locationManager?.startUpdatingLocation() // Start location updates only when needed
}

// LocationManager Delegate Methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Process new locations
// Possibly stop updates if they are no longer needed
locationManager?.stopUpdatingLocation()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import CoreLocation

class LocationTracker: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager?

override init() {
super.init()
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestAlwaysAuthorization() // Request appropriate authorization
locationManager?.startUpdatingLocation() // Start location updates
}

// LocationManager Delegate Methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Process new locations
}
}

0 comments on commit daea639

Please sign in to comment.