nus-yam/ex-repair huggingface dataset:
Program: CWE-918
Project: CVE-2022-31188
Buggy source:
attrs==21.2.0
click==7.1.2
Django==3.2.12
django-appconf==1.0.4
django-auth-ldap==2.2.0
django-compressor==2.4
django-rq==2.3.2
EasyProcess==0.3
Pillow==9.0.1
numpy==1.22.0
python-ldap==3.4.0
pytz==2020.1
pyunpack==0.2.1
rcssmin==1.0.6
redis==3.5.3
rjsmin==1.1.0
requests==2.26.0
rq==1.5.1
rq-scheduler==0.10.0
sqlparse==0.4.2
django-sendfile2==0.6.1
dj-pagination==2.5.0
python-logstash-async==2.2.0
rules==2.2
GitPython==3.1.27
coreapi==2.3.3
django-filter==2.4.0
Markdown==3.2.2
djangorestframework==3.12.4
Pygments==2.7.4
drf-spectacular==0.21.2
Shapely==1.7.1
pdf2image==1.14.0
django-rest-auth[with_social]==0.9.5
opencv-python-headless==4.4.0.42
h5py==2.10.0
django-cors-headers==3.5.0
furl==2.1.0
av==8.0.2 --no-binary=av
tensorflow==2.8.0 # Optional requirement of Datumaro
# The package is used by pyunpack as a command line tool to support multiple
# archives. Don't use as a python module because it has GPL license.
patool==1.12
diskcache==5.0.2
open3d==0.11.2
boto3==1.17.61
azure-storage-blob==12.8.1
google-cloud-storage==1.42.0
# --no-binary=datumaro: workaround for pip to install
# opencv-headless instead of regular opencv, to actually run setup script
datumaro==0.2.0 --no-binary=datumaro
urllib3>=1.26.5 # not directly required, pinned by Snyk to avoid a vulnerability
natsort==8.0.0
mistune>=2.0.1 # not directly required, pinned by Snyk to avoid a vulnerability


Fixed version (ground truth):
attrs==21.2.0
click==7.1.2
Django==3.2.12
django-appconf==1.0.4
django-auth-ldap==2.2.0
django-compressor==2.4
django-rq==2.3.2
EasyProcess==0.3
Pillow==9.0.1
numpy==1.22.0
python-ldap==3.4.0
pytz==2020.1
pyunpack==0.2.1
rcssmin==1.0.6
redis==3.5.3
rjsmin==1.1.0
requests==2.26.0
rq==1.5.1
rq-scheduler==0.10.0
sqlparse==0.4.2
django-sendfile2==0.6.1
dj-pagination==2.5.0
python-logstash-async==2.2.0
rules==2.2
GitPython==3.1.27
coreapi==2.3.3
django-filter==2.4.0
Markdown==3.2.2
djangorestframework==3.12.4
Pygments==2.7.4
drf-spectacular==0.21.2
Shapely==1.7.1
pdf2image==1.14.0
django-rest-auth[with_social]==0.9.5
opencv-python-headless==4.4.0.42
h5py==2.10.0
django-cors-headers==3.5.0
furl==2.1.0
av==8.0.2 --no-binary=av
tensorflow==2.8.0 # Optional requirement of Datumaro
# The package is used by pyunpack as a command line tool to support multiple
# archives. Don't use as a python module because it has GPL license.
patool==1.12
diskcache==5.0.2
open3d==0.11.2
boto3==1.17.61
azure-storage-blob==12.8.1
google-cloud-storage==1.42.0
# --no-binary=datumaro: workaround for pip to install
# opencv-headless instead of regular opencv, to actually run setup script
datumaro==0.2.0 --no-binary=datumaro
urllib3>=1.26.5 # not directly required, pinned by Snyk to avoid a vulnerability
natsort==8.0.0
mistune>=2.0.1 # not directly required, pinned by Snyk to avoid a vulnerability
dnspython==2.2.0
Program: CWE-306
Project: CVE-2020-13405
Buggy source:
<?php

dd(User::all());

Fixed version (ground truth):
<?php
Program: CWE-306
Project: CVE-2022-31022
Buggy source:
# http support in bleve

This http package is purely for the demonstration purposes and is used by sample
applications like https://github.com/blevesearch/bleve-explorer.

Please be aware that the http handler implementations neither provide exhaustive 
user input validations nor authentication or authorization of the user access. 

So, it is recommended to remain cautious against the use of the http package in 
production use cases.

Fixed version (ground truth):
# http support in bleve

This http package is purely for the demonstration purposes and is used by sample
applications like https://github.com/blevesearch/bleve-explorer.

Please be aware that the http handler implementations neither provide exhaustive
user input validations nor authentication or authorization of the user access.

So, it is strongly recommended that users exercise caution while using the http
package in production situations.

