mirror of
https://github.com/hoppscotch/hoppscotch
synced 2024-11-21 22:50:51 +00:00
fix: process headers correctly in Digest Auth and other updates (#4494)
This commit is contained in:
parent
1236e6b719
commit
8ac934599a
@ -422,7 +422,7 @@ describe("hopp test [options] <file_path_or_id>", () => {
|
|||||||
describe("Digest Authorization type", () => {
|
describe("Digest Authorization type", () => {
|
||||||
test("Successfully translates the authorization information to headers/query params and sends it along with the request", async () => {
|
test("Successfully translates the authorization information to headers/query params and sends it along with the request", async () => {
|
||||||
const COLL_PATH = getTestJsonFilePath(
|
const COLL_PATH = getTestJsonFilePath(
|
||||||
"digest-auth-coll.json",
|
"digest-auth-success-coll.json",
|
||||||
"collection"
|
"collection"
|
||||||
);
|
);
|
||||||
const ENVS_PATH = getTestJsonFilePath(
|
const ENVS_PATH = getTestJsonFilePath(
|
||||||
@ -436,6 +436,22 @@ describe("hopp test [options] <file_path_or_id>", () => {
|
|||||||
expect(error).toBeNull();
|
expect(error).toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("Supports disabling request retries", async () => {
|
||||||
|
const COLL_PATH = getTestJsonFilePath(
|
||||||
|
"digest-auth-failure-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).toBeTruthy();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("Test `hopp test <file_path_or_id> --delay <delay_in_ms>` command:", () => {
|
describe("Test `hopp test <file_path_or_id> --delay <delay_in_ms>` command:", () => {
|
||||||
|
@ -1,43 +0,0 @@
|
|||||||
{
|
|
||||||
"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": []
|
|
||||||
}
|
|
@ -15,6 +15,7 @@ export interface DigestAuthParams {
|
|||||||
nc?: string;
|
nc?: string;
|
||||||
opaque?: string;
|
opaque?: string;
|
||||||
cnonce?: string; // client nonce (optional but typically required in qop='auth')
|
cnonce?: string; // client nonce (optional but typically required in qop='auth')
|
||||||
|
reqBody?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DigestAuthInfo {
|
export interface DigestAuthInfo {
|
||||||
@ -55,18 +56,28 @@ export const generateDigestAuthHeader = async (params: DigestAuthParams) => {
|
|||||||
nc = "00000001",
|
nc = "00000001",
|
||||||
opaque,
|
opaque,
|
||||||
cnonce,
|
cnonce,
|
||||||
|
reqBody = "",
|
||||||
} = params;
|
} = params;
|
||||||
|
|
||||||
const uri = endpoint.replace(/(^\w+:|^)\/\//, "");
|
const url = new URL(endpoint);
|
||||||
|
const uri = url.pathname + url.search;
|
||||||
|
|
||||||
// Generate client nonce if not provided
|
// Generate client nonce if not provided
|
||||||
const generatedCnonce = cnonce || md5(`${Math.random()}`);
|
const generatedCnonce = cnonce || md5(`${Math.random()}`);
|
||||||
|
|
||||||
// Step 1: Hash the username, realm, and password
|
// Step 1: Hash the username, realm, password and any additional fields based on the algorithm
|
||||||
const ha1 = md5(`${username}:${realm}:${password}`);
|
const ha1 =
|
||||||
|
algorithm === "MD5-sess"
|
||||||
|
? md5(
|
||||||
|
`${md5(`${username}:${realm}:${password}`)}:${nonce}:${generatedCnonce}`
|
||||||
|
)
|
||||||
|
: md5(`${username}:${realm}:${password}`);
|
||||||
|
|
||||||
// Step 2: Hash the method and URI
|
// Step 2: Hash the method and URI
|
||||||
const ha2 = md5(`${method}:${uri}`);
|
const ha2 =
|
||||||
|
qop === "auth-int"
|
||||||
|
? md5(`${method}:${uri}:${md5(reqBody)}`) // Entity body hash for `auth-int`
|
||||||
|
: md5(`${method}:${uri}`);
|
||||||
|
|
||||||
// Step 3: Compute the response hash
|
// Step 3: Compute the response hash
|
||||||
const response = md5(
|
const response = md5(
|
||||||
@ -95,9 +106,21 @@ export const fetchInitialDigestAuthInfo = async (
|
|||||||
validateStatus: () => true, // Allow handling of all status codes
|
validateStatus: () => true, // Allow handling of all status codes
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (disableRetry) {
|
||||||
|
throw new Error(
|
||||||
|
`Received status: ${initialResponse.status}. Retry is disabled as specified, so no further attempts will be made.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Check if the response status is 401 (which is expected in Digest Auth flow)
|
// Check if the response status is 401 (which is expected in Digest Auth flow)
|
||||||
if (initialResponse.status === 401 && !disableRetry) {
|
if (initialResponse.status === 401) {
|
||||||
const authHeader = initialResponse.headers["www-authenticate"];
|
const authHeaderEntry = Object.keys(initialResponse.headers).find(
|
||||||
|
(header) => header.toLowerCase() === "www-authenticate"
|
||||||
|
);
|
||||||
|
|
||||||
|
const authHeader = authHeaderEntry
|
||||||
|
? (initialResponse.headers[authHeaderEntry] ?? null)
|
||||||
|
: null;
|
||||||
|
|
||||||
if (authHeader) {
|
if (authHeader) {
|
||||||
const authParams = parseDigestAuthHeader(authHeader);
|
const authParams = parseDigestAuthHeader(authHeader);
|
||||||
@ -119,13 +142,9 @@ export const fetchInitialDigestAuthInfo = async (
|
|||||||
throw new Error(
|
throw new Error(
|
||||||
"Failed to parse authentication parameters from WWW-Authenticate header"
|
"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}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected response: ${initialResponse.status}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errMsg = error instanceof Error ? error.message : error;
|
const errMsg = error instanceof Error ? error.message : error;
|
||||||
|
|
||||||
|
@ -120,6 +120,15 @@ export async function getEffectiveRESTRequest(
|
|||||||
}
|
}
|
||||||
const effectiveFinalParams = _effectiveFinalParams.right;
|
const effectiveFinalParams = _effectiveFinalParams.right;
|
||||||
|
|
||||||
|
// Parsing final-body with applied ENVs.
|
||||||
|
const _effectiveFinalBody = getFinalBodyFromRequest(
|
||||||
|
request,
|
||||||
|
resolvedVariables
|
||||||
|
);
|
||||||
|
if (E.isLeft(_effectiveFinalBody)) {
|
||||||
|
return _effectiveFinalBody;
|
||||||
|
}
|
||||||
|
|
||||||
// Authentication
|
// Authentication
|
||||||
if (request.auth.authActive) {
|
if (request.auth.authActive) {
|
||||||
// TODO: Support a better b64 implementation than btoa ?
|
// TODO: Support a better b64 implementation than btoa ?
|
||||||
@ -266,6 +275,7 @@ export async function getEffectiveRESTRequest(
|
|||||||
opaque: request.auth.opaque
|
opaque: request.auth.opaque
|
||||||
? parseTemplateString(request.auth.opaque, resolvedVariables)
|
? parseTemplateString(request.auth.opaque, resolvedVariables)
|
||||||
: authInfo.opaque,
|
: authInfo.opaque,
|
||||||
|
reqBody: typeof request.body.body === "string" ? request.body.body : "",
|
||||||
};
|
};
|
||||||
|
|
||||||
// Step 3: Generate the Authorization header
|
// Step 3: Generate the Authorization header
|
||||||
@ -280,14 +290,6 @@ export async function getEffectiveRESTRequest(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parsing final-body with applied ENVs.
|
|
||||||
const _effectiveFinalBody = getFinalBodyFromRequest(
|
|
||||||
request,
|
|
||||||
resolvedVariables
|
|
||||||
);
|
|
||||||
if (E.isLeft(_effectiveFinalBody)) {
|
|
||||||
return _effectiveFinalBody;
|
|
||||||
}
|
|
||||||
const effectiveFinalBody = _effectiveFinalBody.right;
|
const effectiveFinalBody = _effectiveFinalBody.right;
|
||||||
|
|
||||||
if (
|
if (
|
||||||
|
@ -240,7 +240,9 @@ export const processRequest =
|
|||||||
|
|
||||||
// Updating report for errors & current result
|
// Updating report for errors & current result
|
||||||
report.errors.push(preRequestRes.left);
|
report.errors.push(preRequestRes.left);
|
||||||
report.result = report.result;
|
|
||||||
|
// Ensure, the CLI fails with a non-zero exit code if there are any errors
|
||||||
|
report.result = false;
|
||||||
} else {
|
} else {
|
||||||
// Updating effective-request and consuming updated envs after pre-request script execution
|
// Updating effective-request and consuming updated envs after pre-request script execution
|
||||||
({ effectiveRequest, updatedEnvs } = preRequestRes.right);
|
({ effectiveRequest, updatedEnvs } = preRequestRes.right);
|
||||||
@ -268,7 +270,9 @@ export const processRequest =
|
|||||||
if (E.isLeft(requestRunnerRes)) {
|
if (E.isLeft(requestRunnerRes)) {
|
||||||
// Updating report for errors & current result
|
// Updating report for errors & current result
|
||||||
report.errors.push(requestRunnerRes.left);
|
report.errors.push(requestRunnerRes.left);
|
||||||
report.result = report.result;
|
|
||||||
|
// Ensure, the CLI fails with a non-zero exit code if there are any errors
|
||||||
|
report.result = false;
|
||||||
|
|
||||||
printRequestRunner.fail();
|
printRequestRunner.fail();
|
||||||
} else {
|
} else {
|
||||||
@ -291,7 +295,9 @@ export const processRequest =
|
|||||||
|
|
||||||
// Updating report with current errors & result.
|
// Updating report with current errors & result.
|
||||||
report.errors.push(testRunnerRes.left);
|
report.errors.push(testRunnerRes.left);
|
||||||
report.result = report.result;
|
|
||||||
|
// Ensure, the CLI fails with a non-zero exit code if there are any errors
|
||||||
|
report.result = false;
|
||||||
} else {
|
} else {
|
||||||
const { envs, testsReport, duration } = testRunnerRes.right;
|
const { envs, testsReport, duration } = testRunnerRes.right;
|
||||||
const _hasFailedTestCases = hasFailedTestCases(testsReport);
|
const _hasFailedTestCases = hasFailedTestCases(testsReport);
|
||||||
|
@ -129,14 +129,15 @@
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="px-4 pt-3 pb-6">
|
<!-- TODO: Enable once request failure due to disabling retries is handled gracefully -->
|
||||||
|
<!-- <div class="px-4 pt-3 pb-6">
|
||||||
<HoppSmartCheckbox
|
<HoppSmartCheckbox
|
||||||
:on="auth.disableRetry"
|
:on="auth.disableRetry"
|
||||||
@change="auth.disableRetry = !auth.disableRetry"
|
@change="auth.disableRetry = !auth.disableRetry"
|
||||||
>
|
>
|
||||||
{{ t("authorization.digest.disable_retry") }}
|
{{ t("authorization.digest.disable_retry") }}
|
||||||
</HoppSmartCheckbox>
|
</HoppSmartCheckbox>
|
||||||
</div>
|
</div> -->
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
@ -17,6 +17,7 @@ export interface DigestAuthParams {
|
|||||||
nc?: string
|
nc?: string
|
||||||
opaque?: string
|
opaque?: string
|
||||||
cnonce?: string // client nonce (optional but typically required in qop='auth')
|
cnonce?: string // client nonce (optional but typically required in qop='auth')
|
||||||
|
reqBody?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to generate Digest Auth Header
|
// Function to generate Digest Auth Header
|
||||||
@ -33,18 +34,28 @@ export async function generateDigestAuthHeader(params: DigestAuthParams) {
|
|||||||
nc = "00000001",
|
nc = "00000001",
|
||||||
opaque,
|
opaque,
|
||||||
cnonce,
|
cnonce,
|
||||||
|
reqBody = " ",
|
||||||
} = params
|
} = params
|
||||||
|
|
||||||
const uri = endpoint.replace(/(^\w+:|^)\/\//, "")
|
const url = new URL(endpoint)
|
||||||
|
const uri = url.pathname + url.search
|
||||||
|
|
||||||
// Generate client nonce if not provided
|
// Generate client nonce if not provided
|
||||||
const generatedCnonce = cnonce || md5(`${Math.random()}`)
|
const generatedCnonce = cnonce || md5(`${Math.random()}`)
|
||||||
|
|
||||||
// Step 1: Hash the username, realm, and password
|
// Step 1: Hash the username, realm, password and any additional fields based on the algorithm
|
||||||
const ha1 = md5(`${username}:${realm}:${password}`)
|
const ha1 =
|
||||||
|
algorithm === "MD5-sess"
|
||||||
|
? md5(
|
||||||
|
`${md5(`${username}:${realm}:${password}`)}:${nonce}:${generatedCnonce}`
|
||||||
|
)
|
||||||
|
: md5(`${username}:${realm}:${password}`)
|
||||||
|
|
||||||
// Step 2: Hash the method and URI
|
// Step 2: Hash the method and URI
|
||||||
const ha2 = md5(`${method}:${uri}`)
|
const ha2 =
|
||||||
|
qop === "auth-int"
|
||||||
|
? md5(`${method}:${uri}:${md5(reqBody)}`) // Entity body hash for `auth-int`
|
||||||
|
: md5(`${method}:${uri}`)
|
||||||
|
|
||||||
// Step 3: Compute the response hash
|
// Step 3: Compute the response hash
|
||||||
const response = md5(`${ha1}:${nonce}:${nc}:${generatedCnonce}:${qop}:${ha2}`)
|
const response = md5(`${ha1}:${nonce}:${nc}:${generatedCnonce}:${qop}:${ha2}`)
|
||||||
@ -69,8 +80,7 @@ export interface DigestAuthInfo {
|
|||||||
|
|
||||||
export async function fetchInitialDigestAuthInfo(
|
export async function fetchInitialDigestAuthInfo(
|
||||||
url: string,
|
url: string,
|
||||||
method: string,
|
method: string
|
||||||
disableRetry: boolean
|
|
||||||
): Promise<DigestAuthInfo> {
|
): Promise<DigestAuthInfo> {
|
||||||
const t = getI18n()
|
const t = getI18n()
|
||||||
|
|
||||||
@ -91,8 +101,14 @@ export async function fetchInitialDigestAuthInfo(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check if the response status is 401 (which is expected in Digest Auth flow)
|
// Check if the response status is 401 (which is expected in Digest Auth flow)
|
||||||
if (initialResponse.right.status === 401 && !disableRetry) {
|
if (initialResponse.right.status === 401) {
|
||||||
const authHeader = initialResponse.right.headers["www-authenticate"]
|
const authHeaderEntry = Object.keys(initialResponse.right.headers).find(
|
||||||
|
(header) => header.toLowerCase() === "www-authenticate"
|
||||||
|
)
|
||||||
|
|
||||||
|
const authHeader = authHeaderEntry
|
||||||
|
? (initialResponse.right.headers[authHeaderEntry] ?? null)
|
||||||
|
: null
|
||||||
|
|
||||||
if (authHeader) {
|
if (authHeader) {
|
||||||
const authParams = parseDigestAuthHeader(authHeader)
|
const authParams = parseDigestAuthHeader(authHeader)
|
||||||
@ -111,16 +127,13 @@ export async function fetchInitialDigestAuthInfo(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new Error(
|
throw new Error(
|
||||||
"Failed to parse authentication parameters from WWW-Authenticate header"
|
"Failed to parse authentication parameters from WWW-Authenticate header"
|
||||||
)
|
)
|
||||||
} else if (initialResponse.right.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.right.status}`)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unexpected response: ${initialResponse.right.status}`)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const errMsg = error instanceof Error ? error.message : error
|
const errMsg = error instanceof Error ? error.message : error
|
||||||
|
|
||||||
|
@ -111,8 +111,13 @@ export const getComputedAuthHeaders = async (
|
|||||||
// Step 1: Fetch the initial auth info (nonce, realm, etc.)
|
// Step 1: Fetch the initial auth info (nonce, realm, etc.)
|
||||||
const authInfo = await fetchInitialDigestAuthInfo(
|
const authInfo = await fetchInitialDigestAuthInfo(
|
||||||
parseTemplateString(endpoint, envVars),
|
parseTemplateString(endpoint, envVars),
|
||||||
method,
|
method
|
||||||
request.auth.disableRetry
|
)
|
||||||
|
|
||||||
|
const reqBody = getFinalBodyFromRequest(
|
||||||
|
req as HoppRESTRequest,
|
||||||
|
envVars,
|
||||||
|
showKeyIfSecret
|
||||||
)
|
)
|
||||||
|
|
||||||
// Step 2: Set up the parameters for the digest authentication header
|
// Step 2: Set up the parameters for the digest authentication header
|
||||||
@ -134,6 +139,7 @@ export const getComputedAuthHeaders = async (
|
|||||||
opaque: request.auth.opaque
|
opaque: request.auth.opaque
|
||||||
? parseTemplateString(request.auth.opaque, envVars)
|
? parseTemplateString(request.auth.opaque, envVars)
|
||||||
: authInfo.opaque,
|
: authInfo.opaque,
|
||||||
|
reqBody: typeof reqBody === "string" ? reqBody : "",
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 3: Generate the Authorization header
|
// Step 3: Generate the Authorization header
|
||||||
|
Loading…
Reference in New Issue
Block a user