This document provides a step by step deep dive into JWT usage within NATS. Starting with related concepts, it will introduce JWTs and how they can be used in NATS. This will NOT list every JWT/nsc option, but will focus on the important options and concepts.
To exercise listed examples please have the following installed:
To install
nats-server,nats,nk,nsc:To practice the examples below:
Save the configuration below in a file named say
server.conf, and start nats server via:So that the server started. Later when we change the configuration we can do a reload like this:
Accounts are the NATS isolation context.
Messages published in one account won't be received in another.
Listen for any message on account a:
Publish a message from account b:
Note that you do not see this message received by your subscriber.
Now publish a messages from account a:
This time the message is received by the subscriber:
The above example shows no message flow between user a associated with account A and user b in account B. Messages are delivered only within the same account. That is, unless you explicitly define it.
Below is a similar example, this time with messages crossing explicit account boundaries.
Modify
server.confand runnats-server --signal reload
Subscribe to everything as user 'a'
Publish on 'foo' as user 'b':
This time the message is received by the subscriber:
Accounts are a lot more powerful than what has been demonstrated here. Take a look at the complete documentation of accounts and the users associated with them. All of this is in a plain NATS config file. (Copy the above config and try it using this command: nats-server -c <filename>) In order to make any changes, every participating nats-server config file in the same security domain has to change. This configuration is typically controlled by one organization or the administrator.
nats-server --signal reload.NKEYs are decorated, Base32 encoded, CRC16 check-summed, Ed25519 keys.
Ed25519 is:
NATS server can be configured with public NKEYs as user (identities). When a client connects the nats-server sends a challenge for the client to sign in order to prove it is in possession of the corresponding private key. The nats-server then verifies the signed challenge. Unlike with a password based scheme, the secret never left the client.
To assist with knowing what type of key one is looking at, in config or logs, the keys are decorated as follows:
O, A, U for various
types, O for operator, A for account, and U meaning user.SO, SA, SU. S stands
for seed. The remainders(O, A and U) are the same meaning as
in public keys.NKEYs are generated as follows:
To view the key:
Create another key:
View the key:
Replacing the user/password with NKEY in account config example:
Simple example:
Subscribe with nats -s nats://localhost:4222 sub --nkey=a.nk ">"
Publish a message using nats -s nats://localhost:4222 pub --nkey=b.nk foo nkey the subscriber should receive it.
When the nats-server was started with -V tracing, you can see the signature in the CONNECT message (formatting added manually):
On connect, clients are instantly sent the nonce to sign as part of the INFO message (formatting added manually). Since telnet will not authenticate, the server closes the connection after hitting the authorization timeout.
In a large organization the centralized configuration approach can lead to less flexibility and more resistance to change when controlled by one entity. Alternatively, instead of operating one infrastructure, it can be deployed more often (say per team) thus making import/export relationships harder as they have to bridge separate systems. In order to make accounts truly powerful, they should ideally be configured separately from the infrastructure, only constrained by limits. This is similar for user. An account contains the user but this relationship could be a reference as well, such that alterations to user do not alter the account. Users of the same account should be able to connect from anywhere in the same infrastructure and be able to exchange messages as long as they are in the same authentication domain.
Account and User creation managed as separate artifacts in a decentralized fashion using NKEYs. Relying upon a hierarchical chain of trust between three distinct NKEYs and associated roles:
Each NKEY is referenced, together with additional configuration, in a JWT document. Each JWT has a subject field and its value is the public portion of an NKEY and serves as identity. Names exist in JWT but as of now are only used by tooling, nats-server does not read this value. The referenced NKEY's role determines the JWT content:
In addition, JWTs can contain settings related to their decentralized nature, such as expiration/revocation/signing. At no point do JWTs contain the private portion of an NKEY, only signatures that can be verified with public NKEY. JWT content can be viewed as public, although it's content may reveal which subjects/limits/permissions exist.
A nats-server is configured to trust an operator. Meaning, the
Operator JWT is part of its server configuration and requires a
restart or nats-server --signal reload once the configuration
changed. It is also configured with a way to obtain account JWT in one
of three ways (explained below).
Clients provide a User JWT when connecting. An Account JWT is not used by clients talking to a nats-server. The clients also possess the private NKEY corresponding to the JWT identity, so that they can prove their identity as described above.
The issuer field of the User JWT identifies the Account, and the nats-server then independently obtains the current Account JWT from its configured source. The server can then verify that signature on the User JWT was issued by an NKEY of the claimed Account, and in turn that the Account has an issuer of the Operator and that an NKEY of the Operator signed the Account JWT. The entire three-level hierarchy is verified.
To obtain an Account JWT, the nats-server is configured with one of three resolver types. Which one to pick depends upon your needs:
mem-resolver, except you do not need to modify the
server configurations when accounts are added or changed,nats-account-server is
such a webserver. When set up correctly, it will inform
nats-server of Account JWT changes.nats-resolver: Same as url-resolver, just uses NATS instead of
http
nats-account-server. Will
eventually converge on the union of all account JWTs known to
every participating nats-server,nats-server to exclusively write to (it can be on a shared Network File System, but the directories themselves can not be shared between servers),nats-resolver and url-resolver, the nats-resolver is
the clear recommendation.JWT nats-resolver is recommended to use in production
environment. With JWT nats-resolver, you can manage huge accounts
and users without server reloading. But before adopting JWT
nat-resolver, make sure you understand correctly how it works. You
can make use of static account settings(probably with NKEYs) and
memory-resolver as the necessary steps forwarding JWT
nats-resolver fully understanding.
Each JWT document has a subject(sub) it represents. This is the
public identity NKEY represented by the JWT document. JWT documents
contain an issued at (iat) time of signing. This time is in seconds
since Unix epoch. It is also used to determine which of two JWTs for
the same subject is more recent. Furthermore JWT documents have an
issuer, this may be an (identity) NKEY or a dedicated signing NKEY of
an item one level above it in the trust hierarchy. A key is a signing
key if it is listed as such in the JWT (above). Signing NKEYs adhere
to same NKEY roles and are additional keys that unlike identity NKEY
may change over time. In the hierarchy, signing keys can only be used
to sign JWT for the role right below them. User JWTs have no signing
keys for this reason. To modify one role's set of signing keys, the
identity NKEY needs to be used.
Each JWT is signed as below:
If a JWT is valid, the JWT above it is validated as well. If all of them are valid, the chain of trust between them is tested top down as follows:
| Type | Trust Rule | Obtained |
|---|---|---|
| Operator | jwt.issuer == jwt.subject (self signed) |
configured to trust |
| Account | jwt.issuer == trusted issuing operator (signing/identity) key |
configured to obtain |
| User | jwt.issuer == trusted issuing account (signing/identity) key && jwt.issuedAt > issuing account revocations[jwt.subject] |
provided on connect |
This is a conceptual view. While all these checks happen, the results of earlier evaluations might be cached: if the Operator/Account is trusted already and the JWT did not change since, then there is no reason to re-evaluate.
Below are examples of decoded JWT (iss == issuer, sub ==
subject, iat == issuedAt):
nsc describe account -n demo-test --json:
nsc describe user -a demo-test -n alpha --json:
When a client connects, the steps below have to succeed. The following nats-server configuration is used (for ease of understanding, we are using url-resolver):
Client connects and the nats-server responds with INFO
(identical to NKEYs) and a containing
nonce.
For ease of use, the NATS CLI uses a creds file that is the concatenation of JWT and private user identity/NKEY.
The Client responds with a CONNECT message (formatting added
manually), containing a JWT and signed nonce. (output copied from
nats-server started with -V)
Server verifies if a JWT returned is a user JWT and if it is
consistent: sign(jwt.sig, jwt.issuer) == hash(jwt.header+jwt.body) (issuer is part of body),
Server verifies if nonce matches JWT.subject, thus proving client's possession of private user NKEY,
Server either knows referenced account or downloads it from
http://localhost:9090/jwt/v1/accouts/AAAXAUVSGK7TCRHFIRAS4SYXVJ76EWDMNXZM6ARFGXP7BASNDGLKU7A5,
Server verifies downloaded JWT is an account JWT and if it is
consistent: sign(jwt.sig, jwt.issuer) == hash(jwt.header+jwt.body) (issuer is part of body),
Server verifies if an account JWT issuer is in configured list of trusted operator keys (derived from operator JWT in configuration),
Server verifies that a user JWT subject is not in the account's revoked list, or if jwt.issuedAt field has a higher value,
Server verifies that a user JWT issuer is either identical to the account JWT subject or part of the account JWT signing keys,
If all of the above holds true, the above invocation will succeed, only if the user JWT does not contain permissions or limits restricting the operation otherwise
Output if user.creds were to contain a JWT where the maximum
message payload is limited to 5 bytes
Depending on which entity has access to private Operator/Account identity or signing NKEYs, different deployment models are enabled. When picking one, it is important to pick the simplest deployment model that enables what you need it to do. Everything beyond just results in unnecessary configuration and steps.
Centralized config: one (set of) user(s) has access to all private operator and account NKEYs,
Administrators operating the shared infrastructure call all the shots
Decentralized config (with multiple nsc environments, explained later):
This can also be used by a single entity to not mix up nsc environments as well.
Self-service, decentralized config (shared dev cluster):
Is similar to 2, but sets of users in 2.1 have access to an operator private signing NKEY.
This allows teams to add/modify their own accounts.
Since administrators give up control over limits, there should be at least one organizational mechanism to prevent unchecked usage.
Administrators operating the infrastructure can add/revoke access by controlling the set of operator signing keys.
Mix of the above - as needed: separate sets of users (with
multiple nsc environments).
For some user/teams the Administrator operates everything.
Signing keys can not only be used by individuals in one or more nsc
environments, but also by programs facilitating
JWT and
NKEY libraries. This allows the
implementation of sign-up services.
A deeper understanding of accounts will help you to best setup NATS JWT based security.
What entity do accounts correspond to:
Our official suggestion is to scope accounts by application/service offered.
This is very fine grained and will require some configuration.
This is why some users gravitate to accounts per team. One account for all Applications of a team.
It is possible to start out with less granular accounts and as applications grow in importance or scale become more fine grained.
Compared to file based config, Imports and Exports change slightly.
To control who gets to import an export, activation tokens are introduced.
These are JWTs that an importer can embed.
They comply to similar verification rules as user JWT, thus enabling
a nats-server to check if the exporting account gave explicit
consent.
Due to the use of a token, the exporting account's JWT does not have to be modified for each importing account.
Updates of JWTs are applied as nats-server discover them
mem-resolver require nats-server --signal reload to re-read
all configured account JWTs,url-resolver and nats-resolver listen on a dedicated update
subject of the system account and applied if the file is valid,nats-resolver will also also update the corresponding JWT file
and compensate in case the update message was not received due
to temporary disconnect.The System Account is the account under which nats-server offers
(administrative) services and monitoring events.
This section will introduce nsc cli to generate and manage
operator/accounts/user. Even if you intend to primarily generate your
Accounts/User programmatically, in all likelihood, you won't do so for
an operator or all accounts. Key Management and how to do so using
nsc will also be part of this section.
nsc is a tool that uses the JWT and NKEY libraries to create NKEYs (if asked to) and all types of JWT. It then stores these artifacts in separate directories.
It keeps track of the last operator/account used. Because of this,
commands do not need to reference operator/accounts but can be
instructed to do so (recommended for scripts). It supports an
interactive mode when -i is provided. When used, referencing
accounts/keys is easier.
nsc env will show where NKEYS/JWT are stored and what current defaults are. For testing you may want to switch between nsc environments: Changing the (JWT) store directory: nsc env --store <different folder> Changing the (NKEY) store directory by having an environment variable set: export NKEYS_PATH=<different folder>
Subsequent sections will refer to different environments in context of different deployment modes. As such you can skip over all mentions for modes not of interest to you. The mixed deployment mode is not mentioned and left as an exercise to the reader.
Possessing NKEYS gives access to the system. Backups should therefore best be offline and access to them should be severely restricted. In cases where regenerating all/parts of the operator/accounts is not an option, signing NKEYs must be used and identity NKEYs should be archived and then removed from the original store directory, so that in the event of a data breach you can recover without a flag-day change-over of identities. Thus, depending on your scenario, relevant identity NKEYS need to only exist in very secure offline backup(s).
The store directory contains JWTs for operators, accounts, and users. It does not contain private keys. Therefore it is ok to back these up or even store them in a VCS such as git. But be aware that depending on content, JWT may reveal which permissions/subjects/public-nkeys exist. Knowing the content of a JWT does not grant access; only private keys will. However, organizations may not wish to make those public outright and thus have to make sure that these external systems are secured appropriately.
When restoring an older version, be aware that:
JWTs allow you to specify names. But names do NOT represent an
identity, they are only used to ease referencing of identities in our
tooling. At no point are these names used to reference each other,
instead, the public identity NKEY is used for that. The nats-server
does not read them at all. Because names do not relate to identity,
they may collide. Therefore, when using nsc, these names need to be
keep unique.
Create operator with system account and system account user:
The command nsc edit operator [flags] can subsequently be used to
modify the operator. For example if you are setting the account server
url (used by url-resolver and nats-resolver), nsc does not
require them being specified on subsequent commands. nsc edit operator --account-jwt-server-url "nats://localhost:4222"
Note that if you update an operator JWT that is installed on a server you will need to manually update the operator JWT and reload the server While
nscis able to update accounts, it never updates the operator.
We always recommend using signing keys for an operator. Generate one
for an operator (-o) and store it in the key directory
(--store). The output will display the public portion of the signing
key, use that to assign it to the operator (--sk O...). nsc generate nkey -o --store followed by nsc edit operator --sk OB742OV63OE2U55Z7UZHUB2DUVGQHRA5QVR4RZU6NXNOKBKJGKF6WRTZ. To pick the
operator signing key for account generation, provide the -i option
when doing so.
The system account is the account under which nats-server offers
system services as will be explained below in the
system-account section. To access these
services a user with credentials for the system account is
needed. Unless this user is restricted with appropriate permissions,
this user is essentially the admin user. They are created like any
other user.
For cases where signing keys are generated and immediately added --sk generate will create an NKEY on the fly and assign it as signing NKEY.
In order to import an Operator JWT, say the one just created, into a separate nsc environment maintained by a different entity/team, the following has to happen:
nsc describe operator --raw and
store the output in a file named operator.jwt. The option --raw
causes the raw JWT to be emitted,nsc add operator -u operator.jwt.If the operator should been changed and an update is required, simply
repeat these steps but provide the --force option in the last
step. This will overwrite the stored operator JWT.
In addition to the previous step, self service deployments require an operator signing key and a system account user. Ideally you would want an operator signing key per entity to distribute a signing key too. Simply repeat the command shown earlier but:
nsc generate nkey -o --store in this environment instead,nsc edit operator --sk in the operator environment,--forceTo import the system account user needed for administrative purposes as well as monitoring, perform these steps:
Perform nsc describe account -n SYS --raw and store the output in
a file named SYS.jwt.
The option -n specifies the (system) account named SYS.
Exchange the file,
Import the account nsc import account --file SYS.jwt,
Perform nsc generate nkey -u --store in this environment,
Exchange the public key printed by the command with the Administrator/Operator via a way that assures you sent the public key and not someone elses,
Create a system account user named (-n) any way you like (here
named sys-non-op) providing (-k) the exchanged public key nsc add user -a SYS -n sys-non-op -k UDJKPL7H6QY4KP4LISNHENU6Z434G6RLDEXL2C64YZXDABNCEOAZ4YY2 in the
operator environment. (-a references the Account SYS.),
If desired edit the user,
Export the user nsc describe user -a SYS -n sys-non-op --raw from
the operator environment and store it in a file named
sys.jwt. (-n references the user sys-non-op),
Exchange the file,
Import the user in this environment using nsc import user --file sys.jwt
As a result of these operations, your operator environment should have these keys and signing keys:
And your account should have the following ones:
Between the two outputs, compare the Stored column.
Alternatively if the administrator is willing to exchange private keys
and the exchange can be done securely, a few of these steps fall
away. The signing key and system account user can be generated in the
administrator/operator environment, omitting --store to avoid
unnecessary key copies. Then the public/private signing NKEYS are
exchanged together with the system account user as creds file. A creds
file can be generated with nsc generate creds -a SYS -n sys-non-op
and imported into this environment with nsc import user --file sys.jwt. If the signing key is generated before the operator is
imported into this environment, operator update falls away.
Create an account as follows:
In case you have multiple operator signing keys -i will prompt you
to select one. nsc edit account [flags] can subsequently be used to
modify the account. (Edit is also applicable to the system account)
Similar to the operator signing keys are recommended. Generate signing key for an account (-a) and store it in the key directory maintained by nsc (--store) The output will display the public portion of the signing key, use that to assign it to the account (--sk A...) nsc generate nkey -a --store nsc edit account --sk ACW2QC262CIQUX4ACGOOS5XLKSZ2BY2QFBAAOF3VOP7AWAVI37E2OQZX To pick the signing key for user generation, provide the -i option when doing so.
In this mode, the created account is self-signed. To have it signed by the operator perform these steps:
In this environment export the created account as a JWT like this
nsc describe account -n <account name> --raw.
Store the output in a file named import.jwt.
Exchange the file with the Administrator/Operator via a way that assures it is your JWT and not someone elses.
In the operator environment import the account with nsc import account --file import.jwt.
This step also re-signs the JWT so that it is no longer self-signed.
The Administrator/operator can now modify the account with nsc edit account [flags]
If the account should be changed and an update is required, simply
repeat these steps but provide the --force option during the last
step. This will overwrite the stored account JWT.
This environment is set up with a signing key, thus the account is already created properly signed. The only step that is needed is to push the Account into the NATS network. However, this depends on your ability to do so. If you have no permissions, you have to perform the same steps as for the decentralized deployment mode. The main difference is that upon import, the account won't be re-signed.
How accounts can be publicized wholly depends on the resolver you are using:
nsc push will send an HTTP POST request to the hosting webserver
or nats-account-server,nats-resolver: Every environment with a system account user that
has permissions to send properly signed account JWT as requests to:
$SYS.REQ.CLAIMS.UPDATE can upload and update all
accounts. Currently, nsc push uses this subject.$SYS.REQ.ACCOUNT.*.CLAIMS.UPDATE can upload and update specific
accounts.nsc generate config <resolver-type> is an utility that generates the
relevant NATS config. Where <resolver-type> can be --mem-resolver
or --nats-resolver for the corresponding resolver. Typically the
generated output is stored in a file that is then
included
by the NATS config. Every server within the same authentication domain
needs to be configured with this configuration.
This is a quick demo of the nats-based resolver from operator creation to publishing a message. Please be aware that the ability to push only relates to permissions to do so and does not require an account keys. Thus, how accounts to be pushed into the environment (outright creation/import) does not matter. For simplicity, this example uses the operator environment.
Operator Setup:
Inspect the setup:
nsc describe operator:
nsc describe account:
Generate the config and start the server in the background. Also, inspect the generated config. It consists of the mandatory operator, explicitly lists the system account and corresponding JWT:
Add an account and a user for testing:
Without having pushed the account the user can't be used yet.
Doesn't work
Push the account, or push all accounts:
For the NATS resolver, each nats-server that responds will be
listed. In case you get fewer responses than you have servers or a
server reports an error, it is best practice to resolve this issue and
retry. The NATS resolver will gossip missing JWTs in an eventually
consistent way. Servers without a copy will perform a lookup from
servers that do. If during an initial push only one server responds
there is a window where this server goes down or worse, loses its
disk. During that time the pushed account is not available to the
network at large. Because of this, it is important to make sure that
initially, more servers respond than what you are comfortable with
losing in such a way at once.
Once the account is pushed, its user can be used:
Create a user as follows: nsc add user --account <account name> --name <user name> -i nsc edit user [flags] can subsequently be used to modify the user. In case you have multiple account signing keys, for either command, -i will prompt you to select one.
In case you generate a user on behalf of another entity that has no nsc environment, you may want to consider not exchanging the NKEY. 1. To do this, have the other entity generate a user NKEY pair like this: nsc generate nkey -u (--store is omitted so as to not have an unnecessary copy of the key) 2. Exchange the public key printed by the command via a way that assures what is used is not someone elses. 3. Create the user by providing (-k) the exchanged public key nsc add user --account SYS -n sys-non-op -k UDJKPL7H6QY4KP4LISNHENU6Z434G6RLDEXL2C64YZXDABNCEOAZ4YY2 in your environment. (system account user example) 4. If desired edit the user 5. Export the user nsc describe user --account SYS -n sys-non-op --raw from your environment and store the output in a JWT file. 6. Exchange the JWT file 7. Use the JWT file and the NKEY pair in your application.
nsc essentially uses the NKEY and JWT libraries to generate operator/accounts/users. You can use these libraries to generate the necessary artifacts as well. Because there is only one, generating the operator this way makes little sense. Accounts only if you need them dynamically, say for everyone of your customer. Dynamically provision user and integrate that process with your existing infrastructure, say LDAP, is the most common use case for these libraries.
The next sub sections demonstrate dynamic user generation. The mechanisms shown are applicable to dynamic account creation as well. For dynamic user/account creation, signing keys are highly recommended.
By generating users or accounts dynamically, it becomes YOUR RESPONSIBILITY to properly authenticate incoming requests for these users or accounts
For sign up service issued JWTs, ALWAYS set the SHORTEST POSSIBLE EXPIRATION
This example illustrates the linear flow of the algorithm and how to use the generated artifacts. In a real world application you would want this algorithm to be distributed over multiple processes. For simplicity of the examples, keys may be hard coded and error handling is omitted.
Inspect the user claim for all available properties/limits/permissions to set. When using an account claim instead, you can dynamically generate accounts. Additional steps are to push the new account as outlined here. Depending on your needs, you may want to consider exchanging the accounts identity NKEY in a similar way that the users key is exchanged in the next section.
As mentioned earlier this example needs to be distributed. This example makes uses of Go channels to encode the same algorithm, uses closures to encapsulate functionalities and Go routines to show which processes exist. Sending and receiving from channels basically illustrates the information flow. To realize this, you can pick HTTP, NATS itself etc... (For simplicity, properly closing channels, error handling, waiting for Go routines to finish is omitted.)
The above example did not need authentication mechanisms, RequestUser possessed the signing key. How you decide to trust an incoming request is completely up to you. Here are a few examples:
In this example, this logic is encapsulated as placeholder closures ObtainAuthorizationToken and IsTokenAuthorized that do nothing.
In this example the users NKEY is generated by the requesting process and the public key is sent to the user sign up service. This way the service does not need to know or send the private key. Furthermore, any process receiving the initial request or even response, may have the user JWT but will not be able to proof possession of private NKEY. However, you can have the provisioning service generate the NKEY pair and respond with the NKEY pair and the user JWT. This is less secure but would enable a less complicated protocol where permissable.
The previous example used Go channels to demonstrate data flows. You can use all sorts of protocols to achieve this data flow and pick whatever fits best in your existing infrastructure. However, you can use NATS for this purpose as well.
You can replace send and receive <- with nats publish and subscribe or - for added redundancy on the sign up service - queue subscribe. To do so, you will need connections that enable the sign up service as well as the requestor to exchange messages. The sign up service uses the same connection all of the time and (queue) subscribes to a well known subject. The requestor uses the connection and sends a request to the well known subject. Once the response is received the first connection is closed and the obtained JWT is used to establish a new connection.
Here in lies a chicken and and egg problem. The first connection to request the JWT itself needs credentials. The simplest approach is to set up a different NATS server/cluster that does not require authentication, connect first to cluster 1 and keep requesting the user JWT. Once obtained disconnect from cluster 1 and connect to cluster 2 using the obtained JWT.
The earlier setup can be simplified by using accounts instead of separate server/clusters. But a JWT/operator based setup requires JWT authentication. Thus, would be, connections to a different cluster are replaced by connections to the same cluster but different accounts.
signup account.Connections to the signup accounts use two kinds of credentials. 1. Sign up service(s) use(s) credentials generated for it/them. 2. All requestors use the same JWT and NKEY, neither of which are used for actual authentication.
nsc itself.The NKEY library does exist or is incorporated in all languages where NATS supports NKEY. The NATS JWT library on the other hand is written in Go. This may not be your language of choice. Other than encoding JWTs, most of what the that library does is maintain the NATS JWT schema. If you use nsc to generate a user as a template for the sign up service and work off of that template you don't need the JWT library. The sample shows how a program that takes an account identity NKEY and account signing NKEY as arguments and outputs a valid creds file.
If .NET is your language of choice, you can also use the NATS.Jwt package.
The system account is the account under which nats-server offer
services. To use it either the operator JWT has to specify it, which
happens during nsc init or when providing --sys to nsc add operator. Alternatively you can encode it in the server configuration
by providing system_account with the public NKEY of the account you
want to be the system account:
It is NOT recommended to use this account to facilitate communication
between your own applications. Its sole purpose is to facilitate
communication with and between nats-server.
Events are published as they happen. But you MUST NOT rely on a
particular ordering or due to the possibility of loss, events
matching. Say, CONNECT for a client always matching a DISCONNECT
for the same client. Your subscriber may simply be disconnected when
either event happens. Some messages carry aggregate data and are
periodically emitted. There, missing a message for one reason or
another is compensated by the next one.
| Subjects to subscribe on | Description | Repeats |
|---|---|---|
$SYS.SERVER.<server-id>.SHUTDOWN |
Sent when a server shuts down | |
$SYS.SERVER.<server-id>.CLIENT.AUTH.ERR |
Sent when client fails to authenticate | |
$SYS.SERVER.<server-id>.STATSZ |
Basic server stats | Periodically |
$SYS.ACCOUNT.<account-id>.LEAFNODE.CONNECT |
Sent when Leafnode connected | |
$SYS.ACCOUNT.<account-id>.CONNECT |
Sent when client connected | |
$SYS.ACCOUNT.<account-id>.DISCONNECT |
Sent when Client disconnected | |
$SYS.ACCOUNT.<account-id>.SERVER.CONNS |
Sent when an accounts connections change |
The subject $SYS.SERVER.ACCOUNT.<account-id>.CONNS is still used but it is recommended to subscribe to it's new name $SYS.ACCOUNT.<account-id>.SERVER.CONNS.
| Subjects to publish requests to | Description | Message Output |
|---|---|---|
$SYS.REQ.SERVER.PING.STATZ |
Exposes the STATZ HTTP monitoring endpoint, each server will respond with one message |
Same as HTTP endpoint |
$SYS.REQ.SERVER.PING.VARZ |
- same as above for - VARZ |
- same as above - |
$SYS.REQ.SERVER.PING.SUBZ |
- same as above for - SUBZ |
- same as above - |
$SYS.REQ.SERVER.PING.CONNZ |
- same as above for - CONNZ |
- same as above - |
$SYS.REQ.SERVER.PING.ROUTEZ |
- same as above for - ROUTEZ |
- same as above - |
$SYS.REQ.SERVER.PING.GATEWAYZ |
- same as above for - GATEWAYZ |
- same as above - |
$SYS.REQ.SERVER.PING.LEAFZ |
- same as above for - LEAFZ |
- same as above - |
$SYS.REQ.SERVER.PING.ACCOUNTZ |
- same as above for - ACCOUNTZ |
- same as above - |
$SYS.REQ.SERVER.PING.JSZ |
- same as above for - JSZ |
- same as above - |
$SYS.REQ.SERVER.<server-id>.STATZ |
Exposes the STATZ HTTP monitoring endpoint, only requested server responds |
Same as HTTP endpoint |
$SYS.REQ.SERVER.<server-id>.VARZ |
- same as above for - VARZ |
- same as above - |
$SYS.REQ.SERVER.<server-id>.SUBZ |
- same as above for - SUBZ |
- same as above - |
$SYS.REQ.SERVER.<server-id>.CONNZ |
- same as above for - CONNZ |
- same as above - |
$SYS.REQ.SERVER.<server-id>.ROUTEZ |
- same as above for - ROUTEZ |
- same as above - |
$SYS.REQ.SERVER.<server-id>.GATEWAYZ |
- same as above for - GATEWAYZ |
- same as above - |
$SYS.REQ.SERVER.<server-id>.LEAFZ |
- same as above for - LEAFZ |
- same as above - |
$SYS.REQ.SERVER.<server-id>.ACCOUNTZ |
- same as above for - ACCOUNTZ |
- same as above - |
$SYS.REQ.SERVER.<server-id>.JSZ |
- same as above for - JSZ |
- same as above - |
$SYS.REQ.ACCOUNT.<account-id>.SUBSZ |
Exposes the SUBSZ HTTP monitoring endpoint, filtered by account-id. |
Same as HTTP endpoint |
$SYS.REQ.ACCOUNT.<account-id>.CONNZ |
- same as above for CONNZ - |
- same as above - |
$SYS.REQ.ACCOUNT.<account-id>.LEAFZ |
- same as above for LEAFZ - |
- same as above - |
$SYS.REQ.ACCOUNT.<account-id>.JSZ |
- same as above for JSZ - |
- same as above - |
$SYS.REQ.ACCOUNT.<account-id>.CONNS |
Exposes the event $SYS.ACCOUNT.<account-id>.SERVER.CONNS as request |
- same as above - |
$SYS.REQ.ACCOUNT.<account-id>.INFO |
Exposes account specific information similar to ACCOUNTZ |
Similar to ACCOUNTZ |
Each of the subjects can be used without any input. However, for each request type (STATZ, VARZ, SUBSZ, CONNS, ROUTEZ, GATEWAYZ, LEAFZ, ACCOUNTZ, JSZ) a json with type specific options can be sent. Furthermore all subjects allow for filtering by providing these values as json:
| Option | Effect |
|---|---|
server_name |
Only server with matching server name will respond. |
cluster |
Only server with matching cluster name will respond. |
host |
Only server running on that host will respond. |
tags |
Filter responders by tags. All tags must match. |
| Subject | Description | Input | Output |
|---|---|---|---|
$SYS.REQ.ACCOUNT.<account-id>.CLAIMS.UPDATE |
Update a particular account JWT (only possible if properly signed) | JWT body | |
$SYS.REQ.ACCOUNT.<account-id>.CLAIMS.LOOKUP |
Responds with requested JWT | JWT body | |
$SYS.REQ.CLAIMS.PACK |
Single responder compares input, sends all JWT if different. | xor of all sha256(stored-jwt). Send empty message to download all JWT. | If different, responds with all stored JWT (one message per JWT). Empty message to signify EOF |
$SYS.REQ.CLAIMS.LIST |
Each server responds with list of account ids it stores | list of account ids separated by newline | |
$SYS.REQ.CLAIMS.UPDATE |
Exposes $SYS.REQ.ACCOUNT..CLAIMS.UPDATE without the need for <account-id> |
JWT body | |
$SYS.REQ.CLAIMS.DELETE |
When the resolver is configured with allow_delete: true, deleting accounts is enabled. |
Generic operator signed JWT claim with a field accounts containing a list of account ids. |
| Subject | Alternative Mapping |
|---|---|
$SYS.REQ.SERVER.PING |
$SYS.REQ.SERVER.PING.STATSZ |
$SYS.ACCOUNT.<account-id>.CLAIMS.UPDATE |
$SYS.REQ.ACCOUNT.<account-id>.CLAIMS.LOOKUP |
It is important to understand that leaf nodes do not multiplex between accounts. Every account that you wish to connect across a leaf node connection needs to be explicitly listed. Thus, the system account is not automatically connected, even if both ends of a leaf node connection use the same system account. For leaf nodes connecting into a cluster or super cluster, the system account needs to be explicitly connected as separate remote to the same URL(s) used for the other account(s). The system account user used by providing credentials can be heavily restricted and for example, only allow publishing on some subjects. This also holds true when you don't use the system account yourself, but indirectly need it for NATS based account resolver or centralized monitoring.
Examples in sub sections below assume that the cluster to connect into is in operator mode.
The outgoing connection is not in Operator mode, thus the system account may differ from the user account. This example shows how to configure a user account and the system account in a leaf node. Credentials files provided have to contain credentials that are valid server/cluster reachable by url. In the example, no accounts are explicitly configured, yet some are referenced. These are the default Account $G and the default system account $SYS
Outgoing connection is in operator mode as well. This example assumes usage of the same operator and thus system account. However, using a different operator would look almost identical. Only the credentials would be issued by accounts of the other operator.
As shown in what are accounts, they can be connected via exports and imports. While in configuration files this is straight forward, this becomes a bit more complicated when using JWTs. In part this is due to the addition of new concepts such as public/private/activation tokens that do not make sense in a config based context.
Add an export with: nsc add export --name <export name> --subject <export subject> This will export a public stream that can be imported by any account. To alter the export to be a service add --service.
To have more control over which account is allowed to import provide the option --private. When doing so only accounts for which you generate tokens can add the matching import. A token can be generated and stored in a file as follows: nsc generate activation --account <account name> --subject <export subject> --output-file <token file> --target-account <account identity public NKEY> The resulting file can then be exchanged with the importer.
To add an import for a public export use nsc add import --account <account name> --src-account <account identity public NKEY> --remote-subject <subject of export>. To import a service provide the option --service.
To add an import for a private export use nsc add import --account <account name> --token <token file or url> If your nsc environment contains operator and account signing NKEYs, nsc add import -i will generate token to embed on the fly
Between export/import/activation tokens there are many subjects in use. Their relationship is as follows:
In order to be independent of subject names chosen by the exporter, importing allows to remap the imported subject. To do so provide the option --remote-subject <subject name> to the import command.
This example will change the subject name the importing account uses locally from the exporter picked subject foo to bar.
NSC can generate diagrams of inter account relationships using: nsc generate diagram component --output-file test.uml The generated file contains a plantuml component diagram of all accounts connected through their exports/imports. To turn the file into a .png execute: plantuml -tpng test.uml If the diagram is cut off, increase available memory and image size limit with these options: -Xmx2048m -DPLANTUML_LIMIT_SIZE=16384
Identity keys are extremely important, so you may want to keep them safe and instead hand out more easily replaceable signing keys to operators. Key importance generally follows the chain of trust with operator keys being more important than account keys. Furthermore, identity keys are more important than signing keys.
There are instances where regenerating a completely new identity key of either type is not a feasible option. For example, you might have an extremely large deployment (IoT) where there is simply too much institutional overhead. In this case, we suggest you securely backup identity keys offline and use exchangeable signing keys instead. Depending on which key was compromised, you may have to exchange signing keys and re-sign all JWTs signed with the compromised key. The compromised key may also have to be revoked.
Whether you simply plan to regenerate new NKEY/JWT or exchange signing NKEYs and re-sign JWTs, in either case, you need to prepare and try this out beforehand and not wait until disaster strikes.
Usage of signing keys for Operator and Account has been shown in the nsc section. This shows how to take an identity key offline. Identity NKEY of the operator/account is the only one allowed to modify the corresponding JWT and thus add/remove signing keys. Thus, initial signing keys are best created and assigned prior to removing the private identity NKEY.
Basic strategy: take them offline & delete in nsc NKEY directory.
Use nsc env to determine your NKEY directory. (Assuming ~/.nkeys for this example) nsc list keys --all lists all keys under your operator and indicates if they are present and if they are signing keys.
Keys for your Operator/Account can be found under <nkyesdir>/keys/O/../<public-nkey>.nk or <nkyesdir>/keys/A/../<public-nkey>.nk. The operator identity NKEY ODMFND7EIJ2MBHNPO2JHCKOZIAY6NAK7OT4V2ZT2C5O6LEB3DPKYV3QL would reside under ~/.nkeys/keys/O/DM/ODMFND7EIJ2MBHNPO2JHCKOZIAY6NAK7OT4V2ZT2C5O6LEB3DPKYV3QL.nk.
Please note that key storage is sharded by the 2nd and 3rd letter in the key
Once these files are backed up and deleted nsc list keys --all will show them as not stored. You can continue as normal, nsc will pick up signing keys instead.
Since you typically distribute user keys or creds files to your applications, there is no need for nsc to hold on to them in the first place. Credentials files are a concatenated user JWT and the corresponding private key, so don't forget to delete that as well.
Key and creds can be found under <nkyesdir>/keys/U/../<public-nkey>.nk and <nkyesdir>/creds/<operator-name>/<account-name>/<user-name>.creds
If you can easily re-deploy all necessary keys and JWTs, simply by re-generating a new account/user (possibly operator) this will be the simplest solution. The steps necessary are identical to the initial setup, which is why it would be preferred. In fact, for user NKEYs and JWT, generating and distributing new ones to affected applications is the best option.
Even if regeneration of an account or operator is not your first choice, it may be your method of last resort. Below sections outline the steps this would entail.
In order to reissue an operator identity NKEY use nsc reissue operator. It will generate a new identity NKEY and use it to sign the operator. nsc will also re-sign all accounts signed by the original identity NKEY. Accounts signed by operator signing keys will remain untouched.
The altered operator JWT will have to be deployed to all affected nats-server (one server at a time). Once all nats-server have been restarted with the new operator, push the altered accounts. Depending on your deployment mode you may have to distribute the operator JWT and altered account JWT to all other nsc environments.
This process will be a lot easier when operator signing keys were used throughout and no account will be re-signed because of this. If they were not, you can convert the old identity NKEY into a signing key using nsc reissue operator --convert-to-signing-key. On your own time - you can then remove the then signing NKEY using nsc edit operator --rm-sk O.. and redeploy the operator JWT to all nats-server.
Unlike with the operator, account identity NKEYs can not be changed as easily. User JWT explicitly reference the account identity NKEY such that the nats-server can download them via a resolver. This complicates reissuing these kind of NKEYs, which is why we strongly suggest sticking to signing keys.
The basic approach is to:
When signing keys were used, the account identity NKEY would only be
needed to self-sign the account JWT exchange with an
administrators/operators nsc environment.
JWTs for user, activations and accounts can be explicitly revoked. Furthermore, signing keys can be removed, thus invalidating all JWTs signed by the removed NKEY.
To revoke all JWTs for a user in a account issue nsc revocations add-user --account <account name> --name <user name>.
With the argument --at you can specify a time different than
now. Use nsc revocations list-users --account <account name> to
inspect the result or nsc revocations delete-user --account <account name> --name <user name> to remove the revocation.
Please note that the revocation created only applies to JWTs issued before the time listed. Users created or updated after revocation will be valid as they are outside of the revocation time. Also, please be aware that adding a revocation will modify the account and therefore has to be pushed in order to publicize the revocation.
To revoke all activations of the export, identified by --account and --subject (--stream if the export is a stream), issued for a given Account identity NKEY use:
Use nsc revocations list-activations --account SYS to inspect the result or:
to remove the revocation.
Please note the revocation created only applies to JWTs issued before the time listed. Activations created or edited after, will be valid as they are outside of the revocation time. Also be aware that adding a revocation will modify the account and therefore has to be pushed in order to publicize the revocation.
Account identity NKEYS can not be revoked like user or activations. Instead lock out all users by setting the connection count to 0 using nsc edit account --name <account name> --conns 0 and pushing the change using nsc push --all.
Alternatively you can also remove the account using nsc delete account --name and keep it from found by the account resolver. How to
do this depends on your resolver type:
Remove the JWT from the configuration field resolver_preload and
restart all nats-server
Manually delete the JWT from the nats-account-server store
directory.
nats-resolver: Prune removed accounts using: nsc push --all --prune.
For this to work, the resolver has to have deletion enabled
(allow_delete: true) and you need to be in possession of an
operator signing key.
Accounts, Activations, and Users can be revoked in bulk by removing the respective signing key.
Remove an operator signing key: nsc edit operator --rm-sk <signing key> As a modification of the operator, in order to take effect, all
dependent nsc installations as well as nats-server
will need this new version of the operator JWT.
Remove an account signing key: nsc edit account --name <account name> --rm-sk <signing key>. In order to take effect, a modification of an
account needs to be pushed: nsc push --all.