From daea63943237ccc40b661c043b7abab871c12004 Mon Sep 17 00:00:00 2001 From: rgoussu-exalt <108715229+rgoussu-exalt@users.noreply.github.com> Date: Wed, 29 May 2024 17:41:43 +0200 Subject: [PATCH] feat(ec513) : ported location leakage rule EC513 to swift (#29) * 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 --- .../checks/sobriety/LocationLeakCheck.java | 55 ++++++++++++++++++ .../main/resources/ecocode_swift_profile.json | 17 +++--- .../io/ecocode/rules/swift/EC513.html | 49 ++++++++++++++++ .../io/ecocode/rules/swift/EC513.json | 19 +++++++ .../EcoCodeSwiftRulesDefinitionTest.java | 2 +- .../sobriety/LocationLeakCheckTest.java | 57 +++++++++++++++++++ ...cationLeakCheck_compliant_no_trigger.swift | 20 +++++++ ...ionLeakCheck_missing_release_trigger.swift | 18 ++++++ 8 files changed, 227 insertions(+), 10 deletions(-) create mode 100644 swift-lang/src/main/java/io/ecocode/ios/swift/checks/sobriety/LocationLeakCheck.java create mode 100644 swift-lang/src/main/resources/io/ecocode/rules/swift/EC513.html create mode 100644 swift-lang/src/main/resources/io/ecocode/rules/swift/EC513.json create mode 100644 swift-lang/src/test/java/io/ecocode/ios/swift/checks/sobriety/LocationLeakCheckTest.java create mode 100644 swift-lang/src/test/resources/checks/sobriety/LocationLeakCheck_compliant_no_trigger.swift create mode 100644 swift-lang/src/test/resources/checks/sobriety/LocationLeakCheck_missing_release_trigger.swift diff --git a/swift-lang/src/main/java/io/ecocode/ios/swift/checks/sobriety/LocationLeakCheck.java b/swift-lang/src/main/java/io/ecocode/ios/swift/checks/sobriety/LocationLeakCheck.java new file mode 100644 index 0000000..9d2243a --- /dev/null +++ b/swift-lang/src/main/java/io/ecocode/ios/swift/checks/sobriety/LocationLeakCheck.java @@ -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 . + */ +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("")) { + if (firstCallExist && !secondCallExist) { + this.recordIssue(id.getStart().getStartIndex(), DEFAULT_ISSUE_MESSAGE); + } + firstCallExist = false; + secondCallExist = false; + } + } +} diff --git a/swift-lang/src/main/resources/ecocode_swift_profile.json b/swift-lang/src/main/resources/ecocode_swift_profile.json index ff79db7..c4d584f 100644 --- a/swift-lang/src/main/resources/ecocode_swift_profile.json +++ b/swift-lang/src/main/resources/ecocode_swift_profile.json @@ -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" ] } diff --git a/swift-lang/src/main/resources/io/ecocode/rules/swift/EC513.html b/swift-lang/src/main/resources/io/ecocode/rules/swift/EC513.html new file mode 100644 index 0000000..106bc2e --- /dev/null +++ b/swift-lang/src/main/resources/io/ecocode/rules/swift/EC513.html @@ -0,0 +1,49 @@ +

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).

+
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.
+Consequently, calls must be carefully pairwised: CLLocationManager.startUpdatingLocation() and CLLocationManager.stopUpdatingLocation().
+Failing to do so can drain the battery in just a few hours.

+

Noncompliant Code Example

+
+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
+    }
+}
+
+
+

Compliant Code Example

+
+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()
+    }
+}
+
\ No newline at end of file diff --git a/swift-lang/src/main/resources/io/ecocode/rules/swift/EC513.json b/swift-lang/src/main/resources/io/ecocode/rules/swift/EC513.json new file mode 100644 index 0000000..d152814 --- /dev/null +++ b/swift-lang/src/main/resources/io/ecocode/rules/swift/EC513.json @@ -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" + } + \ No newline at end of file diff --git a/swift-lang/src/test/java/io/ecocode/ios/swift/EcoCodeSwiftRulesDefinitionTest.java b/swift-lang/src/test/java/io/ecocode/ios/swift/EcoCodeSwiftRulesDefinitionTest.java index 646cdc8..db5c5f3 100644 --- a/swift-lang/src/test/java/io/ecocode/ios/swift/EcoCodeSwiftRulesDefinitionTest.java +++ b/swift-lang/src/test/java/io/ecocode/ios/swift/EcoCodeSwiftRulesDefinitionTest.java @@ -55,7 +55,7 @@ public void testMetadata() { @Test public void testRegistredRules() { - assertThat(repository.rules()).hasSize(11); + assertThat(repository.rules()).hasSize(12); } @Test diff --git a/swift-lang/src/test/java/io/ecocode/ios/swift/checks/sobriety/LocationLeakCheckTest.java b/swift-lang/src/test/java/io/ecocode/ios/swift/checks/sobriety/LocationLeakCheckTest.java new file mode 100644 index 0000000..d23134e --- /dev/null +++ b/swift-lang/src/test/java/io/ecocode/ios/swift/checks/sobriety/LocationLeakCheckTest.java @@ -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 . + */ + +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 = 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(); + } +} diff --git a/swift-lang/src/test/resources/checks/sobriety/LocationLeakCheck_compliant_no_trigger.swift b/swift-lang/src/test/resources/checks/sobriety/LocationLeakCheck_compliant_no_trigger.swift new file mode 100644 index 0000000..9504503 --- /dev/null +++ b/swift-lang/src/test/resources/checks/sobriety/LocationLeakCheck_compliant_no_trigger.swift @@ -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() + } +} \ No newline at end of file diff --git a/swift-lang/src/test/resources/checks/sobriety/LocationLeakCheck_missing_release_trigger.swift b/swift-lang/src/test/resources/checks/sobriety/LocationLeakCheck_missing_release_trigger.swift new file mode 100644 index 0000000..0c117cd --- /dev/null +++ b/swift-lang/src/test/resources/checks/sobriety/LocationLeakCheck_missing_release_trigger.swift @@ -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 + } +} \ No newline at end of file