feat: add support for Digest authorization (#4339)
Co-authored-by: jamesgeorge007 <25279263+jamesgeorge007@users.noreply.github.com> Co-authored-by: nivedin <nivedinp@gmail.com>
This commit is contained in:
@@ -370,19 +370,7 @@ describe("hopp test [options] <file_path_or_id>", () => {
|
||||
);
|
||||
|
||||
describe("Request variables", () => {
|
||||
test("Picks active request variables and ignores inactive entries", async () => {
|
||||
const COLL_PATH = getTestJsonFilePath(
|
||||
"request-vars-coll.json",
|
||||
"collection"
|
||||
);
|
||||
|
||||
const args = `test ${COLL_PATH}`;
|
||||
|
||||
const { error } = await runCLI(args);
|
||||
expect(error).toBeNull();
|
||||
});
|
||||
|
||||
test("Supports the usage of request variables along with environment variables", async () => {
|
||||
test("Picks active request variables and ignores inactive entries alongside the usage of environment variables", async () => {
|
||||
const env = {
|
||||
...process.env,
|
||||
secretBasicAuthPasswordEnvVar: "password",
|
||||
@@ -430,6 +418,24 @@ describe("hopp test [options] <file_path_or_id>", () => {
|
||||
expect(error).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Digest Authorization type", () => {
|
||||
test("Successfully translates the authorization information to headers/query params and sends it along with the request", async () => {
|
||||
const COLL_PATH = getTestJsonFilePath(
|
||||
"digest-auth-coll.json",
|
||||
"collection"
|
||||
);
|
||||
const ENVS_PATH = getTestJsonFilePath(
|
||||
"digest-auth-envs.json",
|
||||
"environment"
|
||||
);
|
||||
|
||||
const args = `test ${COLL_PATH} -e ${ENVS_PATH}`;
|
||||
const { error } = await runCLI(args);
|
||||
|
||||
expect(error).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Test `hopp test <file_path_or_id> --delay <delay_in_ms>` command:", () => {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"v": 3,
|
||||
"name": "Digest Auth - collection",
|
||||
"folders": [],
|
||||
"requests": [
|
||||
{
|
||||
"v": "8",
|
||||
"id": "cm0dm70cw000687bnxi830zz7",
|
||||
"auth": {
|
||||
"authType": "digest",
|
||||
"authActive": true,
|
||||
"username": "<<username>>",
|
||||
"password": "<<password>>",
|
||||
"realm": "",
|
||||
"nonce": "",
|
||||
"algorithm": "MD5",
|
||||
"qop": "auth",
|
||||
"nc": "",
|
||||
"cnonce": "",
|
||||
"opaque": "",
|
||||
"disableRetry": false
|
||||
},
|
||||
"body": {
|
||||
"body": null,
|
||||
"contentType": null
|
||||
},
|
||||
"name": "digest-auth-headers",
|
||||
"method": "GET",
|
||||
"params": [],
|
||||
"headers": [],
|
||||
"endpoint": "<<url>>",
|
||||
"testScript": "pw.test(\"Status code is 200\", ()=> { pw.expect(pw.response.status).toBe(200);}); \n pw.test(\"Receives the www-authenticate header\", ()=> { pw.expect(pw.response.headers['www-authenticate']).toBeType('string');});",
|
||||
"preRequestScript": "",
|
||||
"responses": {},
|
||||
"requestVariables": []
|
||||
}
|
||||
],
|
||||
"auth": {
|
||||
"authType": "inherit",
|
||||
"authActive": true
|
||||
},
|
||||
"headers": []
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"v": 3,
|
||||
"name": "Digest Auth (failure state) - collection",
|
||||
"folders": [],
|
||||
"requests": [
|
||||
{
|
||||
"v": "8",
|
||||
"id": "cm0dm70cw000687bnxi830zz7",
|
||||
"auth": {
|
||||
"authType": "digest",
|
||||
"authActive": true,
|
||||
"username": "<<username>>",
|
||||
"password": "<<password>>",
|
||||
"realm": "",
|
||||
"nonce": "",
|
||||
"algorithm": "MD5",
|
||||
"qop": "auth",
|
||||
"nc": "",
|
||||
"cnonce": "",
|
||||
"opaque": "",
|
||||
"disableRetry": true
|
||||
},
|
||||
"body": {
|
||||
"body": null,
|
||||
"contentType": null
|
||||
},
|
||||
"name": "digest-auth-headers",
|
||||
"method": "GET",
|
||||
"params": [],
|
||||
"headers": [],
|
||||
"endpoint": "<<url>>",
|
||||
"testScript": "pw.test(\"Status code is not 200\", ()=> { pw.expect(pw.response.status).not.toBe(200);}); \n pw.test(\"Receives the www-authenticate header\", ()=> { pw.expect(pw.response.headers['www-authenticate']).not.toBeType('string');});",
|
||||
"preRequestScript": "",
|
||||
"responses": {},
|
||||
"requestVariables": []
|
||||
}
|
||||
],
|
||||
"auth": {
|
||||
"authType": "inherit",
|
||||
"authActive": true
|
||||
},
|
||||
"headers": []
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"v": 3,
|
||||
"name": "Digest Auth (success state) - collection",
|
||||
"folders": [],
|
||||
"requests": [
|
||||
{
|
||||
"v": "8",
|
||||
"id": "cm0dm70cw000687bnxi830zz7",
|
||||
"auth": {
|
||||
"authType": "digest",
|
||||
"authActive": true,
|
||||
"username": "<<username>>",
|
||||
"password": "<<password>>",
|
||||
"realm": "",
|
||||
"nonce": "",
|
||||
"algorithm": "MD5",
|
||||
"qop": "auth",
|
||||
"nc": "",
|
||||
"cnonce": "",
|
||||
"opaque": "",
|
||||
"disableRetry": false
|
||||
},
|
||||
"body": {
|
||||
"body": null,
|
||||
"contentType": null
|
||||
},
|
||||
"name": "digest-auth-headers",
|
||||
"method": "GET",
|
||||
"params": [],
|
||||
"headers": [],
|
||||
"endpoint": "<<url>>",
|
||||
"testScript": "pw.test(\"Status code is 200\", ()=> { pw.expect(pw.response.status).toBe(200);}); \n pw.test(\"Receives the www-authenticate header\", ()=> { pw.expect(pw.response.headers['www-authenticate']).toBeType('string');});",
|
||||
"preRequestScript": "",
|
||||
"responses": {},
|
||||
"requestVariables": []
|
||||
}
|
||||
],
|
||||
"auth": {
|
||||
"authType": "inherit",
|
||||
"authActive": true
|
||||
},
|
||||
"headers": []
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"v": 1,
|
||||
"id": "cm0dsn3v70004p4qk3l9b7sjm",
|
||||
"name": "Digest Auth - environments",
|
||||
"variables": [
|
||||
{
|
||||
"key": "username",
|
||||
"value": "admin",
|
||||
"secret": true
|
||||
},
|
||||
{
|
||||
"key": "password",
|
||||
"value": "admin",
|
||||
"secret": true
|
||||
},
|
||||
{
|
||||
"key": "url",
|
||||
"value": "https://test.insightres.org/digest/"
|
||||
}
|
||||
]
|
||||
}
|
||||
139
packages/hoppscotch-cli/src/utils/auth/digest.ts
Normal file
139
packages/hoppscotch-cli/src/utils/auth/digest.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import axios from "axios";
|
||||
import { md5 } from "js-md5";
|
||||
|
||||
import { exceptionColors } from "../getters";
|
||||
|
||||
export interface DigestAuthParams {
|
||||
username: string;
|
||||
password: string;
|
||||
realm: string;
|
||||
nonce: string;
|
||||
endpoint: string;
|
||||
method: string;
|
||||
algorithm: string;
|
||||
qop: string;
|
||||
nc?: string;
|
||||
opaque?: string;
|
||||
cnonce?: string; // client nonce (optional but typically required in qop='auth')
|
||||
}
|
||||
|
||||
export interface DigestAuthInfo {
|
||||
realm: string;
|
||||
nonce: string;
|
||||
qop: string;
|
||||
opaque?: string;
|
||||
algorithm: string;
|
||||
}
|
||||
|
||||
// Utility function to parse Digest auth header values
|
||||
const parseDigestAuthHeader = (
|
||||
header: string
|
||||
): { [key: string]: string } | null => {
|
||||
const matches = header.match(/([a-z0-9]+)="([^"]+)"/gi);
|
||||
if (!matches) return null;
|
||||
|
||||
const authParams: { [key: string]: string } = {};
|
||||
matches.forEach((match) => {
|
||||
const parts = match.split("=");
|
||||
authParams[parts[0]] = parts[1].replace(/"/g, "");
|
||||
});
|
||||
|
||||
return authParams;
|
||||
};
|
||||
|
||||
// Function to generate Digest Auth Header
|
||||
export const generateDigestAuthHeader = async (params: DigestAuthParams) => {
|
||||
const {
|
||||
username,
|
||||
password,
|
||||
realm,
|
||||
nonce,
|
||||
endpoint,
|
||||
method,
|
||||
algorithm = "MD5",
|
||||
qop,
|
||||
nc = "00000001",
|
||||
opaque,
|
||||
cnonce,
|
||||
} = params;
|
||||
|
||||
const uri = endpoint.replace(/(^\w+:|^)\/\//, "");
|
||||
|
||||
// Generate client nonce if not provided
|
||||
const generatedCnonce = cnonce || md5(`${Math.random()}`);
|
||||
|
||||
// Step 1: Hash the username, realm, and password
|
||||
const ha1 = md5(`${username}:${realm}:${password}`);
|
||||
|
||||
// Step 2: Hash the method and URI
|
||||
const ha2 = md5(`${method}:${uri}`);
|
||||
|
||||
// Step 3: Compute the response hash
|
||||
const response = md5(
|
||||
`${ha1}:${nonce}:${nc}:${generatedCnonce}:${qop}:${ha2}`
|
||||
);
|
||||
|
||||
// Build the Digest header
|
||||
let authHeader = `Digest username="${username}", realm="${realm}", nonce="${nonce}", uri="${uri}", algorithm="${algorithm}", response="${response}", qop=${qop}, nc=${nc}, cnonce="${generatedCnonce}"`;
|
||||
|
||||
if (opaque) {
|
||||
authHeader += `, opaque="${opaque}"`;
|
||||
}
|
||||
|
||||
return authHeader;
|
||||
};
|
||||
|
||||
export const fetchInitialDigestAuthInfo = async (
|
||||
url: string,
|
||||
method: string,
|
||||
disableRetry: boolean
|
||||
): Promise<DigestAuthInfo> => {
|
||||
try {
|
||||
const initialResponse = await axios.request({
|
||||
url,
|
||||
method,
|
||||
validateStatus: () => true, // Allow handling of all status codes
|
||||
});
|
||||
|
||||
// Check if the response status is 401 (which is expected in Digest Auth flow)
|
||||
if (initialResponse.status === 401 && !disableRetry) {
|
||||
const authHeader = initialResponse.headers["www-authenticate"];
|
||||
|
||||
if (authHeader) {
|
||||
const authParams = parseDigestAuthHeader(authHeader);
|
||||
if (
|
||||
authParams &&
|
||||
authParams.realm &&
|
||||
authParams.nonce &&
|
||||
authParams.qop
|
||||
) {
|
||||
return {
|
||||
realm: authParams.realm,
|
||||
nonce: authParams.nonce,
|
||||
qop: authParams.qop,
|
||||
opaque: authParams.opaque,
|
||||
algorithm: authParams.algorithm,
|
||||
};
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
"Failed to parse authentication parameters from WWW-Authenticate header"
|
||||
);
|
||||
} else if (initialResponse.status === 401 && disableRetry) {
|
||||
throw new Error(
|
||||
`401 Unauthorized received. Retry is disabled as specified, so no further attempts will be made.`
|
||||
);
|
||||
} else {
|
||||
throw new Error(`Unexpected response: ${initialResponse.status}`);
|
||||
}
|
||||
} catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : error;
|
||||
|
||||
console.error(
|
||||
exceptionColors.FAIL(
|
||||
`\n Error fetching initial digest auth info: ${errMsg} \n`
|
||||
)
|
||||
);
|
||||
throw error; // Re-throw the error to handle it further up the chain if needed
|
||||
}
|
||||
};
|
||||
@@ -26,6 +26,11 @@ import { isHoppCLIError } from "./checks";
|
||||
import { arrayFlatMap, arraySort, tupleToRecord } from "./functions/array";
|
||||
import { getEffectiveFinalMetaData, getResolvedVariables } from "./getters";
|
||||
import { toFormData } from "./mutators";
|
||||
import {
|
||||
DigestAuthParams,
|
||||
fetchInitialDigestAuthInfo,
|
||||
generateDigestAuthHeader,
|
||||
} from "./auth/digest";
|
||||
|
||||
/**
|
||||
* Runs pre-request-script runner over given request which extracts set ENVs and
|
||||
@@ -232,6 +237,46 @@ export async function getEffectiveRESTRequest(
|
||||
});
|
||||
});
|
||||
}
|
||||
} else if (request.auth.authType === "digest") {
|
||||
const { method, endpoint } = request as HoppRESTRequest;
|
||||
|
||||
// Step 1: Fetch the initial auth info (nonce, realm, etc.)
|
||||
const authInfo = await fetchInitialDigestAuthInfo(
|
||||
parseTemplateString(endpoint, resolvedVariables),
|
||||
method,
|
||||
request.auth.disableRetry
|
||||
);
|
||||
|
||||
// Step 2: Set up the parameters for the digest authentication header
|
||||
const digestAuthParams: DigestAuthParams = {
|
||||
username: parseTemplateString(request.auth.username, resolvedVariables),
|
||||
password: parseTemplateString(request.auth.password, resolvedVariables),
|
||||
realm: request.auth.realm
|
||||
? parseTemplateString(request.auth.realm, resolvedVariables)
|
||||
: authInfo.realm,
|
||||
nonce: request.auth.nonce
|
||||
? parseTemplateString(authInfo.nonce, resolvedVariables)
|
||||
: authInfo.nonce,
|
||||
endpoint: parseTemplateString(endpoint, resolvedVariables),
|
||||
method,
|
||||
algorithm: request.auth.algorithm ?? authInfo.algorithm,
|
||||
qop: request.auth.qop
|
||||
? parseTemplateString(request.auth.qop, resolvedVariables)
|
||||
: authInfo.qop,
|
||||
opaque: request.auth.opaque
|
||||
? parseTemplateString(request.auth.opaque, resolvedVariables)
|
||||
: authInfo.opaque,
|
||||
};
|
||||
|
||||
// Step 3: Generate the Authorization header
|
||||
const authHeaderValue = await generateDigestAuthHeader(digestAuthParams);
|
||||
|
||||
effectiveFinalHeaders.push({
|
||||
active: true,
|
||||
key: "Authorization",
|
||||
value: authHeaderValue,
|
||||
description: "",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -240,6 +240,7 @@ export const processRequest =
|
||||
|
||||
// Updating report for errors & current result
|
||||
report.errors.push(preRequestRes.left);
|
||||
console.error(`Report result is `, report.result);
|
||||
report.result = report.result;
|
||||
} else {
|
||||
// Updating effective-request and consuming updated envs after pre-request script execution
|
||||
|
||||
Reference in New Issue
Block a user