Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions compiler-plugin-tests/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ dependencies {
testImplementation group: 'org.ballerinalang', name: 'ballerina-lang', version: "${ballerinaLangVersion}"
testImplementation group: 'org.ballerinalang', name: 'ballerina-tools-api', version: "${ballerinaLangVersion}"
testImplementation group: 'org.ballerinalang', name: 'ballerina-parser', version: "${ballerinaLangVersion}"
testImplementation group: 'io.ballerina.scan', name: 'scan-command', version: "${balScanVersion}"
testImplementation group: 'io.ballerina.scan', name: 'scan-command-test-utils', version: "${balScanVersion}"

testImplementation group: 'org.testng', name: 'testng', version: "${testngVersion}"
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/*
* Copyright (c) 2025, WSO2 LLC. (http://www.wso2.org)
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package io.ballerina.stdlib.crypto.compiler.staticcodeanalyzer;

import io.ballerina.projects.Project;
import io.ballerina.projects.ProjectEnvironmentBuilder;
import io.ballerina.projects.directory.BuildProject;
import io.ballerina.projects.environment.Environment;
import io.ballerina.projects.environment.EnvironmentBuilder;
import io.ballerina.scan.Issue;
import io.ballerina.scan.Rule;
import io.ballerina.scan.RuleKind;
import io.ballerina.scan.Source;
import io.ballerina.scan.test.Assertions;
import io.ballerina.scan.test.TestOptions;
import io.ballerina.scan.test.TestRunner;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

public class StaticCodeAnalyzerTest {
private static final Path RESOURCE_PACKAGES_DIRECTORY = Paths
.get("src", "test", "resources", "static_code_analyzer", "ballerina_packages").toAbsolutePath();
private static final Path EXPECTED_OUTPUT_DIRECTORY = Paths
.get("src", "test", "resources", "static_code_analyzer", "expected_output").toAbsolutePath();
private static final Path JSON_RULES_FILE_PATH = Paths
.get("../", "compiler-plugin", "src", "main", "resources", "rules.json").toAbsolutePath();
private static final Path DISTRIBUTION_PATH = Paths.get("../", "target", "ballerina-runtime");

@Test
public void validateRulesJson() throws IOException {
String expectedRules = "[" + Arrays.stream(CryptoRule.values())
.map(CryptoRule::toString).collect(Collectors.joining(",")) + "]";
String actualRules = Files.readString(JSON_RULES_FILE_PATH);
assertJsonEqual(actualRules, expectedRules);
}

@Test
public void testStaticCodeRulesWithAPI() throws IOException {
ByteArrayOutputStream console = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(console);
for (CryptoRule rule : CryptoRule.values()) {
String targetPackageName = "rule" + rule.getId();
Path targetPackagePath = RESOURCE_PACKAGES_DIRECTORY.resolve(targetPackageName);
Project project = BuildProject.load(getEnvironmentBuilder(), targetPackagePath);
TestOptions options = TestOptions.builder(project)
.setOutputStream(printStream)
.build();
TestRunner testRunner = new TestRunner(options);
testRunner.performScan();

// validate the Crypto rules
List<Rule> rules = testRunner.getRules();
Assertions.assertRule(
rules,
"ballerina/crypto:1",
"Encryption algorithms should be used with secure mode and padding scheme",
RuleKind.VULNERABILITY);

// validate the issues
List<Issue> issues = testRunner.getIssues();
Assert.assertEquals(issues.size(), 4);
Assertions.assertIssue(issues, 0, "ballerina/crypto:1", "aes_cbc.bal",
30, 30, Source.BUILT_IN);
Assertions.assertIssue(issues, 1, "ballerina/crypto:1", "aes_cbc_as_import.bal",
30, 30, Source.BUILT_IN);
Assertions.assertIssue(issues, 2, "ballerina/crypto:1", "aes_ecb.bal",
26, 26, Source.BUILT_IN);
Assertions.assertIssue(issues, 3, "ballerina/crypto:1", "aes_ecb_as_import.bal",
26, 26, Source.BUILT_IN);

// validate the output
String output = console.toString();
String jsonOutput = extractJson(output);
String expectedOutput = Files.readString(EXPECTED_OUTPUT_DIRECTORY.resolve(targetPackageName
+ ".json"));
assertJsonEqual(jsonOutput, expectedOutput);
}
}

private static ProjectEnvironmentBuilder getEnvironmentBuilder() {
Environment environment = EnvironmentBuilder.getBuilder().setBallerinaHome(DISTRIBUTION_PATH).build();
return ProjectEnvironmentBuilder.getBuilder(environment);
}

private String extractJson(String consoleOutput) {
int startIndex = consoleOutput.indexOf("[");
int endIndex = consoleOutput.lastIndexOf("]");
if (startIndex == -1 || endIndex == -1) {
return "";
}
return consoleOutput.substring(startIndex, endIndex + 1);
}

private void assertJsonEqual(String actual, String expected) {
Assert.assertEquals(normalizeString(actual), normalizeString(expected));
}

private static String normalizeString(String json) {
String normalizedJson = json.replaceAll("\\s*\"\\s*", "\"")
.replaceAll("\\s*:\\s*", ":")
.replaceAll("\\s*,\\s*", ",")
.replaceAll("\\s*\\{\\s*", "{")
.replaceAll("\\s*}\\s*", "}")
.replaceAll("\\s*\\[\\s*", "[")
.replaceAll("\\s*]\\s*", "]")
.replaceAll("\n", "")
.replaceAll(":\".*module-ballerina-crypto", ":\"module-ballerina-crypto");
return isWindows() ? normalizedJson.replaceAll("/", "\\\\\\\\") : normalizedJson;
}

private static boolean isWindows() {
return System.getProperty("os.name").toLowerCase(Locale.ENGLISH).startsWith("windows");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
org = "wso2"
name = "rule1"
version = "0.1.0"
distribution = "2201.12.3"

[build-options]
observabilityIncluded = true
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (c) 2025 WSO2 LLC. (http://www.wso2.org)
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import ballerina/crypto;
import ballerina/random;

public function aesCbc() returns error? {
string dataString = "Hello Ballerina!";
byte[] data = dataString.toBytes();
byte[16] key = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
foreach int i in 0 ... 15 {
key[i] = <byte>(check random:createIntInRange(0, 255));
}
byte[16] initialVector = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
foreach int i in 0 ... 15 {
initialVector[i] = <byte>(check random:createIntInRange(0, 255));
}
byte[] _ = check crypto:encryptAesCbc(data, key, initialVector);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (c) 2025 WSO2 LLC. (http://www.wso2.org)
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import ballerina/crypto as c;
import ballerina/random;

public function aesCbcAsImport() returns error? {
string dataString = "Hello Ballerina!";
byte[] data = dataString.toBytes();
byte[16] key = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
foreach int i in 0 ... 15 {
key[i] = <byte>(check random:createIntInRange(0, 255));
}
byte[16] initialVector = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
foreach int i in 0 ... 15 {
initialVector[i] = <byte>(check random:createIntInRange(0, 255));
}
byte[] _ = check c:encryptAesCbc(data, key, initialVector);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (c) 2025 WSO2 LLC. (http://www.wso2.org)
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import ballerina/crypto;
import ballerina/random;

public function aesEcb() returns error? {
string dataString = "Hello Ballerina!";
byte[] data = dataString.toBytes();
byte[16] key = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
foreach int i in 0 ... 15 {
key[i] = <byte>(check random:createIntInRange(0, 255));
}
byte[] _ = check crypto:encryptAesEcb(data, key);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (c) 2025 WSO2 LLC. (http://www.wso2.org)
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import ballerina/crypto as c;
import ballerina/random;

public function aesEcbAsImport() returns error? {
string dataString = "Hello Ballerina!";
byte[] data = dataString.toBytes();
byte[16] key = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
foreach int i in 0 ... 15 {
key[i] = <byte>(check random:createIntInRange(0, 255));
}
byte[] _ = check c:encryptAesEcb(data, key);
}
Loading