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,147 @@
import * as E from "fp-ts/Either"
import { md5 } from "js-md5"
import { getService } from "~/modules/dioc"
import { getI18n } from "~/modules/i18n"
import { InterceptorService } from "~/services/interceptor.service"
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')
}
// Function to generate Digest Auth Header
export async function generateDigestAuthHeader(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 interface DigestAuthInfo {
realm: string
nonce: string
qop: string
opaque?: string
algorithm: string
}
export async function fetchInitialDigestAuthInfo(
url: string,
method: string,
disableRetry: boolean
): Promise<DigestAuthInfo> {
const t = getI18n()
try {
const service = getService(InterceptorService)
const initialResponse = await service.runRequest({
url,
method,
}).response
if (E.isLeft(initialResponse)) {
const initialFetchFailureReason =
initialResponse.left === "cancellation"
? initialResponse.left
: initialResponse.left.humanMessage.heading(t)
throw new Error(initialFetchFailureReason)
}
// Check if the response status is 401 (which is expected in Digest Auth flow)
if (initialResponse.right.status === 401 && !disableRetry) {
const authHeader = initialResponse.right.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.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}`)
}
} catch (error) {
const errMsg = error instanceof Error ? error.message : error
console.error(`Failed to fetch initial Digest Auth info: ${errMsg}`)
throw error // Re-throw the error to handle it further up the chain if needed
}
}
// Utility function to parse Digest auth header values
function 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
}

View File

@@ -23,8 +23,9 @@ import { replaceInsomniaTemplating } from "./insomniaEnv"
// TODO: Insomnia allows custom prefixes for Bearer token auth, Hoppscotch doesn't. We just ignore the prefix for now
type UnwrapPromise<T extends Promise<any>> =
T extends Promise<infer Y> ? Y : never
type UnwrapPromise<T extends Promise<any>> = T extends Promise<infer Y>
? Y
: never
type InsomniaDoc = UnwrapPromise<ReturnType<typeof convert>>
type InsomniaResource = ImportRequest

View File

@@ -30,6 +30,11 @@ import { tupleWithSameKeysToRecord } from "../functional/record"
import { isJSONContentType } from "./contenttypes"
import { stripComments } from "../editor/linting/jsonc"
import {
DigestAuthParams,
fetchInitialDigestAuthInfo,
generateDigestAuthHeader,
} from "../auth/digest"
export interface EffectiveHoppRESTRequest extends HoppRESTRequest {
/**
* The effective final URL.
@@ -100,6 +105,46 @@ export const getComputedAuthHeaders = async (
value: `Basic ${btoa(`${username}:${password}`)}`,
description: "",
})
} 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, envVars),
method,
request.auth.disableRetry
)
// Step 2: Set up the parameters for the digest authentication header
const digestAuthParams: DigestAuthParams = {
username: parseTemplateString(request.auth.username, envVars),
password: parseTemplateString(request.auth.password, envVars),
realm: request.auth.realm
? parseTemplateString(request.auth.realm, envVars)
: authInfo.realm,
nonce: request.auth.nonce
? parseTemplateString(authInfo.nonce, envVars)
: authInfo.nonce,
endpoint: parseTemplateString(endpoint, envVars),
method,
algorithm: request.auth.algorithm ?? authInfo.algorithm,
qop: request.auth.qop
? parseTemplateString(request.auth.qop, envVars)
: authInfo.qop,
opaque: request.auth.opaque
? parseTemplateString(request.auth.opaque, envVars)
: authInfo.opaque,
}
// Step 3: Generate the Authorization header
const authHeaderValue = await generateDigestAuthHeader(digestAuthParams)
headers.push({
active: true,
key: "Authorization",
value: authHeaderValue,
description: "",
})
} else if (
request.auth.authType === "bearer" ||
(request.auth.authType === "oauth-2" && request.auth.addTo === "HEADERS")
@@ -132,7 +177,7 @@ export const getComputedAuthHeaders = async (
false,
showKeyIfSecret
)
: (request.auth.value ?? ""),
: request.auth.value ?? "",
description: "",
})
}