Skip to content

Commit

Permalink
[FIX] while runtime authorization errors are notified, errors related…
Browse files Browse the repository at this point in the history
… to connection lastError were not properly reported by the closed() promise - this typically resulted in a "Connection Refused" rather than the actual reason. (#294)

FIX #268
  • Loading branch information
aricart committed May 12, 2022
1 parent 8ac0687 commit 9fbbb89
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
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();
});

0 comments on commit 9fbbb89

Please sign in to comment.