[Here](https://github.com/blevesearch/bleve/security/advisories/GHSA-9w9f-6mg8-jp7w) is the security advisory on this.
Program: CWE-362
Project: CVE-2018-3759
Buggy source:
require 'test_helper'
require 'private_address_check/tcpsocket_ext'

class TCPSocketExtTest < Minitest::Test
  def test_private_address
    assert_raises PrivateAddressCheck::PrivateConnectionAttemptedError do
      PrivateAddressCheck.only_public_connections do
        TCPSocket.new("localhost", 80)
      end
    end
  end

  def test_public_address
    connected = false
    PrivateAddressCheck.only_public_connections do
      TCPSocket.new("example.com", 80)
      connected = true
    end

    assert connected
  end

  def test_invalid_domain
    assert_raises SocketError do
      PrivateAddressCheck.only_public_connections do
        TCPSocket.new("not_a_domain", 80)
      end
    end
  end
end


Fixed version (ground truth):
require 'test_helper'
require 'private_address_check/tcpsocket_ext'

class TCPSocketExtTest < Minitest::Test
  def test_private_address
    server = TCPServer.new(63453)
    thread = Thread.start { server.accept }
    assert_raises PrivateAddressCheck::PrivateConnectionAttemptedError do
      PrivateAddressCheck.only_public_connections do
        TCPSocket.new("localhost", 63453)
      end
    end
  ensure
    thread.exit if thread
  end

  def test_public_address
    connected = false
    PrivateAddressCheck.only_public_connections do
      TCPSocket.new("example.com", 80)
      connected = true
    end

    assert connected
  end

  def test_invalid_domain
    assert_raises SocketError do
      PrivateAddressCheck.only_public_connections do
        TCPSocket.new("not_a_domain", 80)
      end
    end
  end
end
Program: CWE-362
Project: CVE-2019-16779
Buggy source:
require 'sinatra'
require 'json'
require File.join(File.dirname(__FILE__), 'webrick_patch')

class Basic < Sinatra::Base
  set :environment, :production
  enable :dump_errors

  get('/content-length/:value') do |value|
    headers("Custom" => "Foo: bar")
    'x' * value.to_i
  end

  get('/headers') do
    content_type :json
    request.env.select{|key, _| key.start_with? 'HTTP_'}.to_json
  end

  post('/body-sink') do
    request.body.read.size.to_s
  end

  post('/echo') do
    echo
  end

  put('/echo') do
    echo
  end

  get('/echo dirty') do
    echo
  end

  private

  def echo
    request.body.read
  end

end


Fixed version (ground truth):
require 'sinatra'
require 'json'
require File.join(File.dirname(__FILE__), 'webrick_patch')

class Basic < Sinatra::Base
  set :environment, :production
  enable :dump_errors

  get('/content-length/:value') do |value|
    headers("Custom" => "Foo: bar")
    'x' * value.to_i
  end

  get('/headers') do
    content_type :json
    request.env.select{|key, _| key.start_with? 'HTTP_'}.to_json
  end

  post('/body-sink') do
    request.body.read.size.to_s
  end

  post('/echo') do
    echo
  end

  put('/echo') do
    echo
  end

  get('/echo dirty') do
    echo
  end

  get('/foo') do
    'foo'
  end

  get('/bar') do
    'bar'
  end

  private

  def echo
    request.body.read
  end

end
Program: CWE-362
Project: CVE-2022-31015
Buggy source:
None

Fixed version (ground truth):
None
Program: CWE-269
Project: CVE-2022-25372
Buggy source:
package platform

import (
	"os"

	"github.com/dropbox/godropbox/errors"
	"github.com/hectane/go-acl"
	"github.com/pritunl/pritunl-client-electron/service/errortypes"
	"golang.org/x/sys/windows"
)

func MkdirSecure(pth string) (err error) {
	err = os.MkdirAll(pth, 0755)
	if err != nil {
		err = &errortypes.WriteError{
			errors.Wrap(err, "utils: Failed to create directory"),
		}
		return
	}

	err = acl.Apply(
		pth,
		true,
		false,
		acl.GrantName(windows.GENERIC_ALL, "CREATOR OWNER"),
		acl.GrantName(windows.GENERIC_ALL, "SYSTEM"),
		acl.GrantName(windows.GENERIC_ALL, "Administrators"),
	)
	if err != nil {
		err = &errortypes.WriteError{
			errors.Wrap(err, "utils: Failed to acl directory"),
		}
		return
	}

	return
}


Fixed version (ground truth):
package platform

import (
	"os"

	"github.com/dropbox/godropbox/errors"
	"github.com/hectane/go-acl"
	"github.com/pritunl/pritunl-client-electron/service/errortypes"
	"golang.org/x/sys/windows"
)

func MkdirSecure(pth string) (err error) {
	err = os.MkdirAll(pth, 0755)
	if err != nil {
		err = &errortypes.WriteError{
			errors.Wrap(err, "utils: Failed to create directory"),
		}
		return
	}

	err = acl.Apply(
		pth,
		true,
		false,
		acl.GrantName(windows.GENERIC_ALL, "SYSTEM"),
		acl.GrantName(windows.GENERIC_ALL, "Administrators"),
	)
	if err != nil {
		err = &errortypes.WriteError{
			errors.Wrap(err, "utils: Failed to acl directory"),
		}
		return
	}

	return
}
Program: CWE-94
Project: CVE-2012-4406
Buggy source:
[memcache]
# You can use this single conf file instead of having memcache_servers set in
# several other conf files under [filter:cache] for example. You can specify
# multiple servers separated with commas, as in: 10.1.2.3:11211,10.1.2.4:11211
# memcache_servers = 127.0.0.1:11211


Fixed version (ground truth):
[memcache]
# You can use this single conf file instead of having memcache_servers set in
# several other conf files under [filter:cache] for example. You can specify
# multiple servers separated with commas, as in: 10.1.2.3:11211,10.1.2.4:11211
# memcache_servers = 127.0.0.1:11211
#
# Sets how memcache values are serialized and deserialized:
# 0 = older, insecure pickle serialization
# 1 = json serialization but pickles can still be read (still insecure)
# 2 = json serialization only (secure and the default)
# To avoid an instant full cache flush, existing installations should
# upgrade with 0, then set to 1 and reload, then after some time (24 hours)
# set to 2 and reload.
# In the future, the ability to use pickle serialization will be removed.
# memcache_serialization_support = 2
Program: CWE-94
Project: CVE-2013-4203
Buggy source:
module Rgpg
  module GemInfo
    MAJOR_VERSION = 0
    MINOR_VERSION = 2
    PATCH_VERSION = 2

    def self.version_string
      [MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION].join('.')
    end
  end
end



Fixed version (ground truth):
module Rgpg
  module GemInfo
    MAJOR_VERSION = 0
    MINOR_VERSION = 2
    PATCH_VERSION = 3

    def self.version_string
      [MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION].join('.')
    end
  end
end
Program: CWE-94
Project: CVE-2014-7192
Buggy source:
var esprima = require('esprima-fb');

module.exports = function (src, file) {
    if (typeof src !== 'string') src = String(src);
    
    try {
        Function(src);
        return;
    }
    catch (err) {
        if (err.constructor.name !== 'SyntaxError') throw err;
        return errorInfo(src, file);
    }
};

function errorInfo (src, file) {
    try {
        esprima.parse(src);
        return;
    }
    catch (err) {
        return new ParseError(err, src, file);
    }
}

function ParseError (err, src, file) {
    SyntaxError.call(this);
    
    this.message = err.message.replace(/^Line \d+: /, '');
    
    this.line = err.lineNumber;
    this.column = err.column;
    
    this.annotated = '\n'
        + (file || '(anonymous file)')
        + ':' + this.line
        + '\n'
        + src.split('\n')[this.line - 1]
        + '\n'
        + Array(this.column).join(' ') + '^'
        + '\n'
        + 'ParseError: ' + this.message
    ;
}

ParseError.prototype = Object.create(SyntaxError.prototype);

ParseError.prototype.toString = function () {
    return this.annotated;
};

ParseError.prototype.inspect = function () {
    return this.annotated;
};


Fixed version (ground truth):
var esprima = require('esprima-fb');

module.exports = function (src, file) {
    if (typeof src !== 'string') src = String(src);
    
    try {
        eval('throw "STOP"; (function () { ' + src + '})()');
        return;
    }
    catch (err) {
        if (err === 'STOP') return undefined;
        if (err.constructor.name !== 'SyntaxError') throw err;
        return errorInfo(src, file);
    }
};

function errorInfo (src, file) {
    try {
        esprima.parse(src);
        return;
    }
    catch (err) {
        return new ParseError(err, src, file);
    }
}

function ParseError (err, src, file) {
    SyntaxError.call(this);
    
    this.message = err.message.replace(/^Line \d+: /, '');
    
    this.line = err.lineNumber;
    this.column = err.column;
    
    this.annotated = '\n'
        + (file || '(anonymous file)')
        + ':' + this.line
        + '\n'
        + src.split('\n')[this.line - 1]
        + '\n'
        + Array(this.column).join(' ') + '^'
        + '\n'
        + 'ParseError: ' + this.message
    ;
}

ParseError.prototype = Object.create(SyntaxError.prototype);

ParseError.prototype.toString = function () {
    return this.annotated;
};

ParseError.prototype.inspect = function () {
    return this.annotated;
};
Program: CWE-94
Project: CVE-2017-2809
Buggy source:
=============
ansible-vault
=============

.. image:: https://travis-ci.org/jptomo/ansible-vault.svg?branch=master
   :target: https://travis-ci.org/jptomo/ansible-vault

This project aim to R/W an ansible-vault yaml file

You can install with pip.

.. code-block:: console

   $ pip install ansible-vault

When you have an ansible-vault file, then you can read file. See below.

.. code-block:: python

   from ansible_vault import Vault

   vault = Vault('password')
   data = vault.load(open('vault.yml').read())

When you have to write data, then you can write data to file. See below.

.. code-block:: python

   from ansible_vault import Vault

   vault = Vault('password')
   vault.dump(data, open('vault.yml', 'w'))

   # also you can get encrypted text
   print(vault.dump(data))


Fixed version (ground truth):
=============
ansible-vault
=============

.. image:: https://travis-ci.org/tomoh1r/ansible-vault.svg?branch=master
   :target: https://travis-ci.org/tomoh1r/ansible-vault

This project aim to R/W an ansible-vault yaml file

You can install with pip.

.. code-block:: console

   $ pip install ansible-vault

When you have an ansible-vault file, then you can read file. See below.

.. code-block:: python

   from ansible_vault import Vault

   vault = Vault('password')
   data = vault.load(open('vault.yml').read())

When you have to write data, then you can write data to file. See below.

.. code-block:: python

   from ansible_vault import Vault

   vault = Vault('password')
   vault.dump(data, open('vault.yml', 'w'))

   # also you can get encrypted text
   print(vault.dump(data))
Program: CWE-94
Project: CVE-2018-1000070
Buggy source:
from importlib import import_module
from os import path, listdir
from string import lower

from debug import logger
import paths

class MsgBase(object):
    def encode(self):
        self.data = {"": lower(type(self).__name__)}


def constructObject(data):
    try:
        classBase = eval(data[""] + "." + data[""].title())
    except NameError:
        logger.error("Don't know how to handle message type: \"%s\"", data[""])
        return None
    try:
        returnObj = classBase()
        returnObj.decode(data)
    except KeyError as e:
        logger.error("Missing mandatory key %s", e)
        return None
    except:
        logger.error("classBase fail", exc_info=True)
        return None
    else:
        return returnObj

if paths.frozen is not None:
    import messagetypes.message
    import messagetypes.vote
else:
    for mod in listdir(path.dirname(__file__)):
        if mod == "__init__.py":
            continue
        splitted = path.splitext(mod)
        if splitted[1] != ".py":
            continue
        try:
            import_module("." + splitted[0], "messagetypes")
        except ImportError:
            logger.error("Error importing %s", mod, exc_info=True)
        else:
            logger.debug("Imported message type module %s", mod)


Fixed version (ground truth):
from importlib import import_module
from os import path, listdir
from string import lower

from debug import logger
import paths

class MsgBase(object):
    def encode(self):
        self.data = {"": lower(type(self).__name__)}


def constructObject(data):
    try:
        m = import_module("messagetypes." + data[""])
        classBase = getattr(m, data[""].title())
    except (NameError, ImportError):
        logger.error("Don't know how to handle message type: \"%s\"", data[""], exc_info=True)
        return None
    try:
        returnObj = classBase()
        returnObj.decode(data)
    except KeyError as e:
        logger.error("Missing mandatory key %s", e)
        return None
    except:
        logger.error("classBase fail", exc_info=True)
        return None
    else:
        return returnObj

if paths.frozen is not None:
    import messagetypes.message
    import messagetypes.vote
else:
    for mod in listdir(path.dirname(__file__)):
        if mod == "__init__.py":
            continue
        splitted = path.splitext(mod)
        if splitted[1] != ".py":
            continue
        try:
            import_module("." + splitted[0], "messagetypes")
        except ImportError:
            logger.error("Error importing %s", mod, exc_info=True)
        else:
            logger.debug("Imported message type module %s", mod)
Program: CWE-94
Project: CVE-2018-9113
Buggy source:
const express = require('express')
const PORT = process.env.PORT || 5000

express()
  .use(express.static(__dirname))
  .listen(PORT, () => console.log(`Listening on ${ PORT }`))


Fixed version (ground truth):
#!/usr/bin/env node

const express = require('express');

express()
  .use(express.static(__dirname))
  .listen(process.env.PORT || 5000);
Program: CWE-94
Project: CVE-2022-0944
Buggy source:
const _ = require('lodash');

/**
 * Iterates over connection object, replacing any template strings with values from user
 * This allows dynamic values inserted based on logged in user
 * This uses a mustache-like syntax, using double mustaches.
 * User variables can be referenced in connection strings using dot notation
 * Example: {{user.someKey}} and {{user.data.someKey}}
 * @param {object} connection
 * @param {object} user
 */
function renderConnection(connection, user) {
  const replaced = {};
  Object.keys(connection).forEach((key) => {
    // data is an object of values, but values may be top level too
    if (key === 'data') {
      const value = renderConnection(connection.data, user);
      connection.data = value;
    } else {
      const value = connection[key];
      if (typeof value === 'string') {
        _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
        const compiled = _.template(value);
        replaced[key] = compiled({ user });
      } else {
        replaced[key] = value;
      }
    }
  });
  return replaced;
}

module.exports = renderConnection;


Fixed version (ground truth):
const mustache = require('mustache');

// Disable HTML escaping. We're not using it for HTML
mustache.escape = function (text) {
  return text;
};

/**
 * Iterates over connection object, replacing any template strings with values from user
 * This allows dynamic values inserted based on logged in user
 * This uses a mustache-like syntax, using double mustaches.
 * User variables can be referenced in connection strings using dot notation
 * Example: {{user.someKey}} and {{user.data.someKey}}
 * @param {object} connection
 * @param {object} user
 */
function renderConnection(connection, user) {
  const replaced = {};
  Object.keys(connection).forEach((key) => {
    // data is an object of values, but values may be top level too
    if (key === 'data') {
      const value = renderConnection(connection.data, user);
      connection.data = value;
    } else {
      const value = connection[key];
      if (typeof value === 'string') {
        replaced[key] = mustache.render(value, { user });
      } else {
        replaced[key] = value;
      }
    }
  });
  return replaced;
}

module.exports = renderConnection;
Program: CWE-94
Project: CVE-2022-21122
Buggy source:
'use strict';

const metavm = require('metavm');

const getValue = (target, prop) => {
  if (prop === 'Math') return Math;
  const { expressions, data } = target;
  if (!expressions.has(prop)) return data.get(prop);
  const expression = expressions.get(prop);
  return expression();
};

const getCell = (target, prop) => {
  const { expressions, data } = target;
  const collection = expressions.has(prop) ? expressions : data;
  return collection.get(prop);
};

const setCell = (target, prop, value) => {
  if (typeof value === 'string' && value[0] === '=') {
    const src = '() => ' + value.substring(1);
    const options = { context: target.context };
    const script = metavm.createScript(prop, src, options);
    target.expressions.set(prop, script.exports);
  } else {
    target.data.set(prop, value);
  }
  return true;
};

class Sheet {
  constructor() {
    this.data = new Map();
    this.expressions = new Map();
    this.values = new Proxy(this, { get: getValue });
    this.context = metavm.createContext(this.values);
    this.cells = new Proxy(this, { get: getCell, set: setCell });
  }
}

module.exports = { Sheet };


Fixed version (ground truth):
'use strict';

const metavm = require('metavm');

const wrap = (target) =>
  new Proxy(target, {
    get: (target, prop) => {
      if (prop === 'constructor') return null;
      const value = target[prop];
      if (typeof value === 'number') return value;
      return wrap(value);
    },
  });

const math = wrap(Math);

const getValue = (target, prop) => {
  if (prop === 'Math') return math;
  const { expressions, data } = target;
  if (!expressions.has(prop)) return data.get(prop);
  const expression = expressions.get(prop);
  return expression();
};

const getCell = (target, prop) => {
  const { expressions, data } = target;
  const collection = expressions.has(prop) ? expressions : data;
  return collection.get(prop);
};

const setCell = (target, prop, value) => {
  if (typeof value === 'string' && value[0] === '=') {
    const src = '() => ' + value.substring(1);
    const options = { context: target.context };
    const script = metavm.createScript(prop, src, options);
    target.expressions.set(prop, script.exports);
  } else {
    target.data.set(prop, value);
  }
  return true;
};

class Sheet {
  constructor() {
    this.data = new Map();
    this.expressions = new Map();
    this.values = new Proxy(this, { get: getValue });
    this.context = metavm.createContext(this.values);
    this.cells = new Proxy(this, { get: getCell, set: setCell });
  }
}

module.exports = { Sheet };
Program: CWE-94
Project: CVE-2022-21686
Buggy source:
'use strict';

const metavm = require('metavm');

const getValue = (target, prop) => {
  if (prop === 'Math') return Math;
  const { expressions, data } = target;
  if (!expressions.has(prop)) return data.get(prop);
  const expression = expressions.get(prop);
  return expression();
};

const getCell = (target, prop) => {
  const { expressions, data } = target;
  const collection = expressions.has(prop) ? expressions : data;
  return collection.get(prop);
};

const setCell = (target, prop, value) => {
  if (typeof value === 'string' && value[0] === '=') {
    const src = '() => ' + value.substring(1);
    const options = { context: target.context };
    const script = metavm.createScript(prop, src, options);
    target.expressions.set(prop, script.exports);
  } else {
    target.data.set(prop, value);
  }
  return true;
};

class Sheet {
  constructor() {
    this.data = new Map();
    this.expressions = new Map();
    this.values = new Proxy(this, { get: getValue });
    this.context = metavm.createContext(this.values);
    this.cells = new Proxy(this, { get: getCell, set: setCell });
  }
}

module.exports = { Sheet };


Fixed version (ground truth):
'use strict';

const metavm = require('metavm');

const wrap = (target) =>
  new Proxy(target, {
    get: (target, prop) => {
      if (prop === 'constructor') return null;
      const value = target[prop];
      if (typeof value === 'number') return value;
      return wrap(value);
    },
  });

const math = wrap(Math);

const getValue = (target, prop) => {
  if (prop === 'Math') return math;
  const { expressions, data } = target;
  if (!expressions.has(prop)) return data.get(prop);
  const expression = expressions.get(prop);
  return expression();
};

const getCell = (target, prop) => {
  const { expressions, data } = target;
  const collection = expressions.has(prop) ? expressions : data;
  return collection.get(prop);
};

const setCell = (target, prop, value) => {
  if (typeof value === 'string' && value[0] === '=') {
    const src = '() => ' + value.substring(1);
    const options = { context: target.context };
    const script = metavm.createScript(prop, src, options);
    target.expressions.set(prop, script.exports);
  } else {
    target.data.set(prop, value);
  }
  return true;
};

class Sheet {
  constructor() {
    this.data = new Map();
    this.expressions = new Map();
    this.values = new Proxy(this, { get: getValue });
    this.context = metavm.createContext(this.values);
    this.cells = new Proxy(this, { get: getCell, set: setCell });
  }
}

module.exports = { Sheet };
Program: CWE-94
Project: CVE-2022-24816
Buggy source:
None

Fixed version (ground truth):
/* JAI-Ext - OpenSource Java Advanced Image Extensions Library
 *    http://www.geo-solutions.it/
 *    Copyright 2018 GeoSolutions
 *
 * Licensed 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 it.geosolutions.jaiext.jiffle.runtime;

import it.geosolutions.jaiext.jiffle.Jiffle;
import it.geosolutions.jaiext.jiffle.JiffleException;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class JiffleRuntimeTest {

    @Test
    public void testSkipSource() throws Exception {
        Jiffle jiffle = getJiffleWithComment();
        String source = jiffle.getRuntimeSource(false);

        // by default, it does not contain the source
        assertFalse(source.contains("This is a comment"));
    }

    @Test
    public void testEscapeSource() throws Exception {
        Jiffle jiffle = getJiffleWithComment();
        String source = jiffle.getRuntimeSource(true);

        // source is in the javadocs, and properly escaped
        assertTrue(source.contains("* &#47;* This is a comment *&#47;"));
        assertTrue(source.contains("* dest=10;"));
    }

    private Jiffle getJiffleWithComment() throws JiffleException {
        String script = "/* This is a comment */\ndest=10;";
        Jiffle jiffle = new Jiffle();
        jiffle.setScript(script);
        Map<String, Jiffle.ImageRole> params = new HashMap<>();
        params.put("dest", Jiffle.ImageRole.DEST);
        jiffle.setImageParams(params);

        jiffle.compile();
        return jiffle;
    }
}
Program: CWE-94
Project: CVE-2022-25759
Buggy source:
{
  "name": "convert-svg-core",
  "version": "0.6.1",
  "description": "Supports converting SVG into another format using headless Chromium",
  "homepage": "https://github.com/neocotic/convert-svg",
  "bugs": {
    "url": "https://github.com/neocotic/convert-svg/issues"
  },
  "author": {
    "name": "neocotic",
    "url": "https://github.com/neocotic"
  },
  "funding": [
    {
      "type": "individual",
      "url": "https://github.com/sponsors/neocotic"
    },
    {
      "type": "patreon",
      "url": "https://www.patreon.com/neocotic"
    }
  ],
  "license": "MIT",
  "keywords": [
    "convert",
    "converter",
    "svg",
    "core",
    "headless",
    "chromium"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/neocotic/convert-svg.git",
    "directory": "packages/convert-svg-core"
  },
  "dependencies": {
    "chalk": "^4.1.2",
    "cheerio": "^1.0.0-rc.10",
    "commander": "^9.2.0",
    "file-url": "^3.0.0",
    "get-stdin": "^8.0.0",
    "glob": "^8.0.1",
    "lodash.omit": "^4.5.0",
    "lodash.pick": "^4.4.0",
    "pollock": "^0.2.0",
    "puppeteer": "^13.7.0",
    "tmp": "^0.2.1"
  },
  "devDependencies": {
    "mocha": "^9.2.2",
    "sinon": "^13.0.2"
  },
  "main": "src/index.js",
  "engines": {
    "node": "^12.20.0 || >=14"
  }
}


