Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rust target with reqwest #328

Merged
merged 6 commits into from
Jul 12, 2024
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
7 changes: 3 additions & 4 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ on:
jobs:
scan:
permissions:
packages: write
packages: write
contents: write # publish sbom to GH releases/tag assets
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -74,14 +74,14 @@ jobs:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-depth: 0

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20.9.0
registry-url: 'https://registry.npmjs.org'

- name: Install
run: npm ci

Expand All @@ -92,4 +92,3 @@ jobs:
run: npm publish --no-git-checks --provenance --tag ${{ github.sha }}
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ jobs:
id: core_tag_and_release
with:
tag: v${{ env.TAG }}
name: "httpsnippet v${{ env.TAG }} 📦"
name: 'httpsnippet v${{ env.TAG }} 📦'
generateReleaseNotes: true
prerelease: false
draft: false
draft: false
3 changes: 1 addition & 2 deletions .github/workflows/sast.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ on:
pull_request: {}
push:
branches:
- master
- master
workflow_dispatch: {}


jobs:
semgrep:
name: Semgrep SAST
Expand Down
2 changes: 1 addition & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ At HTTPSnippet, we take security issues very seriously. If you believe you have
## How to Report

1. **Do not publicly disclose the vulnerability**: Please do not create a GitHub issue or post the vulnerability on public forums. Instead, contact us directly at [[email protected]](mailto:[email protected]).
2. **Provide detailed information**: When reporting a vulnerability, please include as much information as possible to help us understand and reproduce the issue. This may include:
1. **Provide detailed information**: When reporting a vulnerability, please include as much information as possible to help us understand and reproduce the issue. This may include:
- Description of the vulnerability
- Steps to reproduce the issue
- Potential impact
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"request",
"requests",
"ruby",
"rust",
"shell",
"snippet",
"swift",
Expand Down Expand Up @@ -72,8 +73,8 @@
"eslint-plugin-jest": "^26.1.3",
"eslint-plugin-jest-formatting": "^3.1.0",
"eslint-plugin-simple-import-sort": "^7.0.0",
"markdownlint-cli2": "^0.5.1",
"jest": "^27.5.1",
"markdownlint-cli2": "^0.5.1",
"prettier": "^2.6.2",
"ts-jest": "^27.1.4",
"type-fest": "^2.12.2",
Expand Down
14 changes: 14 additions & 0 deletions src/helpers/__snapshots__/utils.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,20 @@ Array [
"key": "ruby",
"title": "Ruby",
},
Object {
"clients": Array [
Object {
"description": "reqwest HTTP library",
"key": "reqwest",
"link": "https://docs.rs/reqwest/latest/reqwest/",
"title": "reqwest",
},
],
"default": "reqwest",
"extname": ".rs",
"key": "rust",
"title": "Rust",
},
Object {
"clients": Array [
Object {
Expand Down
12 changes: 12 additions & 0 deletions src/helpers/code-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ export class CodeBuilder {
this.code.push(newLine);
};

/**
* Add the line to the end of the last line. Creates a new line
* if no lines exist yet.
*/
pushToLast = (line: string) => {
if (!this.code) {
this.push(line);
}
const updatedLine = `${this.code[this.code.length - 1]}${line}`;
this.code[this.code.length - 1] = updatedLine;
};

/**
* Add an empty line at the end of current lines
*/
Expand Down
20 changes: 6 additions & 14 deletions src/helpers/escape.test.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,26 @@
import { escapeString } from './escape';

describe('Escape methods', () => {
describe('escape methods', () => {
describe('escapeString', () => {
it('does nothing to a safe string', () => {
expect(
escapeString("hello world")
).toBe("hello world");
expect(escapeString('hello world')).toBe('hello world');
});

it('escapes double quotes by default', () => {
expect(
escapeString('"hello world"')
).toBe('\\"hello world\\"');
expect(escapeString('"hello world"')).toBe('\\"hello world\\"');
});

it('escapes newlines by default', () => {
expect(
escapeString('hello\r\nworld')
).toBe('hello\\r\\nworld');
expect(escapeString('hello\r\nworld')).toBe('hello\\r\\nworld');
});

it('escapes backslashes', () => {
expect(
escapeString('hello\\world')
).toBe('hello\\\\world');
expect(escapeString('hello\\world')).toBe('hello\\\\world');
});

it('escapes unrepresentable characters', () => {
expect(
escapeString('hello \u0000') // 0 = ASCII 'null' character
escapeString('hello \u0000'), // 0 = ASCII 'null' character
).toBe('hello \\u0000');
});
});
Expand Down
69 changes: 31 additions & 38 deletions src/helpers/escape.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,47 +31,42 @@ export interface EscapeOptions {
* for the complete original algorithm.
*/
export function escapeString(rawValue: any, options: EscapeOptions = {}) {
const {
delimiter = '"',
escapeChar = '\\',
escapeNewlines = true
} = options;
const { delimiter = '"', escapeChar = '\\', escapeNewlines = true } = options;

const stringValue = rawValue.toString();

return [...stringValue].map((c) => {
if (c === '\b') {
return escapeChar + 'b';
} else if (c === '\t') {
return escapeChar + 't';
} else if (c === '\n') {
if (escapeNewlines) {
return escapeChar + 'n';
} else {
return [...stringValue]
.map(c => {
if (c === '\b') {
return `${escapeChar}b`;
} else if (c === '\t') {
return `${escapeChar}t`;
} else if (c === '\n') {
if (escapeNewlines) {
return `${escapeChar}n`;
}
return c; // Don't just continue, or this is caught by < \u0020
}
} else if (c === '\f') {
return escapeChar + 'f';
} else if (c === '\r') {
if (escapeNewlines) {
return escapeChar + 'r';
} else {
} else if (c === '\f') {
return `${escapeChar}f`;
} else if (c === '\r') {
if (escapeNewlines) {
return `${escapeChar}r`;
}
return c; // Don't just continue, or this is caught by < \u0020
} else if (c === escapeChar) {
return escapeChar + escapeChar;
} else if (c === delimiter) {
return escapeChar + delimiter;
} else if (c < '\u0020' || c > '\u007E') {
// Delegate the trickier non-ASCII cases to the normal algorithm. Some of these
// are escaped as \uXXXX, whilst others are represented literally. Since we're
// using this primarily for header values that are generally (though not 100%
// strictly?) ASCII-only, this should almost never happen.
return JSON.stringify(c).slice(1, -1);
}
} else if (c === escapeChar) {
return escapeChar + escapeChar;
} else if (c === delimiter) {
return escapeChar + delimiter;
} else if (c < '\u0020' || c > '\u007E') {
// Delegate the trickier non-ASCII cases to the normal algorithm. Some of these
// are escaped as \uXXXX, whilst others are represented literally. Since we're
// using this primarily for header values that are generally (though not 100%
// strictly?) ASCII-only, this should almost never happen.
return JSON.stringify(c).slice(1, -1);
} else {
return c;
}
}).join('');
})
.join('');
}

/**
Expand All @@ -81,8 +76,7 @@ export function escapeString(rawValue: any, options: EscapeOptions = {}) {
*
* If value is not a string, it will be stringified with .toString() first.
*/
export const escapeForSingleQuotes = (value: any) =>
escapeString(value, { delimiter: "'" });
export const escapeForSingleQuotes = (value: any) => escapeString(value, { delimiter: "'" });

/**
* Make a string value safe to insert literally into a snippet within double quotes,
Expand All @@ -91,5 +85,4 @@ export const escapeForSingleQuotes = (value: any) =>
*
* If value is not a string, it will be stringified with .toString() first.
*/
export const escapeForDoubleQuotes = (value: any) =>
escapeString(value, { delimiter: '"' });
export const escapeForDoubleQuotes = (value: any) => escapeString(value, { delimiter: '"' });
2 changes: 0 additions & 2 deletions src/helpers/headers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { ValueOf } from 'type-fest';

type Headers<T> = Record<string, T>;

/**
Expand Down
6 changes: 5 additions & 1 deletion src/targets/c/libcurl/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ export const libcurl: Client = {
push('struct curl_slist *headers = NULL;');

headers.forEach(header => {
push(`headers = curl_slist_append(headers, "${header}: ${escapeForDoubleQuotes(headersObj[header])}");`);
push(
`headers = curl_slist_append(headers, "${header}: ${escapeForDoubleQuotes(
headersObj[header],
)}");`,
);
});

push('curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);');
Expand Down
4 changes: 3 additions & 1 deletion src/targets/ocaml/cohttp/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ export const cohttp: Client = {

if (headers.length === 1) {
push(
`let headers = Header.add (Header.init ()) "${headers[0]}" "${escapeForDoubleQuotes(allHeaders[headers[0]])}" in`,
`let headers = Header.add (Header.init ()) "${headers[0]}" "${escapeForDoubleQuotes(
allHeaders[headers[0]],
)}" in`,
);
} else if (headers.length > 1) {
push('let headers = Header.add_list (Header.init ()) [');
Expand Down
8 changes: 6 additions & 2 deletions src/targets/php/guzzle/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,19 @@ export const guzzle: Client<GuzzleOptions> = {
const headers = Object.keys(headersObj)
.sort()
.map(function (key) {
return `${opts.indent}${opts.indent}'${key}' => '${escapeForSingleQuotes(headersObj[key])}',`;
return `${
opts.indent
}${opts.indent}'${key}' => '${escapeForSingleQuotes(headersObj[key])}',`;
});

// construct cookies
const cookieString = cookies
.map(cookie => `${encodeURIComponent(cookie.name)}=${encodeURIComponent(cookie.value)}`)
.join('; ');
if (cookieString.length) {
headers.push(`${opts.indent}${opts.indent}'cookie' => '${escapeForSingleQuotes(cookieString)}',`);
headers.push(
`${opts.indent}${opts.indent}'cookie' => '${escapeForSingleQuotes(cookieString)}',`,
);
}

if (headers.length) {
Expand Down
2 changes: 1 addition & 1 deletion src/targets/php/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { escapeString } from "../../helpers/escape";
import { escapeString } from '../../helpers/escape';

export const convertType = (obj: any[] | any, indent?: string, lastIndent?: string) => {
lastIndent = lastIndent || '';
Expand Down
9 changes: 6 additions & 3 deletions src/targets/powershell/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,12 @@ export const generatePowershellConvert = (command: PowershellCommand) => {
}

if (postData.text) {
commandOptions.push(`-ContentType '${
escapeString(getHeader(allHeaders, 'content-type'), { delimiter: "'", escapeChar: '`' })
}'`);
commandOptions.push(
`-ContentType '${escapeString(getHeader(allHeaders, 'content-type'), {
delimiter: "'",
escapeChar: '`',
})}'`,
);
commandOptions.push(`-Body '${postData.text}'`);
}

Expand Down
25 changes: 11 additions & 14 deletions src/targets/r/httr/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,31 +98,26 @@ export const httr: Client = {

// Construct headers
const cookieHeader = getHeader(allHeaders, 'cookie');
let acceptHeader = getHeader(allHeaders, 'accept');
const acceptHeader = getHeader(allHeaders, 'accept');

const setCookies = cookieHeader
? `set_cookies(\`${String(cookieHeader)
.replace(/;/g, '", `')
.replace(/` /g, '`')
.replace(/[=]/g, '` = "')
}")`
: undefined
.replace(/[=]/g, '` = "')}")`
: undefined;

const setAccept = acceptHeader
? `accept("${escapeForDoubleQuotes(acceptHeader)}")`
: undefined
const setAccept = acceptHeader ? `accept("${escapeForDoubleQuotes(acceptHeader)}")` : undefined;

const setContentType = `content_type("${escapeForDoubleQuotes(postData.mimeType)}")`
const setContentType = `content_type("${escapeForDoubleQuotes(postData.mimeType)}")`;

const otherHeaders = Object.entries(allHeaders)
// These headers are all handled separately:
.filter(([key]) => !['cookie', 'accept', 'content-type'].includes(key.toLowerCase()))
.map(([key, value]) => `'${key}' = '${escapeForSingleQuotes(value)}'`)
.join(', ')
.join(', ');

const setHeaders = otherHeaders
? `add_headers(${otherHeaders})`
: undefined
const setHeaders = otherHeaders ? `add_headers(${otherHeaders})` : undefined;

// Construct request
let request = `response <- VERB("${method}", url`;
Expand All @@ -135,10 +130,12 @@ export const httr: Client = {
request += ', query = queryString';
}

const headerAdditions = [setHeaders, setContentType, setAccept, setCookies].filter(x => !!x).join(', ');
const headerAdditions = [setHeaders, setContentType, setAccept, setCookies]
.filter(x => !!x)
.join(', ');

if (headerAdditions) {
request += ', ' + headerAdditions
request += `, ${headerAdditions}`;
}

if (postData.text || postData.jsonObj || postData.params) {
Expand Down
Loading
Loading