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

[INTERNAL] mechanism to retrieve connection info #684

Merged
merged 1 commit into from
Apr 10, 2024
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,7 @@ The following is the list of connection options and default values.
### TlsOptions

| Option | Default | Description |
| ---------------- | ------- |---------------------------------------------------------------------------------------------------------------------------------|
| ---------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `ca` | N/A | CA certificate |
| `caFile` | | CA certificate filepath |
| `cert` | N/A | Client certificate |
Expand Down
61 changes: 61 additions & 0 deletions nats-base-client/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1434,3 +1434,64 @@ export enum ServiceVerb {
STATS = "STATS",
INFO = "INFO",
}

export type Context = {
server: ContextServer;
data: ContextUser;
};

export type ContextServer = {
name: string;
host: string;
id: string;
version: string;
tags: string[];
jetstream: boolean;
flags: number;
seq: number;
time: Date;
};

export type ContextUser = {
user: string;
account: string;
permissions?: {
publish?: ContextPermission;
subscribe?: ContextPermission;
responses?: ContextResponsePermission;
};
};

export type ContextPermission = {
deny?: string[];
allow?: string[];
};

export type ContextResponsePermission = {
max: number;
ttl: number;
};

export type RequestInfo = {
acc: string;
rtt: number;
start?: Date;
host?: string;
id?: string;
svc?: string;
user?: string;
name?: string;
lang?: string;
ver?: string;
server?: string;
cluster?: string;
alts?: string[];
stop?: Date;
jwt?: string;
issuer_key?: string;
name_tag?: string;
tags?: string[];
client_type?: string;
client_id?: string;
nonce?: string;
};
17 changes: 17 additions & 0 deletions nats-base-client/msg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
MsgHdrs,
NatsError,
Publisher,
RequestInfo,
ReviverFn,
} from "./core.ts";

Expand Down Expand Up @@ -113,4 +114,20 @@ export class MsgImpl implements Msg {
string(): string {
return TD.decode(this.data);
}

requestInfo(): RequestInfo | null {
const v = this.headers?.get("Nats-Request-Info");
if (v) {
return JSON.parse(
v,
function (this: unknown, key: string, value: unknown): unknown {
if ((key === "start" || key === "stop") && value !== "") {
return new Date(Date.parse(value as string));
}
return value;
},
) as RequestInfo;
}
return null;
}
}
11 changes: 11 additions & 0 deletions nats-base-client/nats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { ServiceClientImpl } from "./serviceclient.ts";
import { JetStreamClient, JetStreamManager } from "../jetstream/types.ts";
import {
ConnectionOptions,
Context,
createInbox,
ErrorCode,
JetStreamManagerOptions,
Expand Down Expand Up @@ -477,6 +478,16 @@ export class NatsConnectionImpl implements NatsConnection {
return this.protocol.isClosed() ? undefined : this.protocol.info;
}

async context(): Promise<Context> {
const r = await this.request(`$SYS.REQ.USER.INFO`);
return r.json<Context>((key, value) => {
if (key === "time") {
return new Date(Date.parse(value));
}
return value;
});
}

stats(): Stats {
return {
inBytes: this.protocol.inBytes,
Expand Down
74 changes: 66 additions & 8 deletions tests/auth_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*/

import {
assertArrayIncludes,
assertEquals,
assertRejects,
fail,
Expand All @@ -39,6 +40,7 @@ import {
import { assertErrorCode, cleanup, NatsServer, setup } from "./helpers/mod.ts";
import {
deferred,
MsgImpl,
NatsConnectionImpl,
nkeys,
} from "../nats-base-client/internal_mod.ts";
Expand Down Expand Up @@ -144,11 +146,11 @@ Deno.test("auth - sub no permissions keeps connection", async () => {
}, { user: "a", pass: "a", reconnect: false });

const errStatus = deferred<Status>();
const _ = (async () => {
(async () => {
for await (const s of nc.status()) {
errStatus.resolve(s);
}
})();
})().then();

const cbErr = deferred<Error | null>();
const sub = nc.subscribe("bar", {
Expand Down Expand Up @@ -180,11 +182,11 @@ Deno.test("auth - sub iterator no permissions keeps connection", async () => {
}, { user: "a", pass: "a", reconnect: false });

const errStatus = deferred<Status>();
const _ = (async () => {
(async () => {
for await (const s of nc.status()) {
errStatus.resolve(s);
}
})();
})().then();

const iterErr = deferred<Error | null>();
const sub = nc.subscribe("bar");
Expand Down Expand Up @@ -222,11 +224,11 @@ Deno.test("auth - pub permissions keep connection", async () => {
}, { user: "a", pass: "a", reconnect: false });

const errStatus = deferred<Status>();
const _ = (async () => {
(async () => {
for await (const s of nc.status()) {
errStatus.resolve(s);
}
})();
})().then();

nc.publish("bar");

Expand All @@ -249,11 +251,11 @@ Deno.test("auth - req permissions keep connection", async () => {
}, { user: "a", pass: "a", reconnect: false });

const errStatus = deferred<Status>();
const _ = (async () => {
(async () => {
for await (const s of nc.status()) {
errStatus.resolve(s);
}
})();
})().then();

const err = await assertRejects(
async () => {
Expand Down Expand Up @@ -1194,3 +1196,59 @@ Deno.test("auth - creds and un and pw and token", async () => {
await nc.close();
await ns.stop();
});

Deno.test("auth - request context", async () => {
const { ns, nc } = await setup({
accounts: {
S: {
users: [{
user: "s",
password: "s",
permission: {
subscribe: ["q.>", "_INBOX.>"],
publish: "$SYS.REQ.USER.INFO",
allow_responses: true,
},
}],
exports: [
{ service: "q.>" },
],
},
A: {
users: [{ user: "a", password: "a" }],
imports: [
{ service: { subject: "q.>", account: "S" } },
],
},
},
}, { user: "s", pass: "s" });

const srv = await (nc as NatsConnectionImpl).context();
assertEquals(srv.data.user, "s");
assertEquals(srv.data.account, "S");
assertArrayIncludes(srv.data.permissions?.publish?.allow || [], [
"$SYS.REQ.USER.INFO",
]);
assertArrayIncludes(srv.data.permissions?.subscribe?.allow || [], [
"q.>",
"_INBOX.>",
]);
assertEquals(srv.data.permissions?.responses?.max, 1);

nc.subscribe("q.>", {
callback(err, msg) {
if (err) {
fail(err.message);
}
const info = (msg as MsgImpl).requestInfo();
assertEquals(info?.acc, "A");
msg.respond();
},
});

const a = await connect({ user: "a", pass: "a", port: ns.port });
console.log(await (a as NatsConnectionImpl).context());
await a.request("q.hello");

await cleanup(ns, nc, a);
});
Loading