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

conn.closed() resolved error not always the actual reason for the error #294

Merged
merged 1 commit into from
May 12, 2022
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
10 changes: 8 additions & 2 deletions nats-base-client/protocol.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2018-2021 The NATS Authors
* Copyright 2018-2022 The NATS Authors
* 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
Expand Down Expand Up @@ -339,7 +339,13 @@ export class ProtocolHandler implements Dispatcher<ParserEvent> {
let maxWait = wait;
const srv = this.selectServer();
if (!srv || this.abortReconnect) {
throw lastError || NatsError.errorForCode(ErrorCode.ConnectionRefused);
if (lastError) {
throw lastError;
} else if (this.lastError) {
throw this.lastError;
} else {
throw NatsError.errorForCode(ErrorCode.ConnectionRefused);
}
}
const now = Date.now();
if (srv.lastConnect === 0 || srv.lastConnect + wait <= now) {
Expand Down
37 changes: 37 additions & 0 deletions tests/auth_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import {
encodeOperator,
encodeUser,
} from "https://raw.githubusercontent.com/nats-io/jwt.js/main/src/jwt.ts";
import { UserPass } from "https://raw.githubusercontent.com/nats-io/nats.deno/main/nats-base-client/authenticator.ts";

const conf = {
authorization: {
Expand Down Expand Up @@ -582,3 +583,39 @@ Deno.test("auth - expiration is notified", async () => {
assertErrorCode(err!, ErrorCode.AuthenticationExpired);
await cleanup(ns);
});

Deno.test("auth - bad auth is notified", async () => {
let ns = await NatsServer.start(conf);

let count = 0;

// authenticator that works once
const authenticator = (): UserPass => {
const pass = count === 0 ? "foobar" : "bad";
count++;
return { user: "derek", pass };
};

const nc = await connect(
{ port: ns.port, authenticator, debug: true },
);
let badAuths = 0;
(async () => {
for await (const s of nc.status()) {
if (
s.type === Events.Error && s.data === ErrorCode.AuthorizationViolation
) {
badAuths++;
}
}
})().then();

await ns.stop();
ns = await ns.restart();

const err = await nc.closed();
assert(badAuths > 1);
assertErrorCode(err!, ErrorCode.AuthorizationViolation);

await ns.stop();
});