Fixed version (ground truth):
{
  "name": "convert-svg-core",
  "version": "0.6.1",
  "description": "Supports converting SVG into another format using headless Chromium",
  "homepage": "https://github.com/neocotic/convert-svg",
  "bugs": {
    "url": "https://github.com/neocotic/convert-svg/issues"
  },
  "author": {
    "name": "neocotic",
    "url": "https://github.com/neocotic"
  },
  "funding": [
    {
      "type": "individual",
      "url": "https://github.com/sponsors/neocotic"
    },
    {
      "type": "patreon",
      "url": "https://www.patreon.com/neocotic"
    }
  ],
  "license": "MIT",
  "keywords": [
    "convert",
    "converter",
    "svg",
    "core",
    "headless",
    "chromium"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/neocotic/convert-svg.git",
    "directory": "packages/convert-svg-core"
  },
  "dependencies": {
    "chalk": "^4.1.2",
    "cheerio": "^1.0.0-rc.11",
    "commander": "^9.2.0",
    "file-url": "^3.0.0",
    "get-stdin": "^8.0.0",
    "glob": "^8.0.1",
    "lodash.omit": "^4.5.0",
    "lodash.pick": "^4.4.0",
    "pollock": "^0.2.0",
    "puppeteer": "^13.7.0",
    "tmp": "^0.2.1"
  },
  "devDependencies": {
    "mocha": "^9.2.2",
    "sinon": "^13.0.2"
  },
  "main": "src/index.js",
  "engines": {
    "node": "^12.20.0 || >=14"
  }
}
Program: CWE-863
Project: CVE-2020-14214
Buggy source:
class Widget extends App.Controller
  constructor: ->

    # for browser test
    App.Event.bind('user_signup_verify', (user) ->
      new Modal(user: user)
      'user_signup_verify'
    )

    App.Event.bind('auth:login', (user) =>
      return if !user
      @verifyLater(user.id)
      'user_signup_verify'
    )
    user = App.User.current()
    @verifyLater(user.id) if user?

  verifyLater: (userId) =>
    delay = =>
      @verify(userId)
    @delay(delay, 5000, 'user_signup_verify_dialog')

  verify: (userId) ->
    return if !userId
    return if !App.User.exists(userId)
    user = App.User.find(userId)
    return if user.source isnt 'signup'
    return if user.verified is true
    currentTime = new Date().getTime()
    createdAt = Date.parse(user.created_at)
    diff = currentTime - createdAt
    max = 1000 * 60 * 30 # show message if account is older then 30 minutes
    return if diff < max
    new Modal(user: user)

