Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
fix: ensure GraphQL connection sends authentication headers (#4746)
Anwarul Islam903448186bf3
diff --git a/packages/hoppscotch-common/src/components/graphql/Request.vue b/packages/hoppscotch-common/src/components/graphql/Request.vueindex 6d674d4a3..e9632b748 100644--- a/packages/hoppscotch-common/src/components/graphql/Request.vue+++ b/packages/hoppscotch-common/src/components/graphql/Request.vue@@ -72,6 +72,7 @@ import { InterceptorService } from "~/services/interceptor.service"import { useService } from "dioc/vue"import { defineActionHandler } from "~/helpers/actions"import { GQLTabService } from "~/services/tab/graphql"+import { HoppGQLAuth, HoppGQLRequest } from "@hoppscotch/data"const t = useI18n()const tabs = useService(GQLTabService)@@ -98,7 +99,23 @@ const onConnectClick = () => {}const gqlConnect = () => {- connect(url.value, tabs.currentActiveTab.value?.document.request.headers)+ const inheritedHeaders =+ tabs.currentActiveTab.value.document.inheritedProperties?.headers.map(+ (header) => {+ if (header.inheritedHeader) {+ return header.inheritedHeader+ }+ return []+ }+ ) as HoppGQLRequest["headers"]++ connect({+ url: url.value,+ request: tabs.currentActiveTab.value.document.request,+ inheritedHeaders,+ inheritedAuth: tabs.currentActiveTab.value.document.inheritedProperties+ ?.auth.inheritedAuth as HoppGQLAuth,+ })platform.analytics?.logEvent({type: "HOPP_REQUEST_RUN",diff --git a/packages/hoppscotch-common/src/components/graphql/RequestOptions.vue b/packages/hoppscotch-common/src/components/graphql/RequestOptions.vueindex cf5c5190a..1f0ab9c4c 100644--- a/packages/hoppscotch-common/src/components/graphql/RequestOptions.vue+++ b/packages/hoppscotch-common/src/components/graphql/RequestOptions.vue@@ -57,26 +57,25 @@<script setup lang="ts">import { useI18n } from "@composables/i18n"import { useToast } from "@composables/toast"-import { completePageProgress, startPageProgress } from "~/modules/loadingbar"+import { HoppGQLAuth, HoppGQLRequest } from "@hoppscotch/data"+import { computedWithControl, useVModel } from "@vueuse/core"+import { useService } from "dioc/vue"import * as gql from "graphql"import { clone } from "lodash-es"import { computed, ref, watch } from "vue"import { defineActionHandler } from "~/helpers/actions"-import { HoppGQLRequest } from "@hoppscotch/data"-import { platform } from "~/platform"-import { computedWithControl, useVModel } from "@vueuse/core"import {+ connection,+ gqlMessageEvent,GQLResponseEvent,runGQLOperation,- gqlMessageEvent,- connection,} from "~/helpers/graphql/connection"-import { useService } from "dioc/vue"-import { InterceptorService } from "~/services/interceptor.service"+import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"+import { completePageProgress, startPageProgress } from "~/modules/loadingbar"import { editGraphqlRequest } from "~/newstore/collections"+import { platform } from "~/platform"+import { InterceptorService } from "~/services/interceptor.service"import { GQLTabService } from "~/services/tab/graphql"-import { HoppInheritedProperty } from "~/helpers/types/HoppInheritedProperties"-import { HoppRESTHeaders } from "@hoppscotch/data"const VALID_GQL_OPERATIONS = ["query",@@ -139,13 +138,6 @@ const runQuery = async (const runURL = clone(url.value)const runQuery = clone(request.value.query)const runVariables = clone(request.value.variables)- const runAuth =- request.value.auth.authType === "inherit" && request.value.auth.authActive- ? clone(- tabs.currentActiveTab.value.document.inheritedProperties?.auth- .inheritedAuth- )- : clone(request.value.auth)const inheritedHeaders =tabs.currentActiveTab.value.document.inheritedProperties?.headers.map(@@ -155,26 +147,17 @@ const runQuery = async (}return []}- )-- let runHeaders: HoppGQLRequest["headers"] = []-- if (inheritedHeaders) {- runHeaders = [- ...inheritedHeaders,- ...clone(request.value.headers),- ] as HoppRESTHeaders- } else {- runHeaders = clone(request.value.headers)- }+ ) as HoppGQLRequest["headers"]await runGQLOperation({name: request.value.name,url: runURL,- headers: runHeaders,+ request: request.value,+ inheritedHeaders: inheritedHeaders,+ inheritedAuth: tabs.currentActiveTab.value.document.inheritedProperties+ ?.auth.inheritedAuth as HoppGQLAuth,query: runQuery,variables: runVariables,- auth: runAuth ?? { authType: "none", authActive: false },operationName: definition?.name?.value,operationType: definition?.operation ?? "query",})diff --git a/packages/hoppscotch-common/src/helpers/graphql/connection.ts b/packages/hoppscotch-common/src/helpers/graphql/connection.tsindex 7a963e53c..ce9dd8598 100644--- a/packages/hoppscotch-common/src/helpers/graphql/connection.ts+++ b/packages/hoppscotch-common/src/helpers/graphql/connection.ts@@ -1,4 +1,9 @@-import { GQLHeader, HoppGQLAuth, makeGQLRequest } from "@hoppscotch/data"+import {+ HoppGQLAuth,+ HoppGQLRequest,+ HoppRESTHeaders,+ makeGQLRequest,+} from "@hoppscotch/data"import { OperationType } from "@urql/core"import { AwsV4Signer } from "aws4fetch"import * as E from "fp-ts/Either"@@ -12,6 +17,7 @@ import {getIntrospectionQuery,printSchema,} from "graphql"+import { clone } from "lodash-es"import { Component, computed, reactive, ref } from "vue"import { useToast } from "~/composables/toast"import { getService } from "~/modules/dioc"@@ -24,13 +30,21 @@ import { GQLTabService } from "~/services/tab/graphql"const GQL_SCHEMA_POLL_INTERVAL = 7000+type ConnectionRequestOptions = {+ url: string+ request: HoppGQLRequest+ inheritedHeaders: HoppGQLRequest["headers"]+ inheritedAuth: HoppGQLAuth+}+type RunQueryOptions = {name?: stringurl: string- headers: GQLHeader[]+ request: HoppGQLRequest+ inheritedHeaders: HoppGQLRequest["headers"]+ inheritedAuth: HoppGQLAuthquery: stringvariables: string- auth: HoppGQLAuthoperationName: string | undefinedoperationType: OperationType}@@ -162,8 +176,7 @@ export const graphqlTypes = computed(() => {let timeoutSubscription: anyexport const connect = async (- url: string,- headers: GQLHeader[],+ options: ConnectionRequestOptions,isRunGQLOperation = false) => {if (connection.state === "CONNECTED") {@@ -179,7 +192,7 @@ export const connect = async (const poll = async () => {try {- await getSchema(url, headers)+ await getSchema(options)// polling for schemaif (connection.state !== "CONNECTED") connection.state = "CONNECTED"timeoutSubscription = setTimeout(() => {@@ -217,20 +230,50 @@ export const reset = () => {connection.schema = null}-const getSchema = async (url: string, headers: GQLHeader[]) => {+const getSchema = async (options: ConnectionRequestOptions) => {try {const introspectionQuery = JSON.stringify({query: getIntrospectionQuery(),})+ const { url, request, inheritedHeaders, inheritedAuth } = options++ const headers = request?.headers || []++ const auth =+ request?.auth.authType === "inherit" && request.auth.authActive+ ? clone(inheritedAuth)+ : clone(request.auth)++ let runHeaders: HoppGQLRequest["headers"] = []++ if (inheritedHeaders) {+ runHeaders = [+ ...inheritedHeaders,+ ...clone(request.headers),+ ] as HoppRESTHeaders+ } else {+ runHeaders = clone(request.headers)+ }+const finalHeaders: Record<string, string> = {}++ const { authHeaders } = await generateAuthHeader(url, auth)++ runHeaders.forEach((header) => {+ if (header.active && header.key !== "") {+ finalHeaders[header.key] = header.value+ }+ })+ Object.assign(finalHeaders, authHeaders)+headers- .filter((x) => x.active && x.key !== "")- .forEach((x) => (finalHeaders[x.key] = x.value))+ .filter((item) => item.active && item.key !== "")+ .forEach(({ key, value }) => (finalHeaders[key] = value))const reqOptions = {method: "POST",- url,+ url: options.url,headers: {...finalHeaders,"content-type": "application/json",@@ -293,71 +336,60 @@ const getSchema = async (url: string, headers: GQLHeader[]) => {export const runGQLOperation = async (options: RunQueryOptions) => {if (connection.state !== "CONNECTED") {- await connect(options.url, options.headers, true)+ await connect(+ {+ url: options.url,+ request: options.request,+ inheritedHeaders: options.inheritedHeaders,+ inheritedAuth: options.inheritedAuth,+ },+ true+ )}- const { url, headers, query, variables, auth, operationName, operationType } =- options+ const {+ url,+ request,+ query,+ variables,+ operationName,+ inheritedHeaders,+ inheritedAuth,+ operationType,+ } = options- const finalHeaders: Record<string, string> = {}+ const headers = request?.headers || []- const parsedVariables = JSON.parse(variables || "{}")+ const auth =+ request?.auth.authType === "inherit" && request.auth.authActive+ ? clone(inheritedAuth)+ : clone(request.auth)- const params: Record<string, string> = {}+ let runHeaders: HoppGQLRequest["headers"] = []- if (auth.authActive) {- if (auth.authType === "basic") {- const username = auth.username- const password = auth.password- finalHeaders.Authorization = `Basic ${btoa(`${username}:${password}`)}`- } else if (auth.authType === "bearer") {- finalHeaders.Authorization = `Bearer ${auth.token}`- } else if (auth.authType === "oauth-2") {- const { addTo } = auth+ if (inheritedHeaders) {+ runHeaders = [+ ...inheritedHeaders,+ ...clone(request.headers),+ ] as HoppRESTHeaders+ } else {+ runHeaders = clone(request.headers)+ }- if (addTo === "HEADERS") {- finalHeaders.Authorization = `Bearer ${auth.grantTypeInfo.token}`- } else if (addTo === "QUERY_PARAMS") {- params["access_token"] = auth.grantTypeInfo.token- }- } else if (auth.authType === "api-key") {- const { key, value, addTo } = auth- if (addTo === "HEADERS") {- finalHeaders[key] = value- } else if (addTo === "QUERY_PARAMS") {- params[key] = value- }- } else if (auth.authType === "aws-signature") {- const { accessKey, secretKey, region, serviceName, addTo, serviceToken } =- auth+ const finalHeaders: Record<string, string> = {}- const currentDate = new Date()- const amzDate = currentDate.toISOString().replace(/[:-]|\.\d{3}/g, "")+ const { authHeaders, authParams } = await generateAuthHeader(url, auth)- const signer = new AwsV4Signer({- datetime: amzDate,- signQuery: addTo === "QUERY_PARAMS",- accessKeyId: accessKey,- secretAccessKey: secretKey,- region: region ?? "us-east-1",- service: serviceName,- url,- sessionToken: serviceToken,- })+ runHeaders.forEach((header) => {+ if (header.active && header.key !== "") {+ finalHeaders[header.key] = header.value+ }+ })+ Object.assign(finalHeaders, authHeaders)- const sign = await signer.sign()+ const parsedVariables = JSON.parse(variables || "{}")- if (addTo === "HEADERS") {- sign.headers.forEach((v, k) => {- finalHeaders[k] = v- })- } else if (addTo === "QUERY_PARAMS") {- for (const [k, v] of sign.url.searchParams) {- params[k] = v- }- }- }- }+ const params: Record<string, string> = {}headers.filter((item) => item.active && item.key !== "")@@ -377,6 +409,7 @@ export const runGQLOperation = async (options: RunQueryOptions) => {}),params: {...params,+ ...authParams,},}@@ -424,6 +457,70 @@ export const runGQLOperation = async (options: RunQueryOptions) => {return responseText}+const generateAuthHeader = async (+ url: string,+ auth: HoppGQLAuth | undefined+) => {+ const finalHeaders: Record<string, string> = {}+ const params: Record<string, string> = {}++ if (auth?.authActive) {+ if (auth.authType === "basic") {+ const username = auth.username+ const password = auth.password+ finalHeaders.Authorization = `Basic ${btoa(`${username}:${password}`)}`+ } else if (auth.authType === "bearer") {+ finalHeaders.Authorization = `Bearer ${auth.token}`+ } else if (auth.authType === "oauth-2") {+ const { addTo } = auth++ if (addTo === "HEADERS") {+ finalHeaders.Authorization = `Bearer ${auth.grantTypeInfo.token}`+ } else if (addTo === "QUERY_PARAMS") {+ params["access_token"] = auth.grantTypeInfo.token+ }+ } else if (auth.authType === "api-key") {+ const { key, value, addTo } = auth+ if (addTo === "HEADERS") {+ finalHeaders[key] = value+ } else if (addTo === "QUERY_PARAMS") {+ params[key] = value+ }+ } else if (auth.authType === "aws-signature") {+ const { accessKey, secretKey, region, serviceName, addTo, serviceToken } =+ auth++ const currentDate = new Date()+ const amzDate = currentDate.toISOString().replace(/[:-]|\.\d{3}/g, "")++ const signer = new AwsV4Signer({+ datetime: amzDate,+ signQuery: addTo === "QUERY_PARAMS",+ accessKeyId: accessKey,+ secretAccessKey: secretKey,+ region: region ?? "us-east-1",+ service: serviceName,+ url,+ sessionToken: serviceToken,+ })++ const sign = await signer.sign()++ if (addTo === "HEADERS") {+ sign.headers.forEach((v, k) => {+ finalHeaders[k] = v+ })+ } else if (addTo === "QUERY_PARAMS") {+ for (const [k, v] of sign.url.searchParams) {+ params[k] = v+ }+ }+ }+ }++ return { authHeaders: finalHeaders, authParams: params }+}+export const runSubscription = (options: RunQueryOptions,headers?: Record<string, string>@@ -502,16 +599,16 @@ export const socketDisconnect = () => {}const addQueryToHistory = (options: RunQueryOptions, response: string) => {- const { name, url, headers, query, variables, auth } = options+ const { name, url, request, query, variables } = optionsaddGraphqlHistoryEntry(makeGQLHistoryEntry({request: makeGQLRequest({name: name ?? "Untitled Request",url,query,- headers,+ headers: request.headers,variables,- auth,+ auth: request.auth as HoppGQLAuth,}),response,star: false,