Improve authentication handling (#908)

This commit is contained in:
Tomas Della Vedova
2019-07-18 10:33:11 +02:00
committed by GitHub
parent 24e674469e
commit 0ebbd71e9a
12 changed files with 602 additions and 142 deletions

View File

@ -34,8 +34,7 @@ class Connection {
this.url = opts.url
this.ssl = opts.ssl || null
this.id = opts.id || stripAuth(opts.url.href)
this.headers = opts.headers || null
this.auth = opts.auth || { username: null, password: null }
this.headers = prepareHeaders(opts.headers, opts.auth)
this.deadCount = 0
this.resurrectTimeout = 0
@ -181,7 +180,6 @@ class Connection {
buildRequestObject (params) {
const url = this.url
const { username, password } = this.auth
const request = {
protocol: url.protocol,
hostname: url.hostname[0] === '['
@ -196,9 +194,6 @@ class Connection {
// https://github.com/elastic/elasticsearch-js/issues/843
port: url.port !== '' ? url.port : undefined,
headers: this.headers,
auth: username != null && password != null
? `${username}:${password}`
: undefined,
agent: this.agent
}
@ -230,10 +225,15 @@ class Connection {
// the logs very hard to read. The user can still
// access them with `instance.agent` and `instance.ssl`.
[inspect.custom] (depth, options) {
const {
authorization,
...headers
} = this.headers
return {
url: stripAuth(this.url.toString()),
id: this.id,
headers: this.headers,
headers,
deadCount: this.deadCount,
resurrectTimeout: this.resurrectTimeout,
_openRequests: this._openRequests,
@ -243,10 +243,15 @@ class Connection {
}
toJSON () {
const {
authorization,
...headers
} = this.headers
return {
url: stripAuth(this.url.toString()),
id: this.id,
headers: this.headers,
headers,
deadCount: this.deadCount,
resurrectTimeout: this.resurrectTimeout,
_openRequests: this._openRequests,
@ -302,4 +307,21 @@ function resolve (host, path) {
}
}
function prepareHeaders (headers = {}, auth) {
if (auth != null && headers.authorization == null) {
if (auth.username && auth.password) {
headers.authorization = 'Basic ' + Buffer.from(`${auth.username}:${auth.password}`).toString('base64')
}
if (auth.apiKey) {
if (typeof auth.apiKey === 'object') {
headers.authorization = 'ApiKey ' + Buffer.from(`${auth.apiKey.id}:${auth.apiKey.api_key}`).toString('base64')
} else {
headers.authorization = `ApiKey ${auth.apiKey}`
}
}
}
return headers
}
module.exports = Connection