class Modal extends App.ControllerModal
  backdrop: false
  keyboard: false
  head: 'Account not verified'
  small: true
  buttonClose: false
  buttonCancel: false
  buttonSubmit: 'Resend verification email'

  constructor: ->
    super

  content: =>
    if !@sent
      return App.i18n.translateContent('Your account has not been verified. Please click the link in the verification email.')
    content = App.i18n.translateContent('We\'ve sent an email to _%s_. Click the link in the email to verify your account.', @user.email)
    content += '<br><br>'
    content += App.i18n.translateContent('If you don\'t see the email, check other places it might be, like your junk, spam, social, or other folders.')
    content

  onSubmit: =>
    @ajax(
      id:          'email_verify_send'
      type:        'POST'
      url:         @apiPath + '/users/email_verify_send'
      data:        JSON.stringify(email: @user.email)
      processData: true
      success:     @success
      error:       @error
    )

  success: (data) =>
    @sent = true
    @update()

    # if in developer mode, redirect to verify
    if data.token && @Config.get('developer_mode') is true
      redirect = =>
        @close()
        @navigate "#email_verify/#{data.token}"
      App.Delay.set(redirect, 4000)

  error: =>
    @contentInline = App.i18n.translateContent('Unable to send verify email.')
    @update()

App.Config.set('user_signup', Widget, 'Widgets')


