Skip to content

Add acceptance test to neo4j-deno-driver and implement deno specific channel #900

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 35 commits into from
Oct 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
6763bc8
Add Testkit support to DenoJS
bigmontz Mar 14, 2022
0dff616
Add `deno-channel` for non-encrypted connection and fix deno-backend
bigmontz Sep 23, 2022
9c72390
Add support to TLS
bigmontz Sep 26, 2022
83a77a0
Ajust testkit scripts
bigmontz Sep 26, 2022
4d89c83
Adjust neo4j import and tls import
bigmontz Sep 26, 2022
286d208
Revert browser channel
bigmontz Sep 26, 2022
65d2691
Fix missing neo4j definition
bigmontz Sep 27, 2022
6ea7a14
Move Deno implemenation for its own folder
bigmontz Sep 27, 2022
f2e9436
Refactory DenoJS implementation
bigmontz Sep 27, 2022
2de0f8d
deno fmt
bigmontz Sep 27, 2022
8385ef6
Revert changes in the log config
bigmontz Sep 27, 2022
04894e6
Adjust linter issues
bigmontz Sep 27, 2022
2af4009
Improve logs in the backend
bigmontz Sep 28, 2022
00fbae2
Add dependencies
bigmontz Sep 28, 2022
8f5022e
Prevent write in a broken socket
bigmontz Sep 28, 2022
f541c0b
Capture and log unhandledrejection
bigmontz Sep 28, 2022
577a375
Move dependencies to deps and fix text encode.
bigmontz Sep 28, 2022
9edf9ec
Move deno-channel implemantation to bolt-connection
bigmontz Sep 28, 2022
a7beadc
Fix deps
bigmontz Sep 28, 2022
1cbdeca
Disable eslint for Deno files
bigmontz Sep 28, 2022
ccdc4af
Add copyright notice to version.ts
bigmontz Sep 28, 2022
befa3c8
Configuring linter and formatter fr the deno backend files
bigmontz Sep 29, 2022
6d56f08
Fix `writeError` function
bigmontz Sep 29, 2022
ed8f1c4
Skip test which timesout
bigmontz Sep 29, 2022
a79e61f
Fix listener
bigmontz Sep 29, 2022
b6e659a
Handling connection write errors
bigmontz Sep 29, 2022
468dc5b
Skip timedout test
bigmontz Sep 29, 2022
46f95b4
fix connection timeout
bigmontz Sep 29, 2022
d950957
Apply suggestions from code review
bigmontz Oct 3, 2022
bfb81bc
Move binder creation and log env-variable read to the controller.
bigmontz Oct 3, 2022
e31cddd
Waiting for connection be closed during timeout
bigmontz Oct 3, 2022
3d68810
docs improvement
bigmontz Oct 3, 2022
6852df6
Apply suggestions from code review
bigmontz Oct 3, 2022
b47d05e
Fix CypherNativeBinder import
bigmontz Oct 3, 2022
d9c32e1
Install specific Deno version
bigmontz Oct 4, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@
"packages/neo4j-driver/**/*.ts": [
"npm run ts-standard::neo4j-driver",
"git add"
],
"packages/testkit-backend/deno/**/*.{ts,js}": [
"deno fmt",
"deno lint",
"git add"
]
},
"scripts": {
Expand All @@ -46,6 +51,7 @@
"start-neo4j": "lerna run start-neo4j --scope neo4j-driver",
"stop-neo4j": "lerna run stop-neo4j --scope neo4j-driver",
"start-testkit-backend": "lerna run start --scope testkit-backend --stream",
"start-testkit-backend::deno": "lerna run start::deno --scope testkit-backend --stream",
"lerna": "lerna",
"prepare": "husky install",
"lint-staged": "lint-staged",
Expand Down
336 changes: 336 additions & 0 deletions packages/bolt-connection/src/channel/deno/deno-channel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,336 @@
/**
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable */
import ChannelBuffer from '../channel-buf'
import { newError, internal } from 'neo4j-driver-core'
import { iterateReader } from 'https://deno.land/std@0.157.0/streams/conversion.ts';

const {
util: { ENCRYPTION_OFF, ENCRYPTION_ON }
} = internal

let _CONNECTION_IDGEN = 0
/**
* Create a new DenoChannel to be used in Deno runtime.
* @access private
*/
export default class DenoChannel {
/**
* Create new instance
* @param {ChannelConfig} config - configuration for this channel.
*/
constructor (
config,
connect = _connect
) {
this.id = _CONNECTION_IDGEN++
this._conn = null
this._pending = []
this._open = true
this._error = null
this._handleConnectionError = this._handleConnectionError.bind(this)
this._handleConnectionTerminated = this._handleConnectionTerminated.bind(
this
)
this._connectionErrorCode = config.connectionErrorCode
this._receiveTimeout = null
this._receiveTimeoutStarted = false
this._receiveTimeoutId = null

this._config = config

connect(config)
.then(conn => {
this._clearConnectionTimeout()
if (!this._open) {
return conn.close()
}
this._conn = conn

setupReader(this)
.catch(this._handleConnectionError)

const pending = this._pending
this._pending = null
for (let i = 0; i < pending.length; i++) {
this.write(pending[i])
}
})
.catch(this._handleConnectionError)

this._connectionTimeoutFired = false
this._connectionTimeoutId = this._setupConnectionTimeout()
}

_setupConnectionTimeout () {
const timeout = this._config.connectionTimeout
if (timeout) {
return setTimeout(() => {
this._connectionTimeoutFired = true
this.close()
.then(e => this._handleConnectionError(newError(`Connection timeout after ${timeout} ms`)))
.catch(this._handleConnectionError)
}, timeout)
}
return null
}

/**
* Remove active connection timeout, if any.
* @private
*/
_clearConnectionTimeout () {
const timeoutId = this._connectionTimeoutId
if (timeoutId !== null) {
this._connectionTimeoutFired = false
this._connectionTimeoutId = null
clearTimeout(timeoutId)
}
}

_handleConnectionError (err) {
let msg =
'Failed to connect to server. ' +
'Please ensure that your database is listening on the correct host and port ' +
'and that you have compatible encryption settings both on Neo4j server and driver. ' +
'Note that the default encryption setting has changed in Neo4j 4.0.'
if (err.message) msg += ' Caused by: ' + err.message
this._error = newError(msg, this._connectionErrorCode)
if (this.onerror) {
this.onerror(this._error)
}
}

_handleConnectionTerminated () {
this._open = false
this._error = newError(
'Connection was closed by server',
this._connectionErrorCode
)
if (this.onerror) {
this.onerror(this._error)
}
}


/**
* Write the passed in buffer to connection
* @param {ChannelBuffer} buffer - Buffer to write
*/
write (buffer) {
if (this._pending !== null) {
this._pending.push(buffer)
} else if (buffer instanceof ChannelBuffer) {
this._conn.write(buffer._buffer).catch(this._handleConnectionError)
} else {
throw newError("Don't know how to send buffer: " + buffer)
}
}

/**
* Close the connection
* @returns {Promise} A promise that will be resolved after channel is closed
*/
async close () {
if (this._open) {
this._open = false
if (this._conn != null) {
await this._conn.close()
}
}
}

/**
* Setup the receive timeout for the channel.
*
* Not supported for the browser channel.
*
* @param {number} receiveTimeout The amount of time the channel will keep without receive any data before timeout (ms)
* @returns {void}
*/
setupReceiveTimeout (receiveTimeout) {
this._receiveTimeout = receiveTimeout
}

/**
* Stops the receive timeout for the channel.
*/
stopReceiveTimeout () {
if (this._receiveTimeout !== null && this._receiveTimeoutStarted) {
this._receiveTimeoutStarted = false
if (this._receiveTimeoutId != null) {
clearTimeout(this._receiveTimeoutId)
}
this._receiveTimeoutId = null
}
}

/**
* Start the receive timeout for the channel.
*/
startReceiveTimeout () {
if (this._receiveTimeout !== null && !this._receiveTimeoutStarted) {
this._receiveTimeoutStarted = true
this._resetTimeout()
}
}

_resetTimeout () {
if (!this._receiveTimeoutStarted) {
return
}

if (this._receiveTimeoutId !== null) {
clearTimeout(this._receiveTimeoutId)
}

this._receiveTimeoutId = setTimeout(() => {
this._receiveTimeoutId = null
this.stopReceiveTimeout()
this._error = newError(
`Connection lost. Server didn't respond in ${this._receiveTimeout}ms`,
this._config.connectionErrorCode
)

this.close()
.catch(() => {
// ignoring error during the close timeout connections since they
// not valid
})
.finally(() => {
if (this.onerror) {
this.onerror(this._error)
}
})
}, this._receiveTimeout)
}
}

const TrustStrategy = {
TRUST_CUSTOM_CA_SIGNED_CERTIFICATES: async function (config) {
if (
!config.trustedCertificates ||
config.trustedCertificates.length === 0
) {
throw newError(
'You are using TRUST_CUSTOM_CA_SIGNED_CERTIFICATES as the method ' +
'to verify trust for encrypted connections, but have not configured any ' +
'trustedCertificates. You must specify the path to at least one trusted ' +
'X.509 certificate for this to work. Two other alternatives is to use ' +
'TRUST_ALL_CERTIFICATES or to disable encryption by setting encrypted="' +
ENCRYPTION_OFF +
'"' +
'in your driver configuration.'
);
}

const caCerts = await Promise.all(
config.trustedCertificates.map(f => Deno.readTextFile(f))
)

return Deno.connectTls({
hostname: config.address.resolvedHost(),
port: config.address.port(),
caCerts
})
},
TRUST_SYSTEM_CA_SIGNED_CERTIFICATES: function (config) {
return Deno.connectTls({
hostname: config.address.resolvedHost(),
port: config.address.port()
})
},
TRUST_ALL_CERTIFICATES: function (config) {
throw newError(
`"${config.trust}" is not available in DenoJS. ` +
'For trust in any certificates, you should use the DenoJS flag ' +
'"--unsafely-ignore-certificate-errors". '+
'See, https://deno.com/blog/v1.13#disable-tls-verification'
)
}
}

async function _connect (config) {
if (!isEncrypted(config)) {
return Deno.connect({
hostname: config.address.resolvedHost(),
port: config.address.port()
})
}
const trustStrategyName = getTrustStrategyName(config)
const trustStrategy = TrustStrategy[trustStrategyName]

if (trustStrategy != null) {
return await trustStrategy(config)
}

throw newError(
'Unknown trust strategy: ' +
config.trust +
'. Please use either ' +
"trust:'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' configuration " +
'or the System CA. ' +
'Alternatively, you can disable encryption by setting ' +
'`encrypted:"' +
ENCRYPTION_OFF +
'"`. There is no mechanism to use encryption without trust verification, ' +
'because this incurs the overhead of encryption without improving security. If ' +
'the driver does not verify that the peer it is connected to is really Neo4j, it ' +
'is very easy for an attacker to bypass the encryption by pretending to be Neo4j.'

)
}

function isEncrypted (config) {
const encryptionNotConfigured =
config.encrypted == null || config.encrypted === undefined
if (encryptionNotConfigured) {
// default to using encryption if trust-all-certificates is available
return false
}
return config.encrypted === true || config.encrypted === ENCRYPTION_ON
}

function getTrustStrategyName (config) {
if (config.trust) {
return config.trust
}
return 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'
}

async function setupReader (channel) {
try {
for await (const message of iterateReader(channel._conn)) {
channel._resetTimeout()

if (!channel._open) {
return
}
if (channel.onmessage) {
channel.onmessage(new ChannelBuffer(message))
}
}
channel._handleConnectionTerminated()
} catch (error) {
if (channel._open) {
channel._handleConnectionError(error)
}
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { internal } from 'neo4j-driver-core'

const {
resolver: { BaseHostNameResolver }
} = internal

export default class DenoHostNameResolver extends BaseHostNameResolver {
resolve (address) {
return this._resolveToItself(address)
}
}
Loading