From 89012bda0a8fe3541f2875a76877f7678cc15925 Mon Sep 17 00:00:00 2001 From: Nizar Malangadan Date: Tue, 29 Jan 2019 13:14:53 +0530 Subject: [PATCH 01/36] 1) Support both X-Hasura-Access-Key and X-Hasura-Admin-Secret as headers for access key in the server 2) Change X-Hasura-Access-Key to X-Hasura-Admin-Secret everywhere else --- cli/commands/console.go | 2 +- cli/commands/migrate.go | 2 +- cli/util/server.go | 2 +- .../event-triggers/aws-lambda/nodejs6/mutation/index.js | 2 +- .../aws-lambda/python/mutation/mutation.py | 2 +- .../azure-functions/nodejs/mutation/HTTPTrigger/index.js | 2 +- .../react-apollo-todo/cypress/helpers/dataHelpers.js | 2 +- community/tools/firebase2graphql/src/command.js | 4 ++-- community/tools/firebase2graphql/test/verifyBlog.js | 4 ++-- community/tools/firebase2graphql/test/verifyChinook.js | 4 ++-- .../tools/firebase2graphql/test/verifyChinookNested.js | 4 ++-- community/tools/firebase2graphql/test/verifyRE1.js | 4 ++-- .../src/components/ApiExplorer/ApiRequest.js | 4 ++-- community/tools/json2graphql/src/command.js | 4 ++-- community/tools/json2graphql/test/verify.js | 4 ++-- console/cypress/helpers/dataHelpers.js | 2 +- console/cypress/helpers/eventHelpers.js | 2 +- console/cypress/helpers/remoteSchemaHelpers.js | 2 +- console/src/components/ApiExplorer/ApiRequest.js | 9 +++------ console/src/components/Common/validateLogin.js | 6 +++--- console/src/components/Main/Actions.js | 4 ++-- console/src/utils/requestAction.js | 2 +- .../manual/api-reference/schema-metadata-api/run-sql.rst | 2 +- docs/graphql/manual/auth/config.rst.wip | 8 ++++---- docs/graphql/manual/auth/jwt.rst | 4 ++-- docs/graphql/manual/auth/webhook.rst | 4 ++-- .../manual/deployment/graphql-engine-flags/reference.rst | 4 ++-- docs/graphql/manual/event-triggers/serverless.rst | 2 +- .../manual/guides/deployment/digital-ocean-one-click.rst | 2 +- docs/graphql/manual/schema/export-graphql-schema.rst | 2 +- server/src-lib/Hasura/Server/Auth.hs | 8 +++++--- server/src-lib/Hasura/Server/Utils.hs | 5 ++++- server/tests-py/context.py | 2 +- server/tests-py/test_subscriptions.py | 4 ++-- server/tests-py/validate.py | 6 +++--- 35 files changed, 64 insertions(+), 62 deletions(-) diff --git a/cli/commands/console.go b/cli/commands/console.go index 982605618f38a..b622dfdfbefe6 100644 --- a/cli/commands/console.go +++ b/cli/commands/console.go @@ -218,7 +218,7 @@ func setLogger(logger *logrus.Logger) gin.HandlerFunc { func allowCors() gin.HandlerFunc { config := cors.DefaultConfig() config.AddAllowHeaders("X-Hasura-User-Id") - config.AddAllowHeaders("X-Hasura-Access-Key") + config.AddAllowHeaders("X-Hasura-Admin-Secret") config.AddAllowHeaders("X-Hasura-Role") config.AddAllowHeaders("X-Hasura-Allowed-Roles") config.AddAllowMethods("DELETE") diff --git a/cli/commands/migrate.go b/cli/commands/migrate.go index a692cbf90a36d..49814a3e574a3 100644 --- a/cli/commands/migrate.go +++ b/cli/commands/migrate.go @@ -87,7 +87,7 @@ func getDataPath(nurl *url.URL, accessKey string) *url.URL { q.Set("sslmode", "disable") } if accessKey != "" { - q.Add("headers", "X-Hasura-Access-Key:"+accessKey) + q.Add("headers", "X-Hasura-Admin-Secret:"+accessKey) } host.RawQuery = q.Encode() return host diff --git a/cli/util/server.go b/cli/util/server.go index edebd434669ce..06502e82a3d97 100644 --- a/cli/util/server.go +++ b/cli/util/server.go @@ -38,7 +38,7 @@ func GetServerState(endpoint, accessKey string, serverVersion *semver.Version, l }` req := gorequest.New() req = req.Post(endpoint + "/v1/query").Send(payload) - req.Set("X-Hasura-Access-Key", accessKey) + req.Set("X-Hasura-Admin-Secret", accessKey) var r []hdbVersion _, _, errs := req.EndStruct(&r) diff --git a/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/index.js b/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/index.js index d819ee5ee9f5d..e92263e21a7a8 100644 --- a/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/index.js +++ b/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/index.js @@ -34,7 +34,7 @@ exports.handler = (event, context, callback) => { fetch(hgeEndpoint + '/v1alpha1/graphql', { method: 'POST', body: JSON.stringify({query: query, variables: qv}), - headers: {'Content-Type': 'application/json', 'x-hasura-access-key': accessKey}, + headers: {'Content-Type': 'application/json', 'x-hasura-admin-secret': accessKey}, }) .then(res => res.json()) .then(json => { diff --git a/community/boilerplates/event-triggers/aws-lambda/python/mutation/mutation.py b/community/boilerplates/event-triggers/aws-lambda/python/mutation/mutation.py index 0cb0682b879b0..4a67796df1c62 100644 --- a/community/boilerplates/event-triggers/aws-lambda/python/mutation/mutation.py +++ b/community/boilerplates/event-triggers/aws-lambda/python/mutation/mutation.py @@ -8,7 +8,7 @@ HEADERS = { 'Content-Type': 'application/json', - 'X-Hasura-Access-Key': ACCESS_KEY, + 'X-Hasura-Admin-Secret': ACCESS_KEY, } query = """ diff --git a/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/HTTPTrigger/index.js b/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/HTTPTrigger/index.js index 74567da89f661..8821c6ad3193a 100644 --- a/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/HTTPTrigger/index.js +++ b/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/HTTPTrigger/index.js @@ -28,7 +28,7 @@ module.exports = function (context, req) { endpoint: HGE_ENDPOINT + '/v1alpha1/graphql', variables: qv, headers: { - 'x-hasura-access-key': ACCESS_KEY + 'x-hasura-admin-secret': ACCESS_KEY } }).then((response) => { context.log(response); diff --git a/community/sample-apps/react-apollo-todo/cypress/helpers/dataHelpers.js b/community/sample-apps/react-apollo-todo/cypress/helpers/dataHelpers.js index eff56f4366db7..8cd0c5e965f59 100644 --- a/community/sample-apps/react-apollo-todo/cypress/helpers/dataHelpers.js +++ b/community/sample-apps/react-apollo-todo/cypress/helpers/dataHelpers.js @@ -8,7 +8,7 @@ export const makeDataAPIOptions = (dataApiUrl, key, body) => ({ method: "POST", url: makeDataAPIUrl(dataApiUrl), headers: { - "x-hasura-access-key": key + "x-hasura-admin-secret": key }, body, failOnStatusCode: false diff --git a/community/tools/firebase2graphql/src/command.js b/community/tools/firebase2graphql/src/command.js index 5f97d614bea25..97355088d4774 100644 --- a/community/tools/firebase2graphql/src/command.js +++ b/community/tools/firebase2graphql/src/command.js @@ -24,7 +24,7 @@ class Firebase2GraphQL extends Command { throw new CLIError('path to firebase JSON database is required: \'firebase2graphql -d ./db.js\''); } const dbJson = this.getDbJson(db); - const headers = key ? {'x-hasura-access-key': key} : {}; + const headers = key ? {'x-hasura-admin-secret': key} : {}; const urlVerification = await this.verifyUrl(safeUrl, headers); if (urlVerification.error) { throwError(`Message: ${urlVerification.message}`); @@ -91,7 +91,7 @@ Firebase2GraphQL.flags = { // Access key to Hasura GraphQL Engine 'access-key': flags.string({ char: 'k', - description: 'Access key to Hasura GraphQL Engine (X-Hasura-Access-Key)', + description: 'Access key to Hasura GraphQL Engine (X-Hasura-Admin-Secret)', }), db: flags.string({ diff --git a/community/tools/firebase2graphql/test/verifyBlog.js b/community/tools/firebase2graphql/test/verifyBlog.js index 4e9ea4f4396da..351fbb2a7e968 100644 --- a/community/tools/firebase2graphql/test/verifyBlog.js +++ b/community/tools/firebase2graphql/test/verifyBlog.js @@ -21,7 +21,7 @@ const verifyDataImport = () => { query({ query: complexQuery, endpoint: `${process.env.TEST_HGE_URL}/v1alpha1/graphql`, - headers: {'x-hasura-access-key': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, }).then(response => { if ( response.data.f2g_test_posts[0].title === 'My first post' && @@ -36,7 +36,7 @@ const verifyDataImport = () => { `${process.env.TEST_HGE_URL}/v1/query`, { method: 'POST', - headers: {'x-hasura-access-key': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, body: JSON.stringify({ type: 'run_sql', args: { diff --git a/community/tools/firebase2graphql/test/verifyChinook.js b/community/tools/firebase2graphql/test/verifyChinook.js index eed5406318e69..3e25c604c7f04 100644 --- a/community/tools/firebase2graphql/test/verifyChinook.js +++ b/community/tools/firebase2graphql/test/verifyChinook.js @@ -26,7 +26,7 @@ const verifyDataImport = () => { query({ query: complexQuery, endpoint: `${process.env.TEST_HGE_URL}/v1alpha1/graphql`, - headers: {'x-hasura-access-key': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, }).then(response => { if ( response.data.f2g_test_Album[0].f2g_test_Album_artist.ArtistId === 1 && @@ -40,7 +40,7 @@ const verifyDataImport = () => { `${process.env.TEST_HGE_URL}/v1/query`, { method: 'POST', - headers: {'x-hasura-access-key': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, body: JSON.stringify({ type: 'run_sql', args: { diff --git a/community/tools/firebase2graphql/test/verifyChinookNested.js b/community/tools/firebase2graphql/test/verifyChinookNested.js index 65d754fb90b73..197292ded6beb 100644 --- a/community/tools/firebase2graphql/test/verifyChinookNested.js +++ b/community/tools/firebase2graphql/test/verifyChinookNested.js @@ -29,7 +29,7 @@ const verifyDataImport = () => { query({ query: complexQuery, endpoint: `${process.env.TEST_HGE_URL}/v1alpha1/graphql`, - headers: {'x-hasura-access-key': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, }).then(response => { if ( response.data.f2gt_Album[0]._id === '1' && @@ -46,7 +46,7 @@ const verifyDataImport = () => { `${process.env.TEST_HGE_URL}/v1/query`, { method: 'POST', - headers: {'x-hasura-access-key': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, body: JSON.stringify({ type: 'run_sql', args: { diff --git a/community/tools/firebase2graphql/test/verifyRE1.js b/community/tools/firebase2graphql/test/verifyRE1.js index 03b3df759857b..2415624d0b472 100644 --- a/community/tools/firebase2graphql/test/verifyRE1.js +++ b/community/tools/firebase2graphql/test/verifyRE1.js @@ -22,7 +22,7 @@ const verifyDataImport = () => { query({ query: complexQuery, endpoint: `${process.env.TEST_HGE_URL}/v1alpha1/graphql`, - headers: {'x-hasura-access-key': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, }).then(response => { if ( response.data && @@ -37,7 +37,7 @@ const verifyDataImport = () => { `${process.env.TEST_HGE_URL}/v1/query`, { method: 'POST', - headers: {'x-hasura-access-key': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, body: JSON.stringify({ type: 'run_sql', args: { diff --git a/community/tools/graphiql-online/src/components/ApiExplorer/ApiRequest.js b/community/tools/graphiql-online/src/components/ApiExplorer/ApiRequest.js index 5998f028e5245..22b9f15c7a44b 100644 --- a/community/tools/graphiql-online/src/components/ApiExplorer/ApiRequest.js +++ b/community/tools/graphiql-online/src/components/ApiExplorer/ApiRequest.js @@ -194,7 +194,7 @@ class ApiRequest extends Component { onBlur={this.handleBlur} data-test={`header-value-${i}`} type={ - header.key === 'X-Hasura-Access-Key' && + header.key === 'X-Hasura-Admin-Secret' && !this.state.accessKeyVisible ? 'password' : 'text' @@ -203,7 +203,7 @@ class ApiRequest extends Component { {header.isNewHeader ? null : ( - {header.key === 'X-Hasura-Access-Key' ? ( + {header.key === 'X-Hasura-Admin-Secret' ? ( -d ./db.js\''); } const dbJson = this.getDbJson(db); - const headers = key ? {'x-hasura-access-key': key} : {}; + const headers = key ? {'x-hasura-admin-secret': key} : {}; const urlVerification = await this.verifyUrl(safeUrl, headers); if (urlVerification.error) { throw new CLIError(urlVerification.message); @@ -83,7 +83,7 @@ JSON2GraphQL.flags = { // Access key to Hasura GraphQL Engine 'access-key': flags.string({ char: 'k', - description: 'Access key to Hasura GraphQL Engine (X-Hasura-Access-Key)', + description: 'Access key to Hasura GraphQL Engine (X-Hasura-Admin-Secret)', }), db: flags.string({ diff --git a/community/tools/json2graphql/test/verify.js b/community/tools/json2graphql/test/verify.js index 8121040b408b4..5949532e23d55 100644 --- a/community/tools/json2graphql/test/verify.js +++ b/community/tools/json2graphql/test/verify.js @@ -66,7 +66,7 @@ const deleteTables = () => { `${process.env.TEST_HGE_URL}/v1/query`, { method: 'POST', - headers: {'x-hasura-access-key': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, body: JSON.stringify(deleteQuery), } ).then(() => { @@ -79,7 +79,7 @@ const verifyDataImport = () => { return query({ query: complexQuery, endpoint: `${process.env.TEST_HGE_URL}/v1alpha1/graphql`, - headers: {'x-hasura-access-key': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, }).then(response => { resp = response; if (response.data.j2g_test_favoriteRoutes[0] diff --git a/console/cypress/helpers/dataHelpers.js b/console/cypress/helpers/dataHelpers.js index b71af934555b5..7794ecc4a81c5 100644 --- a/console/cypress/helpers/dataHelpers.js +++ b/console/cypress/helpers/dataHelpers.js @@ -33,7 +33,7 @@ export const makeDataAPIOptions = (dataApiUrl, key, body) => ({ method: 'POST', url: makeDataAPIUrl(dataApiUrl), headers: { - 'x-hasura-access-key': key, + 'x-hasura-admin-secret': key, }, body, failOnStatusCode: false, diff --git a/console/cypress/helpers/eventHelpers.js b/console/cypress/helpers/eventHelpers.js index ebeaa84d3df66..33a7e36631beb 100644 --- a/console/cypress/helpers/eventHelpers.js +++ b/console/cypress/helpers/eventHelpers.js @@ -13,7 +13,7 @@ export const makeDataAPIOptions = (dataApiUrl, key, body) => ({ method: 'POST', url: makeDataAPIUrl(dataApiUrl), headers: { - 'x-hasura-access-key': key, + 'x-hasura-admin-secret': key, }, body, failOnStatusCode: false, diff --git a/console/cypress/helpers/remoteSchemaHelpers.js b/console/cypress/helpers/remoteSchemaHelpers.js index 3c08417fbff19..779310c301e08 100644 --- a/console/cypress/helpers/remoteSchemaHelpers.js +++ b/console/cypress/helpers/remoteSchemaHelpers.js @@ -14,7 +14,7 @@ export const makeDataAPIOptions = (dataApiUrl, key, body) => ({ method: 'POST', url: makeDataAPIUrl(dataApiUrl), headers: { - 'x-hasura-access-key': key, + 'x-hasura-admin-secret': key, }, body, failOnStatusCode: false, diff --git a/console/src/components/ApiExplorer/ApiRequest.js b/console/src/components/ApiExplorer/ApiRequest.js index 846b33b59c8c1..658dc7fabd35d 100644 --- a/console/src/components/ApiExplorer/ApiRequest.js +++ b/console/src/components/ApiExplorer/ApiRequest.js @@ -144,10 +144,7 @@ class ApiRequest extends Component { value={this.props.url} type="text" readOnly - className={ - styles.inputGroupInput + - ' form-control ' - } + className={styles.inputGroupInput + ' form-control '} /> @@ -323,7 +320,7 @@ class ApiRequest extends Component { onBlur={this.handleBlur} data-test={`header-value-${i}`} type={ - header.key.toLowerCase() === 'x-hasura-access-key' && + header.key.toLowerCase() === 'x-hasura-admin-secret' && !this.state.accessKeyVisible ? 'password' : 'text' @@ -332,7 +329,7 @@ class ApiRequest extends Component { {header.isNewHeader ? null : ( - {header.key.toLowerCase() === 'x-hasura-access-key' ? ( + {header.key.toLowerCase() === 'x-hasura-admin-secret' ? ( { const currentSchema = 'public'; const headers = { 'Content-Type': 'application/json', - 'X-Hasura-Access-Key': accessKey, + 'X-Hasura-Admin-Secret': accessKey, }; const options = { credentials: globalCookiePolicy, @@ -56,11 +56,11 @@ const validateLogin = ({ dispatch }) => { type: UPDATE_DATA_HEADERS, data: { 'Content-Type': 'application/json', - 'X-Hasura-Access-Key': accessKey, + 'X-Hasura-Admin-Secret': accessKey, }, }), dispatch( - changeRequestHeader(1, 'key', 'X-Hasura-Access-Key', true) + changeRequestHeader(1, 'key', 'X-Hasura-Admin-Secret', true) ), dispatch(changeRequestHeader(1, 'value', accessKey, true)), ]); diff --git a/console/src/components/Main/Actions.js b/console/src/components/Main/Actions.js index 4f1436182c6e3..325573a07d769 100644 --- a/console/src/components/Main/Actions.js +++ b/console/src/components/Main/Actions.js @@ -152,12 +152,12 @@ const loginClicked = () => (dispatch, getState) => { // redirect to / to test the accessKeyInput; const updatedDataHeaders = { 'Content-Type': 'application/json', - 'X-Hasura-Access-Key': accessKeyInput, + 'X-Hasura-Admin-Secret': accessKeyInput, }; Promise.all([ dispatch({ type: ACCESS_KEY_ERROR, data: false }), dispatch({ type: UPDATE_DATA_HEADERS, data: updatedDataHeaders }), - dispatch(changeRequestHeader(1, 'key', 'X-Hasura-Access-Key', true)), + dispatch(changeRequestHeader(1, 'key', 'X-Hasura-Admin-Secret', true)), dispatch(changeRequestHeader(1, 'value', accessKeyInput, true)), // dispatch(push('/')) ]).then(() => { diff --git a/console/src/utils/requestAction.js b/console/src/utils/requestAction.js index d0f193871eea9..5d274e568b58b 100644 --- a/console/src/utils/requestAction.js +++ b/console/src/utils/requestAction.js @@ -63,7 +63,7 @@ const requestAction = ( type: UPDATE_DATA_HEADERS, data: { 'Content-Type': 'application/json', - 'X-Hasura-Access-Key': globals.accessKey, + 'X-Hasura-Admin-Secret': globals.accessKey, }, }); dispatch({ type: LOGIN_IN_PROGRESS, data: false }); diff --git a/docs/graphql/manual/api-reference/schema-metadata-api/run-sql.rst b/docs/graphql/manual/api-reference/schema-metadata-api/run-sql.rst index 9776d332f668b..5ad7212205050 100644 --- a/docs/graphql/manual/api-reference/schema-metadata-api/run-sql.rst +++ b/docs/graphql/manual/api-reference/schema-metadata-api/run-sql.rst @@ -15,7 +15,7 @@ run_sql This is an admin-only query, i.e. the query can only be executed by a request having ``X-Hasura-Role: admin``. This can be set by passing - ``X-Hasura-Access-Key`` or by setting the right role in Webhook/JWT + ``X-Hasura-Admin-Secret`` or by setting the right role in Webhook/JWT authorization mode. This is deliberate as it is hard to enforce any sort of permissions on arbitrary SQL. If diff --git a/docs/graphql/manual/auth/config.rst.wip b/docs/graphql/manual/auth/config.rst.wip index 9753c45aa7bcf..1d5d2aa1b3f13 100644 --- a/docs/graphql/manual/auth/config.rst.wip +++ b/docs/graphql/manual/auth/config.rst.wip @@ -8,7 +8,7 @@ You can run Hasura's GraphQL Engine in three modes: - When ``--access-key`` and ``--auth-hook`` are not set -- It is useful when you're developing . It is not recommended to use in production but however you can have proxy gateway that will set (``X-Hasura-Access-Key``) header and other required ``X-Hasura-*`` headers. +- It is useful when you're developing . It is not recommended to use in production but however you can have proxy gateway that will set (``X-Hasura-Admin-Secret``) header and other required ``X-Hasura-*`` headers. Run server in this mode using following docker command. @@ -27,7 +27,7 @@ Run server in this mode using following docker command. - When only ``--access-key`` is set. See :doc:`GraphQL Server Options <../deployment/options>` -- Server authenticates based on ``X-Hasura-Access-Key`` header and expects all other required ``X-Hasura-*`` headers. +- Server authenticates based on ``X-Hasura-Admin-Secret`` header and expects all other required ``X-Hasura-*`` headers. Run server in this mode using following docker command. @@ -47,9 +47,9 @@ Run server in this mode using following docker command. - When both ``--access-key`` and ``--auth-hook`` are set -- This mode is useful in production. When server founds ``X-Hasura-Access-Key`` header it ignores webhook and expects all other required ``X-Hasura*`` headers +- This mode is useful in production. When server founds ``X-Hasura-Admin-Secret`` header it ignores webhook and expects all other required ``X-Hasura*`` headers -- If ``X-Hasura-Access-key`` header not found then server authenticaters through webhook. See :doc:`Authorization +- If ``X-Hasura-Admin-Secret`` header not found then server authenticaters through webhook. See :doc:`Authorization Webhook ` Run server in this mode using following docker command. diff --git a/docs/graphql/manual/auth/jwt.rst b/docs/graphql/manual/auth/jwt.rst index 95fa801d66438..ea843fa8a75f7 100644 --- a/docs/graphql/manual/auth/jwt.rst +++ b/docs/graphql/manual/auth/jwt.rst @@ -26,9 +26,9 @@ is used for the permissions system. .. note:: Configuring JWT requires Hasura to run with an access key (``--access-key``). - - The authorization is **enforced** when ``X-Hasura-Access-Key`` header is + - The authorization is **enforced** when ``X-Hasura-Admin-Secret`` header is **not found** in the request. - - The authorization is **skipped** when ``X-Hasura-Access-Key`` header **is + - The authorization is **skipped** when ``X-Hasura-Admin-Secret`` header **is found** in the request. .. :doc:`Read more`. diff --git a/docs/graphql/manual/auth/webhook.rst b/docs/graphql/manual/auth/webhook.rst index f2a642e9759cb..dc44917aa73f6 100644 --- a/docs/graphql/manual/auth/webhook.rst +++ b/docs/graphql/manual/auth/webhook.rst @@ -16,8 +16,8 @@ to authenticate all incoming requests to the Hasura GraphQL engine server. .. :doc:`Read more`. -- The configured webhook is **called** when ``X-Hasura-Access-Key`` header is not found in the request. -- The configured webhook is **ignored** when ``X-Hasura-Access-Key`` header is found in the request. +- The configured webhook is **called** when ``X-Hasura-Admin-Secret`` header is not found in the request. +- The configured webhook is **ignored** when ``X-Hasura-Admin-Secret`` header is found in the request. Spec for the webhook diff --git a/docs/graphql/manual/deployment/graphql-engine-flags/reference.rst b/docs/graphql/manual/deployment/graphql-engine-flags/reference.rst index b9b44553e2b12..7277b86054703 100644 --- a/docs/graphql/manual/deployment/graphql-engine-flags/reference.rst +++ b/docs/graphql/manual/deployment/graphql-engine-flags/reference.rst @@ -45,7 +45,7 @@ For ``serve`` subcommand these are the flags available --server-port Port on which graphql-engine should be served (default: 8080) --access-key Secret access key, required to access this instance. - If specified client needs to send 'X-Hasura-Access-Key' + If specified client needs to send 'X-Hasura-Admin-Secret' header --cors-domain The domain, including sheme and port, to allow CORS for @@ -125,7 +125,7 @@ These are the environment variables which are available: HASURA_GRAPHQL_ACCESS_KEY Secret access key, required to access this instance. If specified client needs to send - 'X-Hasura-Access-Key' header + 'X-Hasura-Admin-Secret' header HASURA_GRAPHQL_AUTH_HOOK The authentication webhook, required to authenticate incoming request diff --git a/docs/graphql/manual/event-triggers/serverless.rst b/docs/graphql/manual/event-triggers/serverless.rst index d3c653d7c86f3..8df7009324557 100644 --- a/docs/graphql/manual/event-triggers/serverless.rst +++ b/docs/graphql/manual/event-triggers/serverless.rst @@ -99,7 +99,7 @@ Our AWS Lambda code looks like this: fetch(hgeEndpoint + '/v1alpha1/graphql', { method: 'POST', body: JSON.stringify({query: query, variables: qv}), - headers: {'Content-Type': 'application/json', 'x-hasura-access-key': accessKey}, + headers: {'Content-Type': 'application/json', 'x-hasura-admin-secret': accessKey}, }) .then(res => res.json()) .then(json => { diff --git a/docs/graphql/manual/guides/deployment/digital-ocean-one-click.rst b/docs/graphql/manual/guides/deployment/digital-ocean-one-click.rst index 5e6859ee2c943..47e23782ffc49 100644 --- a/docs/graphql/manual/guides/deployment/digital-ocean-one-click.rst +++ b/docs/graphql/manual/guides/deployment/digital-ocean-one-click.rst @@ -157,7 +157,7 @@ following header: .. code-block:: bash - X-Hasura-Access-Key: mysecretaccesskey + X-Hasura-Admin-Secret: mysecretaccesskey Adding a domain & Enabling HTTPS diff --git a/docs/graphql/manual/schema/export-graphql-schema.rst b/docs/graphql/manual/schema/export-graphql-schema.rst index ff2d3224b5812..e253e2bdee59a 100644 --- a/docs/graphql/manual/schema/export-graphql-schema.rst +++ b/docs/graphql/manual/schema/export-graphql-schema.rst @@ -25,7 +25,7 @@ GraphQL schema: gq https://my-graphql-engine.com/v1alpha1/graphql --introspect > schema.graphql # If Hasura GraphQL Engine is running with an access key - gq https://my-graphql-engine.com/v1alpha1/graphql -H 'X-Hasura-Access-Key: secretaccesskey' --introspect > schema.graphql + gq https://my-graphql-engine.com/v1alpha1/graphql -H 'X-Hasura-Admin-Secret: secretaccesskey' --introspect > schema.graphql By default, it downloads the schema in ``.graphql`` format. If you want it in JSON format, you can use an additional flag ``--format json``: diff --git a/server/src-lib/Hasura/Server/Auth.hs b/server/src-lib/Hasura/Server/Auth.hs index 05b186bb21d7c..a445241a68e8e 100644 --- a/server/src-lib/Hasura/Server/Auth.hs +++ b/server/src-lib/Hasura/Server/Auth.hs @@ -239,7 +239,7 @@ getUserInfo logger manager rawHeaders = \case AMNoAuth -> return userInfoFromHeaders AMAccessKey accKey unAuthRole -> - case getVarVal accessKeyHeader usrVars of + case accessKeyM of Just givenAccKey -> userInfoWhenAccessKey accKey givenAccKey Nothing -> userInfoWhenNoAccessKey unAuthRole @@ -253,7 +253,9 @@ getUserInfo logger manager rawHeaders = \case -- when access key is absent, run the action to retrieve UserInfo, otherwise -- accesskey override whenAccessKeyAbsent ak action = - maybe action (userInfoWhenAccessKey ak) $ getVarVal accessKeyHeader usrVars + maybe action (userInfoWhenAccessKey ak) $ accessKeyM + + accessKeyM = foldl1 (<|>) $ map (flip getVarVal usrVars) [accessKeyHeader, deprecatedAccessKeyHeader] usrVars = mkUserVars $ hdrsToText rawHeaders @@ -267,5 +269,5 @@ getUserInfo logger manager rawHeaders = \case return userInfoFromHeaders userInfoWhenNoAccessKey = \case - Nothing -> throw401 $ accessKeyHeader <> " required, but not found" + Nothing -> throw401 $ accessKeyHeader <> "/" <> deprecatedAccessKeyHeader <> " required, but not found" Just role -> return $ mkUserInfo role usrVars diff --git a/server/src-lib/Hasura/Server/Utils.hs b/server/src-lib/Hasura/Server/Utils.hs index 2e3cf73ca7abc..8af1992c7bc68 100644 --- a/server/src-lib/Hasura/Server/Utils.hs +++ b/server/src-lib/Hasura/Server/Utils.hs @@ -26,8 +26,11 @@ jsonHeader = ("Content-Type", "application/json; charset=utf-8") userRoleHeader :: T.Text userRoleHeader = "x-hasura-role" +deprecatedAccessKeyHeader :: T.Text +deprecatedAccessKeyHeader = "x-hasura-access-key" + accessKeyHeader :: T.Text -accessKeyHeader = "x-hasura-access-key" +accessKeyHeader = "x-hasura-admin-secret" userIdHeader :: T.Text userIdHeader = "x-hasura-user-id" diff --git a/server/tests-py/context.py b/server/tests-py/context.py index f91f364091202..ad9d7b4a53e69 100644 --- a/server/tests-py/context.py +++ b/server/tests-py/context.py @@ -140,7 +140,7 @@ def anyq(self, u, q, h): def v1q(self, q, headers = {}): h = headers.copy() if self.hge_key is not None: - h['X-Hasura-Access-Key'] = self.hge_key + h['X-Hasura-Admin-Secret'] = self.hge_key resp = self.http.post( self.hge_url + "/v1/query", json=q, diff --git a/server/tests-py/test_subscriptions.py b/server/tests-py/test_subscriptions.py index 1c4451cf987c1..77e8439d4f27a 100644 --- a/server/tests-py/test_subscriptions.py +++ b/server/tests-py/test_subscriptions.py @@ -31,7 +31,7 @@ def test_init(hge_ctx): if hge_ctx.hge_key is not None: payload = { 'headers' : { - 'X-Hasura-Access-Key': hge_ctx.hge_key + 'X-Hasura-Admin-Secret': hge_ctx.hge_key } } obj = { @@ -169,7 +169,7 @@ def test_live_queries(self, hge_ctx): if hge_ctx.hge_key is not None: payload = { 'headers' : { - 'X-Hasura-Access-Key': hge_ctx.hge_key + 'X-Hasura-Admin-Secret': hge_ctx.hge_key } } obj = { diff --git a/server/tests-py/validate.py b/server/tests-py/validate.py index 4a0042326e46a..762996d2cbc25 100644 --- a/server/tests-py/validate.py +++ b/server/tests-py/validate.py @@ -71,7 +71,7 @@ def test_forbidden_when_access_key_reqd(hge_ctx, conf): }) # Test with random access key - headers['X-Hasura-Access-Key'] = base64.b64encode(os.urandom(30)) + headers['X-Hasura-Admin-Secret'] = base64.b64encode(os.urandom(30)) code, resp = hge_ctx.anyq(conf['url'], conf['query'], headers) assert code == 401, "\n" + yaml.dump({ "expected": "Should be access denied as an incorrect access key is provided", @@ -127,11 +127,11 @@ def check_query(hge_ctx, conf, add_auth=True): elif ( hge_ctx.hge_webhook is not None or hge_ctx.hge_jwt_key is not None) and hge_ctx.hge_key is not None and len( headers) == 0: - headers['X-Hasura-Access-Key'] = hge_ctx.hge_key + headers['X-Hasura-Admin-Secret'] = hge_ctx.hge_key elif hge_ctx.hge_key is not None and hge_ctx.hge_webhook is None and hge_ctx.hge_jwt_key is None: test_forbidden_when_access_key_reqd(hge_ctx, conf) - headers['X-Hasura-Access-Key'] = hge_ctx.hge_key + headers['X-Hasura-Admin-Secret'] = hge_ctx.hge_key code, resp = hge_ctx.anyq(conf['url'], conf['query'], headers) print(headers) From f42d0643c98a91148d93fb3128f91d76e24553be Mon Sep 17 00:00:00 2001 From: Nizar Malangadan Date: Tue, 29 Jan 2019 18:15:19 +0530 Subject: [PATCH 02/36] In server and docs 1) Change EnvVar HASURA_GRAPHQL_ACCESS_KEY to HASURA_GRAPHQL_ADMIN_SECRET 2) Change flag --access-key to --admin-secret --- docs/graphql/manual/auth/config.rst.wip | 14 ++--- docs/graphql/manual/auth/jwt.rst | 6 +- docs/graphql/manual/auth/roles-variables.rst | 2 +- docs/graphql/manual/auth/webhook.rst | 2 +- .../docker/securing-graphql-endpoint.rst | 6 +- .../graphql-engine-flags/config-examples.rst | 46 +++++++------- .../deployment/graphql-engine-flags/index.rst | 4 +- .../graphql-engine-flags/reference.rst | 12 ++-- .../heroku/securing-graphql-endpoint.rst | 16 ++--- .../heroku/using-existing-heroku-database.rst | 4 +- .../kubernetes/securing-graphql-endpoint.rst | 16 ++--- .../deployment/securing-graphql-endpoint.rst | 4 +- .../manual/event-triggers/serverless.rst | 4 +- .../deployment/digital-ocean-one-click.rst | 16 ++--- .../manual/hasura-cli/hasura_console.rst | 2 +- .../graphql/manual/hasura-cli/hasura_init.rst | 14 ++--- .../hasura-cli/hasura_metadata_apply.rst | 6 +- .../hasura-cli/hasura_metadata_export.rst | 6 +- .../hasura-cli/hasura_metadata_reload.rst | 6 +- .../hasura-cli/hasura_metadata_reset.rst | 6 +- .../hasura-cli/hasura_migrate_apply.rst | 14 ++--- .../hasura-cli/hasura_migrate_status.rst | 6 +- .../migrations/database-with-migrations.rst | 6 +- .../manual/migrations/existing-project.rst | 6 +- .../graphql/manual/migrations/new-project.rst | 6 +- .../manual/schema/export-graphql-schema.rst | 6 +- .../docker-compose-https/docker-compose.yaml | 4 +- .../docker-compose.yaml | 4 +- .../docker-compose/docker-compose.yaml | 4 +- server/src-exec/Main.hs | 6 +- server/src-lib/Hasura/RQL/Types/Permission.hs | 4 +- server/src-lib/Hasura/Server/App.hs | 8 +-- server/src-lib/Hasura/Server/Auth.hs | 61 +++++++++---------- server/src-lib/Hasura/Server/Init.hs | 57 +++++++++++------ server/src-lib/Hasura/Server/Utils.hs | 4 +- server/src-rsr/console.html | 3 +- server/test/Main.hs | 4 +- server/tests-py/conftest.py | 2 +- server/tests-py/test_subscriptions.py | 2 +- server/tests-py/validate.py | 12 ++-- 40 files changed, 216 insertions(+), 195 deletions(-) diff --git a/docs/graphql/manual/auth/config.rst.wip b/docs/graphql/manual/auth/config.rst.wip index 1d5d2aa1b3f13..2f5b3dd50e307 100644 --- a/docs/graphql/manual/auth/config.rst.wip +++ b/docs/graphql/manual/auth/config.rst.wip @@ -6,7 +6,7 @@ You can run Hasura's GraphQL Engine in three modes: 1. No Authentication mode ^^^^^^^^^^^^^^^^^^^^^^^^^ -- When ``--access-key`` and ``--auth-hook`` are not set +- When ``--admin-secret`` and ``--auth-hook`` are not set - It is useful when you're developing . It is not recommended to use in production but however you can have proxy gateway that will set (``X-Hasura-Admin-Secret``) header and other required ``X-Hasura-*`` headers. @@ -22,10 +22,10 @@ Run server in this mode using following docker command. serve --server-port 9000 --cors-domain "*" -2. Access key mode +2. Admin secret mode ^^^^^^^^^^^^^^^^^^ -- When only ``--access-key`` is set. See :doc:`GraphQL Server Options <../deployment/options>` +- When only ``--admin-secret`` is set. See :doc:`GraphQL Server Options <../deployment/options>` - Server authenticates based on ``X-Hasura-Admin-Secret`` header and expects all other required ``X-Hasura-*`` headers. @@ -38,14 +38,14 @@ Run server in this mode using following docker command. -d hasura/graphql-engine:latest graphql-engine \ --database-url \ postgres://postgres:mysecretpassword@postgres:5432/postgres \ - serve --server-port 9000 --access-key myAccKey \ + serve --server-port 9000 --admin-secret myAdminSecretKey \ --cors-domain "*" -3. Access key and Authorization webhook mode +3. Admin secret key and Authorization webhook mode ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- When both ``--access-key`` and ``--auth-hook`` are set +- When both ``--admin-secret`` and ``--auth-hook`` are set - This mode is useful in production. When server founds ``X-Hasura-Admin-Secret`` header it ignores webhook and expects all other required ``X-Hasura*`` headers @@ -61,5 +61,5 @@ Run server in this mode using following docker command. -d hasura/graphql-engine:latest graphql-engine \ --database-url \ postgres://postgres:mysecretpassword@postgres:5432/postgres \ - serve --server-port 9000 --access-key myAccKey \ + serve --server-port 9000 --admin-secret myAdminSecretKey \ --auth-hook http://myAuthhook/ --cors-domain "*" diff --git a/docs/graphql/manual/auth/jwt.rst b/docs/graphql/manual/auth/jwt.rst index ea843fa8a75f7..3706d3c7eabfc 100644 --- a/docs/graphql/manual/auth/jwt.rst +++ b/docs/graphql/manual/auth/jwt.rst @@ -24,7 +24,7 @@ If the authorization passes, then all of the ``x-hasura-*`` values in the claim is used for the permissions system. .. note:: - Configuring JWT requires Hasura to run with an access key (``--access-key``). + Configuring JWT requires Hasura to run with an admin secret (``--admin-secret``). - The authorization is **enforced** when ``X-Hasura-Admin-Secret`` header is **not found** in the request. @@ -235,7 +235,7 @@ Using the flag: graphql-engine \ --database-url postgres://username:password@hostname:port/dbname \ serve \ - --access-key mysecretkey \ + --admin-secret myadminsecretkey \ --jwt-secret '{"type":"HS256", "key": "3EK6FD+o0+c7tzBNVfjpMkNDi2yARAAKzQlk8O2IKoxQu4nF7EdAh8s3TwpHwrdWT6R"}' Using env vars: @@ -243,7 +243,7 @@ Using env vars: .. code-block:: shell $ docker run -p 8080:8080 \ - -e HASURA_GRAPHQL_ACCESS_KEY="mysecretkey" \ + -e HASURA_GRAPHQL_ADMIN_SECRET="myadminsecretkey" \ -e HASURA_GRAPHQL_JWT_SECRET='{"type":"RS512", "key": "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDdlatRjRjogo3WojgGHFHYLugd\nUWAY9iR3fy4arWNA1KoS8kVw33cJibXr8bvwUAUparCwlvdbH6dvEOfou0/gCFQs\nHUfQrSDv+MuSUMAe8jzKE4qW+jK+xQU9a03GUnKHkkle+Q0pX/g6jXZ7r1/xAK5D\no2kQ+X5xK9cipRgEKwIDAQAB\n-----END PUBLIC KEY-----\n"}' \ hasura/graphql-engine:latest \ graphql-engine \ diff --git a/docs/graphql/manual/auth/roles-variables.rst b/docs/graphql/manual/auth/roles-variables.rst index 66c7e8747df53..6535a676f0233 100644 --- a/docs/graphql/manual/auth/roles-variables.rst +++ b/docs/graphql/manual/auth/roles-variables.rst @@ -106,7 +106,7 @@ the request: .. note:: - If you've enabled Hasura GraphQL engine with an access key, make sure you add the ACCESS_KEY header as well. + If you've enabled Hasura GraphQL engine with an admin secret key, make sure you add the ADMIN_SECRET header as well. Option 2: In production, from apps diff --git a/docs/graphql/manual/auth/webhook.rst b/docs/graphql/manual/auth/webhook.rst index dc44917aa73f6..bc740960a52bc 100644 --- a/docs/graphql/manual/auth/webhook.rst +++ b/docs/graphql/manual/auth/webhook.rst @@ -12,7 +12,7 @@ to authenticate all incoming requests to the Hasura GraphQL engine server. .. image:: ../../../img/graphql/manual/auth/webhook-auth.png .. note:: - Configuring webhook requires Hasura to run with an access key (``--access-key``). + Configuring webhook requires Hasura to run with an admin secret (``--admin-secret``). .. :doc:`Read more`. diff --git a/docs/graphql/manual/deployment/docker/securing-graphql-endpoint.rst b/docs/graphql/manual/deployment/docker/securing-graphql-endpoint.rst index 67ddeb852a740..fa79ace8cc36e 100644 --- a/docs/graphql/manual/deployment/docker/securing-graphql-endpoint.rst +++ b/docs/graphql/manual/deployment/docker/securing-graphql-endpoint.rst @@ -7,9 +7,9 @@ Securing the GraphQL endpoint (Docker) :local: To make sure that your GraphQL endpoint and the Hasura console are not publicly accessible, you need to -configure an access key. +configure an admin secret key. -Run the docker command with an access-key env var +Run the docker command with an admin-secret env var ------------------------------------------------- .. code-block:: bash @@ -19,7 +19,7 @@ Run the docker command with an access-key env var docker run -d -p 8080:8080 \ -e HASURA_GRAPHQL_DATABASE_URL=postgres://username:password@hostname:port/dbname \ -e HASURA_GRAPHQL_ENABLE_CONSOLE=true \ - -e HASURA_GRAPHQL_ACCESS_KEY=mysecretkey \ + -e HASURA_GRAPHQL_ADMIN_SECRET=myadminsecretkey \ hasura/graphql-engine:latest diff --git a/docs/graphql/manual/deployment/graphql-engine-flags/config-examples.rst b/docs/graphql/manual/deployment/graphql-engine-flags/config-examples.rst index d2163d0824fd0..f3b7fff412df7 100644 --- a/docs/graphql/manual/deployment/graphql-engine-flags/config-examples.rst +++ b/docs/graphql/manual/deployment/graphql-engine-flags/config-examples.rst @@ -8,12 +8,12 @@ GraphQL engine server config examples The following are a few configuration use cases: -.. _add-access-key: +.. _add-admin-secret: -Add an access key ------------------ +Add an admin secret +------------------- -To add an access-key to Hasura, pass the ``--access-key`` flag with a secret +To add an admin-secret to Hasura, pass the ``--admin-secret`` flag with a secret generated by you. Run server in this mode using following docker command: @@ -23,7 +23,7 @@ Run server in this mode using following docker command: docker run -P -d hasura/graphql-engine:latest graphql-engine \ --database-url postgres://username:password@host:5432/dbname \ serve \ - --access-key XXXXXXXXXXXXXXXX + --admin-secret XXXXXXXXXXXXXXXX Typically, you will also have a webhook for authentication: @@ -32,60 +32,60 @@ Typically, you will also have a webhook for authentication: docker run -P -d hasura/graphql-engine:latest graphql-engine \ --database-url postgres://username:password@host:5432/dbname \ serve \ - --access-key XXXXXXXXXXXXXXXX + --admin-secret XXXXXXXXXXXXXXXX --auth-hook https://myauth.mywebsite.com/user/session-info In addition to flags, the GraphQL Engine also accepts Environment variables. -In the above case, for adding an access key you will use the ``HASURA_GRAPHQL_ACCESS_KEY`` +In the above case, for adding an admin secret you will use the ``HASURA_GRAPHQL_ADMIN_SECRET`` and for the webhook, you will use the ``HASURA_GRAPHQL_AUTH_HOOK`` environment variables. -.. _cli-with-access-key: +.. _cli-with-admin-secret: -Using CLI commands with access key ----------------------------------- +Using CLI commands with admin secret +------------------------------------ -When you start the GraphQL Engine with an access key, CLI commands will also -need this access key to contact APIs. It can be set in ``config.yaml`` or as an +When you start the GraphQL Engine with an admin secret key, CLI commands will also +need this admin secret to contact APIs. It can be set in ``config.yaml`` or as an environment variable or as a flag to the command. For example, let's look at the case of the ``console`` command: -In the ``my-project/config.yaml`` file, set a new key ``access_key``: +In the ``my-project/config.yaml`` file, set a new key ``admin_secret``: .. code-block:: yaml # config.yaml endpoint: https://my-graphql-endpoint.com - access_key: XXXXXXXXXXXXXXXX + admin_secret: XXXXXXXXXXXXXXXX -The console can now contact the GraphQL APIs with the specified access key. +The console can now contact the GraphQL APIs with the specified admin secret. .. note:: - If you're setting ``access_key`` in ``config.yaml`` please make sure you do + If you're setting ``admin_secret`` in ``config.yaml`` please make sure you do not check this file into a public repository. -An alternate and safe way is to pass the access key value to the command +An alternate and safe way is to pass the admin secret value to the command as an environment variable: .. code-block:: bash - export HASURA_GRAPHQL_ACCESS_KEY=xxxxx + export HASURA_GRAPHQL_ADMIN_SECRET=xxxxx hasura console # OR in a single line - HASURA_GRAPHQL_ACCESS_KEY=xxxxx hasura console + HASURA_GRAPHQL_ADMIN_SECRET=xxxxx hasura console -You can also set the access key using a flag to the command: +You can also set the admin secret using a flag to the command: .. code-block:: bash - hasura console --access-key=XXXXXXXXXXXX + hasura console --admin-secret=XXXXXXXXXXXX .. note:: - The order of precedence for access key and endpoint is as follows: + The order of precedence for admin secret and endpoint is as follows: CLI flag > Environment variable > Config file @@ -103,5 +103,5 @@ For example: docker run -P -d hasura/graphql-engine:latest graphql-engine \ --database-url postgres://username:password@host:5432/dbname \ serve \ - --access-key XXXXXXXXXXXXXXXX + --admin-secret XXXXXXXXXXXXXXXX --cors-domain https://mywebsite.com:8090 diff --git a/docs/graphql/manual/deployment/graphql-engine-flags/index.rst b/docs/graphql/manual/deployment/graphql-engine-flags/index.rst index 5c51418d90c1f..9e01f839c540d 100644 --- a/docs/graphql/manual/deployment/graphql-engine-flags/index.rst +++ b/docs/graphql/manual/deployment/graphql-engine-flags/index.rst @@ -18,8 +18,8 @@ Use cases The following are a few configuration use cases: -- :ref:`add-access-key` -- :ref:`cli-with-access-key` +- :ref:`add-admin-secret` +- :ref:`cli-with-admin-secret` - :ref:`configure-cors` .. toctree:: diff --git a/docs/graphql/manual/deployment/graphql-engine-flags/reference.rst b/docs/graphql/manual/deployment/graphql-engine-flags/reference.rst index 7277b86054703..030368311db1c 100644 --- a/docs/graphql/manual/deployment/graphql-engine-flags/reference.rst +++ b/docs/graphql/manual/deployment/graphql-engine-flags/reference.rst @@ -44,7 +44,7 @@ For ``serve`` subcommand these are the flags available --server-port Port on which graphql-engine should be served (default: 8080) - --access-key Secret access key, required to access this instance. + --admin-secret Admin secret key, required to access this instance. If specified client needs to send 'X-Hasura-Admin-Secret' header @@ -62,8 +62,8 @@ For ``serve`` subcommand these are the flags available ""}`,`{"type": "RS256", "key": ""} - --unauthorized-role Unauthorized role, used when access-key is not sent in - access-key only mode or "Authorization" header is absent + --unauthorized-role Unauthorized role, used when admin-secret is not sent in + admin-secret only mode or "Authorization" header is absent in JWT mode -s, --stripes Number of stripes (default: 1) @@ -123,7 +123,7 @@ These are the environment variables which are available: HASURA_GRAPHQL_SERVER_PORT Port on which graphql-engine should be served - HASURA_GRAPHQL_ACCESS_KEY Secret access key, required to access this + HASURA_GRAPHQL_ADMIN_SECRET Admin secret key, required to access this instance. If specified client needs to send 'X-Hasura-Admin-Secret' header @@ -142,8 +142,8 @@ These are the environment variables which are available: "key": ""} Enable JWT mode, the value of which is a JSON - HASURA_GRAPHQL_UNAUTHORIZED_ROLE Unauthorized role, used when access-key is not sent - in access-key only mode or "Authorization" header + HASURA_GRAPHQL_UNAUTHORIZED_ROLE Unauthorized role, used when admin-secret is not sent + in admin-secret only mode or "Authorization" header is absent in JWT mode HASURA_GRAPHQL_ENABLE_CONSOLE Enable API console. It is served at diff --git a/docs/graphql/manual/deployment/heroku/securing-graphql-endpoint.rst b/docs/graphql/manual/deployment/heroku/securing-graphql-endpoint.rst index 880f94d861feb..c88fbdef5762b 100644 --- a/docs/graphql/manual/deployment/heroku/securing-graphql-endpoint.rst +++ b/docs/graphql/manual/deployment/heroku/securing-graphql-endpoint.rst @@ -7,33 +7,33 @@ Securing the GraphQL endpoint (Heroku) :local: To make sure that your GraphQL endpoint and the Hasura console are not publicly accessible, you need to -configure an access key. +configure an admin secret key. -Add the HASURA_GRAPHQL_ACCESS_KEY env var +Add the HASURA_GRAPHQL_ADMIN_SECRET env var ----------------------------------------- -Head to the config-vars URL on your Heroku dashboard and set the ``HASURA_GRAPHQL_ACCESS_KEY`` environment variable. +Head to the config-vars URL on your Heroku dashboard and set the ``HASURA_GRAPHQL_ADMIN_SECRET`` environment variable. .. image:: ../../../../img/graphql/manual/deployment/secure-heroku.png Setting this environment variable will automatically restart the dyno. Now when you access your console, you'll be -prompted for the access key. +prompted for the admin secret key. .. image:: ../../../../img/graphql/manual/deployment/access-key-console.png -(optional) Use the access key with the CLI +(optional) Use the admin secret with the CLI ------------------------------------------ -In case you're using the CLI to open the Hasura console, use the ``access-key`` flag when you open the console: +In case you're using the CLI to open the Hasura console, use the ``admin-secret`` flag when you open the console: .. code-block:: bash - hasura console --access-key=mysecretkey + hasura console --admin-secret=myadminsecretkey .. note:: If you're looking at adding authentication and access control to your GraphQL API then head - to :doc:`Authentication / access control <../../auth/index>`. \ No newline at end of file + to :doc:`Authentication / access control <../../auth/index>`. diff --git a/docs/graphql/manual/deployment/heroku/using-existing-heroku-database.rst b/docs/graphql/manual/deployment/heroku/using-existing-heroku-database.rst index 8b9862b172d4e..5b61e7c2f2f4f 100644 --- a/docs/graphql/manual/deployment/heroku/using-existing-heroku-database.rst +++ b/docs/graphql/manual/deployment/heroku/using-existing-heroku-database.rst @@ -11,7 +11,7 @@ like add GraphQL on it. .. note:: - In case you're exposing an existing database (esp. if it is production), please configure an access key + In case you're exposing an existing database (esp. if it is production), please configure an admin secret key for the console and the GraphQL endpoint. Step 0: Deploy Hasura on Heroku @@ -38,7 +38,7 @@ Head to your Heroku dashboard and delete the Postgres addon: Step 2: Configure environment variables --------------------------------------- -Now configure the ``DATABASE_URL`` with your existing Heroku Postgres database URL and a ``HASURA_GRAPHQL_ACCESS_KEY`` +Now configure the ``DATABASE_URL`` with your existing Heroku Postgres database URL and a ``HASURA_GRAPHQL_ADMIN_SECRET`` if you want to secure your endpoint. .. image:: ../../../../img/graphql/manual/deployment/heroku-database-url-access.png diff --git a/docs/graphql/manual/deployment/kubernetes/securing-graphql-endpoint.rst b/docs/graphql/manual/deployment/kubernetes/securing-graphql-endpoint.rst index 58d075380c75f..1cdc31a70334d 100644 --- a/docs/graphql/manual/deployment/kubernetes/securing-graphql-endpoint.rst +++ b/docs/graphql/manual/deployment/kubernetes/securing-graphql-endpoint.rst @@ -7,13 +7,13 @@ Securing the GraphQL endpoint (Kubernetes) :local: To make sure that your GraphQL endpoint and the Hasura console are not publicly accessible, you need to -configure an access key. +configure an admin secret key. -Add the HASURA_GRAPHQL_ACCESS_KEY env var +Add the HASURA_GRAPHQL_ADMIN_SECRET env var ----------------------------------------- -Update the ``deployment.yaml`` to set the ``HASURA_GRAPHQL_ACCESS_KEY`` environment variable. +Update the ``deployment.yaml`` to set the ``HASURA_GRAPHQL_ADMIN_SECRET`` environment variable. .. code-block:: yaml :emphasize-lines: 10,11 @@ -27,7 +27,7 @@ Update the ``deployment.yaml`` to set the ``HASURA_GRAPHQL_ACCESS_KEY`` environm env: - name: HASURA_GRAPHQL_DATABASE_URL value: postgres://username:password@hostname:port/dbname - - name: HASURA_GRAPHQL_ACCESS_KEY + - name: HASURA_GRAPHQL_ADMIN_SECRET value: mysecretkey ports: - containerPort: 8080 @@ -36,17 +36,17 @@ Update the ``deployment.yaml`` to set the ``HASURA_GRAPHQL_ACCESS_KEY`` environm -(optional) Use the access key with the CLI +(optional) Use the admin secret key with the CLI ------------------------------------------ -In case you're using the CLI to open the Hasura console, use the ``access-key`` flag when you open the console: +In case you're using the CLI to open the Hasura console, use the ``admin-secret`` flag when you open the console: .. code-block:: bash - hasura console --access-key=mysecretkey + hasura console --admin-secret=myadminsecretkey .. note:: If you're looking at adding authentication and access control to your GraphQL API then head - to :doc:`Authentication / access control <../../auth/index>`. \ No newline at end of file + to :doc:`Authentication / access control <../../auth/index>`. diff --git a/docs/graphql/manual/deployment/securing-graphql-endpoint.rst b/docs/graphql/manual/deployment/securing-graphql-endpoint.rst index 1184eea1d2e7e..a59743d9b7148 100644 --- a/docs/graphql/manual/deployment/securing-graphql-endpoint.rst +++ b/docs/graphql/manual/deployment/securing-graphql-endpoint.rst @@ -7,9 +7,9 @@ Securing the GraphQL endpoint :local: To make sure that your GraphQL endpoint and the Hasura console are not publicly accessible, you need to -configure an access key. +configure an admin secret key. -Depending on your deployment method, follow one of these guides to configure an access key, and prevent public +Depending on your deployment method, follow one of these guides to configure an admin secret key, and prevent public access to your GraphQL endpoint and the Hasura console: - :doc:`For Heroku ` diff --git a/docs/graphql/manual/event-triggers/serverless.rst b/docs/graphql/manual/event-triggers/serverless.rst index 8df7009324557..79125faf2e9e0 100644 --- a/docs/graphql/manual/event-triggers/serverless.rst +++ b/docs/graphql/manual/event-triggers/serverless.rst @@ -67,7 +67,7 @@ Our AWS Lambda code looks like this: const fetch = require('node-fetch'); - const accessKey = process.env.ACCESS_KEY; + const adminSecret = process.env.ADMIN_SECRET; const hgeEndpoint = process.env.HGE_ENDPOINT; const query = ` @@ -99,7 +99,7 @@ Our AWS Lambda code looks like this: fetch(hgeEndpoint + '/v1alpha1/graphql', { method: 'POST', body: JSON.stringify({query: query, variables: qv}), - headers: {'Content-Type': 'application/json', 'x-hasura-admin-secret': accessKey}, + headers: {'Content-Type': 'application/json', 'x-hasura-admin-secret': adminSecret}, }) .then(res => res.json()) .then(json => { diff --git a/docs/graphql/manual/guides/deployment/digital-ocean-one-click.rst b/docs/graphql/manual/guides/deployment/digital-ocean-one-click.rst index 47e23782ffc49..c5411eeaa5212 100644 --- a/docs/graphql/manual/guides/deployment/digital-ocean-one-click.rst +++ b/docs/graphql/manual/guides/deployment/digital-ocean-one-click.rst @@ -108,12 +108,12 @@ Switch to the ``GraphiQL`` tab on top and execute the following GraphQL query: Secure the GraphQL endpoint --------------------------- -By default Hasura is exposed without any access key. Anyone can read and write +By default Hasura is exposed without any secret key. Anyone can read and write to your database using GraphQL. When deploying to production, you should secure -the endpoint by adding an access key and then setting up permission rules on +the endpoint by adding an admin secret key and then setting up permission rules on tables. -To add an access key, follow the steps given below: +To add an admin secret key, follow the steps given below: 1. Connect to the Droplet via SSH: @@ -129,7 +129,7 @@ To add an access key, follow the steps given below: cd /etc/hasura -3. Edit ``docker-compose.yaml`` and un-comment the line that mentions access key. +3. Edit ``docker-compose.yaml`` and un-comment the line that mentions admin secret key. Also change it to some unique secret: .. code-block:: bash @@ -137,8 +137,8 @@ To add an access key, follow the steps given below: vim docker-compose.yaml ... - # un-comment next line to add an access key - HASURA_GRAPHQL_ACCESS_KEY: mysecretaccesskey + # un-comment next line to add an admin secret key + HASURA_GRAPHQL_ADMIN_SECRET: myadminsecretkey ... # type ESC followed by :wq to save and quit @@ -152,12 +152,12 @@ To add an access key, follow the steps given below: That's it. Visit the console at ``http://your_droplet_ip/console`` and it should -prompt for the access key. Further API requests can be made by adding the +prompt for the admin secret key. Further API requests can be made by adding the following header: .. code-block:: bash - X-Hasura-Admin-Secret: mysecretaccesskey + X-Hasura-Admin-Secret: myadminsecretkey Adding a domain & Enabling HTTPS diff --git a/docs/graphql/manual/hasura-cli/hasura_console.rst b/docs/graphql/manual/hasura-cli/hasura_console.rst index 1a27389bc813e..2c34efb78f67b 100644 --- a/docs/graphql/manual/hasura-cli/hasura_console.rst +++ b/docs/graphql/manual/hasura-cli/hasura_console.rst @@ -31,7 +31,7 @@ Options :: - --access-key string access key for Hasura GraphQL Engine + --admin-secret string admin secret key for Hasura GraphQL Engine --address string address to use (default "localhost") --api-port string port for serving migrate api (default "9693") --console-port string port for serving console (default "9695") diff --git a/docs/graphql/manual/hasura-cli/hasura_init.rst b/docs/graphql/manual/hasura-cli/hasura_init.rst index f8dccd6f9abb9..a178da1b6a919 100644 --- a/docs/graphql/manual/hasura-cli/hasura_init.rst +++ b/docs/graphql/manual/hasura-cli/hasura_init.rst @@ -23,10 +23,10 @@ Examples # Create a directory to store migrations hasura init - # Now, edit /config.yaml to add endpoint and access key + # Now, edit /config.yaml to add endpoint and admin secret key - # Create a directory with endpoint and access key configured: - hasura init --directory --endpoint https://my-graphql-engine.com --access-key secretaccesskey + # Create a directory with endpoint and admin secret key configured: + hasura init --directory --endpoint https://my-graphql-engine.com --admin-secret adminsecretkey # See https://docs.hasura.io/1.0/graphql/manual/migrations/index.html for more details @@ -35,10 +35,10 @@ Options :: - --access-key string access key for Hasura GraphQL Engine - --directory string name of directory where files will be created - --endpoint string http(s) endpoint for Hasura GraphQL Engine - -h, --help help for init + --admin-secret string admin secret key for Hasura GraphQL Engine + --directory string name of directory where files will be created + --endpoint string http(s) endpoint for Hasura GraphQL Engine + -h, --help help for init Options inherited from parent commands ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/graphql/manual/hasura-cli/hasura_metadata_apply.rst b/docs/graphql/manual/hasura-cli/hasura_metadata_apply.rst index e888d9339fe21..38a143308ebfd 100644 --- a/docs/graphql/manual/hasura-cli/hasura_metadata_apply.rst +++ b/docs/graphql/manual/hasura-cli/hasura_metadata_apply.rst @@ -28,9 +28,9 @@ Options :: - --access-key string access key for Hasura GraphQL Engine - --endpoint string http(s) endpoint for Hasura GraphQL Engine - -h, --help help for apply + --admin-secret string admin secret key for Hasura GraphQL Engine + --endpoint string http(s) endpoint for Hasura GraphQL Engine + -h, --help help for apply Options inherited from parent commands ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/graphql/manual/hasura-cli/hasura_metadata_export.rst b/docs/graphql/manual/hasura-cli/hasura_metadata_export.rst index 5b5d6e488a6e7..8a662e0832186 100644 --- a/docs/graphql/manual/hasura-cli/hasura_metadata_export.rst +++ b/docs/graphql/manual/hasura-cli/hasura_metadata_export.rst @@ -32,9 +32,9 @@ Options :: - --access-key string access key for Hasura GraphQL Engine - --endpoint string http(s) endpoint for Hasura GraphQL Engine - -h, --help help for export + --admin-secret string admin secret key for Hasura GraphQL Engine + --endpoint string http(s) endpoint for Hasura GraphQL Engine + -h, --help help for export Options inherited from parent commands ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/graphql/manual/hasura-cli/hasura_metadata_reload.rst b/docs/graphql/manual/hasura-cli/hasura_metadata_reload.rst index 0795be364ee92..5ab69a0733218 100644 --- a/docs/graphql/manual/hasura-cli/hasura_metadata_reload.rst +++ b/docs/graphql/manual/hasura-cli/hasura_metadata_reload.rst @@ -28,9 +28,9 @@ Options :: - --access-key string access key for Hasura GraphQL Engine - --endpoint string http(s) endpoint for Hasura GraphQL Engine - -h, --help help for reload + --admin-secret string admin secret key for Hasura GraphQL Engine + --endpoint string http(s) endpoint for Hasura GraphQL Engine + -h, --help help for reload Options inherited from parent commands ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/graphql/manual/hasura-cli/hasura_metadata_reset.rst b/docs/graphql/manual/hasura-cli/hasura_metadata_reset.rst index 569ebb249aa92..fbb48ca97b261 100644 --- a/docs/graphql/manual/hasura-cli/hasura_metadata_reset.rst +++ b/docs/graphql/manual/hasura-cli/hasura_metadata_reset.rst @@ -28,9 +28,9 @@ Options :: - --access-key string access key for Hasura GraphQL Engine - --endpoint string http(s) endpoint for Hasura GraphQL Engine - -h, --help help for reset + --admin-secret string admin secret for Hasura GraphQL Engine + --endpoint string http(s) endpoint for Hasura GraphQL Engine + -h, --help help for reset Options inherited from parent commands ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/graphql/manual/hasura-cli/hasura_migrate_apply.rst b/docs/graphql/manual/hasura-cli/hasura_migrate_apply.rst index b1d51f4ecbb38..f4ef7fc16661e 100644 --- a/docs/graphql/manual/hasura-cli/hasura_migrate_apply.rst +++ b/docs/graphql/manual/hasura-cli/hasura_migrate_apply.rst @@ -20,13 +20,13 @@ Options :: - --access-key string access key for Hasura GraphQL Engine - --down string apply all or N down migration steps - --endpoint string http(s) endpoint for Hasura GraphQL Engine - -h, --help help for apply - --type string type of migration (up, down) to be used with version flag (default "up") - --up string apply all or N up migration steps - --version string migrate the database to a specific version + --admin-secret string admin secret key for Hasura GraphQL Engine + --down string apply all or N down migration steps + --endpoint string http(s) endpoint for Hasura GraphQL Engine + -h, --help help for apply + --type string type of migration (up, down) to be used with version flag (default "up") + --up string apply all or N up migration steps + --version string migrate the database to a specific version Options inherited from parent commands ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/graphql/manual/hasura-cli/hasura_migrate_status.rst b/docs/graphql/manual/hasura-cli/hasura_migrate_status.rst index cb742e456995a..a102d79681892 100644 --- a/docs/graphql/manual/hasura-cli/hasura_migrate_status.rst +++ b/docs/graphql/manual/hasura-cli/hasura_migrate_status.rst @@ -20,9 +20,9 @@ Options :: - --access-key string access key for Hasura GraphQL Engine - --endpoint string http(s) endpoint for Hasura GraphQL Engine - -h, --help help for status + --admin-secret string admin secret key for Hasura GraphQL Engine + --endpoint string http(s) endpoint for Hasura GraphQL Engine + -h, --help help for status Options inherited from parent commands ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/graphql/manual/migrations/database-with-migrations.rst b/docs/graphql/manual/migrations/database-with-migrations.rst index 7363a39fcf42b..08cf1f4bc4d81 100644 --- a/docs/graphql/manual/migrations/database-with-migrations.rst +++ b/docs/graphql/manual/migrations/database-with-migrations.rst @@ -78,11 +78,11 @@ Instead of using the console at ``http://my-graphql.herokuapp.com/console`` you .. code-block:: bash - # Without access key + # Without admin secret key hasura console - # With access key - hasura console --access-key mysecretkey + # With admin secret key + hasura console --admin-secret-key myadminsecretkey Step 4: Disable database schema modifications --------------------------------------------- diff --git a/docs/graphql/manual/migrations/existing-project.rst b/docs/graphql/manual/migrations/existing-project.rst index 5fc3c50e3e598..be29d3a500b4a 100644 --- a/docs/graphql/manual/migrations/existing-project.rst +++ b/docs/graphql/manual/migrations/existing-project.rst @@ -125,11 +125,11 @@ Instead of using the console at ``http://my-graphql.herokuapp.com/console`` you .. code-block:: bash - # Without access key + # Without admin secret key hasura console - # With access key - hasura console --access-key mysecretkey + # With admin secret key + hasura console --admin-secret myadminsecretkey Step 5: Add a new table and see how a migration is added -------------------------------------------------------- diff --git a/docs/graphql/manual/migrations/new-project.rst b/docs/graphql/manual/migrations/new-project.rst index 453bdfd51373a..46e6b5410757f 100644 --- a/docs/graphql/manual/migrations/new-project.rst +++ b/docs/graphql/manual/migrations/new-project.rst @@ -84,11 +84,11 @@ Instead of using the console at ``http://my-graphql.herokuapp.com/console`` you .. code-block:: bash - # Without access key + # Without admin secret key hasura console - # With access key - hasura console --access-key mysecretkey + # With admin secret key + hasura console --admin-secret adminsecretkey Step 4: Add a new table and see how a migration is added -------------------------------------------------------- diff --git a/docs/graphql/manual/schema/export-graphql-schema.rst b/docs/graphql/manual/schema/export-graphql-schema.rst index e253e2bdee59a..2123a8452e5cb 100644 --- a/docs/graphql/manual/schema/export-graphql-schema.rst +++ b/docs/graphql/manual/schema/export-graphql-schema.rst @@ -21,11 +21,11 @@ GraphQL schema: .. code-block:: bash # If the GraphQL engine is running at https://my-graphql-engine.com/v1alpha1/graphql, - # without an access key + # without an admin secret key gq https://my-graphql-engine.com/v1alpha1/graphql --introspect > schema.graphql - # If Hasura GraphQL Engine is running with an access key - gq https://my-graphql-engine.com/v1alpha1/graphql -H 'X-Hasura-Admin-Secret: secretaccesskey' --introspect > schema.graphql + # If Hasura GraphQL Engine is running with an admin secret + gq https://my-graphql-engine.com/v1alpha1/graphql -H 'X-Hasura-Admin-Secret: adminsecretkey' --introspect > schema.graphql By default, it downloads the schema in ``.graphql`` format. If you want it in JSON format, you can use an additional flag ``--format json``: diff --git a/install-manifests/docker-compose-https/docker-compose.yaml b/install-manifests/docker-compose-https/docker-compose.yaml index cb620036448df..2c633193d1637 100644 --- a/install-manifests/docker-compose-https/docker-compose.yaml +++ b/install-manifests/docker-compose-https/docker-compose.yaml @@ -15,8 +15,8 @@ services: HASURA_GRAPHQL_DATABASE_URL: postgres://postgres:@postgres:5432/postgres # enable the console served by server HASURA_GRAPHQL_ENABLE_CONSOLE: "true" # set "false" to disable console - ## uncomment next line to set an access key - # HASURA_GRAPHQL_ACCESS_KEY: mysecretaccesskey + ## uncomment next line to set an admin secret key + # HASURA_GRAPHQL_ADMIN_SECRET: myadminsecretkey command: - graphql-engine - serve diff --git a/install-manifests/docker-compose-postgis/docker-compose.yaml b/install-manifests/docker-compose-postgis/docker-compose.yaml index 785d8b62263f1..7e2b8712014c5 100644 --- a/install-manifests/docker-compose-postgis/docker-compose.yaml +++ b/install-manifests/docker-compose-postgis/docker-compose.yaml @@ -15,7 +15,7 @@ services: environment: HASURA_GRAPHQL_DATABASE_URL: postgres://postgres:@postgres:5432/postgres HASURA_GRAPHQL_ENABLE_CONSOLE: "true" # set to "false" to disable console - ## uncomment next line to set an access key - # HASURA_GRAPHQL_ACCESS_KEY: mysecretaccesskey + ## uncomment next line to set the admin secret key + # HASURA_GRAPHQL_ADMIN_SECRET: myadminsecretkey volumes: db_data: diff --git a/install-manifests/docker-compose/docker-compose.yaml b/install-manifests/docker-compose/docker-compose.yaml index 7d0e09c96d2e1..2f48e659a5415 100644 --- a/install-manifests/docker-compose/docker-compose.yaml +++ b/install-manifests/docker-compose/docker-compose.yaml @@ -15,7 +15,7 @@ services: environment: HASURA_GRAPHQL_DATABASE_URL: postgres://postgres:@postgres:5432/postgres HASURA_GRAPHQL_ENABLE_CONSOLE: "true" # set to "false" to disable console - ## uncomment next line to set an access key - # HASURA_GRAPHQL_ACCESS_KEY: mysecretaccesskey + ## uncomment next line to set an admin secret + # HASURA_GRAPHQL_ADMIN_SECRET: myadminsecretkey volumes: db_data: diff --git a/server/src-exec/Main.hs b/server/src-exec/Main.hs index b834b9bf83933..e9e95f810a450 100644 --- a/server/src-exec/Main.hs +++ b/server/src-exec/Main.hs @@ -66,7 +66,7 @@ parseHGECommand = <*> parseServerHost <*> parseConnParams <*> parseTxIsolation - <*> parseAccessKey + <*> (parseAdminSecret <|> parseAccessKey) <*> parseWebHook <*> parseJwtSecret <*> parseUnAuthRole @@ -102,13 +102,13 @@ main = do loggerCtx <- mkLoggerCtx $ defaultLoggerSettings True let logger = mkLogger loggerCtx case hgeCmd of - HCServe so@(ServeOptions port host cp isoL mAccessKey mAuthHook mJwtSecret + HCServe so@(ServeOptions port host cp isoL mAdminSecret mAuthHook mJwtSecret mUnAuthRole corsCfg enableConsole enableTelemetry) -> do -- log serve options unLogger logger $ serveOptsToLog so hloggerCtx <- mkLoggerCtx $ defaultLoggerSettings False - authModeRes <- runExceptT $ mkAuthMode mAccessKey mAuthHook mJwtSecret + authModeRes <- runExceptT $ mkAuthMode mAdminSecret mAuthHook mJwtSecret mUnAuthRole httpManager loggerCtx am <- either (printErrExit . T.unpack) return authModeRes diff --git a/server/src-lib/Hasura/RQL/Types/Permission.hs b/server/src-lib/Hasura/RQL/Types/Permission.hs index 55380490c8984..76d2bd970b3a0 100644 --- a/server/src-lib/Hasura/RQL/Types/Permission.hs +++ b/server/src-lib/Hasura/RQL/Types/Permission.hs @@ -23,7 +23,7 @@ module Hasura.RQL.Types.Permission ) where import Hasura.Prelude -import Hasura.Server.Utils (accessKeyHeader, userRoleHeader) +import Hasura.Server.Utils (adminSecretHeader, deprecatedAccessKeyHeader, userRoleHeader) import Hasura.SQL.Types import qualified Database.PG.Query as Q @@ -89,7 +89,7 @@ data UserInfo mkUserInfo :: RoleName -> UserVars -> UserInfo mkUserInfo rn (UserVars v) = UserInfo rn $ UserVars $ Map.insert userRoleHeader (getRoleTxt rn) $ - Map.delete accessKeyHeader v + foldl (flip Map.delete) v [adminSecretHeader, deprecatedAccessKeyHeader] instance Hashable UserInfo diff --git a/server/src-lib/Hasura/Server/App.hs b/server/src-lib/Hasura/Server/App.hs index af8374fe52af1..601a1112b276a 100644 --- a/server/src-lib/Hasura/Server/App.hs +++ b/server/src-lib/Hasura/Server/App.hs @@ -58,9 +58,9 @@ consoleTmplt = $(M.embedSingleTemplate "src-rsr/console.html") boolToText :: Bool -> T.Text boolToText = bool "false" "true" -isAccessKeySet :: AuthMode -> T.Text -isAccessKeySet AMNoAuth = boolToText False -isAccessKeySet _ = boolToText True +isAdminSecretSet :: AuthMode -> T.Text +isAdminSecretSet AMNoAuth = boolToText False +isAdminSecretSet _ = boolToText True #ifdef LocalConsole consoleAssetsLoc :: Text @@ -77,7 +77,7 @@ mkConsoleHTML path authMode enableTelemetry = where (errs, res) = M.checkedSubstitute consoleTmplt $ object [ "consoleAssetsLoc" .= consoleAssetsLoc - , "isAccessKeySet" .= isAccessKeySet authMode + , "isAdminSecretSet" .= isAdminSecretSet authMode , "consolePath" .= consolePath , "enableTelemetry" .= boolToText enableTelemetry ] diff --git a/server/src-lib/Hasura/Server/Auth.hs b/server/src-lib/Hasura/Server/Auth.hs index a445241a68e8e..19887a0927dca 100644 --- a/server/src-lib/Hasura/Server/Auth.hs +++ b/server/src-lib/Hasura/Server/Auth.hs @@ -5,7 +5,7 @@ module Hasura.Server.Auth ( getUserInfo , AuthMode(..) , mkAuthMode - , AccessKey (..) + , AdminSecret (..) , AuthHookType(..) , AuthHookG (..) , AuthHook @@ -45,8 +45,8 @@ import Hasura.Server.Utils import qualified Hasura.Logging as L -newtype AccessKey - = AccessKey { getAccessKey :: T.Text } +newtype AdminSecret + = AdminSecret { getAdminSecret :: T.Text } deriving (Show, Eq) data AuthHookType @@ -68,9 +68,9 @@ type AuthHook = AuthHookG T.Text AuthHookType data AuthMode = AMNoAuth - | AMAccessKey !AccessKey !(Maybe RoleName) - | AMAccessKeyAndHook !AccessKey !AuthHook - | AMAccessKeyAndJWT !AccessKey !JWTCtx !(Maybe RoleName) + | AMAdminSecret !AdminSecret !(Maybe RoleName) + | AMAdminSecretAndHook !AdminSecret !AuthHook + | AMAdminSecretAndJWT !AdminSecret !JWTCtx !(Maybe RoleName) deriving (Show, Eq) hdrsToText :: [N.Header] -> [(T.Text, T.Text)] @@ -83,7 +83,7 @@ mkAuthMode :: ( MonadIO m , MonadError T.Text m ) - => Maybe AccessKey + => Maybe AdminSecret -> Maybe AuthHook -> Maybe T.Text -> Maybe RoleName @@ -93,24 +93,23 @@ mkAuthMode mkAuthMode mAccessKey mWebHook mJwtSecret mUnAuthRole httpManager lCtx = case (mAccessKey, mWebHook, mJwtSecret) of (Nothing, Nothing, Nothing) -> return AMNoAuth - (Just key, Nothing, Nothing) -> return $ AMAccessKey key mUnAuthRole + (Just key, Nothing, Nothing) -> return $ AMAdminSecret key mUnAuthRole (Just key, Just hook, Nothing) -> unAuthRoleNotReqForWebHook >> - return (AMAccessKeyAndHook key hook) + return (AMAdminSecretAndHook key hook) (Just key, Nothing, Just jwtConf) -> do jwtCtx <- mkJwtCtx jwtConf httpManager lCtx - return $ AMAccessKeyAndJWT key jwtCtx mUnAuthRole + return $ AMAdminSecretAndJWT key jwtCtx mUnAuthRole (Nothing, Just _, Nothing) -> throwError $ - "Fatal Error : --auth-hook (HASURA_GRAPHQL_AUTH_HOOK)" - <> " requires --access-key (HASURA_GRAPHQL_ACCESS_KEY) to be set" + "Fatal Error : --auth-hook (HASURA_GRAPHQL_AUTH_HOOK)" <> requiresAdminScrtMsg (Nothing, Nothing, Just _) -> throwError $ - "Fatal Error : --jwt-secret (HASURA_GRAPHQL_JWT_SECRET)" - <> " requires --access-key (HASURA_GRAPHQL_ACCESS_KEY) to be set" + "Fatal Error : --jwt-secret (HASURA_GRAPHQL_JWT_SECRET)" <> requiresAdminScrtMsg (Nothing, Just _, Just _) -> throwError "Fatal Error: Both webhook and JWT mode cannot be enabled at the same time" (Just _, Just _, Just _) -> throwError "Fatal Error: Both webhook and JWT mode cannot be enabled at the same time" where + requiresAdminScrtMsg = " requires --admin-secret (HASURA_GRAPHQL_ADMIN_SECRET) or --access-key (HASURA_GRAPHQL_ACCESS_KEY) to be set" unAuthRoleNotReqForWebHook = when (isJust mUnAuthRole) $ throwError $ "Fatal Error: --unauthorized-role (HASURA_GRAPHQL_UNAUTHORIZED_ROLE) is not allowed" @@ -238,24 +237,24 @@ getUserInfo logger manager rawHeaders = \case AMNoAuth -> return userInfoFromHeaders - AMAccessKey accKey unAuthRole -> - case accessKeyM of - Just givenAccKey -> userInfoWhenAccessKey accKey givenAccKey - Nothing -> userInfoWhenNoAccessKey unAuthRole + AMAdminSecret adminScrt unAuthRole -> + case adminSecretM of + Just givenAdminScrt -> userInfoWhenAdminSecret adminScrt givenAdminScrt + Nothing -> userInfoWhenNoAdminSecret unAuthRole - AMAccessKeyAndHook accKey hook -> - whenAccessKeyAbsent accKey (userInfoFromAuthHook logger manager hook rawHeaders) + AMAdminSecretAndHook accKey hook -> + whenAdminSecretAbsent accKey (userInfoFromAuthHook logger manager hook rawHeaders) - AMAccessKeyAndJWT accKey jwtSecret unAuthRole -> - whenAccessKeyAbsent accKey (processJwt jwtSecret rawHeaders unAuthRole) + AMAdminSecretAndJWT accKey jwtSecret unAuthRole -> + whenAdminSecretAbsent accKey (processJwt jwtSecret rawHeaders unAuthRole) where - -- when access key is absent, run the action to retrieve UserInfo, otherwise - -- accesskey override - whenAccessKeyAbsent ak action = - maybe action (userInfoWhenAccessKey ak) $ accessKeyM + -- when admin secret is absent, run the action to retrieve UserInfo, otherwise + -- adminsecret override + whenAdminSecretAbsent ak action = + maybe action (userInfoWhenAdminSecret ak) $ adminSecretM - accessKeyM = foldl1 (<|>) $ map (flip getVarVal usrVars) [accessKeyHeader, deprecatedAccessKeyHeader] + adminSecretM= foldl1 (<|>) $ map (flip getVarVal usrVars) [adminSecretHeader, deprecatedAccessKeyHeader] usrVars = mkUserVars $ hdrsToText rawHeaders @@ -264,10 +263,10 @@ getUserInfo logger manager rawHeaders = \case Just rn -> mkUserInfo rn usrVars Nothing -> mkUserInfo adminRole usrVars - userInfoWhenAccessKey key reqKey = do - when (reqKey /= getAccessKey key) $ throw401 $ "invalid " <> accessKeyHeader + userInfoWhenAdminSecret key reqKey = do + when (reqKey /= getAdminSecret key) $ throw401 $ "invalid " <> adminSecretHeader return userInfoFromHeaders - userInfoWhenNoAccessKey = \case - Nothing -> throw401 $ accessKeyHeader <> "/" <> deprecatedAccessKeyHeader <> " required, but not found" + userInfoWhenNoAdminSecret = \case + Nothing -> throw401 $ adminSecretHeader <> "/" <> deprecatedAccessKeyHeader <> " required, but not found" Just role -> return $ mkUserInfo role usrVars diff --git a/server/src-lib/Hasura/Server/Init.hs b/server/src-lib/Hasura/Server/Init.hs index ef14e2ed505b5..25afe9d68f90c 100644 --- a/server/src-lib/Hasura/Server/Init.hs +++ b/server/src-lib/Hasura/Server/Init.hs @@ -42,7 +42,7 @@ data RawServeOptions , rsoHost :: !(Maybe HostPreference) , rsoConnParams :: !RawConnParams , rsoTxIso :: !(Maybe Q.TxIsolation) - , rsoAccessKey :: !(Maybe AccessKey) + , rsoAdminSecret :: !(Maybe AdminSecret) , rsoAuthHook :: !RawAuthHook , rsoJwtSecret :: !(Maybe Text) , rsoUnAuthRole :: !(Maybe RoleName) @@ -66,7 +66,7 @@ data ServeOptions , soHost :: !HostPreference , soConnParams :: !Q.ConnParams , soTxIso :: !Q.TxIsolation - , soAccessKey :: !(Maybe AccessKey) + , soAdminSecret :: !(Maybe AdminSecret) , soAuthHook :: !(Maybe AuthHook) , soJwtSecret :: !(Maybe Text) , soUnAuthRole :: !(Maybe RoleName) @@ -126,8 +126,8 @@ instance FromEnv AuthHookType where instance FromEnv Int where fromEnv = maybe (Left "Expecting Int value") Right . readMaybe -instance FromEnv AccessKey where - fromEnv = Right . AccessKey . T.pack +instance FromEnv AdminSecret where + fromEnv = Right . AdminSecret . T.pack instance FromEnv RoleName where fromEnv = Right . RoleName . T.pack @@ -177,10 +177,17 @@ considerEnv envVar = do throwErr s = throwError $ "Fatal Error:- Environment variable " ++ envVar ++ ": " ++ s +considerEnvs :: FromEnv a => [String] -> WithEnv (Maybe a) +considerEnvs envVars = fmap (foldl1 (<|>)) $ mapM considerEnv envVars + withEnv :: FromEnv a => Maybe a -> String -> WithEnv (Maybe a) withEnv mVal envVar = maybe (considerEnv envVar) returnJust mVal +withEnvs :: FromEnv a => Maybe a -> [String] -> WithEnv (Maybe a) +withEnvs mVal envVars = + maybe (considerEnvs envVars) returnJust mVal + withEnvBool :: Bool -> String -> WithEnv Bool withEnvBool bVal envVar = bool considerEnv' (return True) bVal @@ -218,7 +225,7 @@ mkServeOptions rso = do connParams <- mkConnParams $ rsoConnParams rso txIso <- fromMaybe Q.ReadCommitted <$> withEnv (rsoTxIso rso) (fst txIsoEnv) - accKey <- withEnv (rsoAccessKey rso) $ fst accessKeyEnv + adminScrt <- withEnvs (rsoAdminSecret rso) $ map fst [adminSecretEnv, accessKeyEnv] authHook <- mkAuthHook $ rsoAuthHook rso jwtSecret <- withEnv (rsoJwtSecret rso) $ fst jwtSecretEnv unAuthRole <- withEnv (rsoUnAuthRole rso) $ fst unAuthRoleEnv @@ -228,7 +235,7 @@ mkServeOptions rso = do enableTelemetry <- fromMaybe True <$> withEnv (rsoEnableTelemetry rso) (fst enableTelemetryEnv) - return $ ServeOptions port host connParams txIso accKey authHook jwtSecret + return $ ServeOptions port host connParams txIso adminScrt authHook jwtSecret unAuthRole corsCfg enableConsole enableTelemetry where mkConnParams (RawConnParams s c i p) = do @@ -307,18 +314,18 @@ serveCmdFooter = , [ "# Start GraphQL Engine on a different port (say 9090) with console disabled" , "graphql-engine --database-url serve --server-port 9090" ] - , [ "# Start GraphQL Engine with access key" - , "graphql-engine --database-url serve --access-key " + , [ "# Start GraphQL Engine with admin secret key" + , "graphql-engine --database-url serve --admin-secret " ] , [ "# Start GraphQL Engine with restrictive CORS policy (only allow https://example.com:8080)" , "graphql-engine --database-url serve --cors-domain https://example.com:8080" ] , [ "# Start GraphQL Engine with Authentication Webhook (GET)" - , "graphql-engine --database-url serve --access-key " + , "graphql-engine --database-url serve --admin-secret " <> " --auth-hook https://mywebhook.com/get" ] , [ "# Start GraphQL Engine with Authentication Webhook (POST)" - , "graphql-engine --database-url serve --access-key " + , "graphql-engine --database-url serve --admin-secret " <> " --auth-hook https://mywebhook.com/post --auth-hook-mode POST" ] , [ "# Start GraphQL Engine with telemetry enabled/disabled" @@ -329,7 +336,7 @@ serveCmdFooter = envVarDoc = mkEnvVarDoc $ envVars <> eventEnvs envVars = [ servePortEnv, serveHostEnv, pgStripesEnv, pgConnsEnv, pgTimeoutEnv - , txIsoEnv, accessKeyEnv, authHookEnv , authHookModeEnv + , txIsoEnv, adminSecretEnv, accessKeyEnv, authHookEnv , authHookModeEnv , jwtSecretEnv , unAuthRoleEnv, corsDomainEnv , enableConsoleEnv , enableTelemetryEnv ] @@ -387,7 +394,13 @@ txIsoEnv = accessKeyEnv :: (String, String) accessKeyEnv = ( "HASURA_GRAPHQL_ACCESS_KEY" - , "Secret access key, required to access this instance" + , "Admin secret key, required to access this instance (deprecated: use HASURA_GRAPHQL_ADMIN_SECRET instead)" + ) + +adminSecretEnv :: (String, String) +adminSecretEnv = + ( "HASURA_GRAPHQL_ADMIN_SECRET" + , "Admin Secret key, required to access this instance" ) authHookEnv :: (String, String) @@ -411,7 +424,7 @@ jwtSecretEnv = unAuthRoleEnv :: (String, String) unAuthRoleEnv = ( "HASURA_GRAPHQL_UNAUTHORIZED_ROLE" - , "Unauthorized role, used when access-key is not sent in access-key only mode " + , "Unauthorized role, used when admin-secret is not sent in admin-secret only mode " ++ "or \"Authorization\" header is absent in JWT mode" ) @@ -553,12 +566,20 @@ parseServerHost = optional $ strOption ( long "server-host" <> help "Host on which graphql-engine will listen (default: *)" ) -parseAccessKey :: Parser (Maybe AccessKey) +parseAccessKey :: Parser (Maybe AdminSecret) parseAccessKey = - optional $ AccessKey <$> + optional $ AdminSecret <$> strOption ( long "access-key" <> - metavar "SECRET ACCESS KEY" <> - help (snd accessKeyEnv) + metavar "ADMIN SECRET KEY (DEPRECATED: USE --admin-secret)" <> + help (snd adminSecretEnv) + ) + +parseAdminSecret :: Parser (Maybe AdminSecret) +parseAdminSecret = + optional $ AdminSecret <$> + strOption ( long "admin-secret" <> + metavar "ADMIN SECRET KEY" <> + help (snd adminSecretEnv) ) readHookType :: String -> Either String AuthHookType @@ -650,7 +671,7 @@ serveOptsToLog so = StartupLog L.LevelInfo "serve_options" infoVal where infoVal = J.object [ "port" J..= soPort so - , "accesskey_set" J..= isJust (soAccessKey so) + , "admin_secret_set" J..= isJust (soAdminSecret so) , "auth_hook" J..= (ahUrl <$> soAuthHook so) , "auth_hook_mode" J..= (show . ahType <$> soAuthHook so) , "unauth_role" J..= soUnAuthRole so diff --git a/server/src-lib/Hasura/Server/Utils.hs b/server/src-lib/Hasura/Server/Utils.hs index 8af1992c7bc68..f6d725dc0291c 100644 --- a/server/src-lib/Hasura/Server/Utils.hs +++ b/server/src-lib/Hasura/Server/Utils.hs @@ -29,8 +29,8 @@ userRoleHeader = "x-hasura-role" deprecatedAccessKeyHeader :: T.Text deprecatedAccessKeyHeader = "x-hasura-access-key" -accessKeyHeader :: T.Text -accessKeyHeader = "x-hasura-admin-secret" +adminSecretHeader :: T.Text +adminSecretHeader = "x-hasura-admin-secret" userIdHeader :: T.Text userIdHeader = "x-hasura-user-id" diff --git a/server/src-rsr/console.html b/server/src-rsr/console.html index f5781f1a3375c..1f15f0db2f39a 100644 --- a/server/src-rsr/console.html +++ b/server/src-rsr/console.html @@ -6,7 +6,8 @@ consoleMode: "server", urlPrefix: "/console", consolePath: "{{consolePath}}", - isAccessKeySet: {{isAccessKeySet}}, + isAccessKeySet: {{isAdminSecretSet}}, + isAdminSecretSet: {{isAdminSecretSet}}, enableTelemetry: {{enableTelemetry}} }; diff --git a/server/test/Main.hs b/server/test/Main.hs index 02b51db6ff134..728fc17294ab3 100644 --- a/server/test/Main.hs +++ b/server/test/Main.hs @@ -45,8 +45,8 @@ ravenApp :: L.LoggerCtx -> PGQ.PGPool -> IO Application ravenApp loggerCtx pool = do let corsCfg = CorsConfigG "*" False -- cors is enabled httpManager <- HTTP.newManager HTTP.tlsManagerSettings - -- spockAsApp $ spockT id $ app Q.Serializable Nothing rlogger pool AMNoAuth corsCfg True -- no access key and no webhook - (app, _) <- mkWaiApp Q.Serializable Nothing loggerCtx pool httpManager AMNoAuth corsCfg True -- no access key and no webhook + -- spockAsApp $ spockT id $ app Q.Serializable Nothing rlogger pool AMNoAuth corsCfg True -- no admin secret and no webhook + (app, _) <- mkWaiApp Q.Serializable Nothing loggerCtx pool httpManager AMNoAuth corsCfg True -- no admin secret and no webhook return app diff --git a/server/tests-py/conftest.py b/server/tests-py/conftest.py index e6737adcd68f1..ec03cd08bbc21 100644 --- a/server/tests-py/conftest.py +++ b/server/tests-py/conftest.py @@ -11,7 +11,7 @@ def pytest_addoption(parser): "--pg-url", metavar="PG_URL", help="url for connecting to Postgres directly", required=True ) parser.addoption( - "--hge-key", metavar="HGE_KEY", help="access key for graphql-engine", required=False + "--hge-key", metavar="HGE_KEY", help="admin secret key for graphql-engine", required=False ) parser.addoption( "--hge-webhook", metavar="HGE_WEBHOOK", help="url for graphql-engine's access control webhook", required=False diff --git a/server/tests-py/test_subscriptions.py b/server/tests-py/test_subscriptions.py index 77e8439d4f27a..2897d05b2619f 100644 --- a/server/tests-py/test_subscriptions.py +++ b/server/tests-py/test_subscriptions.py @@ -12,7 +12,7 @@ def test_init_without_payload(hge_ctx): if hge_ctx.hge_key is not None: - pytest.skip("Payload is needed when access key is set") + pytest.skip("Payload is needed when admin secret is set") obj = { 'type': 'connection_init' } diff --git a/server/tests-py/validate.py b/server/tests-py/validate.py index 762996d2cbc25..96acb2be89b24 100644 --- a/server/tests-py/validate.py +++ b/server/tests-py/validate.py @@ -55,26 +55,26 @@ def check_event(hge_ctx, trig_name, table, operation, exp_ev_data, assert ev['data'] == exp_ev_data, ev -def test_forbidden_when_access_key_reqd(hge_ctx, conf): +def test_forbidden_when_admin_secret_reqd(hge_ctx, conf): headers = {} if 'headers' in conf: headers = conf['headers'] - # Test without access key + # Test without admin secret code, resp = hge_ctx.anyq(conf['url'], conf['query'], headers) assert code == 401, "\n" + yaml.dump({ - "expected": "Should be access denied as access key is not provided", + "expected": "Should be access denied as admin secret is not provided", "actual": { "code": code, "response": resp } }) - # Test with random access key + # Test with random admin secret headers['X-Hasura-Admin-Secret'] = base64.b64encode(os.urandom(30)) code, resp = hge_ctx.anyq(conf['url'], conf['query'], headers) assert code == 401, "\n" + yaml.dump({ - "expected": "Should be access denied as an incorrect access key is provided", + "expected": "Should be access denied as an incorrect admin secret is provided", "actual": { "code": code, "response": resp @@ -130,7 +130,7 @@ def check_query(hge_ctx, conf, add_auth=True): headers['X-Hasura-Admin-Secret'] = hge_ctx.hge_key elif hge_ctx.hge_key is not None and hge_ctx.hge_webhook is None and hge_ctx.hge_jwt_key is None: - test_forbidden_when_access_key_reqd(hge_ctx, conf) + test_forbidden_when_admin_secret_reqd(hge_ctx, conf) headers['X-Hasura-Admin-Secret'] = hge_ctx.hge_key code, resp = hge_ctx.anyq(conf['url'], conf['query'], headers) From ede9ff4f55c74b6db2a5c892351093c9fd6b7df3 Mon Sep 17 00:00:00 2001 From: Nizar Malangadan Date: Thu, 31 Jan 2019 14:59:44 +0530 Subject: [PATCH 03/36] Test to check whether header X-Hasura-Access-Key still works --- server/tests-py/test_compat.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 server/tests-py/test_compat.py diff --git a/server/tests-py/test_compat.py b/server/tests-py/test_compat.py new file mode 100644 index 0000000000000..44dc139acf642 --- /dev/null +++ b/server/tests-py/test_compat.py @@ -0,0 +1,24 @@ +import pytest + +if not pytest.config.getoption("--hge-key"): + pytest.skip("--hge-key flag is missing, skipping tests", allow_module_level=True) + +def v1qCompat(hge_ctx, q, headers = {}): + h = {'X-Hasura-Access-Key': hge_ctx.hge_key} + resp = hge_ctx.http.post( + hge_ctx.hge_url + "/v1/query", + json=q, + headers=h + ) + return resp.status_code, resp.json() + +class TestGraphQLCompatAccessKey(): + + export_metadata = { + "type" : "export_metadata", + "args" : {} + } + + def test_compact_access_key_export_metadata(self, hge_ctx): + code, resp = v1qCompat(hge_ctx, self.export_metadata) + assert code == 200, resp From cd157e1b18a2c8c2043b8aa1280e7d0cac7680c2 Mon Sep 17 00:00:00 2001 From: Nizar Malangadan Date: Thu, 31 Jan 2019 17:55:10 +0530 Subject: [PATCH 04/36] Add tests for 1) Flags --access-key and --admin-secret 2) EnvVars HASURA_GRAPHQL_ACCESS_KEY and HASURA_GRAPHQL_ADMIN_SECRET --- .circleci/config.yml | 11 +++- .circleci/test-cli.sh | 8 +-- .circleci/test-server-flags.sh | 107 ++++++++++++++++++++++++++++----- .circleci/test-server.sh | 34 +++++------ 4 files changed, 122 insertions(+), 38 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index b0f8a3f8e6367..2ab98bb3b87d2 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -96,7 +96,7 @@ refs: GRAPHQL_ENGINE: '/build/_server_output/graphql-engine' command: | apt-get update - apt install --yes jq + apt install --yes jq curl OUTPUT_FOLDER=/build/_server_test_output/$PG_VERSION .circleci/test-server.sh - run: name: Generate coverage report @@ -134,7 +134,7 @@ jobs: - server-deps-cache-{{ checksum "server/graphql-engine.cabal" }}-{{ checksum "server/stack.yaml" }} - restore_cache: keys: - - server-app-cache-{{ .Branch }}-{{ .Revision }} + - server-app-cache-1-{{ .Branch }} - run: name: Build the server working_directory: ./server @@ -145,10 +145,17 @@ jobs: make ci-binary else echo "Non-release branch, non-optimized build with coverage" + echo >> src-lib/Hasura/Server/Version.hs + stack build --only-dependencies --fast --coverage + git checkout HEAD -- src-lib/Hasura/Server/Version.hs BUILD_FLAGS="--fast --coverage" make ci-binary fi make ci-image make ci-save-image + - save_cache: + key: server-app-cache-1-{{ .Branch }} + paths: + - ./server/.stack-work - save_cache: key: server-app-cache-{{ .Branch }}-{{ .Revision }} paths: diff --git a/.circleci/test-cli.sh b/.circleci/test-cli.sh index 343bce27a9cc0..9e36b7aa16b74 100755 --- a/.circleci/test-cli.sh +++ b/.circleci/test-cli.sh @@ -20,7 +20,7 @@ cd "$CLI_ROOT" mkdir -p /build/_cli_output touch /build/_cli_output/server.log -# start graphql-engine without access key +# start graphql-engine without admin secret /build/_server_output/graphql-engine \ --database-url postgres://gql_test@localhost:5432/gql_test serve > /build/_cli_output/server.log 2>&1 & PID=$! @@ -31,10 +31,10 @@ wait_for_port 8080 HASURA_GRAPHQL_TEST_ENDPOINT="http://localhost:8080" make test kill $PID -# start graphql-engine with access key -psql -U gql_test -h localhost -c 'CREATE DATABASE "gql_test_with_access";' +# start graphql-engine with admin secret +psql -U gql_test -h localhost -c 'CREATE DATABASE "gql_test_with_admin_secret";' /build/_server_output/graphql-engine \ - --database-url postgres://gql_test@localhost:5432/gql_test_with_access serve --access-key "abcd" > /build/_cli_output/server.log 2>&1 & + --database-url postgres://gql_test@localhost:5432/gql_test_with_admin_secret serve --admin-secret "abcd" > /build/_cli_output/server.log 2>&1 & PID=$! wait_for_port 8080 diff --git a/.circleci/test-server-flags.sh b/.circleci/test-server-flags.sh index d980adfff91d2..e4d1d31f3f5b1 100755 --- a/.circleci/test-server-flags.sh +++ b/.circleci/test-server-flags.sh @@ -7,6 +7,29 @@ CIRCLECI_FOLDER="$PWD" SERVER_ROOT="$CIRCLECI_FOLDER/../server" +i=1 +echoInfo() { + echo -e "\033[36m$i. $*\033[0m" + i=$[i+1] +} + + +wait_for_port() { + local PORT=$1 + echo "waiting for $PORT" + for _ in $(seq 1 30); + do + nc -z localhost $PORT && echo "port $PORT is ready" && return + echo -n . + sleep 0.2 + done + echo "Failed waiting for $PORT" && exit 1 +} + +test_export_metadata_with_admin_secret() { + curl -f -d'{"type" : "export_metadata", "args" : {} }' localhost:8080/v1/query -H "X-Hasura-Admin-Secret: $1" > /dev/null +} + cd $SERVER_ROOT if [ -z "${HASURA_GRAPHQL_DATABASE_URL:-}" ] ; then @@ -29,43 +52,97 @@ OUTPUT_FOLDER=${OUTPUT_FOLDER:-"$CIRCLECI_FOLDER/test-server-flags-output"} mkdir -p "$OUTPUT_FOLDER" -########## Test --use-prepared-statements +########## Test --use-prepared-statements=false and flag --access-key (deprecated) + +key="HGE$RANDOM$RANDOM" + +stdbuf -o0 "$GRAPHQL_ENGINE" serve --use-prepared-statements=false --access-key="$key" > "$OUTPUT_FOLDER/graphql-engine.log" & PID=$! -"$GRAPHQL_ENGINE" serve --use-prepared-statements=false > "$OUTPUT_FOLDER/graphql-engine.log" & PID=$! +wait_for_port 8080 -sleep 1 +echoInfo "Test flag --access-key=XXXX" +grep -F '"admin_secret_set":true' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null +test_export_metadata_with_admin_secret "$key" + +echoInfo "Test flag --use-prepared-statements=false" +grep -F '"use_prepared_statements":false' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null kill $PID || true +wait $PID || true + + +###### Test --use-prepared-statements=true and --admin-secret +key="HGE$RANDOM$RANDOM" - grep --color -F '"use_prepared_statements":false' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null +stdbuf -o0 "$GRAPHQL_ENGINE" serve --use-prepared-statements=true --admin-secret="$key" > "$OUTPUT_FOLDER/graphql-engine.log" & PID=$! -"$GRAPHQL_ENGINE" serve --use-prepared-statements=true > "$OUTPUT_FOLDER/graphql-engine.log" & PID=$! +wait_for_port 8080 -sleep 1 +echoInfo "Test flag --admin-secret=XXXX" +grep -F '"admin_secret_set":true' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null || (cat "$OUTPUT_FOLDER/graphql-engine.log" && false) +test_export_metadata_with_admin_secret "$key" + +echoInfo "Test --use-prepared-statements=true" +grep -F '"use_prepared_statements":true' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null || (cat "$OUTPUT_FOLDER/graphql-engine.log" && false) kill $PID || true +wait $PID || true + - grep --color -F '"use_prepared_statements":true' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null +######### Test HASURA_GRAPHQL_USE_PREPARED_STATEMENTS=abcd -######### Test HASURA_GRAPHQL_USE_PREPARED_STATEMENTS environmental variable export HASURA_GRAPHQL_USE_PREPARED_STATEMENTS=abcd -"$GRAPHQL_ENGINE" serve > "$OUTPUT_FOLDER/graphql-engine.log" 2>&1 & PID=$! +timeout 3 stdbuf -o0 "$GRAPHQL_ENGINE" serve > "$OUTPUT_FOLDER/graphql-engine.log" 2>&1 & PID=$! -sleep 1 +wait $PID || true -kill $PID || true +echoInfo "Test HASURA_GRAPHQL_USE_PREPARED_STATEMENTS=abcd" +grep -F 'Not a valid boolean text' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null || (cat "$OUTPUT_FOLDER/graphql-engine.log" && false) -grep --color -F 'Not a valid boolean text' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null +######### Test HASURA_GRAPHQL_USE_PREPARED_STATEMENTS=false and deprecated EnvVar HASURA_GRAPHQL_ACCESS_KEY=XXXX +key="HGE$RANDOM$RANDOM" export HASURA_GRAPHQL_USE_PREPARED_STATEMENTS=false -"$GRAPHQL_ENGINE" serve > "$OUTPUT_FOLDER/graphql-engine.log" 2>&1 & PID=$! +export HASURA_GRAPHQL_ACCESS_KEY="$key" + +stdbuf -o0 "$GRAPHQL_ENGINE" serve > "$OUTPUT_FOLDER/graphql-engine.log" 2>&1 & PID=$! + +wait_for_port 8080 + +echoInfo "Test deprecated flag HASURA_GRAPHQL_ACCESS_KEY=XXXX" +grep -F '"admin_secret_set":true' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null || (cat "$OUTPUT_FOLDER/graphql-engine.log" && false) +test_export_metadata_with_admin_secret "$key" -sleep 1 + +echoInfo "Test HASURA_GRAPHQL_USE_PREPARED_STATEMENTS=false" +grep -F '"use_prepared_statements":false' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null || (cat "$OUTPUT_FOLDER/graphql-engine.log" && false) kill $PID || true +wait $PID || true + +unset HASURA_GRAPHQL_ACCESS_KEY + +unset HASURA_GRAPHQL_USE_PREPARED_STATEMENTS + +######### Test HASURA_GRAPHQL_ADMIN_SECRET=XXXX +key="HGE$RANDOM$RANDOM" + +export HASURA_GRAPHQL_ADMIN_SECRET="$key" + +stdbuf -o0 "$GRAPHQL_ENGINE" serve > "$OUTPUT_FOLDER/graphql-engine.log" 2>&1 & PID=$! + +wait_for_port 8080 + +echoInfo "Test deprecated flag HASURA_GRAPHQL_ADMIN_SECRET=XXXX" +grep -F '"admin_secret_set":true' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null || (cat "$OUTPUT_FOLDER/graphql-engine.log" && false) +test_export_metadata_with_admin_secret "$key" + +kill $PID || true +wait $PID || true + +unset $HASURA_GRAPHQL_ADMIN_SECRET -grep --color -F '"use_prepared_statements":false' "$OUTPUT_FOLDER/graphql-engine.log" >/dev/null diff --git a/.circleci/test-server.sh b/.circleci/test-server.sh index b74a60c27074d..c9ac99d437061 100755 --- a/.circleci/test-server.sh +++ b/.circleci/test-server.sh @@ -11,11 +11,11 @@ stop_services() { wait_for_port() { local PORT=$1 echo "waiting for $PORT" - for _ in $(seq 1 60); + for _ in $(seq 1 240); do nc -z localhost $PORT && echo "port $PORT is ready" && return echo -n . - sleep 1 + sleep 0.25 done echo "Failed waiting for $PORT" && exit 1 } @@ -80,7 +80,7 @@ CIRCLECI_FOLDER="${BASH_SOURCE[0]%/*}" cd $CIRCLECI_FOLDER CIRCLECI_FOLDER="$PWD" -if ! $CIRCLECI_FOLDER/test-server-flags.sh ; then +if ! $CIRCLECI_FOLDER/test-server-flags.sh ; then echo "Testing GraphQL server flags failed" exit 1 fi @@ -119,7 +119,7 @@ WH_PID="" trap stop_services ERR trap stop_services INT -echo -e "\n<########## TEST GRAPHQL-ENGINE WITHOUT ACCESS KEYS ###########################################>\n" +echo -e "\n<########## TEST GRAPHQL-ENGINE WITHOUT ADMIN SECRET ###########################################>\n" "$GRAPHQL_ENGINE" serve > "$OUTPUT_FOLDER/graphql-engine.log" & PID=$! @@ -132,22 +132,22 @@ sleep 4 mv graphql-engine.tix graphql-engine-combined.tix || true ########## -echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ACCESS KEY #####################################>\n" +echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ADMIN SECRET #####################################>\n" -export HASURA_GRAPHQL_ACCESS_KEY="HGE$RANDOM$RANDOM" +export HASURA_GRAPHQL_ADMIN_SECRET="HGE$RANDOM$RANDOM" "$GRAPHQL_ENGINE" serve >> "$OUTPUT_FOLDER/graphql-engine.log" & PID=$! wait_for_port 8080 -pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ACCESS_KEY" +pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ADMIN_SECRET" kill -INT $PID sleep 4 combine_hpc_reports ########## -echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ACCESS KEY AND JWT #####################################>\n" +echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ADMIN SECRET AND JWT #####################################>\n" init_jwt @@ -155,7 +155,7 @@ export HASURA_GRAPHQL_JWT_SECRET="$(jq -n --arg key "$(cat $OUTPUT_FOLDER/ssl/jw "$GRAPHQL_ENGINE" serve >> "$OUTPUT_FOLDER/graphql-engine.log" & PID=$! -pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ACCESS_KEY" --hge-jwt-key-file="$OUTPUT_FOLDER/ssl/jwt_private.key" +pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ADMIN_SECRET" --hge-jwt-key-file="$OUTPUT_FOLDER/ssl/jwt_private.key" kill -INT $PID sleep 4 @@ -172,7 +172,7 @@ fi if [ "$RUN_WEBHOOK_TESTS" == "true" ] ; then - echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ACCESS KEY & WEBHOOK (GET) #########################>\n" + echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ADMIN SECRET & WEBHOOK (GET) #########################>\n" export HASURA_GRAPHQL_AUTH_HOOK="https://localhost:9090/" init_ssl @@ -185,20 +185,20 @@ if [ "$RUN_WEBHOOK_TESTS" == "true" ] ; then wait_for_port 9090 - pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ACCESS_KEY" --hge-webhook="$HASURA_GRAPHQL_AUTH_HOOK" + pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ADMIN_SECRET" --hge-webhook="$HASURA_GRAPHQL_AUTH_HOOK" kill -INT $PID sleep 4 combine_hpc_reports - echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ACCESS KEY & WEBHOOK (POST) #########################>\n" + echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ADMIN SECRET & WEBHOOK (POST) #########################>\n" export HASURA_GRAPHQL_AUTH_HOOK_MODE="POST" "$GRAPHQL_ENGINE" serve >> "$OUTPUT_FOLDER/graphql-engine.log" 2>&1 & PID=$! wait_for_port 8080 - pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ACCESS_KEY" --hge-webhook="$HASURA_GRAPHQL_AUTH_HOOK" + pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ADMIN_SECRET" --hge-webhook="$HASURA_GRAPHQL_AUTH_HOOK" rm /etc/ssl/certs/webhook.crt update-ca-certificates @@ -207,27 +207,27 @@ if [ "$RUN_WEBHOOK_TESTS" == "true" ] ; then sleep 4 combine_hpc_reports - echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ACCESS KEY & HTTPS INSECURE WEBHOOK (GET) ########>\n" + echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ADMIN SECRET & HTTPS INSECURE WEBHOOK (GET) ########>\n" export HASURA_GRAPHQL_AUTH_HOOK_MODE="GET" "$GRAPHQL_ENGINE" serve >> "$OUTPUT_FOLDER/graphql-engine.log" 2>&1 & PID=$! wait_for_port 8080 - pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ACCESS_KEY" --hge-webhook="$HASURA_GRAPHQL_AUTH_HOOK" --test-webhook-insecure test_webhook_insecure.py + pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ADMIN_SECRET" --hge-webhook="$HASURA_GRAPHQL_AUTH_HOOK" --test-webhook-insecure test_webhook_insecure.py kill -INT $PID sleep 4 combine_hpc_reports - echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ACCESS KEY & HTTPS INSECURE WEBHOOK (POST) ########>\n" + echo -e "\n<########## TEST GRAPHQL-ENGINE WITH ADMIN_SECRET & HTTPS INSECURE WEBHOOK (POST) ########>\n" export HASURA_GRAPHQL_AUTH_HOOK_MODE="POST" "$GRAPHQL_ENGINE" serve >> "$OUTPUT_FOLDER/graphql-engine.log" 2>&1 & PID=$! wait_for_port 8080 - pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ACCESS_KEY" --hge-webhook="$HASURA_GRAPHQL_AUTH_HOOK" --test-webhook-insecure test_webhook_insecure.py + pytest -vv --hge-url="$HGE_URL" --pg-url="$HASURA_GRAPHQL_DATABASE_URL" --hge-key="$HASURA_GRAPHQL_ADMIN_SECRET" --hge-webhook="$HASURA_GRAPHQL_AUTH_HOOK" --test-webhook-insecure test_webhook_insecure.py kill -INT $PID sleep 4 From c148e26e390a71fe07145a6782f58f1cc986b5ce Mon Sep 17 00:00:00 2001 From: Nizar Malangadan Date: Fri, 1 Feb 2019 15:28:41 +0530 Subject: [PATCH 05/36] Change access key to admin secret in community folder --- .../auth-webhooks/python-flask/README.md | 4 ++-- .../aws-lambda/nodejs6/mutation/README.md | 2 +- .../aws-lambda/nodejs6/mutation/index.js | 4 ++-- .../aws-lambda/python/mutation/README.md | 2 +- .../aws-lambda/python/mutation/mutation.py | 4 ++-- .../azure-functions/nodejs/echo/README.md | 2 +- .../nodejs/mutation/HTTPTrigger/index.js | 4 ++-- .../azure-functions/nodejs/mutation/README.md | 2 +- community/sample-apps/firebase-jwt/README.md | 2 +- .../cypress/integration/validators/validators.js | 8 ++++---- .../react-apollo-todo/hasura/README.md | 2 +- .../src/components/Home/Home.js | 8 ++++---- .../react-apollo-todo/src/styles/App.css | 2 +- community/sample-apps/todo-auth0-jwt/README.md | 6 +++--- .../todo-auth0-jwt/hasura/config.yaml | 2 +- community/tools/firebase2graphql/README.md | 6 +++--- community/tools/firebase2graphql/src/command.js | 16 ++++++++-------- community/tools/firebase2graphql/test/test.sh | 10 +++++----- .../tools/firebase2graphql/test/verifyBlog.js | 4 ++-- .../tools/firebase2graphql/test/verifyChinook.js | 4 ++-- .../firebase2graphql/test/verifyChinookNested.js | 4 ++-- .../tools/firebase2graphql/test/verifyRE1.js | 4 ++-- .../src/components/ApiExplorer/ApiExplorer.scss | 2 +- .../src/components/ApiExplorer/ApiRequest.js | 8 ++++---- community/tools/json2graphql/README.md | 6 +++--- community/tools/json2graphql/src/command.js | 16 ++++++++-------- community/tools/json2graphql/test/test.sh | 4 ++-- community/tools/json2graphql/test/verify.js | 4 ++-- community/tools/ra-data-hasura/README.md | 2 +- 29 files changed, 72 insertions(+), 72 deletions(-) diff --git a/community/boilerplates/auth-webhooks/python-flask/README.md b/community/boilerplates/auth-webhooks/python-flask/README.md index 8fd23474762fe..3a420e1c9ec00 100644 --- a/community/boilerplates/auth-webhooks/python-flask/README.md +++ b/community/boilerplates/auth-webhooks/python-flask/README.md @@ -52,7 +52,7 @@ Webhook will be available at a url like `https://python-flask-lrnfqprjcc.now.sh` ## Configure Hasura -Configure Hasura with the webhook url. You will need to set an access key to +Configure Hasura with the webhook url. You will need to set an admin secret key to enable webhook. When running Hasura as a docker container, `localhost` will point to the @@ -72,7 +72,7 @@ locally or as a container (not on a public url), you'll need to: Set the following environment variables for Hasura: ``` -HASURA_GRAPHQL_ACCESS_KEY=mysecretaccesskey +HASURA_GRAPHQL_ADMIN_SECRET=myadminsecretkey HASURA_GRAPHQL_AUTH_WEBHOOK=http://localhost:5000/auth-webhook ``` diff --git a/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/README.md b/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/README.md index 6924aac6f9b7b..9efbb3b0c38b5 100644 --- a/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/README.md +++ b/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/README.md @@ -31,7 +31,7 @@ Create a lambda function in AWS. This will be our webhook. 7. Add an API to API gateway. 8. Upload the zip from previous step. The handler function of your lambda will be `index.handler`. 9. Add the following enviroment variables in your lambda config: - 1. `ACCESS_KEY`: this is the access key you configured when you setup HGE. + 1. `ADMIN_SECRET`: this is the admin secret key you configured when you setup HGE. 2. `HGE_ENDPOINT`: the URL on which you HGE instance is running. # Add the trigger in Hasura GraphQL diff --git a/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/index.js b/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/index.js index e92263e21a7a8..6f171df0c7e4a 100644 --- a/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/index.js +++ b/community/boilerplates/event-triggers/aws-lambda/nodejs6/mutation/index.js @@ -2,7 +2,7 @@ const fetch = require('node-fetch'); -const accessKey = process.env.ACCESS_KEY; +const adminSecret = process.env.ADMIN_SECRET; const hgeEndpoint = process.env.HGE_ENDPOINT; const query = ` @@ -34,7 +34,7 @@ exports.handler = (event, context, callback) => { fetch(hgeEndpoint + '/v1alpha1/graphql', { method: 'POST', body: JSON.stringify({query: query, variables: qv}), - headers: {'Content-Type': 'application/json', 'x-hasura-admin-secret': accessKey}, + headers: {'Content-Type': 'application/json', 'x-hasura-admin-secret': adminSecret}, }) .then(res => res.json()) .then(json => { diff --git a/community/boilerplates/event-triggers/aws-lambda/python/mutation/README.md b/community/boilerplates/event-triggers/aws-lambda/python/mutation/README.md index b2ed8042dd6b6..e6b5c4ea1f532 100644 --- a/community/boilerplates/event-triggers/aws-lambda/python/mutation/README.md +++ b/community/boilerplates/event-triggers/aws-lambda/python/mutation/README.md @@ -27,7 +27,7 @@ Create a lambda function in AWS. This will be our webhook. 5. Add an API to API gateway. 6. Add the code in `mutation.py`. The handler function of your lambda will be the `mutation.lambda_handler`. 7. Add the following enviroment variables in your lambda config: - 1. `ACCESS_KEY`: this is the access key you configured when you setup HGE. + 1. `ADMIN_SECRET`: this is the admin secret key you configured when you setup HGE. 2. `HGE_ENDPOINT`: the URL on which you HGE instance is running. # Add the trigger in Hasura GraphQL diff --git a/community/boilerplates/event-triggers/aws-lambda/python/mutation/mutation.py b/community/boilerplates/event-triggers/aws-lambda/python/mutation/mutation.py index 4a67796df1c62..7ad5fb58e9b25 100644 --- a/community/boilerplates/event-triggers/aws-lambda/python/mutation/mutation.py +++ b/community/boilerplates/event-triggers/aws-lambda/python/mutation/mutation.py @@ -2,13 +2,13 @@ import json from botocore.vendored import requests -ACCESS_KEY = os.environ['ACCESS_KEY'] +ADMIN_SECRET = os.environ['ADMIN_SECRET'] HGE_ENDPOINT = os.environ['HGE_ENDPOINT'] HGE_URL = HGE_ENDPOINT + '/v1alpha1/graphql' HEADERS = { 'Content-Type': 'application/json', - 'X-Hasura-Admin-Secret': ACCESS_KEY, + 'X-Hasura-Admin-Secret': ADMIN_SECRET, } query = """ diff --git a/community/boilerplates/event-triggers/azure-functions/nodejs/echo/README.md b/community/boilerplates/event-triggers/azure-functions/nodejs/echo/README.md index e9b17dc02b436..3a67d76afc560 100644 --- a/community/boilerplates/event-triggers/azure-functions/nodejs/echo/README.md +++ b/community/boilerplates/event-triggers/azure-functions/nodejs/echo/README.md @@ -20,7 +20,7 @@ func azure login func azure subscriptions set 'Free Trial' func azure functionapp publish 'myfunctionsapp' ``` -2. Set Environment variables `ACCESS_KEY` and `HGE_ENDPOINT` +2. Set Environment variables `ADMIN_SECRET` and `HGE_ENDPOINT` 3. Add a X-Function-Key header if Authorization level is enabled # Running locally diff --git a/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/HTTPTrigger/index.js b/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/HTTPTrigger/index.js index 8821c6ad3193a..84ced4e6c0a1b 100644 --- a/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/HTTPTrigger/index.js +++ b/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/HTTPTrigger/index.js @@ -1,5 +1,5 @@ const { query } = require('graphqurl'); -const ACCESS_KEY = process.env.ACCESS_KEY; +const ADMIN_SECRET = process.env.ADMIN_SECRET; const HGE_ENDPOINT = process.env.HGE_ENDPOINT; const MUTATION_NOTE_REVISION = ` @@ -28,7 +28,7 @@ module.exports = function (context, req) { endpoint: HGE_ENDPOINT + '/v1alpha1/graphql', variables: qv, headers: { - 'x-hasura-admin-secret': ACCESS_KEY + 'x-hasura-admin-secret': ADMIN_SECRET } }).then((response) => { context.log(response); diff --git a/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/README.md b/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/README.md index 64ca14ada32d7..392449d6d77a1 100644 --- a/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/README.md +++ b/community/boilerplates/event-triggers/azure-functions/nodejs/mutation/README.md @@ -32,7 +32,7 @@ func azure subscriptions set 'Free Trial' func azure functionapp publish 'myfunctionsapp' ``` -2. Set Environment variables `ACCESS_KEY` and `HGE_ENDPOINT` +2. Set Environment variables `ADMIN_SECRET` and `HGE_ENDPOINT` 3. Add a X-Function-Key header if Authorization level is enabled # Running locally diff --git a/community/sample-apps/firebase-jwt/README.md b/community/sample-apps/firebase-jwt/README.md index 7d3e669af033c..70b70b005518d 100644 --- a/community/sample-apps/firebase-jwt/README.md +++ b/community/sample-apps/firebase-jwt/README.md @@ -48,7 +48,7 @@ Deploy Hasura GraphQL Engine on Heroku: After deploying, add the following environment variables to configure JWT mode: ``` -HASURA_GRAPHQL_ACCESS_KEY : yoursecretaccesskey +HASURA_GRAPHQL_ADMIN_SECRET : youradminsecretkey ``` ``` diff --git a/community/sample-apps/react-apollo-todo/cypress/integration/validators/validators.js b/community/sample-apps/react-apollo-todo/cypress/integration/validators/validators.js index 1fe9df546e3ce..f9627834c076b 100644 --- a/community/sample-apps/react-apollo-todo/cypress/integration/validators/validators.js +++ b/community/sample-apps/react-apollo-todo/cypress/integration/validators/validators.js @@ -1,14 +1,14 @@ import { makeDataAPIOptions } from "../../helpers/dataHelpers"; // ***************** UTIL FUNCTIONS ************************** -let accessKey; +let adminSecret; let dataApiUrl; export const setMetaData = () => { cy.window().then(win => { - // accessKey = win.__env.accessKey; + // adminSecret = win.__env.adminSecret; // dataApiUrl = win.__env.dataApiUrl; - accessKey = "abcd"; + adminSecret = "abcd"; dataApiUrl = "https://hasura-todo-test.herokuapp.com"; }); }; @@ -27,7 +27,7 @@ export const validateTodo = (todoName, result, is_public) => { where: { user_id: userId, text: todoName, is_public: is_public } } }; - const requestOptions = makeDataAPIOptions(dataApiUrl, accessKey, reqBody); + const requestOptions = makeDataAPIOptions(dataApiUrl, adminSecret, reqBody); cy.request(requestOptions).then(response => { console.log(response); if (result.status === "success") { diff --git a/community/sample-apps/react-apollo-todo/hasura/README.md b/community/sample-apps/react-apollo-todo/hasura/README.md index 66e749aaa7cc3..88b45d78b14f5 100644 --- a/community/sample-apps/react-apollo-todo/hasura/README.md +++ b/community/sample-apps/react-apollo-todo/hasura/README.md @@ -1,6 +1,6 @@ ## Todo GraphQL Migrations -Update config.yaml to point to the right graphql-engine endpoint with/without access_key. +Update config.yaml to point to the right graphql-engine endpoint with/without admin_secret. Run the following commands: ``` diff --git a/community/sample-apps/react-apollo-todo/src/components/Home/Home.js b/community/sample-apps/react-apollo-todo/src/components/Home/Home.js index eeaadf3b36c1b..b17ddd87ce18b 100644 --- a/community/sample-apps/react-apollo-todo/src/components/Home/Home.js +++ b/community/sample-apps/react-apollo-todo/src/components/Home/Home.js @@ -111,15 +111,15 @@ class App extends Component { > Backend - - + + {/* - + */} diff --git a/community/sample-apps/react-apollo-todo/src/styles/App.css b/community/sample-apps/react-apollo-todo/src/styles/App.css index 60ad61e6ff578..2a6f7dece18ab 100644 --- a/community/sample-apps/react-apollo-todo/src/styles/App.css +++ b/community/sample-apps/react-apollo-todo/src/styles/App.css @@ -511,7 +511,7 @@ body { .footerWrapper .footerLinkPadd { margin-left: 20px; } -.footerWrapper .accessKey button { +.footerWrapper .adminSecret button { background-color: #a5b9cc; border: 0; padding-right: 0; diff --git a/community/sample-apps/todo-auth0-jwt/README.md b/community/sample-apps/todo-auth0-jwt/README.md index 431878e41185b..7a13e0aa26fd2 100644 --- a/community/sample-apps/todo-auth0-jwt/README.md +++ b/community/sample-apps/todo-auth0-jwt/README.md @@ -47,7 +47,7 @@ awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' yourauth0subdomain.pem After deploying, add the following environment variables to configure JWT mode: ``` -HASURA_GRAPHQL_ACCESS_KEY: yoursecretaccesskey +HASURA_GRAPHQL_ADMIN_SECRET: youradminsecretkey ``` ``` @@ -70,11 +70,11 @@ Setup values in `todo-app/src/constants.js`: 3. Auth0 application's client id ## Create the initial tables -1. Add your database URL and access key in `hasura/config.yaml` +1. Add your database URL and admin secret in `hasura/config.yaml` ```yaml endpoint: https:// -access_key: +admin_secret: ``` 2. Run `hasura migrate apply` to create the required tables and permissions for the todo app diff --git a/community/sample-apps/todo-auth0-jwt/hasura/config.yaml b/community/sample-apps/todo-auth0-jwt/hasura/config.yaml index 272a4eeffab49..2041748c25d5e 100644 --- a/community/sample-apps/todo-auth0-jwt/hasura/config.yaml +++ b/community/sample-apps/todo-auth0-jwt/hasura/config.yaml @@ -1,2 +1,2 @@ endpoint: https://hasura-todo-auth0-jwt.herokuapp.com -access_key: xxxxxxxxx +admin_secret: xxxxxxxxx diff --git a/community/tools/firebase2graphql/README.md b/community/tools/firebase2graphql/README.md index 635945394f917..3ea16c8120a3b 100644 --- a/community/tools/firebase2graphql/README.md +++ b/community/tools/firebase2graphql/README.md @@ -203,16 +203,16 @@ npm install -g firebase2graphql ## Usage -**Without access key** +**Without admin secret** ``` firebase2graphql https://hge.herokuapp.com -d ./path/to/db.json ``` -**With access key** +**With admin secret** ``` -firebase2graphql https://hge.herokuapp.com -k -d ./path/to/db.json +firebase2graphql https://hge.herokuapp.com -k -d ./path/to/db.json ``` ## Command diff --git a/community/tools/firebase2graphql/src/command.js b/community/tools/firebase2graphql/src/command.js index 97355088d4774..7d5ef769d335d 100644 --- a/community/tools/firebase2graphql/src/command.js +++ b/community/tools/firebase2graphql/src/command.js @@ -14,7 +14,7 @@ class Firebase2GraphQL extends Command { throw new CLIError('endpoint is required: \'firebase2graphql \''); } const {db, overwrite, normalize} = flags; - const key = flags['access-key']; + const key = flags['admin-secret']; if (!url) { throw new CLIError('endpoint is required: \'firebase2graphql -d ./db.js\''); @@ -59,7 +59,7 @@ class Firebase2GraphQL extends Command { }), } ); - return resp.status === 200 ? {error: false} : {error: true, message: 'invalid access key'}; + return resp.status === 200 ? {error: false} : {error: true, message: 'invalid admin secret'}; } catch (e) { return {error: true, message: 'invalid URL'}; } @@ -69,11 +69,11 @@ class Firebase2GraphQL extends Command { Firebase2GraphQL.description = `firebase2graphql: Import JSON data to Hasura GraphQL Engine # Examples: -# Import data from a Firebase JSON database to Hasura GraphQL Engine without access key +# Import data from a Firebase JSON database to Hasura GraphQL Engine without admin secret json2graphql https://hge.herokuapp.com --db=./path/to/db.json -# Import data from a Firebase JSON database to Hasura GraphQL Engine with access key -json2graphql https://hge.herokuapp.com --db=./path/to/db.json -k +# Import data from a Firebase JSON database to Hasura GraphQL Engine with admin secret +json2graphql https://hge.herokuapp.com --db=./path/to/db.json -k # Import data from a Firebase JSON database to Hasura GraphQL Engine while normalizing it json2graphql https://hge.herokuapp.com --db=./path/to/db.json -n @@ -88,10 +88,10 @@ Firebase2GraphQL.flags = { // add --help flag to show CLI version help: flags.help({char: 'h'}), - // Access key to Hasura GraphQL Engine - 'access-key': flags.string({ + // Admin secret to Hasura GraphQL Engine + 'admin-secret': flags.string({ char: 'k', - description: 'Access key to Hasura GraphQL Engine (X-Hasura-Admin-Secret)', + description: 'Admin secret to Hasura GraphQL Engine (X-Hasura-Admin-Secret)', }), db: flags.string({ diff --git a/community/tools/firebase2graphql/test/test.sh b/community/tools/firebase2graphql/test/test.sh index 3b06e36e01b76..fd19bee26b354 100755 --- a/community/tools/firebase2graphql/test/test.sh +++ b/community/tools/firebase2graphql/test/test.sh @@ -1,9 +1,9 @@ #!/bin/bash -if [ -z "$TEST_HGE_URL" ] && [ -z "$TEST_X_HASURA_ACCESS_KEY" ]; then +if [ -z "$TEST_HGE_URL" ] && [ -z "$TEST_X_HASURA_ADMIN_SECRET" ]; then echo "ERROR: Please run the test command with the environment variable TEST_HGE_URL" else - F2G_LOG=0 ../bin/run $TEST_HGE_URL --access-key=$TEST_X_HASURA_ACCESS_KEY --db=./data-sets/chinook.json --overwrite --normalize && node verifyChinook.js - F2G_LOG=0 ../bin/run $TEST_HGE_URL --access-key=$TEST_X_HASURA_ACCESS_KEY --db=./data-sets/blog.json --overwrite --normalize && node verifyBlog.js - F2G_LOG=0 ../bin/run $TEST_HGE_URL --access-key=$TEST_X_HASURA_ACCESS_KEY --db=./data-sets/chinook_nested.json --overwrite --normalize && node verifyChinookNested.js - F2G_LOG=0 ../bin/run $TEST_HGE_URL --access-key=$TEST_X_HASURA_ACCESS_KEY --db=./data-sets/readme-example-1.json --overwrite --normalize && node verifyRE1.js + F2G_LOG=0 ../bin/run $TEST_HGE_URL --admin-secret=$TEST_X_HASURA_ADMIN_SECRET --db=./data-sets/chinook.json --overwrite --normalize && node verifyChinook.js + F2G_LOG=0 ../bin/run $TEST_HGE_URL --admin-secret=$TEST_X_HASURA_ADMIN_SECRET --db=./data-sets/blog.json --overwrite --normalize && node verifyBlog.js + F2G_LOG=0 ../bin/run $TEST_HGE_URL --admin-secret=$TEST_X_HASURA_ADMIN_SECRET --db=./data-sets/chinook_nested.json --overwrite --normalize && node verifyChinookNested.js + F2G_LOG=0 ../bin/run $TEST_HGE_URL --admin-secret=$TEST_X_HASURA_ADMIN_SECRET --db=./data-sets/readme-example-1.json --overwrite --normalize && node verifyRE1.js fi diff --git a/community/tools/firebase2graphql/test/verifyBlog.js b/community/tools/firebase2graphql/test/verifyBlog.js index 351fbb2a7e968..a8c065d7c5c43 100644 --- a/community/tools/firebase2graphql/test/verifyBlog.js +++ b/community/tools/firebase2graphql/test/verifyBlog.js @@ -21,7 +21,7 @@ const verifyDataImport = () => { query({ query: complexQuery, endpoint: `${process.env.TEST_HGE_URL}/v1alpha1/graphql`, - headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ADMIN_SECRET}, }).then(response => { if ( response.data.f2g_test_posts[0].title === 'My first post' && @@ -36,7 +36,7 @@ const verifyDataImport = () => { `${process.env.TEST_HGE_URL}/v1/query`, { method: 'POST', - headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ADMIN_SECRET}, body: JSON.stringify({ type: 'run_sql', args: { diff --git a/community/tools/firebase2graphql/test/verifyChinook.js b/community/tools/firebase2graphql/test/verifyChinook.js index 3e25c604c7f04..8ddac066d9aeb 100644 --- a/community/tools/firebase2graphql/test/verifyChinook.js +++ b/community/tools/firebase2graphql/test/verifyChinook.js @@ -26,7 +26,7 @@ const verifyDataImport = () => { query({ query: complexQuery, endpoint: `${process.env.TEST_HGE_URL}/v1alpha1/graphql`, - headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ADMIN_SECRET}, }).then(response => { if ( response.data.f2g_test_Album[0].f2g_test_Album_artist.ArtistId === 1 && @@ -40,7 +40,7 @@ const verifyDataImport = () => { `${process.env.TEST_HGE_URL}/v1/query`, { method: 'POST', - headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ADMIN_SECRET}, body: JSON.stringify({ type: 'run_sql', args: { diff --git a/community/tools/firebase2graphql/test/verifyChinookNested.js b/community/tools/firebase2graphql/test/verifyChinookNested.js index 197292ded6beb..0df3738c57e8e 100644 --- a/community/tools/firebase2graphql/test/verifyChinookNested.js +++ b/community/tools/firebase2graphql/test/verifyChinookNested.js @@ -29,7 +29,7 @@ const verifyDataImport = () => { query({ query: complexQuery, endpoint: `${process.env.TEST_HGE_URL}/v1alpha1/graphql`, - headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ADMIN_SECRET}, }).then(response => { if ( response.data.f2gt_Album[0]._id === '1' && @@ -46,7 +46,7 @@ const verifyDataImport = () => { `${process.env.TEST_HGE_URL}/v1/query`, { method: 'POST', - headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ADMIN_SECRET}, body: JSON.stringify({ type: 'run_sql', args: { diff --git a/community/tools/firebase2graphql/test/verifyRE1.js b/community/tools/firebase2graphql/test/verifyRE1.js index 2415624d0b472..951ba1d6698da 100644 --- a/community/tools/firebase2graphql/test/verifyRE1.js +++ b/community/tools/firebase2graphql/test/verifyRE1.js @@ -22,7 +22,7 @@ const verifyDataImport = () => { query({ query: complexQuery, endpoint: `${process.env.TEST_HGE_URL}/v1alpha1/graphql`, - headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ADMIN_SECRET}, }).then(response => { if ( response.data && @@ -37,7 +37,7 @@ const verifyDataImport = () => { `${process.env.TEST_HGE_URL}/v1/query`, { method: 'POST', - headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ACCESS_KEY}, + headers: {'x-hasura-admin-secret': process.env.TEST_X_HASURA_ADMIN_SECRET}, body: JSON.stringify({ type: 'run_sql', args: { diff --git a/community/tools/graphiql-online/src/components/ApiExplorer/ApiExplorer.scss b/community/tools/graphiql-online/src/components/ApiExplorer/ApiExplorer.scss index d4caed9c5609f..0eaa5d6b6be05 100644 --- a/community/tools/graphiql-online/src/components/ApiExplorer/ApiExplorer.scss +++ b/community/tools/graphiql-online/src/components/ApiExplorer/ApiExplorer.scss @@ -267,7 +267,7 @@ float: right; display: inline-block; } - .showAccessKey{ + .showAdminSecret{ cursor: pointer; padding-top: 8px; padding-right: 8px; diff --git a/community/tools/graphiql-online/src/components/ApiExplorer/ApiRequest.js b/community/tools/graphiql-online/src/components/ApiExplorer/ApiRequest.js index 22b9f15c7a44b..6fc21492d967b 100644 --- a/community/tools/graphiql-online/src/components/ApiExplorer/ApiRequest.js +++ b/community/tools/graphiql-online/src/components/ApiExplorer/ApiRequest.js @@ -20,7 +20,7 @@ class ApiRequest extends Component { constructor(props) { super(props); this.state = {}; - this.state.accessKeyVisible = false; + this.state.adminSecretVisible = false; this.state.bodyAllowedMethods = ['POST']; this.state.tabIndex = 0; } @@ -195,7 +195,7 @@ class ApiRequest extends Component { data-test={`header-value-${i}`} type={ header.key === 'X-Hasura-Admin-Secret' && - !this.state.accessKeyVisible + !this.state.adminSecretVisible ? 'password' : 'text' } @@ -205,10 +205,10 @@ class ApiRequest extends Component { {header.key === 'X-Hasura-Admin-Secret' ? (