Fixed version (ground truth):
None
Program: CWE-863
Project: CVE-2021-29642
Buggy source:
import * as vscode from "vscode";

const CONFIG_SECTION = "gistpad";

export function get(key: "treeIcons"): boolean;
export function get(key: "apiUrl"): string;
export function get(key: "images.markdownPasteFormat"): "markdown" | "html";
export function get(key: "images.pasteType"): "file" | "base64";
export function get(key: "images.directoryName"): string;
export function get(key: "scratchNotes.directoryFormat"): string;
export function get(key: "scratchNotes.fileExtension"): string;
export function get(key: "scratchNotes.fileFormat"): string;
export function get(key: "scratchNotes.show"): boolean;
export function get(key: "showcaseUrl"): string;
export function get(key: "comments.showThread"): string;
export function get(key: any) {
  const extensionConfig = vscode.workspace.getConfiguration(CONFIG_SECTION);
  return extensionConfig.get(key);
}

export async function set(key: string, value: any) {
  const extensionConfig = vscode.workspace.getConfiguration(CONFIG_SECTION);
  return extensionConfig.update(key, value, true);
}


Fixed version (ground truth):
import * as vscode from "vscode";

const CONFIG_SECTION = "gistpad";

export function get(key: "treeIcons"): boolean;
export function get(key: "images.markdownPasteFormat"): "markdown" | "html";
export function get(key: "images.pasteType"): "file" | "base64";
export function get(key: "images.directoryName"): string;
export function get(key: "scratchNotes.directoryFormat"): string;
export function get(key: "scratchNotes.fileExtension"): string;
export function get(key: "scratchNotes.fileFormat"): string;
export function get(key: "scratchNotes.show"): boolean;
export function get(key: "showcaseUrl"): string;
export function get(key: "comments.showThread"): string;
export function get(key: any) {
  const extensionConfig = vscode.workspace.getConfiguration(CONFIG_SECTION);
  return extensionConfig.get(key);
}

