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

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