DEV Community

Cover image for SecureCode.
SIBI M S
SIBI M S

Posted on

SecureCode.

This is a submission for the Cloudflare AI Challenge.

What We Built

SecureCode.

SecureCode. is an application designed to help code security by pinpointing vulnerabilities. With the help of Cloudflare AI Model, Our app detects various parameters crucial for securing your codebase:

Vulnerability Type: Indicate the type of vulnerability detected in the code snippet (e.g., SQL injection, cross-site scripting, buffer overflow).

Severity Level: Assign a severity level to each detected vulnerability (e.g., critical, high, medium, low) to prioritize remediation efforts.

Location: Highlight the specific location within the code where the vulnerability was detected (e.g., line number, function name, file name) to facilitate debugging and fixing.

Explanation: Provide a brief explanation or description of the detected vulnerability, including how it could potentially be exploited and its impact on security.

Recommendations: Offer recommendations or suggested fixes to address the detected vulnerabilities, such as code changes or security best practices to follow.

Overall Security Percentage: Return the overall security percentage of the given code.

Demo

My Code

SecureCode.

SecureCode. is an application designed to help code security by pinpointing vulnerabilities.

SecureCode. is an application designed to help code security by pinpointing vulnerabilities. With the help of Cloudflare AI Model, Our app detects various parameters crucial for securing your codebase:

Vulnerability Type: Indicate the type of vulnerability detected in the code snippet (e.g., SQL injection, cross-site scripting, buffer overflow).

Severity Level: Assign a severity level to each detected vulnerability (e.g., critical, high, medium, low) to prioritize remediation efforts.

Location: Highlight the specific location within the code where the vulnerability was detected (e.g., line number, function name, file name) to facilitate debugging and fixing.

Explanation: Provide a brief explanation or description of the detected vulnerability, including how it could potentially be exploited and its impact on security.

Recommendations: Offer recommendations or suggested fixes to address the detected vulnerabilities, such as code changes or security best practices to follow.

Overall

SecureCode.

Journey

Initially we had a conversation on what to do for this challenge. We found ourselves pondering the prevalent issue of code security. Realizing the gap between coding and the secure practices, we saw an opportunity to bridge this divide. What if there existed a tool that not only identified vulnerabilities within our code but also served as an educational resource? A solution that not only pinpointed weaknesses but also imparted valuable insights on fortification against potential threats.

We tried to draft the parameters that are essentially helpful for the user for the given code. Then come up with some parameters that will be helpful for the developer. Those are Vulnerability Type, Severity Level, Location, Explanation, Recommendations, and Overall Security Score.

Then we played with the various prompts in the Cloudflare's AI model playground and we have chosen the llama-2-7b-chat-fp16 model because of its better results.

Then we crafted a minimalistic design in Figma. Once we got the blueprint of how it should look like, we started working on building the applcaiiton.

Coming to the backend, we have deployed the AI model in the Cloudflare Workers. Which we have used to genrate the result in the frontend. The following is the code for the deplyed AI worker.

addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const body = await request.json();
  const codeSnippet = body.code;

  // Safety Check: Ensure codeSnippet exists and is a string
  if (!codeSnippet || typeof codeSnippet !== "string") {
    const responseData = {
      status: 400,
      body: {
        message: "Invalid code snippet provided",
      },
    };

    return new Response(JSON.stringify(responseData), {
      headers: {
        "content-type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
    });
  }

  const payload = JSON.stringify({
    messages: [
      {
        role: "system",
        content:
          'You are a helpful assistant tasked with analyzing code snippets for vulnerabilities. \n\nReturn Output in the following example JSON format:\n```

json\n{\n"Vulnerability Type": "<Vulnerability Type>",\n"Severity Level": "<Level>",\n"Location": "<Line Number>",\n"Explanation": "<Explanation about the vulnerability>",\n"Recommendations": "<Offer recommendations or suggested fixes>",\n"Overall Security Score": "<Percentage>"\n}\n

```',
      },
      { role: "user", content: codeSnippet },
    ],
  });

  const response = await fetch(
    "https://api.cloudflare.com/client/v4/accounts/account_ID/ai/run/@cf/meta/llama-2-7b-chat-fp16",
    {
      method: "POST",
      headers: {
        Authorization: `Bearer Account_Token`,
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
      body: payload,
    }
  );

  const aiResult = await response.json();

  try {
    const stringifiedJson = aiResult.result.response;

    const start = stringifiedJson.indexOf("{");
    const end = stringifiedJson.lastIndexOf("}") + 1;

    const jsonPart = stringifiedJson.slice(start, end);

    const parsedJson = JSON.parse(jsonPart);

    const responseData = {
      status: 200,
      body: parsedJson,
    };

    return new Response(JSON.stringify(responseData), {
      headers: {
        "content-type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
    });
  } catch {
    const responseData = {
      status: 500,
      body: {
        message: "Oops! Looks like your input took a wrong turn :(",
      },
    };

    return new Response(JSON.stringify(responseData), {
      headers: {
        "content-type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

We're excited to be exploring the Cloudflare platform for the first time! It's been an amazing learning experience, and we're looking forward to using this tool for many more projects in the future. Thanks a lot for taking the time to read about our journey!

Team members - @engineeredsoul @mohandotdev @santoholic @sanjayalagappan

Top comments (1)

Collapse
 
fyodorio profile image
Fyodor

Dude, that’s a really awesome project for developers, I’d give it the golden prize 👍 And it’s a great team work! You guys rule, keep it up! 🚀