export async function set(key: string, value: any) {
  const extensionConfig = vscode.workspace.getConfiguration(CONFIG_SECTION);
  return extensionConfig.update(key, value, true);
}
Program: CWE-863
Project: CVE-2021-41093
Buggy source:
github "wireapp/Cartography" "4.0.0_xcframework"
github "wireapp/DifferenceKit" "1.1.5_xcframework"
github "wireapp/Down" "v2.3.0_xcframework"
github "wireapp/FLAnimatedImage" "1.0.12_xcframework"
github "wireapp/FormatterKit" "1.8.1_xcframework"
github "wireapp/HTMLString" "6.0.1_xcframework"
github "wireapp/PINCache" "2.3-xcframework"
github "wireapp/ZipArchive" "v2.2.3_xcframework"
github "wireapp/appcenter-sdk-apple" "3.3.4_xcframework"
github "wireapp/avs-ios-binaries" "6.7.244_xcframework"
github "wireapp/countly-sdk-ios" "20.11.1_xcframework"
github "wireapp/ios-snapshot-test-case" "4.0.0-xcframework"
github "wireapp/libPhoneNumber-iOS" "0.9.3_xcframework"
github "wireapp/ocmock" "v3.4.3_xcframework"
github "wireapp/swift-protobuf" "1.15.0_xcframework"
github "wireapp/swift-snapshot-testing" "1.8.2-xcframework"
github "wireapp/wire-ios-canvas" "13.0.2"
github "wireapp/wire-ios-cryptobox" "27.0.6"
github "wireapp/wire-ios-data-model" "261.0.0"
github "wireapp/wire-ios-images" "35.0.4"
github "wireapp/wire-ios-link-preview" "31.0.4"
github "wireapp/wire-ios-protos" "28.0.1"
github "wireapp/wire-ios-request-strategy" "237.0.0"
github "wireapp/wire-ios-share-engine" "222.0.0"
github "wireapp/wire-ios-sync-engine" "385.0.0"
github "wireapp/wire-ios-system" "34.1.1"
github "wireapp/wire-ios-testing" "25.1.1"
github "wireapp/wire-ios-transport" "77.0.4"
github "wireapp/wire-ios-utilities" "41.0.6"
github "wireapp/wire-ios-ziphy" "16.0.3"


