Skip to main content

arminius_lib_nats/
auth_management.rs

1// SPDX-FileCopyrightText: 2025 BWI GmbH
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Utilities for creating NATS Accounts, Users and JWTs
6
7mod tests;
8
9use color_eyre::eyre::Context as _;
10use nats_io_jwt::{Account, Claims, Operator, OperatorLimits, Token, User};
11use nkeys::{KeyPair, KeyPairType};
12
13/// Creates a new operator account (which is the NATS trust root)
14pub fn create_operator_account() -> color_eyre::eyre::Result<(KeyPair, String)> {
15	let key = KeyPair::new(KeyPairType::Operator);
16	let account: Operator =
17		Operator::builder().try_into().context("expected new account to be valid")?;
18	let jwt = create_jwt(&key, account, &key, "operator");
19	Ok((key, jwt))
20}
21
22/// Creates an ordinary NATS account
23pub fn create_account(
24	operator_key: &KeyPair,
25	limits: Option<OperatorLimits>,
26	name: &str,
27) -> color_eyre::eyre::Result<(KeyPair, String)> {
28	let key = KeyPair::new_account();
29	let mut account: Account =
30		Account::builder().try_into().context("error creating new account")?;
31	account.limits = limits;
32	let token = create_jwt(operator_key, account, &key, name);
33	Ok((key, token))
34}
35
36/// Creates a NATS user in the given account.
37pub fn create_user(
38	account_key: &KeyPair,
39	name: &str,
40) -> color_eyre::eyre::Result<(KeyPair, String)> {
41	let user_key = KeyPair::new_user();
42	let user: User = User::builder()
43		.issuer_account(account_key.public_key())
44		.try_into()
45		.context("could not create new user")?;
46	let jwt = create_jwt(account_key, user, &user_key, name);
47	Ok((user_key, jwt))
48}
49
50/// Creates a JWT for the given `key`, signed by the given `signer`
51pub fn create_jwt(
52	signer: &KeyPair,
53	claims: impl Into<Claims>,
54	key: &KeyPair,
55	name: &str,
56) -> String {
57	Token::new(key.public_key()).name(name).claims(claims).sign(signer)
58}