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:
Anwarul Islam
2024-10-29 13:04:40 +06:00
committed by GitHub
parent c1bc74635f
commit 4b2f04df82
29 changed files with 964 additions and 49 deletions

View 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
}
};

View File

@@ -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: "",
});
}
}

View File

@@ -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