Fixed version (ground truth):
github "wireapp/Cartography" "4.0.0_xcframework"
github "wireapp/DifferenceKit" "1.1.5_xcframework"
github "wireapp/Down" "v2.3.0_xcframework"
github "wireapp/FLAnimatedImage" "1.0.12_xcframework"
github "wireapp/FormatterKit" "1.8.1_xcframework"
github "wireapp/HTMLString" "6.0.1_xcframework"
github "wireapp/PINCache" "2.3-xcframework"
github "wireapp/ZipArchive" "v2.2.3_xcframework"
github "wireapp/appcenter-sdk-apple" "3.3.4_xcframework"
github "wireapp/avs-ios-binaries" "6.7.244_xcframework"
github "wireapp/countly-sdk-ios" "20.11.1_xcframework"
github "wireapp/ios-snapshot-test-case" "4.0.0-xcframework"
github "wireapp/libPhoneNumber-iOS" "0.9.3_xcframework"
github "wireapp/ocmock" "v3.4.3_xcframework"
github "wireapp/swift-protobuf" "1.15.0_xcframework"
github "wireapp/swift-snapshot-testing" "1.8.2-xcframework"
github "wireapp/wire-ios-canvas" "13.0.2"
github "wireapp/wire-ios-cryptobox" "27.0.6"
github "wireapp/wire-ios-data-model" "261.0.0"
github "wireapp/wire-ios-images" "35.0.4"
github "wireapp/wire-ios-link-preview" "31.0.4"
github "wireapp/wire-ios-protos" "28.0.1"
github "wireapp/wire-ios-request-strategy" "237.0.0"
github "wireapp/wire-ios-share-engine" "222.0.0"
github "wireapp/wire-ios-sync-engine" "385.0.1"
github "wireapp/wire-ios-transport" "77.1.0"
github "wireapp/wire-ios-system" "34.1.1"
github "wireapp/wire-ios-testing" "25.1.1"
github "wireapp/wire-ios-utilities" "41.0.6"
github "wireapp/wire-ios-ziphy" "16.0.3"
Program: CWE-863
Project: CVE-2022-0905
Buggy source:
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

//go:build pam
// +build pam

package pam

import (
	"errors"

	"github.com/msteinert/pam"
)

// Supported is true when built with PAM
var Supported = true

// Auth pam auth service
func Auth(serviceName, userName, passwd string) (string, error) {
	t, err := pam.StartFunc(serviceName, userName, func(s pam.Style, msg string) (string, error) {
		switch s {
		case pam.PromptEchoOff:
			return passwd, nil
		case pam.PromptEchoOn, pam.ErrorMsg, pam.TextInfo:
			return "", nil
		}
		return "", errors.New("Unrecognized PAM message style")
	})
	if err != nil {
		return "", err
	}

	if err = t.Authenticate(0); err != nil {
		return "", err
	}

	// PAM login names might suffer transformations in the PAM stack.
	// We should take whatever the PAM stack returns for it.
	return t.GetItem(pam.User)
}


