Skip to content
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

fix(binding-opcua;binding-coap) fix some test issues and resource leaks #519

Merged
merged 7 commits into from
Oct 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion packages/binding-coap/src/coap-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ export default class CoapClient implements ProtocolClient {
}

public stop(): boolean {
// FIXME coap does not provide proper API to close Agent
this.agent.close();
return true;
}

Expand Down
47 changes: 18 additions & 29 deletions packages/binding-coap/test/coap-client-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,40 +86,29 @@ class CoapClientTest {
await coapServer.stop();
}

@test "should re-use port"(done: Done) {
@test async "should re-use port"() {
const coapServer = new CoapServer(56834, "localhost");
coapServer.start(null).then(() => {
const coapClient = new CoapClient(coapServer);
coapClient
.readResource({ href: "coap://localhost:56834/" })
.then((res) => {
return coapServer.stop();
})
.then(() => {
done();
});
await coapServer.start(null);
const coapClient = new CoapClient(coapServer);
const res = await coapClient.readResource({
href: "coap://localhost:56834/",
});
false && console.log(res);
await coapServer.stop();
}

@test(timeout(5000)) "subscribe test"(done: Done) {
@test(timeout(5000)) async "subscribe test"() {
const coapServer = new CoapServer(56834, "localhost");
coapServer.start(null).then(() => {
const coapClient = new CoapClient(coapServer);

const form: CoapForm = {
href: "coap://127.0.0.1:56834",
"cov:methodName": "GET",
};

coapClient
.subscribeResource(form, (value) => {})
.then((subscription) => {
subscription.unsubscribe();
return coapServer.stop();
})
.then(() => {
done();
});
await coapServer.start(null);
const coapClient = new CoapClient(coapServer);
const form: CoapForm = {
href: "coap://127.0.0.1:56834",
"cov:methodName": "GET",
};
const subscription = await coapClient.subscribeResource(form, (value) => {
/** */
});
subscription.unsubscribe();
await coapServer.stop();
}
}
8 changes: 4 additions & 4 deletions packages/binding-http/src/http-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ export default class HttpClient implements ProtocolClient {
return { type: result.headers.get("content-type"), body: result.body };
}

public async writeResource(form: HttpForm, content: Content): Promise<any> {
public async writeResource(form: HttpForm, content: Content): Promise<void> {
const request = await this.generateFetchRequest(form, "PUT", {
headers: [["content-type", content.type]],
body: content.body,
Expand Down Expand Up @@ -150,11 +150,11 @@ export default class HttpClient implements ProtocolClient {
): Promise<Subscription> {
return new Promise<Subscription>((resolve, reject) => {
let internalSubscription: InternalSubscription;
if (form.subprotocol == undefined || form.subprotocol == "longpoll") {
//longpoll or subprotocol is not defined default is longpoll
if (form.subprotocol === undefined || form.subprotocol === "longpoll") {
// longpoll or subprotocol is not defined default is longpoll
internalSubscription = new LongPollingSubscription(form, this);
} else if (form.subprotocol == "sse") {
//server sent events
// server sent events
internalSubscription = new SSESubscription(form);
}

Expand Down
82 changes: 52 additions & 30 deletions packages/binding-http/test/http-client-basic-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import * as express from "express";
import { HttpClient } from "../src/http";
import * as https from "https";
import { BasicSecurityScheme } from "@node-wot/td-tools";
import { ProtocolHelpers } from "@node-wot/core";
import * as chai from "chai";
import * as chaiAsPromised from "chai-as-promised";
import { promisify } from "util";
Expand All @@ -26,36 +27,39 @@ const fs = require("fs");
chai.should();
chai.use(chaiAsPromised);

@suite("HTTP auth basic client implementation")
class HttpClientBasicTest {
private client: HttpClient;
function mockService(req: any, res: any, next: any) {
// -----------------------------------------------------------------------
// authentication middleware

private static server: https.Server;
static before() {
const app = express();
app.use((req: any, res: any, next: any) => {
// -----------------------------------------------------------------------
// authentication middleware
const auth = { login: "admin", password: "password" }; // change this

const auth = { login: "admin", password: "password" }; // change this
// parse login and password from headers
const b64auth = (req.headers.authorization || "").split(" ")[1] || "";
const [login, password] = Buffer.from(b64auth, "base64").toString().split(":");

// parse login and password from headers
const b64auth = (req.headers.authorization || "").split(" ")[1] || "";
const [login, password] = Buffer.from(b64auth, "base64").toString().split(":");
// Verify login and password are set and correct
if (login && password && login === auth.login && password === auth.password) {
// Access granted...
res.write("Access granted");
res.end();
return;
}

// Verify login and password are set and correct
if (login && password && login === auth.login && password === auth.password) {
// Access granted...
res.end();
return;
}
// Access denied...
res.set("WWW-Authenticate", 'Basic realm="401"'); // change this
res.status(401).send("Authentication required."); // custom message

// Access denied...
res.set("WWW-Authenticate", 'Basic realm="401"'); // change this
res.status(401).send("Authentication required."); // custom message
// -----------------------------------------------------------------------
}
@suite("HTTP auth basic client implementation")
class HttpClientBasicTest {
private client: HttpClient;

// -----------------------------------------------------------------------
});
private static server: https.Server;

static async before(): Promise<void> {
const app = express();
app.use(mockService);

return new Promise<void>((resolve) => {
HttpClientBasicTest.server = https
Expand All @@ -70,33 +74,51 @@ class HttpClientBasicTest {
});
}

static async after(): Promise<void> {
return new Promise<void>((resolve) => {
HttpClientBasicTest.server.close(() => resolve());
});
}

erossignon marked this conversation as resolved.
Show resolved Hide resolved
before() {
this.client = new HttpClient({ allowSelfSigned: true }, true);
}

static after() {
return promisify(HttpClientBasicTest.server.close.bind(HttpClientBasicTest.server))();
after() {
this.client.stop();
}

@test async "should authorize client with basic"() {
@test async "should authorize client with basic"(): Promise<void> {
const scheme: BasicSecurityScheme = {
scheme: "basic",
in: "header",
};

this.client.setSecurity([scheme], { username: "admin", password: "password" });
return this.client.readResource({
const resource = await this.client.readResource({
href: "https://localhost:3001",
});
const body = await ProtocolHelpers.readStreamFully(resource.body);
body.toString("ascii").should.eql("Access granted");
}

@test async "should fail to authorize client with basic"() {
@test async "should fail to authorize client with basic"(): Promise<void> {
const scheme: BasicSecurityScheme = {
scheme: "basic",
in: "header",
};

this.client.setSecurity([scheme], { username: "other", password: "other" });
return this.client.readResource({ href: "https://localhost:3001" }).should.be.rejected;

const error = await new Promise<Error>((resolve, reject) => {
this.client
.readResource({ href: "https://localhost:3001" })
.then(() => reject("Expecting readResource to fail"))
.catch((err: unknown) => {
resolve(err as Error);
});
});

error.message.should.eql("Client error: Unauthorized");
erossignon marked this conversation as resolved.
Show resolved Hide resolved
}
}
24 changes: 17 additions & 7 deletions packages/binding-http/test/http-client-oauth-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,9 @@ import * as express from "express";
import { HttpClient } from "../src/http";
import { OAuth2SecurityScheme } from "@node-wot/td-tools";

import Memory from "./memory-model";
import InMemoryModel from "./memory-model";
import { promisify } from "util";
import { ProtocolHelpers } from "@node-wot/core";
const OAuthServer = require("express-oauth-server");
const bodyParser = require("body-parser");

Expand All @@ -31,9 +32,10 @@ class HttpClientOAuthTest {
private client: HttpClient;
static model: any;
static server: https.Server;
static before() {

static before(): Promise<void> {
const app: any = express();
HttpClientOAuthTest.model = new Memory();
HttpClientOAuthTest.model = new InMemoryModel();

app.oauth = new OAuthServer({
model: HttpClientOAuthTest.model,
Expand Down Expand Up @@ -82,9 +84,11 @@ class HttpClientOAuthTest {
scopes: ["test"],
};
this.client.setSecurity([scheme], { clientId: "thom", clientSecret: "nightworld" });
return this.client.readResource({
const resource = await this.client.readResource({
href: "https://localhost:3000/resource",
});
const body = await ProtocolHelpers.readStreamFully(resource.body);
body.toString("ascii").should.eql("Ok!");
}

@test async "should authorize client with resource owener flow"() {
Expand All @@ -100,9 +104,11 @@ class HttpClientOAuthTest {
username: "thomseddon",
password: "nightworld",
});
return this.client.readResource({
const resource = await this.client.readResource({
href: "https://localhost:3000/resource",
});
const body = await ProtocolHelpers.readStreamFully(resource.body);
body.toString("ascii").should.eql("Ok!");
}

@test async "should refresh token"() {
Expand All @@ -115,9 +121,11 @@ class HttpClientOAuthTest {
HttpClientOAuthTest.model.expireAllTokens();
await this.client.setSecurity([scheme], { clientId: "thom", clientSecret: "nightworld" });
await sleep(1000);
return this.client.readResource({
const resource = await this.client.readResource({
href: "https://localhost:3000/resource",
});
const body = await ProtocolHelpers.readStreamFully(resource.body);
body.toString("ascii").should.eql("Ok!");
}

@test async "should refresh token with resource owener flow"() {
Expand All @@ -136,9 +144,11 @@ class HttpClientOAuthTest {
password: "nightworld",
});
await sleep(1000);
return this.client.readResource({
const resource = await this.client.readResource({
href: "https://localhost:3000/resource",
});
const body = await ProtocolHelpers.readStreamFully(resource.body);
body.toString("ascii").should.eql("Ok!");
}
}

Expand Down
Loading