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

@@ -46,6 +46,7 @@
"chalk": "5.3.0",
"commander": "12.1.0",
"isolated-vm": "5.0.1",
"js-md5": "0.8.3",
"lodash-es": "4.17.21",
"qs": "6.13.0",
"verzod": "0.2.3",

View File

@@ -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:", () => {

View File

@@ -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": []
}

View File

@@ -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": []
}

View File

@@ -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": []
}

View File

@@ -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/"
}
]
}

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

View File

@@ -209,14 +209,25 @@
"token": "Token",
"type": "Authorization Type",
"username": "Username",
"advance_config": "Advanced Configuration",
"advance_config_description": "Hoppscotch automatically assigns default values to certain fields if no explicit value is provided",
"aws_signature": {
"access_key": "Access Key",
"secret_key": "Secret Key",
"service_name": "Service Name",
"aws_region": "AWS Region",
"service_token": "Service Token",
"advance_config": "Advanced Configuration",
"advance_config_description": "Hoppscotch automatically assigns default values to certain fields if no explicit value is provided"
"service_token": "Service Token"
},
"digest": {
"realm": "Realm",
"nonce": "Nonce",
"algorithm": "Algorithm",
"qop": "qop",
"nonce_count": "Nonce Count",
"client_nonce": "Client Nonce",
"opaque": "Opaque",
"disable_retry": "Disable Retrying Request",
"inspector_warning": "Agent interceptor is recommended when using Digest Authorization."
}
},
"collection": {

View File

@@ -64,6 +64,7 @@
"graphql-tag": "2.12.6",
"insomnia-importers": "3.6.0",
"io-ts": "2.2.21",
"js-md5": "0.8.3",
"js-yaml": "4.1.0",
"jsonc-parser": "3.3.1",
"jsonpath-plus": "10.0.0",

View File

@@ -135,6 +135,7 @@ declare module 'vue' {
HttpAuthorizationASAP: typeof import('./components/http/authorization/ASAP.vue')['default']
HttpAuthorizationAWSSign: typeof import('./components/http/authorization/AWSSign.vue')['default']
HttpAuthorizationBasic: typeof import('./components/http/authorization/Basic.vue')['default']
HttpAuthorizationDigest: typeof import('./components/http/authorization/Digest.vue')['default']
HttpAuthorizationHAWK: typeof import('./components/http/authorization/HAWK.vue')['default']
HttpAuthorizationNTLM: typeof import('./components/http/authorization/NTLM.vue')['default']
HttpAuthorizationOAuth2: typeof import('./components/http/authorization/OAuth2.vue')['default']

View File

@@ -80,10 +80,11 @@ const props = defineProps<{
active: boolean
}>()
const formattedShortcutKeys = computed(() =>
props.entry.meta?.keyboardShortcut?.map(
(key) => SPECIAL_KEY_CHARS[key] ?? capitalize(key)
)
const formattedShortcutKeys = computed(
() =>
props.entry.meta?.keyboardShortcut?.map(
(key) => SPECIAL_KEY_CHARS[key] ?? capitalize(key)
)
)
const emit = defineEmits<{

View File

@@ -39,7 +39,9 @@
:active="item.key === authType"
@click="
() => {
item.handler ? item.handler() : (auth.authType = item.key)
item.handler
? item.handler()
: (auth = { ...auth, authType: item.key } as HoppGQLAuth)
hide()
}
"
@@ -117,7 +119,8 @@
{{
t("authorization.inherited_from", {
auth: getAuthName(
inheritedProperties.auth.inheritedAuth.authType
(inheritedProperties.auth.inheritedAuth as HoppGQLAuth)
.authType
),
collection: inheritedProperties?.auth.parentName,
})
@@ -176,7 +179,11 @@
import { useI18n } from "@composables/i18n"
import { pluckRef } from "@composables/ref"
import { useColorMode } from "@composables/theming"
import { HoppGQLAuth, HoppGQLAuthOAuth2 } from "@hoppscotch/data"
import {
HoppGQLAuth,
HoppGQLAuthOAuth2,
HoppGQLAuthAWSSignature,
} from "@hoppscotch/data"
import { useVModel } from "@vueuse/core"
import { computed, onMounted, ref } from "vue"
@@ -255,15 +262,23 @@ const selectAPIKeyAuthType = () => {
}
const selectAWSSignatureAuthType = () => {
const {
accessKey = "",
secretKey = "",
region = "",
serviceName = "",
addTo = "HEADERS",
} = auth.value as HoppGQLAuthAWSSignature
auth.value = {
...auth.value,
authType: "aws-signature",
addTo: "HEADERS",
accessKey: "",
secretKey: "",
region: "",
serviceName: "",
} as HoppGQLAuth
addTo,
accessKey,
secretKey,
region,
serviceName,
}
}
const authTypes: AuthType[] = [

View File

@@ -231,6 +231,7 @@ import { useColorMode } from "@composables/theming"
import { useToast } from "@composables/toast"
import {
GQLHeader,
HoppGQLAuth,
HoppGQLRequest,
parseRawKeyValueEntriesE,
rawKeyValueEntriesToString,
@@ -675,7 +676,7 @@ const inheritedProperties = computedAsync(async () => {
const [computedAuthHeader] = await getComputedAuthHeaders(
request.value,
props.inheritedProperties.auth.inheritedAuth
props.inheritedProperties.auth.inheritedAuth as HoppGQLAuth
)
if (

View File

@@ -39,7 +39,9 @@
:active="item.key === authType"
@click="
() => {
item.handler ? item.handler() : (auth.authType = item.key)
item.handler
? item.handler()
: (auth = { ...auth, authType: item.key } as HoppRESTAuth)
hide()
}
"
@@ -149,6 +151,9 @@
<div v-if="auth.authType === 'aws-signature'">
<HttpAuthorizationAWSSign v-model="auth" :envs="envs" />
</div>
<div v-if="auth.authType === 'digest'">
<HttpAuthorizationDigest v-model="auth" :envs="envs" />
</div>
</div>
<div
class="z-[9] sticky top-upperTertiaryStickyFold h-full min-w-[12rem] max-w-1/3 flex-shrink-0 overflow-auto overflow-x-auto bg-primary p-4"
@@ -184,7 +189,12 @@ import IconHelpCircle from "~icons/lucide/help-circle"
import IconTrash2 from "~icons/lucide/trash-2"
import { getDefaultAuthCodeOauthFlowParams } from "~/services/oauth/flows/authCode"
import { HoppRESTAuth, HoppRESTAuthOAuth2 } from "@hoppscotch/data"
import {
HoppRESTAuth,
HoppRESTAuthAWSSignature,
HoppRESTAuthDigest,
HoppRESTAuthOAuth2,
} from "@hoppscotch/data"
const t = useI18n()
@@ -236,14 +246,40 @@ const selectAPIKeyAuthType = () => {
}
const selectAWSSignatureAuthType = () => {
const {
accessKey = "",
secretKey = "",
region = "",
serviceName = "",
addTo = "HEADERS",
} = auth.value as HoppRESTAuthAWSSignature
auth.value = {
...auth.value,
authType: "aws-signature",
addTo: "HEADERS",
accessKey: "",
secretKey: "",
region: "",
serviceName: "",
addTo,
accessKey,
secretKey,
region,
serviceName,
}
}
const selectDigestAuthType = () => {
const {
username = "",
password = "",
algorithm = "MD5",
} = auth.value as HoppRESTAuthDigest
console.error(`Auth is `, auth.value)
auth.value = {
...auth.value,
authType: "digest",
username,
password,
algorithm,
} as HoppRESTAuth
}
@@ -260,6 +296,11 @@ const authTypes: AuthType[] = [
key: "basic",
label: "Basic Auth",
},
{
key: "digest",
label: "Digest Auth",
handler: selectDigestAuthType,
},
{
key: "bearer",
label: "Bearer",

View File

@@ -21,11 +21,11 @@
<div class="flex flex-col divide-y divide-dividerLight">
<!-- label as advanced config here -->
<div class="p-4 flex flex-col space-y-1">
<label class="">
{{ t("authorization.aws_signature.advance_config") }}
<label>
{{ t("authorization.advance_config") }}
</label>
<p class="text-secondaryLight">
{{ t("authorization.aws_signature.advance_config_description") }}
{{ t("authorization.advance_config_description") }}
</p>
</div>
<div class="flex flex-1">

View File

@@ -0,0 +1,172 @@
<template>
<div class="flex flex-1 border-b border-dividerLight">
<SmartEnvInput
v-model="auth.username"
:placeholder="t('authorization.username')"
:auto-complete-env="true"
:envs="envs"
/>
</div>
<div class="flex flex-1 border-b border-dividerLight">
<SmartEnvInput
v-model="auth.password"
:placeholder="t('authorization.password')"
:auto-complete-env="true"
:envs="envs"
/>
</div>
<!-- advanced config -->
<div class="flex flex-col divide-y divide-dividerLight">
<!-- label as advanced config here -->
<div class="p-4 flex flex-col space-y-1">
<label>
{{ t("authorization.advance_config") }}
</label>
<p class="text-secondaryLight">
{{ t("authorization.advance_config_description") }}
</p>
</div>
<div class="flex flex-1 border-b border-dividerLight">
<SmartEnvInput
v-model="auth.realm"
:auto-complete-env="true"
:placeholder="`${t(
'authorization.digest.realm'
)} (e.g. testrealm@example.com)
`"
:envs="envs"
/>
</div>
<div class="flex flex-1 border-b border-dividerLight">
<SmartEnvInput
v-model="auth.nonce"
:auto-complete-env="true"
:placeholder="t('authorization.digest.nonce')"
:envs="envs"
/>
</div>
<div class="flex items-center border-b border-dividerLight">
<span class="flex items-center">
<label class="ml-4 text-secondaryLight">
{{ t("authorization.digest.algorithm") }}
</label>
<tippy
interactive
trigger="click"
theme="popover"
:on-shown="() => authTippyActions.focus()"
>
<HoppSmartSelectWrapper>
<HoppButtonSecondary
:label="auth.algorithm"
class="ml-2 rounded-none pr-8"
/>
</HoppSmartSelectWrapper>
<template #content="{ hide }">
<div
ref="authTippyActions"
class="flex flex-col focus:outline-none"
tabindex="0"
@keyup.escape="hide()"
>
<HoppSmartItem
v-for="alg in algorithms"
:key="alg"
:icon="auth.algorithm === alg ? IconCircleDot : IconCircle"
:active="auth.algorithm === alg"
:label="alg"
@click="
() => {
auth.algorithm = alg
hide()
}
"
/>
</div>
</template>
</tippy>
</span>
</div>
<div class="flex flex-1 border-b border-dividerLight">
<SmartEnvInput
v-model="auth.qop"
:auto-complete-env="true"
:placeholder="`${t('authorization.digest.qop')} (e.g. auth-int)
`"
:envs="envs"
/>
</div>
<div class="flex flex-1 border-b border-dividerLight">
<SmartEnvInput
v-model="auth.nc"
:auto-complete-env="true"
:placeholder="`${t('authorization.digest.nonce_count')} (e.g. 00000001)
`"
:envs="envs"
/>
</div>
<div class="flex flex-1 border-b border-dividerLight">
<SmartEnvInput
v-model="auth.cnonce"
:auto-complete-env="true"
:placeholder="`${t('authorization.digest.client_nonce')} (e.g. Oa4f113b)
`"
:envs="envs"
/>
</div>
<div class="flex flex-1 border-b border-dividerLight">
<SmartEnvInput
v-model="auth.opaque"
:auto-complete-env="true"
:placeholder="t('authorization.digest.opaque')"
:envs="envs"
/>
</div>
<div class="px-4 pt-3 pb-6">
<HoppSmartCheckbox
:on="auth.disableRetry"
@change="auth.disableRetry = !auth.disableRetry"
>
{{ t("authorization.digest.disable_retry") }}
</HoppSmartCheckbox>
</div>
</div>
</template>
<script setup lang="ts">
import IconCircle from "~icons/lucide/circle"
import IconCircleDot from "~icons/lucide/circle-dot"
import { useI18n } from "@composables/i18n"
import { HoppRESTAuthDigest } from "@hoppscotch/data"
import { useVModel } from "@vueuse/core"
import { AggregateEnvironment } from "~/newstore/environments"
import { ref } from "vue"
const t = useI18n()
const props = defineProps<{
modelValue: HoppRESTAuthDigest
envs?: AggregateEnvironment[]
}>()
const emit = defineEmits<{
(e: "update:modelValue", value: HoppRESTAuthDigest): void
}>()
const algorithms: HoppRESTAuthDigest["algorithm"][] = ["MD5", "MD5-sess"]
const auth = useVModel(props, "modelValue", emit)
const authTippyActions = ref<any | null>(null)
</script>

View File

@@ -375,7 +375,7 @@ export function useCodemirror(
language.of(
getEditorLanguage(
options.extendedEditorConfig.useLang
? ((options.extendedEditorConfig.mode as any) ?? "")
? (options.extendedEditorConfig.mode as any) ?? ""
: "",
options.linter ?? undefined,
options.completer ?? undefined
@@ -486,7 +486,7 @@ export function useCodemirror(
effects: language.reconfigure(
getEditorLanguage(
options.extendedEditorConfig.useLang
? ((options.extendedEditorConfig.mode as any) ?? "")
? (options.extendedEditorConfig.mode as any) ?? ""
: "",
options.linter ?? undefined,
options.completer ?? undefined

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

View File

@@ -143,6 +143,7 @@ import { cloneDeep } from "lodash-es"
import { RESTTabService } from "~/services/tab/rest"
import { HoppTab } from "~/services/tab"
import { HoppRequestDocument, HoppTabDocument } from "~/helpers/rest/document"
import { AuthorizationInspectorService } from "~/services/inspection/inspectors/authorization.inspector"
const savingRequest = ref(false)
const confirmingCloseForTabID = ref<string | null>(null)
@@ -400,6 +401,7 @@ defineActionHandler("tab.open-new", addNewTab)
useService(HeaderInspectorService)
useService(EnvironmentInspectorService)
useService(ResponseInspectorService)
useService(AuthorizationInspectorService)
for (const inspectorDef of platform.additionalInspectors ?? []) {
useService(inspectorDef.service)
}

View File

@@ -0,0 +1,106 @@
import {
HoppRESTRequest,
HoppRESTResponseOriginalRequest,
} from "@hoppscotch/data"
import { Service } from "dioc"
import { computed, markRaw, Ref } from "vue"
import { getI18n } from "~/modules/i18n"
import { AgentInterceptorService } from "~/platform/std/interceptors/agent"
import { InterceptorService } from "~/services/interceptor.service"
import { RESTTabService } from "~/services/tab/rest"
import IconAlertTriangle from "~icons/lucide/alert-triangle"
import { InspectionService, Inspector, InspectorResult } from ".."
/**
* This inspector is responsible for inspecting the authorization properties of a request.
* Only applies to REST tabs currently.
*
* NOTE: Initializing this service registers it as a inspector with the Inspection Service.
*/
export class AuthorizationInspectorService
extends Service
implements Inspector
{
public static readonly ID = "AUTHORIZATION_INSPECTOR_SERVICE"
private t = getI18n()
public readonly inspectorID = "authorization"
private readonly inspection = this.bind(InspectionService)
private readonly interceptorService = this.bind(InterceptorService)
private readonly agentService = this.bind(AgentInterceptorService)
private readonly restTabService = this.bind(RESTTabService)
override onServiceInit() {
this.inspection.registerInspector(this)
}
private resolveAuthType(auth: HoppRESTRequest["auth"]) {
if (auth.authType !== "inherit") {
return auth.authType
}
const activeTabDocument =
this.restTabService.currentActiveTab.value.document
if (activeTabDocument.type === "example-response") {
return null
}
const { inheritedProperties } = activeTabDocument
if (!inheritedProperties) {
return null
}
return inheritedProperties.auth.inheritedAuth.authType
}
getInspections(
req: Readonly<Ref<HoppRESTRequest | HoppRESTResponseOriginalRequest>>
) {
return computed(() => {
const currentInterceptorIDValue =
this.interceptorService.currentInterceptorID.value
if (!currentInterceptorIDValue) {
return []
}
const auth = req.value.auth
const results: InspectorResult[] = []
// `Agent` interceptor is recommended while using Digest Auth
const isUnsupportedInterceptor =
this.interceptorService.currentInterceptorID.value !==
this.agentService.interceptorID
const resolvedAuthType = this.resolveAuthType(auth)
if (resolvedAuthType === "digest" && isUnsupportedInterceptor) {
results.push({
id: "url",
icon: markRaw(IconAlertTriangle),
text: {
type: "text",
text: this.t("authorization.digest.inspector_warning"),
},
severity: 2,
isApplicable: true,
locations: {
type: "url",
},
doc: {
text: this.t("action.learn_more"),
link: "https://docs.hoppscotch.io/documentation/features/inspections",
},
})
}
return results
})
}
}

View File

@@ -17,7 +17,7 @@ export {
export { HoppGQLAuthAPIKey } from "./v/4"
export { GQLHeader } from "./v/6"
export { GQLHeader, HoppGQLAuthAWSSignature } from "./v/6"
export { HoppGQLAuth, HoppGQLAuthOAuth2 } from "./v/7"
export const GQL_REQ_SCHEMA_VERSION = 7

View File

@@ -47,6 +47,7 @@ export {
ClientCredentialsGrantTypeParams,
HoppRESTAuth,
HoppRESTAuthOAuth2,
HoppRESTAuthDigest,
PasswordGrantTypeParams,
HoppRESTResponseOriginalRequest,
HoppRESTRequestResponse,

View File

@@ -49,6 +49,23 @@ export const HoppRESTAuthOAuth2 = z.object({
export type HoppRESTAuthOAuth2 = z.infer<typeof HoppRESTAuthOAuth2>
// in this new version, we add a new auth type for Digest authentication
export const HoppRESTAuthDigest = z.object({
authType: z.literal("digest"),
username: z.string().catch(""),
password: z.string().catch(""),
realm: z.string().catch(""),
nonce: z.string().catch(""),
algorithm: z.enum(["MD5", "MD5-sess"]).catch("MD5"),
qop: z.enum(["auth", "auth-int"]).catch("auth"),
nc: z.string().catch(""),
cnonce: z.string().catch(""),
opaque: z.string().catch(""),
disableRetry: z.boolean().catch(false),
})
export type HoppRESTAuthDigest = z.infer<typeof HoppRESTAuthDigest>
export const HoppRESTAuth = z
.discriminatedUnion("authType", [
HoppRESTAuthNone,
@@ -58,6 +75,7 @@ export const HoppRESTAuth = z
HoppRESTAuthOAuth2,
HoppRESTAuthAPIKey,
HoppRESTAuthAWSSignature,
HoppRESTAuthDigest,
])
.and(
z.object({

View File

@@ -43,9 +43,8 @@ const setEnv = (
selectedEnv.value = envValue
}
} else if (indexInGlobal >= 0) {
if ("value" in global[indexInGlobal]) {
;(global[indexInGlobal] as { value: string }).value = envValue
}
if ("value" in global[indexInGlobal])
(global[indexInGlobal] as { value: string }).value = envValue
} else {
selected.push({
key: envName,

11
pnpm-lock.yaml generated
View File

@@ -392,6 +392,9 @@ importers:
isolated-vm:
specifier: 5.0.1
version: 5.0.1
js-md5:
specifier: 0.8.3
version: 0.8.3
lodash-es:
specifier: 4.17.21
version: 4.17.21
@@ -570,6 +573,9 @@ importers:
io-ts:
specifier: 2.2.21
version: 2.2.21(fp-ts@2.16.9)
js-md5:
specifier: 0.8.3
version: 0.8.3
js-yaml:
specifier: 4.1.0
version: 4.1.0
@@ -8729,6 +8735,9 @@ packages:
js-base64@3.7.7:
resolution: {integrity: sha512-7rCnleh0z2CkXhH67J8K1Ytz0b2Y+yxTPL+/KOJoa20hfnVQ/3/T6W/KflYI4bRHRagNeXeU2bkNGI3v1oS/lw==}
js-md5@0.8.3:
resolution: {integrity: sha512-qR0HB5uP6wCuRMrWPTrkMaev7MJZwJuuw4fnwAzRgP4J4/F8RwtodOKpGp4XpqsLBFzzgqIO42efFAyz2Et6KQ==}
js-stringify@1.0.2:
resolution: {integrity: sha512-rtS5ATOo2Q5k1G+DADISilDA6lv79zIiwFd6CcjuIxGKLFm5C+RLImRscVap9k55i+MOZwgliw+NejvkLuGD5g==}
@@ -22069,6 +22078,8 @@ snapshots:
js-base64@3.7.7: {}
js-md5@0.8.3: {}
js-stringify@1.0.2:
optional: true