logo

Improper type assignation - Dart


Need

Enforce proper type assignment in the source code


Context

  1. Usage of Dart for building cross-platform mobile, web, and desktop applications
  2. Usage of Shelf for managing and organizing data in Node.js applications

Description

Insecure Code Example

import 'package:shelf/shelf.dart' as shelf;

shelf.Response handleRequest(shelf.Request request) {
  var id = request.url.queryParameters['id'];
  var name = request.url.queryParameters['name'];
  
  // ... more code
}

In the above Dart code, the `handleRequest` function receives a `shelf.Request` object and retrieves parameters from the request URL. The `id` and `name` variables are declared using `var`, which means they are dynamically typed. Dart is a statically typed language, but it allows dynamic typing with the `var` keyword. The type of `var` is determined at runtime, which can lead to inefficiencies because the Dart VM has to determine the type of the variable each time it's used. This can also lead to bugs if the variable is expected to be of a certain type but is assigned a value of a different type at runtime. In this context, `id` and `name` are expected to be strings since they are retrieved from the URL parameters. However, since they are declared with `var`, they could potentially hold values of any type, leading to potential type errors later in the code.

Steps

  1. Declare the specific type for each variable instead of using 'var'.
  2. For 'id', if it is expected to be a string, declare it as 'String id'.
  3. For 'name', if it is expected to be a string, declare it as 'String name'.
  4. This will ensure that the variables are always of the expected type, reducing the need for type checking and casting in the rest of the code.

Secure Code Example

import 'package:shelf/shelf.dart' as shelf;

shelf.Response handleRequest(shelf.Request request) {
  String id = request.url.queryParameters['id'];
  String name = request.url.queryParameters['name'];
  
  // ... more code
}

The original code had a vulnerability due to improper type assignation. The variables `id` and `name` were declared using `var`, which means that their type is determined by the first value that gets assigned to them. This can lead to inefficiencies and potential bugs, as the type of these variables could change throughout the code, leading to unexpected behavior. The fixed code declares `id` and `name` as `String`. This ensures that these variables can only hold string values, preventing potential type-related bugs. This also improves the efficiency of the code, as Dart can now optimize for these specific types, and there is no need for additional type checking or casting when these variables are used later in the code. By explicitly declaring the type of your variables, you make your code safer, more efficient, and easier to understand.


References

  • 113 - Improper type assignation

  • Last updated

    2023/09/18