Fixed version (ground truth):
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

//go:build pam
// +build pam

package pam

import (
	"errors"

	"github.com/msteinert/pam"
)

// Supported is true when built with PAM
var Supported = true

// Auth pam auth service
func Auth(serviceName, userName, passwd string) (string, error) {
	t, err := pam.StartFunc(serviceName, userName, func(s pam.Style, msg string) (string, error) {
		switch s {
		case pam.PromptEchoOff:
			return passwd, nil
		case pam.PromptEchoOn, pam.ErrorMsg, pam.TextInfo:
			return "", nil
		}
		return "", errors.New("Unrecognized PAM message style")
	})
	if err != nil {
		return "", err
	}

	if err = t.Authenticate(0); err != nil {
		return "", err
	}
	
	if err = t.AcctMgmt(0); err != nil {
	  return "", err
  }

	// PAM login names might suffer transformations in the PAM stack.
	// We should take whatever the PAM stack returns for it.
	return t.GetItem(pam.User)
}
Program: CWE-863
Project: CVE-2022-31032
Buggy source:
None

Fixed version (ground truth):
name,action,comment
Program: CWE-863
Project: CVE-2022-35924
Buggy source:
{
  "extends": "@next-auth/tsconfig/base.json",
  "compilerOptions": {
    "emitDeclarationOnly": true,
    "strictNullChecks": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "strict": false,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "stripInternal": true,
    "skipDefaultLibCheck": true,
    "baseUrl": ".",
    "outDir": ".",
    "paths": {
      "next": ["node_modules/next"]
    }
  },
  "exclude": ["./*.js", "./*.d.ts", "config", "**/__tests__", "tests"]
}


Fixed version (ground truth):
{
  "extends": "@next-auth/tsconfig/base.json",
  "compilerOptions": {
    "emitDeclarationOnly": true,
    "strictNullChecks": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "strict": false,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "stripInternal": true,
    "skipDefaultLibCheck": true,
    "baseUrl": ".",
    "outDir": ".",
    "paths": {
      "next": ["node_modules/next"]
    }
  },
  "exclude": [
    "./*.js",
    "./*.d.ts",
    "config",
    "**/__tests__",
    "tests",
    "coverage"
  ]
}
Program: CWE-276
Project: CVE-2020-15145
Buggy source:
None

Fixed version (ground truth):
@echo off

:: remove inheritance
icacls %ALLUSERSPROFILE%\ComposerSetup /inheritance:d /Q

:: remove creator owner
icacls %ALLUSERSPROFILE%\ComposerSetup /remove:g *S-1-3-0 /Q

:: remove builtin\users
icacls %ALLUSERSPROFILE%\ComposerSetup /remove:g *S-1-5-32-545 /Q

:: grant read-execute to builtin\users 
icacls %ALLUSERSPROFILE%\ComposerSetup /grant *S-1-5-32-545:(OI)(CI)(RX) /Q
Program: CWE-276
Project: CVE-2020-15852
Buggy source:
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _ASM_X86_IOBITMAP_H
#define _ASM_X86_IOBITMAP_H

#include <linux/refcount.h>
#include <asm/processor.h>

struct io_bitmap {
	u64		sequence;
	refcount_t	refcnt;
	/* The maximum number of bytes to copy so all zero bits are covered */
	unsigned int	max;
	unsigned long	bitmap[IO_BITMAP_LONGS];
};

struct task_struct;

#ifdef CONFIG_X86_IOPL_IOPERM
void io_bitmap_share(struct task_struct *tsk);
void io_bitmap_exit(struct task_struct *tsk);

void native_tss_update_io_bitmap(void);

#ifdef CONFIG_PARAVIRT_XXL
#include <asm/paravirt.h>
#else
#define tss_update_io_bitmap native_tss_update_io_bitmap
#endif

#else
static inline void io_bitmap_share(struct task_struct *tsk) { }
static inline void io_bitmap_exit(struct task_struct *tsk) { }
static inline void tss_update_io_bitmap(void) { }
#endif

#endif


Fixed version (ground truth):
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _ASM_X86_IOBITMAP_H
#define _ASM_X86_IOBITMAP_H

#include <linux/refcount.h>
#include <asm/processor.h>

struct io_bitmap {
	u64		sequence;
	refcount_t	refcnt;
	/* The maximum number of bytes to copy so all zero bits are covered */
	unsigned int	max;
	unsigned long	bitmap[IO_BITMAP_LONGS];
};

struct task_struct;

#ifdef CONFIG_X86_IOPL_IOPERM
void io_bitmap_share(struct task_struct *tsk);
void io_bitmap_exit(struct task_struct *tsk);

static inline void native_tss_invalidate_io_bitmap(void)
{
	/*
	 * Invalidate the I/O bitmap by moving io_bitmap_base outside the
	 * TSS limit so any subsequent I/O access from user space will
	 * trigger a #GP.
	 *
	 * This is correct even when VMEXIT rewrites the TSS limit
	 * to 0x67 as the only requirement is that the base points
	 * outside the limit.
	 */
	this_cpu_write(cpu_tss_rw.x86_tss.io_bitmap_base,
		       IO_BITMAP_OFFSET_INVALID);
}

void native_tss_update_io_bitmap(void);

#ifdef CONFIG_PARAVIRT_XXL
#include <asm/paravirt.h>
#else
#define tss_update_io_bitmap native_tss_update_io_bitmap
#define tss_invalidate_io_bitmap native_tss_invalidate_io_bitmap
#endif

#else
static inline void io_bitmap_share(struct task_struct *tsk) { }
static inline void io_bitmap_exit(struct task_struct *tsk) { }
static inline void tss_update_io_bitmap(void) { }
#endif

#endif