| 1 |
// Copyright 2018-2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"bufio" |
| 18 |
"context" |
| 19 |
"encoding/base64" |
| 20 |
"encoding/json" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"io" |
| 24 |
"math" |
| 25 |
"net/http" |
| 26 |
"net/http/httptest" |
| 27 |
"os" |
| 28 |
"path/filepath" |
| 29 |
"strings" |
| 30 |
"sync" |
| 31 |
"sync/atomic" |
| 32 |
"testing" |
| 33 |
"time" |
| 34 |
|
| 35 |
"github.com/nats-io/jwt/v2" |
| 36 |
"github.com/nats-io/nats.go" |
| 37 |
"github.com/nats-io/nkeys" |
| 38 |
) |
| 39 |
|
| 40 |
var ( |
| 41 |
// This matches ./configs/nkeys_jwts/test.seed |
| 42 |
oSeed = []byte("SOAFYNORQLQFJYBYNUGC5D7SH2MXMUX5BFEWWGHN3EK4VGG5TPT5DZP7QU") |
| 43 |
// This matches ./configs/nkeys/op.jwt |
| 44 |
ojwt = "eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJhdWQiOiJURVNUUyIsImV4cCI6MTg1OTEyMTI3NSwianRpIjoiWE5MWjZYWVBIVE1ESlFSTlFPSFVPSlFHV0NVN01JNVc1SlhDWk5YQllVS0VRVzY3STI1USIsImlhdCI6MTU0Mzc2MTI3NSwiaXNzIjoiT0NBVDMzTVRWVTJWVU9JTUdOR1VOWEo2NkFIMlJMU0RBRjNNVUJDWUFZNVFNSUw2NU5RTTZYUUciLCJuYW1lIjoiU3luYWRpYSBDb21tdW5pY2F0aW9ucyBJbmMuIiwibmJmIjoxNTQzNzYxMjc1LCJzdWIiOiJPQ0FUMzNNVFZVMlZVT0lNR05HVU5YSjY2QUgyUkxTREFGM01VQkNZQVk1UU1JTDY1TlFNNlhRRyIsInR5cGUiOiJvcGVyYXRvciIsIm5hdHMiOnsic2lnbmluZ19rZXlzIjpbIk9EU0tSN01ZRlFaNU1NQUo2RlBNRUVUQ1RFM1JJSE9GTFRZUEpSTUFWVk40T0xWMllZQU1IQ0FDIiwiT0RTS0FDU1JCV1A1MzdEWkRSVko2NTdKT0lHT1BPUTZLRzdUNEhONk9LNEY2SUVDR1hEQUhOUDIiLCJPRFNLSTM2TFpCNDRPWTVJVkNSNlA1MkZaSlpZTVlXWlZXTlVEVExFWjVUSzJQTjNPRU1SVEFCUiJdfX0.hyfz6E39BMUh0GLzovFfk3wT4OfualftjdJ_eYkLfPvu5tZubYQ_Pn9oFYGCV_6yKy3KMGhWGUCyCdHaPhalBw" |
| 45 |
oKp nkeys.KeyPair |
| 46 |
) |
| 47 |
|
| 48 |
func init() { |
| 49 |
var err error |
| 50 |
oKp, err = nkeys.FromSeed(oSeed) |
| 51 |
if err != nil { |
| 52 |
panic(fmt.Sprintf("Parsing oSeed failed with: %v", err)) |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
func chanRecv(t *testing.T, recvChan <-chan struct{}, limit time.Duration) { |
| 57 |
t.Helper() |
| 58 |
select { |
| 59 |
case <-recvChan: |
| 60 |
case <-time.After(limit): |
| 61 |
t.Fatal("Should have received from channel") |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
func opTrustBasicSetup() *Server { |
| 66 |
kp, _ := nkeys.FromSeed(oSeed) |
| 67 |
pub, _ := kp.PublicKey() |
| 68 |
opts := defaultServerOptions |
| 69 |
opts.TrustedKeys = []string{pub} |
| 70 |
s, c, _, _ := rawSetup(opts) |
| 71 |
c.close() |
| 72 |
return s |
| 73 |
} |
| 74 |
|
| 75 |
func buildMemAccResolver(s *Server) { |
| 76 |
mr := &MemAccResolver{} |
| 77 |
s.SetAccountResolver(mr) |
| 78 |
} |
| 79 |
|
| 80 |
func addAccountToMemResolver(s *Server, pub, jwtclaim string) { |
| 81 |
s.AccountResolver().Store(pub, jwtclaim) |
| 82 |
} |
| 83 |
|
| 84 |
func createClient(t *testing.T, s *Server, akp nkeys.KeyPair) (*testAsyncClient, *bufio.Reader, string) { |
| 85 |
return createClientWithIssuer(t, s, akp, "") |
| 86 |
} |
| 87 |
|
| 88 |
func createClientWithIssuer(t *testing.T, s *Server, akp nkeys.KeyPair, optIssuerAccount string) (*testAsyncClient, *bufio.Reader, string) { |
| 89 |
t.Helper() |
| 90 |
nkp, _ := nkeys.CreateUser() |
| 91 |
pub, _ := nkp.PublicKey() |
| 92 |
nuc := jwt.NewUserClaims(pub) |
| 93 |
if optIssuerAccount != "" { |
| 94 |
nuc.IssuerAccount = optIssuerAccount |
| 95 |
} |
| 96 |
ujwt, err := nuc.Encode(akp) |
| 97 |
if err != nil { |
| 98 |
t.Fatalf("Error generating user JWT: %v", err) |
| 99 |
} |
| 100 |
c, cr, l := newClientForServer(s) |
| 101 |
|
| 102 |
// Sign Nonce |
| 103 |
var info nonceInfo |
| 104 |
json.Unmarshal([]byte(l[5:]), &info) |
| 105 |
sigraw, _ := nkp.Sign([]byte(info.Nonce)) |
| 106 |
sig := base64.RawURLEncoding.EncodeToString(sigraw) |
| 107 |
|
| 108 |
cs := fmt.Sprintf("CONNECT {\"jwt\":%q,\"sig\":\"%s\"}\r\nPING\r\n", ujwt, sig) |
| 109 |
return c, cr, cs |
| 110 |
} |
| 111 |
|
| 112 |
func setupJWTTestWithClaims(t *testing.T, nac *jwt.AccountClaims, nuc *jwt.UserClaims, expected string) (*Server, nkeys.KeyPair, *testAsyncClient, *bufio.Reader) { |
| 113 |
t.Helper() |
| 114 |
|
| 115 |
akp, _ := nkeys.CreateAccount() |
| 116 |
apub, _ := akp.PublicKey() |
| 117 |
if nac == nil { |
| 118 |
nac = jwt.NewAccountClaims(apub) |
| 119 |
} else { |
| 120 |
nac.Subject = apub |
| 121 |
} |
| 122 |
ajwt, err := nac.Encode(oKp) |
| 123 |
if err != nil { |
| 124 |
t.Fatalf("Error generating account JWT: %v", err) |
| 125 |
} |
| 126 |
|
| 127 |
nkp, _ := nkeys.CreateUser() |
| 128 |
pub, _ := nkp.PublicKey() |
| 129 |
if nuc == nil { |
| 130 |
nuc = jwt.NewUserClaims(pub) |
| 131 |
} else { |
| 132 |
nuc.Subject = pub |
| 133 |
} |
| 134 |
jwt, err := nuc.Encode(akp) |
| 135 |
if err != nil { |
| 136 |
t.Fatalf("Error generating user JWT: %v", err) |
| 137 |
} |
| 138 |
|
| 139 |
s := opTrustBasicSetup() |
| 140 |
buildMemAccResolver(s) |
| 141 |
addAccountToMemResolver(s, apub, ajwt) |
| 142 |
|
| 143 |
c, cr, l := newClientForServer(s) |
| 144 |
|
| 145 |
// Sign Nonce |
| 146 |
var info nonceInfo |
| 147 |
json.Unmarshal([]byte(l[5:]), &info) |
| 148 |
sigraw, _ := nkp.Sign([]byte(info.Nonce)) |
| 149 |
sig := base64.RawURLEncoding.EncodeToString(sigraw) |
| 150 |
|
| 151 |
// PING needed to flush the +OK/-ERR to us. |
| 152 |
cs := fmt.Sprintf("CONNECT {\"jwt\":%q,\"sig\":\"%s\",\"verbose\":true,\"pedantic\":true}\r\nPING\r\n", jwt, sig) |
| 153 |
wg := sync.WaitGroup{} |
| 154 |
wg.Add(1) |
| 155 |
go func() { |
| 156 |
c.parse([]byte(cs)) |
| 157 |
wg.Done() |
| 158 |
}() |
| 159 |
l, _ = cr.ReadString('\n') |
| 160 |
if !strings.HasPrefix(l, expected) { |
| 161 |
t.Fatalf("Expected %q, got %q", expected, l) |
| 162 |
} |
| 163 |
wg.Wait() |
| 164 |
|
| 165 |
return s, akp, c, cr |
| 166 |
} |
| 167 |
|
| 168 |
func setupJWTTestWitAccountClaims(t *testing.T, nac *jwt.AccountClaims, expected string) (*Server, nkeys.KeyPair, *testAsyncClient, *bufio.Reader) { |
| 169 |
t.Helper() |
| 170 |
return setupJWTTestWithClaims(t, nac, nil, expected) |
| 171 |
} |
| 172 |
|
| 173 |
// This is used in test to create account claims and pass it |
| 174 |
// to setupJWTTestWitAccountClaims. |
| 175 |
func newJWTTestAccountClaims() *jwt.AccountClaims { |
| 176 |
// We call NewAccountClaims() because it sets some defaults. |
| 177 |
// However, this call needs a subject, but the real subject will |
| 178 |
// be set in setupJWTTestWitAccountClaims(). Use some temporary one |
| 179 |
// here. |
| 180 |
return jwt.NewAccountClaims("temp") |
| 181 |
} |
| 182 |
|
| 183 |
func setupJWTTestWithUserClaims(t *testing.T, nuc *jwt.UserClaims, expected string) (*Server, *testAsyncClient, *bufio.Reader) { |
| 184 |
t.Helper() |
| 185 |
s, _, c, cr := setupJWTTestWithClaims(t, nil, nuc, expected) |
| 186 |
return s, c, cr |
| 187 |
} |
| 188 |
|
| 189 |
// This is used in test to create user claims and pass it |
| 190 |
// to setupJWTTestWithUserClaims. |
| 191 |
func newJWTTestUserClaims() *jwt.UserClaims { |
| 192 |
// As of now, tests could simply do &jwt.UserClaims{}, but in |
| 193 |
// case some defaults are later added, we call NewUserClaims(). |
| 194 |
// However, this call needs a subject, but the real subject will |
| 195 |
// be set in setupJWTTestWithUserClaims(). Use some temporary one |
| 196 |
// here. |
| 197 |
return jwt.NewUserClaims("temp") |
| 198 |
} |
| 199 |
|
| 200 |
func TestJWTUser(t *testing.T) { |
| 201 |
s := opTrustBasicSetup() |
| 202 |
defer s.Shutdown() |
| 203 |
|
| 204 |
// Check to make sure we would have an authTimer |
| 205 |
if !s.info.AuthRequired { |
| 206 |
t.Fatalf("Expect the server to require auth") |
| 207 |
} |
| 208 |
|
| 209 |
c, cr, _ := newClientForServer(s) |
| 210 |
defer c.close() |
| 211 |
|
| 212 |
// Don't send jwt field, should fail. |
| 213 |
c.parseAsync("CONNECT {\"verbose\":true,\"pedantic\":true}\r\nPING\r\n") |
| 214 |
l, _ := cr.ReadString('\n') |
| 215 |
if !strings.HasPrefix(l, "-ERR ") { |
| 216 |
t.Fatalf("Expected an error") |
| 217 |
} |
| 218 |
|
| 219 |
okp, _ := nkeys.FromSeed(oSeed) |
| 220 |
|
| 221 |
// Create an account that will be expired. |
| 222 |
akp, _ := nkeys.CreateAccount() |
| 223 |
apub, _ := akp.PublicKey() |
| 224 |
nac := jwt.NewAccountClaims(apub) |
| 225 |
ajwt, err := nac.Encode(okp) |
| 226 |
if err != nil { |
| 227 |
t.Fatalf("Error generating account JWT: %v", err) |
| 228 |
} |
| 229 |
|
| 230 |
c, cr, cs := createClient(t, s, akp) |
| 231 |
defer c.close() |
| 232 |
|
| 233 |
// PING needed to flush the +OK/-ERR to us. |
| 234 |
// This should fail too since no account resolver is defined. |
| 235 |
c.parseAsync(cs) |
| 236 |
l, _ = cr.ReadString('\n') |
| 237 |
if !strings.HasPrefix(l, "-ERR ") { |
| 238 |
t.Fatalf("Expected an error") |
| 239 |
} |
| 240 |
|
| 241 |
// Ok now let's walk through and make sure all is good. |
| 242 |
// We will set the account resolver by hand to a memory resolver. |
| 243 |
buildMemAccResolver(s) |
| 244 |
addAccountToMemResolver(s, apub, ajwt) |
| 245 |
|
| 246 |
c, cr, cs = createClient(t, s, akp) |
| 247 |
defer c.close() |
| 248 |
|
| 249 |
c.parseAsync(cs) |
| 250 |
l, _ = cr.ReadString('\n') |
| 251 |
if !strings.HasPrefix(l, "PONG") { |
| 252 |
t.Fatalf("Expected a PONG, got %q", l) |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
func TestJWTUserBadTrusted(t *testing.T) { |
| 257 |
s := opTrustBasicSetup() |
| 258 |
defer s.Shutdown() |
| 259 |
|
| 260 |
// Check to make sure we would have an authTimer |
| 261 |
if !s.info.AuthRequired { |
| 262 |
t.Fatalf("Expect the server to require auth") |
| 263 |
} |
| 264 |
// Now place bad trusted key |
| 265 |
s.mu.Lock() |
| 266 |
s.trustedKeys = []string{"bad"} |
| 267 |
s.mu.Unlock() |
| 268 |
|
| 269 |
buildMemAccResolver(s) |
| 270 |
|
| 271 |
okp, _ := nkeys.FromSeed(oSeed) |
| 272 |
|
| 273 |
// Create an account that will be expired. |
| 274 |
akp, _ := nkeys.CreateAccount() |
| 275 |
apub, _ := akp.PublicKey() |
| 276 |
nac := jwt.NewAccountClaims(apub) |
| 277 |
ajwt, err := nac.Encode(okp) |
| 278 |
if err != nil { |
| 279 |
t.Fatalf("Error generating account JWT: %v", err) |
| 280 |
} |
| 281 |
addAccountToMemResolver(s, apub, ajwt) |
| 282 |
|
| 283 |
c, cr, cs := createClient(t, s, akp) |
| 284 |
defer c.close() |
| 285 |
c.parseAsync(cs) |
| 286 |
l, _ := cr.ReadString('\n') |
| 287 |
if !strings.HasPrefix(l, "-ERR ") { |
| 288 |
t.Fatalf("Expected an error") |
| 289 |
} |
| 290 |
} |
| 291 |
|
| 292 |
// Test that if a user tries to connect with an expired user JWT we do the right thing. |
| 293 |
func TestJWTUserExpired(t *testing.T) { |
| 294 |
nuc := newJWTTestUserClaims() |
| 295 |
nuc.IssuedAt = time.Now().Add(-10 * time.Second).Unix() |
| 296 |
nuc.Expires = time.Now().Add(-2 * time.Second).Unix() |
| 297 |
s, c, _ := setupJWTTestWithUserClaims(t, nuc, "-ERR ") |
| 298 |
c.close() |
| 299 |
s.Shutdown() |
| 300 |
} |
| 301 |
|
| 302 |
func TestJWTUserExpiresAfterConnect(t *testing.T) { |
| 303 |
nuc := newJWTTestUserClaims() |
| 304 |
now := time.Now() |
| 305 |
nuc.IssuedAt = now.Unix() |
| 306 |
// JWT expirations have one-second resolution. Leave a full second for setup. |
| 307 |
nuc.Expires = now.Unix() + 2 |
| 308 |
s, c, cr := setupJWTTestWithUserClaims(t, nuc, "+OK") |
| 309 |
defer s.Shutdown() |
| 310 |
defer c.close() |
| 311 |
l, err := cr.ReadString('\n') |
| 312 |
if err != nil { |
| 313 |
t.Fatalf("Received %v", err) |
| 314 |
} |
| 315 |
if !strings.HasPrefix(l, "PONG") { |
| 316 |
t.Fatalf("Expected a PONG, got %q", l) |
| 317 |
} |
| 318 |
|
| 319 |
// Expect an expiration error |
| 320 |
l, err = cr.ReadString('\n') |
| 321 |
if err != nil { |
| 322 |
t.Fatalf("Received %v", err) |
| 323 |
} |
| 324 |
if !strings.HasPrefix(l, "-ERR ") { |
| 325 |
t.Fatalf("Expected an error") |
| 326 |
} |
| 327 |
if !strings.Contains(l, "Expired") { |
| 328 |
t.Fatalf("Expected 'Expired' to be in the error") |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
func TestJWTUserPermissionClaims(t *testing.T) { |
| 333 |
nuc := newJWTTestUserClaims() |
| 334 |
nuc.Permissions.Pub.Allow.Add("foo") |
| 335 |
nuc.Permissions.Pub.Allow.Add("bar") |
| 336 |
nuc.Permissions.Pub.Deny.Add("baz") |
| 337 |
nuc.Permissions.Sub.Allow.Add("foo") |
| 338 |
nuc.Permissions.Sub.Allow.Add("bar") |
| 339 |
nuc.Permissions.Sub.Deny.Add("baz") |
| 340 |
|
| 341 |
s, c, _ := setupJWTTestWithUserClaims(t, nuc, "+OK") |
| 342 |
defer s.Shutdown() |
| 343 |
defer c.close() |
| 344 |
|
| 345 |
// Now check client to make sure permissions transferred. |
| 346 |
c.mu.Lock() |
| 347 |
defer c.mu.Unlock() |
| 348 |
|
| 349 |
if c.perms == nil { |
| 350 |
t.Fatalf("Expected client permissions to be set") |
| 351 |
} |
| 352 |
|
| 353 |
if lpa := c.perms.pub.allow.Count(); lpa != 2 { |
| 354 |
t.Fatalf("Expected 2 publish allow subjects, got %d", lpa) |
| 355 |
} |
| 356 |
if lpd := c.perms.pub.deny.Count(); lpd != 1 { |
| 357 |
t.Fatalf("Expected 1 publish deny subjects, got %d", lpd) |
| 358 |
} |
| 359 |
if lsa := c.perms.sub.allow.Count(); lsa != 2 { |
| 360 |
t.Fatalf("Expected 2 subscribe allow subjects, got %d", lsa) |
| 361 |
} |
| 362 |
if lsd := c.perms.sub.deny.Count(); lsd != 1 { |
| 363 |
t.Fatalf("Expected 1 subscribe deny subjects, got %d", lsd) |
| 364 |
} |
| 365 |
} |
| 366 |
|
| 367 |
func TestJWTAccountDefaultPermissionsUpdateRefreshesClients(t *testing.T) { |
| 368 |
nac := newJWTTestAccountClaims() |
| 369 |
nac.DefaultPermissions.Pub.Allow.Add("foo") |
| 370 |
nac.DefaultPermissions.Sub.Allow.Add("foo") |
| 371 |
|
| 372 |
s, _, c, cr := setupJWTTestWitAccountClaims(t, nac, "+OK") |
| 373 |
defer s.Shutdown() |
| 374 |
defer c.close() |
| 375 |
|
| 376 |
if l, _ := cr.ReadString('\n'); !strings.HasPrefix(l, "PONG") { |
| 377 |
t.Fatalf("Expected PONG, got %q", l) |
| 378 |
} |
| 379 |
|
| 380 |
c.mu.Lock() |
| 381 |
acc := c.acc |
| 382 |
require_True(t, c.pubAllowedFullCheck("foo", true, true)) |
| 383 |
require_True(t, c.canSubscribe("foo")) |
| 384 |
c.mu.Unlock() |
| 385 |
require_NotNil(t, acc) |
| 386 |
|
| 387 |
c.parseAsync("SUB foo 1\r\nPING\r\n") |
| 388 |
if l, _ := cr.ReadString('\n'); !strings.HasPrefix(l, "+OK") { |
| 389 |
t.Fatalf("Expected subscription to be accepted, got %q", l) |
| 390 |
} |
| 391 |
if l, _ := cr.ReadString('\n'); !strings.HasPrefix(l, "PONG") { |
| 392 |
t.Fatalf("Expected PONG, got %q", l) |
| 393 |
} |
| 394 |
|
| 395 |
nac = jwt.NewAccountClaims(acc.Name) |
| 396 |
nac.DefaultPermissions.Pub.Allow.Add("bar") |
| 397 |
nac.DefaultPermissions.Sub.Allow.Add("bar") |
| 398 |
ajwt, err := nac.Encode(oKp) |
| 399 |
require_NoError(t, err) |
| 400 |
|
| 401 |
addAccountToMemResolver(s, acc.Name, ajwt) |
| 402 |
s.UpdateAccountClaims(acc, nac) |
| 403 |
|
| 404 |
c.mu.Lock() |
| 405 |
require_False(t, c.pubAllowedFullCheck("foo", true, true)) |
| 406 |
require_True(t, c.pubAllowedFullCheck("bar", true, true)) |
| 407 |
require_False(t, c.canSubscribe("foo")) |
| 408 |
require_True(t, c.canSubscribe("bar")) |
| 409 |
_, ok := c.subs["1"] |
| 410 |
c.mu.Unlock() |
| 411 |
require_False(t, ok) |
| 412 |
|
| 413 |
line, _ := cr.ReadString('\n') |
| 414 |
require_Contains(t, line, `Permissions Violation for Subscription to "foo"`) |
| 415 |
|
| 416 |
c.parseAsync("PUB foo 0\r\n\r\n") |
| 417 |
line, _ = cr.ReadString('\n') |
| 418 |
require_Contains(t, line, `Permissions Violation for Publish to "foo"`) |
| 419 |
} |
| 420 |
|
| 421 |
func TestJWTAccountDefaultPermissionsUpdateKeepsExplicitUserPermissions(t *testing.T) { |
| 422 |
nac := newJWTTestAccountClaims() |
| 423 |
nac.DefaultPermissions.Pub.Allow.Add("foo") |
| 424 |
nac.DefaultPermissions.Sub.Allow.Add("foo") |
| 425 |
|
| 426 |
nuc := newJWTTestUserClaims() |
| 427 |
nuc.Permissions.Pub.Allow.Add("baz") |
| 428 |
nuc.Permissions.Sub.Allow.Add("baz") |
| 429 |
|
| 430 |
s, _, c, cr := setupJWTTestWithClaims(t, nac, nuc, "+OK") |
| 431 |
defer s.Shutdown() |
| 432 |
defer c.close() |
| 433 |
|
| 434 |
if l, _ := cr.ReadString('\n'); !strings.HasPrefix(l, "PONG") { |
| 435 |
t.Fatalf("Expected PONG, got %q", l) |
| 436 |
} |
| 437 |
|
| 438 |
c.mu.Lock() |
| 439 |
acc := c.acc |
| 440 |
require_True(t, c.pubAllowedFullCheck("baz", true, true)) |
| 441 |
require_False(t, c.pubAllowedFullCheck("foo", true, true)) |
| 442 |
require_True(t, c.canSubscribe("baz")) |
| 443 |
require_False(t, c.canSubscribe("foo")) |
| 444 |
c.mu.Unlock() |
| 445 |
require_NotNil(t, acc) |
| 446 |
|
| 447 |
nac = jwt.NewAccountClaims(acc.Name) |
| 448 |
nac.DefaultPermissions.Pub.Allow.Add("bar") |
| 449 |
nac.DefaultPermissions.Sub.Allow.Add("bar") |
| 450 |
ajwt, err := nac.Encode(oKp) |
| 451 |
require_NoError(t, err) |
| 452 |
|
| 453 |
addAccountToMemResolver(s, acc.Name, ajwt) |
| 454 |
s.UpdateAccountClaims(acc, nac) |
| 455 |
|
| 456 |
c.mu.Lock() |
| 457 |
require_True(t, c.pubAllowedFullCheck("baz", true, true)) |
| 458 |
require_False(t, c.pubAllowedFullCheck("bar", true, true)) |
| 459 |
require_True(t, c.canSubscribe("baz")) |
| 460 |
require_False(t, c.canSubscribe("bar")) |
| 461 |
c.mu.Unlock() |
| 462 |
} |
| 463 |
|
| 464 |
func TestJWTUserResponsePermissionClaims(t *testing.T) { |
| 465 |
nuc := newJWTTestUserClaims() |
| 466 |
nuc.Permissions.Resp = &jwt.ResponsePermission{ |
| 467 |
MaxMsgs: 22, |
| 468 |
Expires: 100 * time.Millisecond, |
| 469 |
} |
| 470 |
s, c, _ := setupJWTTestWithUserClaims(t, nuc, "+OK") |
| 471 |
defer s.Shutdown() |
| 472 |
defer c.close() |
| 473 |
|
| 474 |
// Now check client to make sure permissions transferred. |
| 475 |
c.mu.Lock() |
| 476 |
defer c.mu.Unlock() |
| 477 |
|
| 478 |
if c.perms == nil { |
| 479 |
t.Fatalf("Expected client permissions to be set") |
| 480 |
} |
| 481 |
if c.perms.pub.allow == nil { |
| 482 |
t.Fatalf("Expected client perms for pub allow to be non-nil") |
| 483 |
} |
| 484 |
if lpa := c.perms.pub.allow.Count(); lpa != 0 { |
| 485 |
t.Fatalf("Expected 0 publish allow subjects, got %d", lpa) |
| 486 |
} |
| 487 |
if c.perms.resp == nil { |
| 488 |
t.Fatalf("Expected client perms for response permissions to be non-nil") |
| 489 |
} |
| 490 |
if c.perms.resp.MaxMsgs != nuc.Permissions.Resp.MaxMsgs { |
| 491 |
t.Fatalf("Expected client perms for response permissions MaxMsgs to be same as jwt: %d vs %d", |
| 492 |
c.perms.resp.MaxMsgs, nuc.Permissions.Resp.MaxMsgs) |
| 493 |
} |
| 494 |
if c.perms.resp.Expires != nuc.Permissions.Resp.Expires { |
| 495 |
t.Fatalf("Expected client perms for response permissions Expires to be same as jwt: %v vs %v", |
| 496 |
c.perms.resp.Expires, nuc.Permissions.Resp.Expires) |
| 497 |
} |
| 498 |
} |
| 499 |
|
| 500 |
func TestJWTUserResponsePermissionClaimsDefaultValues(t *testing.T) { |
| 501 |
nuc := newJWTTestUserClaims() |
| 502 |
nuc.Permissions.Resp = &jwt.ResponsePermission{} |
| 503 |
s, c, _ := setupJWTTestWithUserClaims(t, nuc, "+OK") |
| 504 |
defer s.Shutdown() |
| 505 |
defer c.close() |
| 506 |
|
| 507 |
// Now check client to make sure permissions transferred |
| 508 |
// and defaults are set. |
| 509 |
c.mu.Lock() |
| 510 |
defer c.mu.Unlock() |
| 511 |
|
| 512 |
if c.perms == nil { |
| 513 |
t.Fatalf("Expected client permissions to be set") |
| 514 |
} |
| 515 |
if c.perms.pub.allow == nil { |
| 516 |
t.Fatalf("Expected client perms for pub allow to be non-nil") |
| 517 |
} |
| 518 |
if lpa := c.perms.pub.allow.Count(); lpa != 0 { |
| 519 |
t.Fatalf("Expected 0 publish allow subjects, got %d", lpa) |
| 520 |
} |
| 521 |
if c.perms.resp == nil { |
| 522 |
t.Fatalf("Expected client perms for response permissions to be non-nil") |
| 523 |
} |
| 524 |
if c.perms.resp.MaxMsgs != DEFAULT_ALLOW_RESPONSE_MAX_MSGS { |
| 525 |
t.Fatalf("Expected client perms for response permissions MaxMsgs to be default %v, got %v", |
| 526 |
DEFAULT_ALLOW_RESPONSE_MAX_MSGS, c.perms.resp.MaxMsgs) |
| 527 |
} |
| 528 |
if c.perms.resp.Expires != DEFAULT_ALLOW_RESPONSE_EXPIRATION { |
| 529 |
t.Fatalf("Expected client perms for response permissions Expires to be default %v, got %v", |
| 530 |
DEFAULT_ALLOW_RESPONSE_EXPIRATION, c.perms.resp.Expires) |
| 531 |
} |
| 532 |
} |
| 533 |
|
| 534 |
func TestJWTUserResponsePermissionClaimsNegativeValues(t *testing.T) { |
| 535 |
nuc := newJWTTestUserClaims() |
| 536 |
nuc.Permissions.Resp = &jwt.ResponsePermission{ |
| 537 |
MaxMsgs: -1, |
| 538 |
Expires: -1 * time.Second, |
| 539 |
} |
| 540 |
s, c, _ := setupJWTTestWithUserClaims(t, nuc, "+OK") |
| 541 |
defer s.Shutdown() |
| 542 |
defer c.close() |
| 543 |
|
| 544 |
// Now check client to make sure permissions transferred |
| 545 |
// and negative values are transferred. |
| 546 |
c.mu.Lock() |
| 547 |
defer c.mu.Unlock() |
| 548 |
|
| 549 |
if c.perms == nil { |
| 550 |
t.Fatalf("Expected client permissions to be set") |
| 551 |
} |
| 552 |
if c.perms.pub.allow == nil { |
| 553 |
t.Fatalf("Expected client perms for pub allow to be non-nil") |
| 554 |
} |
| 555 |
if lpa := c.perms.pub.allow.Count(); lpa != 0 { |
| 556 |
t.Fatalf("Expected 0 publish allow subjects, got %d", lpa) |
| 557 |
} |
| 558 |
if c.perms.resp == nil { |
| 559 |
t.Fatalf("Expected client perms for response permissions to be non-nil") |
| 560 |
} |
| 561 |
if c.perms.resp.MaxMsgs != -1 { |
| 562 |
t.Fatalf("Expected client perms for response permissions MaxMsgs to be %v, got %v", |
| 563 |
-1, c.perms.resp.MaxMsgs) |
| 564 |
} |
| 565 |
if c.perms.resp.Expires != -1*time.Second { |
| 566 |
t.Fatalf("Expected client perms for response permissions Expires to be %v, got %v", |
| 567 |
-1*time.Second, c.perms.resp.Expires) |
| 568 |
} |
| 569 |
} |
| 570 |
|
| 571 |
func TestJWTAccountExpired(t *testing.T) { |
| 572 |
nac := newJWTTestAccountClaims() |
| 573 |
nac.IssuedAt = time.Now().Add(-10 * time.Second).Unix() |
| 574 |
nac.Expires = time.Now().Add(-2 * time.Second).Unix() |
| 575 |
s, _, c, _ := setupJWTTestWitAccountClaims(t, nac, "-ERR ") |
| 576 |
defer s.Shutdown() |
| 577 |
defer c.close() |
| 578 |
} |
| 579 |
|
| 580 |
func TestJWTAccountExpiresAfterConnect(t *testing.T) { |
| 581 |
nac := newJWTTestAccountClaims() |
| 582 |
now := time.Now() |
| 583 |
nac.IssuedAt = now.Add(-10 * time.Second).Unix() |
| 584 |
nac.Expires = now.Round(time.Second).Add(time.Second).Unix() |
| 585 |
s, akp, c, cr := setupJWTTestWitAccountClaims(t, nac, "+OK") |
| 586 |
defer s.Shutdown() |
| 587 |
defer c.close() |
| 588 |
|
| 589 |
apub, _ := akp.PublicKey() |
| 590 |
acc, err := s.LookupAccount(apub) |
| 591 |
if acc == nil || err != nil { |
| 592 |
t.Fatalf("Expected to retrieve the account") |
| 593 |
} |
| 594 |
|
| 595 |
if l, _ := cr.ReadString('\n'); !strings.HasPrefix(l, "PONG") { |
| 596 |
t.Fatalf("Expected PONG, got %q", l) |
| 597 |
} |
| 598 |
|
| 599 |
// Wait for the account to be expired. |
| 600 |
checkFor(t, 3*time.Second, 100*time.Millisecond, func() error { |
| 601 |
if acc.IsExpired() { |
| 602 |
return nil |
| 603 |
} |
| 604 |
return fmt.Errorf("Account not expired yet") |
| 605 |
}) |
| 606 |
|
| 607 |
l, _ := cr.ReadString('\n') |
| 608 |
if !strings.HasPrefix(l, "-ERR ") { |
| 609 |
t.Fatalf("Expected an error, got %q", l) |
| 610 |
} |
| 611 |
if !strings.Contains(l, "Expired") { |
| 612 |
t.Fatalf("Expected 'Expired' to be in the error") |
| 613 |
} |
| 614 |
|
| 615 |
// Now make sure that accounts that have expired return an error. |
| 616 |
c, cr, cs := createClient(t, s, akp) |
| 617 |
defer c.close() |
| 618 |
c.parseAsync(cs) |
| 619 |
l, _ = cr.ReadString('\n') |
| 620 |
if !strings.HasPrefix(l, "-ERR ") { |
| 621 |
t.Fatalf("Expected an error") |
| 622 |
} |
| 623 |
} |
| 624 |
|
| 625 |
func TestJWTAccountRenew(t *testing.T) { |
| 626 |
nac := newJWTTestAccountClaims() |
| 627 |
// Create an account that has expired. |
| 628 |
nac.IssuedAt = time.Now().Add(-10 * time.Second).Unix() |
| 629 |
nac.Expires = time.Now().Add(-2 * time.Second).Unix() |
| 630 |
// Expect an error |
| 631 |
s, akp, c, _ := setupJWTTestWitAccountClaims(t, nac, "-ERR ") |
| 632 |
defer s.Shutdown() |
| 633 |
defer c.close() |
| 634 |
|
| 635 |
okp, _ := nkeys.FromSeed(oSeed) |
| 636 |
apub, _ := akp.PublicKey() |
| 637 |
|
| 638 |
// Now update with new expiration |
| 639 |
nac.IssuedAt = time.Now().Unix() |
| 640 |
nac.Expires = time.Now().Add(5 * time.Second).Unix() |
| 641 |
ajwt, err := nac.Encode(okp) |
| 642 |
if err != nil { |
| 643 |
t.Fatalf("Error generating account JWT: %v", err) |
| 644 |
} |
| 645 |
|
| 646 |
// Update the account |
| 647 |
addAccountToMemResolver(s, apub, ajwt) |
| 648 |
acc, _ := s.LookupAccount(apub) |
| 649 |
if acc == nil { |
| 650 |
t.Fatalf("Expected to retrieve the account") |
| 651 |
} |
| 652 |
s.UpdateAccountClaims(acc, nac) |
| 653 |
|
| 654 |
// Now make sure we can connect. |
| 655 |
c, cr, cs := createClient(t, s, akp) |
| 656 |
defer c.close() |
| 657 |
c.parseAsync(cs) |
| 658 |
if l, _ := cr.ReadString('\n'); !strings.HasPrefix(l, "PONG") { |
| 659 |
t.Fatalf("Expected a PONG, got: %q", l) |
| 660 |
} |
| 661 |
} |
| 662 |
|
| 663 |
func TestJWTAccountRenewFromResolver(t *testing.T) { |
| 664 |
s := opTrustBasicSetup() |
| 665 |
defer s.Shutdown() |
| 666 |
buildMemAccResolver(s) |
| 667 |
|
| 668 |
okp, _ := nkeys.FromSeed(oSeed) |
| 669 |
|
| 670 |
akp, _ := nkeys.CreateAccount() |
| 671 |
apub, _ := akp.PublicKey() |
| 672 |
nac := jwt.NewAccountClaims(apub) |
| 673 |
nac.IssuedAt = time.Now().Add(-10 * time.Second).Unix() |
| 674 |
nac.Expires = time.Now().Add(time.Second).Unix() |
| 675 |
ajwt, err := nac.Encode(okp) |
| 676 |
if err != nil { |
| 677 |
t.Fatalf("Error generating account JWT: %v", err) |
| 678 |
} |
| 679 |
|
| 680 |
addAccountToMemResolver(s, apub, ajwt) |
| 681 |
// Force it to be loaded by the server and start the expiration timer. |
| 682 |
acc, _ := s.LookupAccount(apub) |
| 683 |
if acc == nil { |
| 684 |
t.Fatalf("Could not retrieve account for %q", apub) |
| 685 |
} |
| 686 |
|
| 687 |
// Create a new user |
| 688 |
c, cr, cs := createClient(t, s, akp) |
| 689 |
defer c.close() |
| 690 |
// Wait for expiration. |
| 691 |
time.Sleep(1250 * time.Millisecond) |
| 692 |
|
| 693 |
c.parseAsync(cs) |
| 694 |
l, _ := cr.ReadString('\n') |
| 695 |
if !strings.HasPrefix(l, "-ERR ") { |
| 696 |
t.Fatalf("Expected an error") |
| 697 |
} |
| 698 |
|
| 699 |
// Now update with new expiration |
| 700 |
nac.IssuedAt = time.Now().Unix() |
| 701 |
nac.Expires = time.Now().Add(5 * time.Second).Unix() |
| 702 |
ajwt, err = nac.Encode(okp) |
| 703 |
if err != nil { |
| 704 |
t.Fatalf("Error generating account JWT: %v", err) |
| 705 |
} |
| 706 |
|
| 707 |
// Update the account |
| 708 |
addAccountToMemResolver(s, apub, ajwt) |
| 709 |
// Make sure the too quick update suppression does not bite us. |
| 710 |
acc.mu.Lock() |
| 711 |
acc.updated = time.Now().UTC().Add(-1 * time.Hour) |
| 712 |
acc.mu.Unlock() |
| 713 |
|
| 714 |
// Do not update the account directly. The resolver should |
| 715 |
// happen automatically. |
| 716 |
|
| 717 |
// Now make sure we can connect. |
| 718 |
c, cr, cs = createClient(t, s, akp) |
| 719 |
defer c.close() |
| 720 |
c.parseAsync(cs) |
| 721 |
l, _ = cr.ReadString('\n') |
| 722 |
if !strings.HasPrefix(l, "PONG") { |
| 723 |
t.Fatalf("Expected a PONG, got: %q", l) |
| 724 |
} |
| 725 |
} |
| 726 |
|
| 727 |
func TestJWTAccountBasicImportExport(t *testing.T) { |
| 728 |
s := opTrustBasicSetup() |
| 729 |
defer s.Shutdown() |
| 730 |
buildMemAccResolver(s) |
| 731 |
|
| 732 |
okp, _ := nkeys.FromSeed(oSeed) |
| 733 |
|
| 734 |
// Create accounts and imports/exports. |
| 735 |
fooKP, _ := nkeys.CreateAccount() |
| 736 |
fooPub, _ := fooKP.PublicKey() |
| 737 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 738 |
|
| 739 |
// Now create Exports. |
| 740 |
streamExport := &jwt.Export{Subject: "foo", Type: jwt.Stream} |
| 741 |
streamExport2 := &jwt.Export{Subject: "private", Type: jwt.Stream, TokenReq: true} |
| 742 |
serviceExport := &jwt.Export{Subject: "req.echo", Type: jwt.Service, TokenReq: true} |
| 743 |
serviceExport2 := &jwt.Export{Subject: "req.add", Type: jwt.Service, TokenReq: true} |
| 744 |
|
| 745 |
fooAC.Exports.Add(streamExport, streamExport2, serviceExport, serviceExport2) |
| 746 |
fooJWT, err := fooAC.Encode(okp) |
| 747 |
if err != nil { |
| 748 |
t.Fatalf("Error generating account JWT: %v", err) |
| 749 |
} |
| 750 |
|
| 751 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 752 |
|
| 753 |
acc, _ := s.LookupAccount(fooPub) |
| 754 |
if acc == nil { |
| 755 |
t.Fatalf("Expected to retrieve the account") |
| 756 |
} |
| 757 |
|
| 758 |
// Check to make sure exports transferred over. |
| 759 |
if les := len(acc.exports.streams); les != 2 { |
| 760 |
t.Fatalf("Expected exports streams len of 2, got %d", les) |
| 761 |
} |
| 762 |
if les := len(acc.exports.services); les != 2 { |
| 763 |
t.Fatalf("Expected exports services len of 2, got %d", les) |
| 764 |
} |
| 765 |
_, ok := acc.exports.streams["foo"] |
| 766 |
if !ok { |
| 767 |
t.Fatalf("Expected to map a stream export") |
| 768 |
} |
| 769 |
se, ok := acc.exports.services["req.echo"] |
| 770 |
if !ok || se == nil { |
| 771 |
t.Fatalf("Expected to map a service export") |
| 772 |
} |
| 773 |
if !se.tokenReq { |
| 774 |
t.Fatalf("Expected the service export to require tokens") |
| 775 |
} |
| 776 |
|
| 777 |
barKP, _ := nkeys.CreateAccount() |
| 778 |
barPub, _ := barKP.PublicKey() |
| 779 |
barAC := jwt.NewAccountClaims(barPub) |
| 780 |
|
| 781 |
streamImport := &jwt.Import{Account: fooPub, Subject: "foo", To: "import.foo", Type: jwt.Stream} |
| 782 |
serviceImport := &jwt.Import{Account: fooPub, Subject: "req.echo", Type: jwt.Service} |
| 783 |
barAC.Imports.Add(streamImport, serviceImport) |
| 784 |
barJWT, err := barAC.Encode(okp) |
| 785 |
if err != nil { |
| 786 |
t.Fatalf("Error generating account JWT: %v", err) |
| 787 |
} |
| 788 |
addAccountToMemResolver(s, barPub, barJWT) |
| 789 |
|
| 790 |
acc, _ = s.LookupAccount(barPub) |
| 791 |
if acc == nil { |
| 792 |
t.Fatalf("Expected to retrieve the account") |
| 793 |
} |
| 794 |
if les := len(acc.imports.streams); les != 1 { |
| 795 |
t.Fatalf("Expected imports streams len of 1, got %d", les) |
| 796 |
} |
| 797 |
// Our service import should have failed without a token. |
| 798 |
if les := len(acc.imports.services); les != 0 { |
| 799 |
t.Fatalf("Expected imports services len of 0, got %d", les) |
| 800 |
} |
| 801 |
|
| 802 |
// Now add in a bad activation token. |
| 803 |
barAC = jwt.NewAccountClaims(barPub) |
| 804 |
serviceImport = &jwt.Import{Account: fooPub, Subject: "req.echo", Token: "not a token", Type: jwt.Service} |
| 805 |
barAC.Imports.Add(serviceImport) |
| 806 |
barJWT, err = barAC.Encode(okp) |
| 807 |
if err != nil { |
| 808 |
t.Fatalf("Error generating account JWT: %v", err) |
| 809 |
} |
| 810 |
addAccountToMemResolver(s, barPub, barJWT) |
| 811 |
|
| 812 |
s.UpdateAccountClaims(acc, barAC) |
| 813 |
|
| 814 |
// Our service import should have failed with a bad token. |
| 815 |
if les := len(acc.imports.services); les != 0 { |
| 816 |
t.Fatalf("Expected imports services len of 0, got %d", les) |
| 817 |
} |
| 818 |
|
| 819 |
// Now make a correct one. |
| 820 |
barAC = jwt.NewAccountClaims(barPub) |
| 821 |
serviceImport = &jwt.Import{Account: fooPub, Subject: "req.echo", Type: jwt.Service} |
| 822 |
|
| 823 |
activation := jwt.NewActivationClaims(barPub) |
| 824 |
activation.ImportSubject = "req.echo" |
| 825 |
activation.ImportType = jwt.Service |
| 826 |
actJWT, err := activation.Encode(fooKP) |
| 827 |
if err != nil { |
| 828 |
t.Fatalf("Error generating activation token: %v", err) |
| 829 |
} |
| 830 |
serviceImport.Token = actJWT |
| 831 |
barAC.Imports.Add(serviceImport) |
| 832 |
barJWT, err = barAC.Encode(okp) |
| 833 |
if err != nil { |
| 834 |
t.Fatalf("Error generating account JWT: %v", err) |
| 835 |
} |
| 836 |
|
| 837 |
vr := jwt.ValidationResults{} |
| 838 |
barAC.Validate(&vr) |
| 839 |
if vr.IsBlocking(true) { |
| 840 |
t.Fatalf("Error generating account JWT: %v", vr) |
| 841 |
} |
| 842 |
|
| 843 |
addAccountToMemResolver(s, barPub, barJWT) |
| 844 |
s.UpdateAccountClaims(acc, barAC) |
| 845 |
// Our service import should have succeeded. |
| 846 |
if les := len(acc.imports.services); les != 1 { |
| 847 |
t.Fatalf("Expected imports services len of 1, got %d", les) |
| 848 |
} |
| 849 |
|
| 850 |
// Now streams |
| 851 |
barAC = jwt.NewAccountClaims(barPub) |
| 852 |
streamImport = &jwt.Import{Account: fooPub, Subject: "private", To: "import.private", Type: jwt.Stream} |
| 853 |
|
| 854 |
barAC.Imports.Add(streamImport) |
| 855 |
barJWT, err = barAC.Encode(okp) |
| 856 |
if err != nil { |
| 857 |
t.Fatalf("Error generating account JWT: %v", err) |
| 858 |
} |
| 859 |
addAccountToMemResolver(s, barPub, barJWT) |
| 860 |
s.UpdateAccountClaims(acc, barAC) |
| 861 |
// Our stream import should have not succeeded. |
| 862 |
if les := len(acc.imports.streams); les != 0 { |
| 863 |
t.Fatalf("Expected imports services len of 0, got %d", les) |
| 864 |
} |
| 865 |
|
| 866 |
// Now add in activation. |
| 867 |
barAC = jwt.NewAccountClaims(barPub) |
| 868 |
streamImport = &jwt.Import{Account: fooPub, Subject: "private", To: "import.private", Type: jwt.Stream} |
| 869 |
|
| 870 |
activation = jwt.NewActivationClaims(barPub) |
| 871 |
activation.ImportSubject = "private" |
| 872 |
activation.ImportType = jwt.Stream |
| 873 |
actJWT, err = activation.Encode(fooKP) |
| 874 |
if err != nil { |
| 875 |
t.Fatalf("Error generating activation token: %v", err) |
| 876 |
} |
| 877 |
streamImport.Token = actJWT |
| 878 |
barAC.Imports.Add(streamImport) |
| 879 |
barJWT, err = barAC.Encode(okp) |
| 880 |
if err != nil { |
| 881 |
t.Fatalf("Error generating account JWT: %v", err) |
| 882 |
} |
| 883 |
addAccountToMemResolver(s, barPub, barJWT) |
| 884 |
s.UpdateAccountClaims(acc, barAC) |
| 885 |
// Our stream import should have not succeeded. |
| 886 |
if les := len(acc.imports.streams); les != 1 { |
| 887 |
t.Fatalf("Expected imports services len of 1, got %d", les) |
| 888 |
} |
| 889 |
} |
| 890 |
|
| 891 |
func TestJWTAccountExportWithResponseType(t *testing.T) { |
| 892 |
s := opTrustBasicSetup() |
| 893 |
defer s.Shutdown() |
| 894 |
buildMemAccResolver(s) |
| 895 |
|
| 896 |
okp, _ := nkeys.FromSeed(oSeed) |
| 897 |
|
| 898 |
// Create accounts and imports/exports. |
| 899 |
fooKP, _ := nkeys.CreateAccount() |
| 900 |
fooPub, _ := fooKP.PublicKey() |
| 901 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 902 |
|
| 903 |
// Now create Exports. |
| 904 |
serviceStreamExport := &jwt.Export{Subject: "test.stream", Type: jwt.Service, ResponseType: jwt.ResponseTypeStream, TokenReq: false} |
| 905 |
serviceChunkExport := &jwt.Export{Subject: "test.chunk", Type: jwt.Service, ResponseType: jwt.ResponseTypeChunked, TokenReq: false} |
| 906 |
serviceSingletonExport := &jwt.Export{Subject: "test.single", Type: jwt.Service, ResponseType: jwt.ResponseTypeSingleton, TokenReq: true} |
| 907 |
serviceDefExport := &jwt.Export{Subject: "test.def", Type: jwt.Service, TokenReq: true} |
| 908 |
serviceOldExport := &jwt.Export{Subject: "test.old", Type: jwt.Service, TokenReq: false} |
| 909 |
|
| 910 |
fooAC.Exports.Add(serviceStreamExport, serviceSingletonExport, serviceChunkExport, serviceDefExport, serviceOldExport) |
| 911 |
fooJWT, err := fooAC.Encode(okp) |
| 912 |
if err != nil { |
| 913 |
t.Fatalf("Error generating account JWT: %v", err) |
| 914 |
} |
| 915 |
|
| 916 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 917 |
|
| 918 |
fooAcc, _ := s.LookupAccount(fooPub) |
| 919 |
if fooAcc == nil { |
| 920 |
t.Fatalf("Expected to retrieve the account") |
| 921 |
} |
| 922 |
|
| 923 |
services := fooAcc.exports.services |
| 924 |
|
| 925 |
if len(services) != 5 { |
| 926 |
t.Fatalf("Expected 4 services") |
| 927 |
} |
| 928 |
|
| 929 |
se, ok := services["test.stream"] |
| 930 |
if !ok || se == nil { |
| 931 |
t.Fatalf("Expected to map a service export") |
| 932 |
} |
| 933 |
if se.tokenReq { |
| 934 |
t.Fatalf("Expected the service export to not require tokens") |
| 935 |
} |
| 936 |
if se.respType != Streamed { |
| 937 |
t.Fatalf("Expected the service export to respond with a stream") |
| 938 |
} |
| 939 |
|
| 940 |
se, ok = services["test.chunk"] |
| 941 |
if !ok || se == nil { |
| 942 |
t.Fatalf("Expected to map a service export") |
| 943 |
} |
| 944 |
if se.tokenReq { |
| 945 |
t.Fatalf("Expected the service export to not require tokens") |
| 946 |
} |
| 947 |
if se.respType != Chunked { |
| 948 |
t.Fatalf("Expected the service export to respond with a stream") |
| 949 |
} |
| 950 |
|
| 951 |
se, ok = services["test.def"] |
| 952 |
if !ok || se == nil { |
| 953 |
t.Fatalf("Expected to map a service export") |
| 954 |
} |
| 955 |
if !se.tokenReq { |
| 956 |
t.Fatalf("Expected the service export to not require tokens") |
| 957 |
} |
| 958 |
if se.respType != Singleton { |
| 959 |
t.Fatalf("Expected the service export to respond with a stream") |
| 960 |
} |
| 961 |
|
| 962 |
se, ok = services["test.single"] |
| 963 |
if !ok || se == nil { |
| 964 |
t.Fatalf("Expected to map a service export") |
| 965 |
} |
| 966 |
if !se.tokenReq { |
| 967 |
t.Fatalf("Expected the service export to not require tokens") |
| 968 |
} |
| 969 |
if se.respType != Singleton { |
| 970 |
t.Fatalf("Expected the service export to respond with a stream") |
| 971 |
} |
| 972 |
|
| 973 |
se, ok = services["test.old"] |
| 974 |
if !ok || se == nil || len(se.approved) > 0 { |
| 975 |
t.Fatalf("Service with a singleton response and no tokens should not be nil and have no approvals") |
| 976 |
} |
| 977 |
} |
| 978 |
|
| 979 |
func expectPong(t *testing.T, cr *bufio.Reader) { |
| 980 |
t.Helper() |
| 981 |
l, _ := cr.ReadString('\n') |
| 982 |
if !strings.HasPrefix(l, "PONG") { |
| 983 |
t.Fatalf("Expected a PONG, got %q", l) |
| 984 |
} |
| 985 |
} |
| 986 |
|
| 987 |
func expectMsg(t *testing.T, cr *bufio.Reader, sub, payload string) { |
| 988 |
t.Helper() |
| 989 |
l, _ := cr.ReadString('\n') |
| 990 |
expected := "MSG " + sub |
| 991 |
if !strings.HasPrefix(l, expected) { |
| 992 |
t.Fatalf("Expected %q, got %q", expected, l) |
| 993 |
} |
| 994 |
l, _ = cr.ReadString('\n') |
| 995 |
if l != payload+"\r\n" { |
| 996 |
t.Fatalf("Expected %q, got %q", payload, l) |
| 997 |
} |
| 998 |
expectPong(t, cr) |
| 999 |
} |
| 1000 |
|
| 1001 |
func TestJWTAccountImportExportUpdates(t *testing.T) { |
| 1002 |
s := opTrustBasicSetup() |
| 1003 |
defer s.Shutdown() |
| 1004 |
buildMemAccResolver(s) |
| 1005 |
|
| 1006 |
okp, _ := nkeys.FromSeed(oSeed) |
| 1007 |
|
| 1008 |
// Create accounts and imports/exports. |
| 1009 |
fooKP, _ := nkeys.CreateAccount() |
| 1010 |
fooPub, _ := fooKP.PublicKey() |
| 1011 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 1012 |
streamExport := &jwt.Export{Subject: "foo", Type: jwt.Stream} |
| 1013 |
|
| 1014 |
fooAC.Exports.Add(streamExport) |
| 1015 |
fooJWT, err := fooAC.Encode(okp) |
| 1016 |
if err != nil { |
| 1017 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1018 |
} |
| 1019 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1020 |
|
| 1021 |
barKP, _ := nkeys.CreateAccount() |
| 1022 |
barPub, _ := barKP.PublicKey() |
| 1023 |
barAC := jwt.NewAccountClaims(barPub) |
| 1024 |
streamImport := &jwt.Import{Account: fooPub, Subject: "foo", To: "import", Type: jwt.Stream} |
| 1025 |
|
| 1026 |
barAC.Imports.Add(streamImport) |
| 1027 |
barJWT, err := barAC.Encode(okp) |
| 1028 |
if err != nil { |
| 1029 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1030 |
} |
| 1031 |
addAccountToMemResolver(s, barPub, barJWT) |
| 1032 |
|
| 1033 |
// Create a client. |
| 1034 |
c, cr, cs := createClient(t, s, barKP) |
| 1035 |
defer c.close() |
| 1036 |
|
| 1037 |
c.parseAsync(cs) |
| 1038 |
expectPong(t, cr) |
| 1039 |
|
| 1040 |
c.parseAsync("SUB import.foo 1\r\nPING\r\n") |
| 1041 |
expectPong(t, cr) |
| 1042 |
|
| 1043 |
checkShadow := func(expected int) { |
| 1044 |
t.Helper() |
| 1045 |
c.mu.Lock() |
| 1046 |
defer c.mu.Unlock() |
| 1047 |
sub := c.subs["1"] |
| 1048 |
if ls := len(sub.shadow); ls != expected { |
| 1049 |
t.Fatalf("Expected shadows to be %d, got %d", expected, ls) |
| 1050 |
} |
| 1051 |
} |
| 1052 |
|
| 1053 |
// We created a SUB on foo which should create a shadow subscription. |
| 1054 |
checkShadow(1) |
| 1055 |
|
| 1056 |
// Now update bar and remove the import which should make the shadow go away. |
| 1057 |
barAC = jwt.NewAccountClaims(barPub) |
| 1058 |
barJWT, _ = barAC.Encode(okp) |
| 1059 |
addAccountToMemResolver(s, barPub, barJWT) |
| 1060 |
acc, _ := s.LookupAccount(barPub) |
| 1061 |
s.UpdateAccountClaims(acc, barAC) |
| 1062 |
|
| 1063 |
checkShadow(0) |
| 1064 |
|
| 1065 |
// Now add it back and make sure the shadow comes back. |
| 1066 |
streamImport = &jwt.Import{Account: string(fooPub), Subject: "foo", To: "import", Type: jwt.Stream} |
| 1067 |
barAC.Imports.Add(streamImport) |
| 1068 |
barJWT, _ = barAC.Encode(okp) |
| 1069 |
addAccountToMemResolver(s, barPub, barJWT) |
| 1070 |
s.UpdateAccountClaims(acc, barAC) |
| 1071 |
|
| 1072 |
checkShadow(1) |
| 1073 |
|
| 1074 |
// Now change export and make sure it goes away as well. So no exports anymore. |
| 1075 |
fooAC = jwt.NewAccountClaims(fooPub) |
| 1076 |
fooJWT, _ = fooAC.Encode(okp) |
| 1077 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1078 |
acc, _ = s.LookupAccount(fooPub) |
| 1079 |
s.UpdateAccountClaims(acc, fooAC) |
| 1080 |
checkShadow(0) |
| 1081 |
|
| 1082 |
// Now add it in but with permission required. |
| 1083 |
streamExport = &jwt.Export{Subject: "foo", Type: jwt.Stream, TokenReq: true} |
| 1084 |
fooAC.Exports.Add(streamExport) |
| 1085 |
fooJWT, _ = fooAC.Encode(okp) |
| 1086 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1087 |
s.UpdateAccountClaims(acc, fooAC) |
| 1088 |
|
| 1089 |
checkShadow(0) |
| 1090 |
|
| 1091 |
// Now put it back as normal. |
| 1092 |
fooAC = jwt.NewAccountClaims(fooPub) |
| 1093 |
streamExport = &jwt.Export{Subject: "foo", Type: jwt.Stream} |
| 1094 |
fooAC.Exports.Add(streamExport) |
| 1095 |
fooJWT, _ = fooAC.Encode(okp) |
| 1096 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1097 |
s.UpdateAccountClaims(acc, fooAC) |
| 1098 |
|
| 1099 |
checkShadow(1) |
| 1100 |
} |
| 1101 |
|
| 1102 |
func TestJWTAccountImportActivationExpires(t *testing.T) { |
| 1103 |
s := opTrustBasicSetup() |
| 1104 |
defer s.Shutdown() |
| 1105 |
buildMemAccResolver(s) |
| 1106 |
|
| 1107 |
okp, _ := nkeys.FromSeed(oSeed) |
| 1108 |
|
| 1109 |
// Create accounts and imports/exports. |
| 1110 |
fooKP, _ := nkeys.CreateAccount() |
| 1111 |
fooPub, _ := fooKP.PublicKey() |
| 1112 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 1113 |
streamExport := &jwt.Export{Subject: "foo", Type: jwt.Stream, TokenReq: true} |
| 1114 |
fooAC.Exports.Add(streamExport) |
| 1115 |
|
| 1116 |
fooJWT, err := fooAC.Encode(okp) |
| 1117 |
if err != nil { |
| 1118 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1119 |
} |
| 1120 |
|
| 1121 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1122 |
acc, _ := s.LookupAccount(fooPub) |
| 1123 |
if acc == nil { |
| 1124 |
t.Fatalf("Expected to retrieve the account") |
| 1125 |
} |
| 1126 |
|
| 1127 |
barKP, _ := nkeys.CreateAccount() |
| 1128 |
barPub, _ := barKP.PublicKey() |
| 1129 |
barAC := jwt.NewAccountClaims(barPub) |
| 1130 |
streamImport := &jwt.Import{Account: fooPub, Subject: "foo", To: "import.", Type: jwt.Stream} |
| 1131 |
|
| 1132 |
activation := jwt.NewActivationClaims(barPub) |
| 1133 |
activation.ImportSubject = "foo" |
| 1134 |
activation.ImportType = jwt.Stream |
| 1135 |
now := time.Now() |
| 1136 |
activation.IssuedAt = now.Add(-10 * time.Second).Unix() |
| 1137 |
// These are second resolution. So round up before adding a second. |
| 1138 |
activation.Expires = now.Round(time.Second).Add(time.Second).Unix() |
| 1139 |
actJWT, err := activation.Encode(fooKP) |
| 1140 |
if err != nil { |
| 1141 |
t.Fatalf("Error generating activation token: %v", err) |
| 1142 |
} |
| 1143 |
streamImport.Token = actJWT |
| 1144 |
barAC.Imports.Add(streamImport) |
| 1145 |
barJWT, err := barAC.Encode(okp) |
| 1146 |
if err != nil { |
| 1147 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1148 |
} |
| 1149 |
addAccountToMemResolver(s, barPub, barJWT) |
| 1150 |
if acc, _ := s.LookupAccount(barPub); acc == nil { |
| 1151 |
t.Fatalf("Expected to retrieve the account") |
| 1152 |
} |
| 1153 |
|
| 1154 |
// Create a client. |
| 1155 |
c, cr, cs := createClient(t, s, barKP) |
| 1156 |
defer c.close() |
| 1157 |
|
| 1158 |
c.parseAsync(cs) |
| 1159 |
expectPong(t, cr) |
| 1160 |
|
| 1161 |
c.parseAsync("SUB import.foo 1\r\nPING\r\n") |
| 1162 |
expectPong(t, cr) |
| 1163 |
|
| 1164 |
checkShadow := func(t *testing.T, expected int) { |
| 1165 |
t.Helper() |
| 1166 |
checkFor(t, 3*time.Second, 15*time.Millisecond, func() error { |
| 1167 |
c.mu.Lock() |
| 1168 |
defer c.mu.Unlock() |
| 1169 |
sub := c.subs["1"] |
| 1170 |
if ls := len(sub.shadow); ls != expected { |
| 1171 |
return fmt.Errorf("Expected shadows to be %d, got %d", expected, ls) |
| 1172 |
} |
| 1173 |
return nil |
| 1174 |
}) |
| 1175 |
} |
| 1176 |
|
| 1177 |
// We created a SUB on foo which should create a shadow subscription. |
| 1178 |
checkShadow(t, 1) |
| 1179 |
|
| 1180 |
time.Sleep(1250 * time.Millisecond) |
| 1181 |
|
| 1182 |
// Should have expired and been removed. |
| 1183 |
checkShadow(t, 0) |
| 1184 |
} |
| 1185 |
|
| 1186 |
func TestJWTAccountLimitsSubs(t *testing.T) { |
| 1187 |
fooAC := newJWTTestAccountClaims() |
| 1188 |
fooAC.Limits.Subs = 10 |
| 1189 |
s, fooKP, c, _ := setupJWTTestWitAccountClaims(t, fooAC, "+OK") |
| 1190 |
defer s.Shutdown() |
| 1191 |
defer c.close() |
| 1192 |
|
| 1193 |
okp, _ := nkeys.FromSeed(oSeed) |
| 1194 |
fooPub, _ := fooKP.PublicKey() |
| 1195 |
|
| 1196 |
// Create a client. |
| 1197 |
c, cr, cs := createClient(t, s, fooKP) |
| 1198 |
defer c.close() |
| 1199 |
|
| 1200 |
c.parseAsync(cs) |
| 1201 |
expectPong(t, cr) |
| 1202 |
|
| 1203 |
// Check to make sure we have the limit set. |
| 1204 |
// Account first |
| 1205 |
fooAcc, _ := s.LookupAccount(fooPub) |
| 1206 |
fooAcc.mu.RLock() |
| 1207 |
if fooAcc.msubs != 10 { |
| 1208 |
fooAcc.mu.RUnlock() |
| 1209 |
t.Fatalf("Expected account to have msubs of 10, got %d", fooAcc.msubs) |
| 1210 |
} |
| 1211 |
fooAcc.mu.RUnlock() |
| 1212 |
// Now test that the client has limits too. |
| 1213 |
c.mu.Lock() |
| 1214 |
if c.msubs != 10 { |
| 1215 |
c.mu.Unlock() |
| 1216 |
t.Fatalf("Expected client msubs to be 10, got %d", c.msubs) |
| 1217 |
} |
| 1218 |
c.mu.Unlock() |
| 1219 |
|
| 1220 |
// Now make sure its enforced. |
| 1221 |
/// These should all work ok. |
| 1222 |
for i := 0; i < 10; i++ { |
| 1223 |
c.parseAsync(fmt.Sprintf("SUB foo %d\r\nPING\r\n", i)) |
| 1224 |
expectPong(t, cr) |
| 1225 |
} |
| 1226 |
|
| 1227 |
// This one should fail. |
| 1228 |
c.parseAsync("SUB foo 22\r\n") |
| 1229 |
l, _ := cr.ReadString('\n') |
| 1230 |
if !strings.HasPrefix(l, "-ERR") { |
| 1231 |
t.Fatalf("Expected an ERR, got: %v", l) |
| 1232 |
} |
| 1233 |
if !strings.Contains(l, "maximum subscriptions exceeded") { |
| 1234 |
t.Fatalf("Expected an ERR for max subscriptions exceeded, got: %v", l) |
| 1235 |
} |
| 1236 |
|
| 1237 |
// Now update the claims and expect if max is lower to be disconnected. |
| 1238 |
fooAC.Limits.Subs = 5 |
| 1239 |
fooJWT, err := fooAC.Encode(okp) |
| 1240 |
if err != nil { |
| 1241 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1242 |
} |
| 1243 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1244 |
s.UpdateAccountClaims(fooAcc, fooAC) |
| 1245 |
l, _ = cr.ReadString('\n') |
| 1246 |
if !strings.HasPrefix(l, "-ERR") { |
| 1247 |
t.Fatalf("Expected an ERR, got: %v", l) |
| 1248 |
} |
| 1249 |
if !strings.Contains(l, "maximum subscriptions exceeded") { |
| 1250 |
t.Fatalf("Expected an ERR for max subscriptions exceeded, got: %v", l) |
| 1251 |
} |
| 1252 |
} |
| 1253 |
|
| 1254 |
func TestJWTAccountLimitsSubsButServerOverrides(t *testing.T) { |
| 1255 |
s := opTrustBasicSetup() |
| 1256 |
defer s.Shutdown() |
| 1257 |
buildMemAccResolver(s) |
| 1258 |
|
| 1259 |
// override with server setting of 2. |
| 1260 |
opts := s.getOpts() |
| 1261 |
opts.MaxSubs = 2 |
| 1262 |
|
| 1263 |
okp, _ := nkeys.FromSeed(oSeed) |
| 1264 |
|
| 1265 |
// Create accounts and imports/exports. |
| 1266 |
fooKP, _ := nkeys.CreateAccount() |
| 1267 |
fooPub, _ := fooKP.PublicKey() |
| 1268 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 1269 |
fooAC.Limits.Subs = 10 |
| 1270 |
fooJWT, err := fooAC.Encode(okp) |
| 1271 |
if err != nil { |
| 1272 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1273 |
} |
| 1274 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1275 |
fooAcc, _ := s.LookupAccount(fooPub) |
| 1276 |
fooAcc.mu.RLock() |
| 1277 |
if fooAcc.msubs != 10 { |
| 1278 |
fooAcc.mu.RUnlock() |
| 1279 |
t.Fatalf("Expected account to have msubs of 10, got %d", fooAcc.msubs) |
| 1280 |
} |
| 1281 |
fooAcc.mu.RUnlock() |
| 1282 |
|
| 1283 |
// Create a client. |
| 1284 |
c, cr, cs := createClient(t, s, fooKP) |
| 1285 |
defer c.close() |
| 1286 |
|
| 1287 |
c.parseAsync(cs) |
| 1288 |
expectPong(t, cr) |
| 1289 |
|
| 1290 |
c.parseAsync("SUB foo 1\r\nSUB bar 2\r\nSUB baz 3\r\nPING\r\n") |
| 1291 |
l, _ := cr.ReadString('\n') |
| 1292 |
|
| 1293 |
if !strings.HasPrefix(l, "-ERR ") { |
| 1294 |
t.Fatalf("Expected an error") |
| 1295 |
} |
| 1296 |
if !strings.Contains(l, "maximum subscriptions exceeded") { |
| 1297 |
t.Fatalf("Expected an ERR for max subscriptions exceeded, got: %v", l) |
| 1298 |
} |
| 1299 |
// Read last PONG so does not hold up test. |
| 1300 |
cr.ReadString('\n') |
| 1301 |
} |
| 1302 |
|
| 1303 |
func TestJWTAccountLimitsMaxPayload(t *testing.T) { |
| 1304 |
fooAC := newJWTTestAccountClaims() |
| 1305 |
fooAC.Limits.Payload = 8 |
| 1306 |
s, fooKP, c, _ := setupJWTTestWitAccountClaims(t, fooAC, "+OK") |
| 1307 |
defer s.Shutdown() |
| 1308 |
defer c.close() |
| 1309 |
|
| 1310 |
fooPub, _ := fooKP.PublicKey() |
| 1311 |
|
| 1312 |
// Create a client. |
| 1313 |
c, cr, cs := createClient(t, s, fooKP) |
| 1314 |
defer c.close() |
| 1315 |
|
| 1316 |
c.parseAsync(cs) |
| 1317 |
expectPong(t, cr) |
| 1318 |
|
| 1319 |
// Check to make sure we have the limit set. |
| 1320 |
// Account first |
| 1321 |
fooAcc, _ := s.LookupAccount(fooPub) |
| 1322 |
fooAcc.mu.RLock() |
| 1323 |
if fooAcc.mpay != 8 { |
| 1324 |
fooAcc.mu.RUnlock() |
| 1325 |
t.Fatalf("Expected account to have mpay of 8, got %d", fooAcc.mpay) |
| 1326 |
} |
| 1327 |
fooAcc.mu.RUnlock() |
| 1328 |
// Now test that the client has limits too. |
| 1329 |
c.mu.Lock() |
| 1330 |
if c.mpay != 8 { |
| 1331 |
c.mu.Unlock() |
| 1332 |
t.Fatalf("Expected client to have mpay of 10, got %d", c.mpay) |
| 1333 |
} |
| 1334 |
c.mu.Unlock() |
| 1335 |
|
| 1336 |
c.parseAsync("PUB foo 4\r\nXXXX\r\nPING\r\n") |
| 1337 |
expectPong(t, cr) |
| 1338 |
|
| 1339 |
c.parseAsync("PUB foo 10\r\nXXXXXXXXXX\r\nPING\r\n") |
| 1340 |
l, _ := cr.ReadString('\n') |
| 1341 |
if !strings.HasPrefix(l, "-ERR ") { |
| 1342 |
t.Fatalf("Expected an error") |
| 1343 |
} |
| 1344 |
if !strings.Contains(l, "Maximum Payload") { |
| 1345 |
t.Fatalf("Expected an ERR for max payload violation, got: %v", l) |
| 1346 |
} |
| 1347 |
} |
| 1348 |
|
| 1349 |
func TestJWTAccountLimitsMaxPayloadButServerOverrides(t *testing.T) { |
| 1350 |
s := opTrustBasicSetup() |
| 1351 |
defer s.Shutdown() |
| 1352 |
buildMemAccResolver(s) |
| 1353 |
|
| 1354 |
// override with server setting of 4. |
| 1355 |
opts := s.getOpts() |
| 1356 |
opts.MaxPayload = 4 |
| 1357 |
|
| 1358 |
okp, _ := nkeys.FromSeed(oSeed) |
| 1359 |
|
| 1360 |
// Create accounts and imports/exports. |
| 1361 |
fooKP, _ := nkeys.CreateAccount() |
| 1362 |
fooPub, _ := fooKP.PublicKey() |
| 1363 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 1364 |
fooAC.Limits.Payload = 8 |
| 1365 |
fooJWT, err := fooAC.Encode(okp) |
| 1366 |
if err != nil { |
| 1367 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1368 |
} |
| 1369 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1370 |
|
| 1371 |
// Create a client. |
| 1372 |
c, cr, cs := createClient(t, s, fooKP) |
| 1373 |
defer c.close() |
| 1374 |
|
| 1375 |
c.parseAsync(cs) |
| 1376 |
expectPong(t, cr) |
| 1377 |
|
| 1378 |
c.parseAsync("PUB foo 6\r\nXXXXXX\r\nPING\r\n") |
| 1379 |
l, _ := cr.ReadString('\n') |
| 1380 |
if !strings.HasPrefix(l, "-ERR ") { |
| 1381 |
t.Fatalf("Expected an error") |
| 1382 |
} |
| 1383 |
if !strings.Contains(l, "Maximum Payload") { |
| 1384 |
t.Fatalf("Expected an ERR for max payload violation, got: %v", l) |
| 1385 |
} |
| 1386 |
} |
| 1387 |
|
| 1388 |
func TestJWTAccountLimitsMaxConns(t *testing.T) { |
| 1389 |
fooAC := newJWTTestAccountClaims() |
| 1390 |
fooAC.Limits.Conn = 8 |
| 1391 |
s, fooKP, c, _ := setupJWTTestWitAccountClaims(t, fooAC, "+OK") |
| 1392 |
defer s.Shutdown() |
| 1393 |
defer c.close() |
| 1394 |
|
| 1395 |
newClient := func(expPre string) *testAsyncClient { |
| 1396 |
t.Helper() |
| 1397 |
// Create a client. |
| 1398 |
c, cr, cs := createClient(t, s, fooKP) |
| 1399 |
c.parseAsync(cs) |
| 1400 |
l, _ := cr.ReadString('\n') |
| 1401 |
if !strings.HasPrefix(l, expPre) { |
| 1402 |
t.Fatalf("Expected a response starting with %q, got %q", expPre, l) |
| 1403 |
} |
| 1404 |
return c |
| 1405 |
} |
| 1406 |
|
| 1407 |
// A connection is created in setupJWTTestWitAccountClaims(), so limit |
| 1408 |
// to 7 here (8 total). |
| 1409 |
for i := 0; i < 7; i++ { |
| 1410 |
c := newClient("PONG") |
| 1411 |
defer c.close() |
| 1412 |
} |
| 1413 |
// Now this one should fail. |
| 1414 |
c = newClient("-ERR ") |
| 1415 |
c.close() |
| 1416 |
} |
| 1417 |
|
| 1418 |
// This will test that we can switch from a public export to a private |
| 1419 |
// one and back with export claims to make sure the claim update mechanism |
| 1420 |
// is working properly. |
| 1421 |
func TestJWTAccountServiceImportAuthSwitch(t *testing.T) { |
| 1422 |
s := opTrustBasicSetup() |
| 1423 |
defer s.Shutdown() |
| 1424 |
buildMemAccResolver(s) |
| 1425 |
|
| 1426 |
okp, _ := nkeys.FromSeed(oSeed) |
| 1427 |
|
| 1428 |
// Create accounts and imports/exports. |
| 1429 |
fooKP, _ := nkeys.CreateAccount() |
| 1430 |
fooPub, _ := fooKP.PublicKey() |
| 1431 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 1432 |
serviceExport := &jwt.Export{Subject: "ngs.usage.*", Type: jwt.Service} |
| 1433 |
fooAC.Exports.Add(serviceExport) |
| 1434 |
fooJWT, err := fooAC.Encode(okp) |
| 1435 |
if err != nil { |
| 1436 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1437 |
} |
| 1438 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1439 |
|
| 1440 |
barKP, _ := nkeys.CreateAccount() |
| 1441 |
barPub, _ := barKP.PublicKey() |
| 1442 |
barAC := jwt.NewAccountClaims(barPub) |
| 1443 |
serviceImport := &jwt.Import{Account: fooPub, Subject: "ngs.usage", To: "ngs.usage.DEREK", Type: jwt.Service} |
| 1444 |
barAC.Imports.Add(serviceImport) |
| 1445 |
barJWT, err := barAC.Encode(okp) |
| 1446 |
if err != nil { |
| 1447 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1448 |
} |
| 1449 |
addAccountToMemResolver(s, barPub, barJWT) |
| 1450 |
|
| 1451 |
// Create a client that will send the request |
| 1452 |
ca, cra, csa := createClient(t, s, barKP) |
| 1453 |
defer ca.close() |
| 1454 |
ca.parseAsync(csa) |
| 1455 |
expectPong(t, cra) |
| 1456 |
|
| 1457 |
// Create the client that will respond to the requests. |
| 1458 |
cb, crb, csb := createClient(t, s, fooKP) |
| 1459 |
defer cb.close() |
| 1460 |
cb.parseAsync(csb) |
| 1461 |
expectPong(t, crb) |
| 1462 |
|
| 1463 |
// Create Subscriber. |
| 1464 |
cb.parseAsync("SUB ngs.usage.* 1\r\nPING\r\n") |
| 1465 |
expectPong(t, crb) |
| 1466 |
|
| 1467 |
// Send Request |
| 1468 |
ca.parseAsync("PUB ngs.usage 2\r\nhi\r\nPING\r\n") |
| 1469 |
expectPong(t, cra) |
| 1470 |
|
| 1471 |
// We should receive the request mapped into our account. PING needed to flush. |
| 1472 |
cb.parseAsync("PING\r\n") |
| 1473 |
expectMsg(t, crb, "ngs.usage.DEREK", "hi") |
| 1474 |
|
| 1475 |
// Now update to make the export private. |
| 1476 |
fooACPrivate := jwt.NewAccountClaims(fooPub) |
| 1477 |
serviceExport = &jwt.Export{Subject: "ngs.usage.*", Type: jwt.Service, TokenReq: true} |
| 1478 |
fooACPrivate.Exports.Add(serviceExport) |
| 1479 |
fooJWTPrivate, err := fooACPrivate.Encode(okp) |
| 1480 |
if err != nil { |
| 1481 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1482 |
} |
| 1483 |
addAccountToMemResolver(s, fooPub, fooJWTPrivate) |
| 1484 |
acc, _ := s.LookupAccount(fooPub) |
| 1485 |
s.UpdateAccountClaims(acc, fooACPrivate) |
| 1486 |
|
| 1487 |
// Send Another Request |
| 1488 |
ca.parseAsync("PUB ngs.usage 2\r\nhi\r\nPING\r\n") |
| 1489 |
expectPong(t, cra) |
| 1490 |
|
| 1491 |
// We should not receive the request this time. |
| 1492 |
cb.parseAsync("PING\r\n") |
| 1493 |
expectPong(t, crb) |
| 1494 |
|
| 1495 |
// Now put it back again to public and make sure it works again. |
| 1496 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1497 |
s.UpdateAccountClaims(acc, fooAC) |
| 1498 |
|
| 1499 |
// Send Request |
| 1500 |
ca.parseAsync("PUB ngs.usage 2\r\nhi\r\nPING\r\n") |
| 1501 |
expectPong(t, cra) |
| 1502 |
|
| 1503 |
// We should receive the request mapped into our account. PING needed to flush. |
| 1504 |
cb.parseAsync("PING\r\n") |
| 1505 |
expectMsg(t, crb, "ngs.usage.DEREK", "hi") |
| 1506 |
} |
| 1507 |
|
| 1508 |
func TestJWTAccountServiceImportExpires(t *testing.T) { |
| 1509 |
s := opTrustBasicSetup() |
| 1510 |
defer s.Shutdown() |
| 1511 |
buildMemAccResolver(s) |
| 1512 |
|
| 1513 |
okp, _ := nkeys.FromSeed(oSeed) |
| 1514 |
|
| 1515 |
// Create accounts and imports/exports. |
| 1516 |
fooKP, _ := nkeys.CreateAccount() |
| 1517 |
fooPub, _ := fooKP.PublicKey() |
| 1518 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 1519 |
serviceExport := &jwt.Export{Subject: "foo", Type: jwt.Service} |
| 1520 |
|
| 1521 |
fooAC.Exports.Add(serviceExport) |
| 1522 |
fooJWT, err := fooAC.Encode(okp) |
| 1523 |
if err != nil { |
| 1524 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1525 |
} |
| 1526 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1527 |
|
| 1528 |
barKP, _ := nkeys.CreateAccount() |
| 1529 |
barPub, _ := barKP.PublicKey() |
| 1530 |
barAC := jwt.NewAccountClaims(barPub) |
| 1531 |
serviceImport := &jwt.Import{Account: fooPub, Subject: "foo", Type: jwt.Service} |
| 1532 |
|
| 1533 |
barAC.Imports.Add(serviceImport) |
| 1534 |
barJWT, err := barAC.Encode(okp) |
| 1535 |
if err != nil { |
| 1536 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1537 |
} |
| 1538 |
addAccountToMemResolver(s, barPub, barJWT) |
| 1539 |
|
| 1540 |
// Create a client that will send the request |
| 1541 |
ca, cra, csa := createClient(t, s, barKP) |
| 1542 |
defer ca.close() |
| 1543 |
ca.parseAsync(csa) |
| 1544 |
expectPong(t, cra) |
| 1545 |
|
| 1546 |
// Create the client that will respond to the requests. |
| 1547 |
cb, crb, csb := createClient(t, s, fooKP) |
| 1548 |
defer cb.close() |
| 1549 |
cb.parseAsync(csb) |
| 1550 |
expectPong(t, crb) |
| 1551 |
|
| 1552 |
// Create Subscriber. |
| 1553 |
cb.parseAsync("SUB foo 1\r\nPING\r\n") |
| 1554 |
expectPong(t, crb) |
| 1555 |
|
| 1556 |
// Send Request |
| 1557 |
ca.parseAsync("PUB foo 2\r\nhi\r\nPING\r\n") |
| 1558 |
expectPong(t, cra) |
| 1559 |
|
| 1560 |
// We should receive the request. PING needed to flush. |
| 1561 |
cb.parseAsync("PING\r\n") |
| 1562 |
expectMsg(t, crb, "foo", "hi") |
| 1563 |
|
| 1564 |
// Now update the exported service to require auth. |
| 1565 |
fooAC = jwt.NewAccountClaims(fooPub) |
| 1566 |
serviceExport = &jwt.Export{Subject: "foo", Type: jwt.Service, TokenReq: true} |
| 1567 |
|
| 1568 |
fooAC.Exports.Add(serviceExport) |
| 1569 |
fooJWT, err = fooAC.Encode(okp) |
| 1570 |
if err != nil { |
| 1571 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1572 |
} |
| 1573 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 1574 |
acc, _ := s.LookupAccount(fooPub) |
| 1575 |
s.UpdateAccountClaims(acc, fooAC) |
| 1576 |
|
| 1577 |
// Send Another Request |
| 1578 |
ca.parseAsync("PUB foo 2\r\nhi\r\nPING\r\n") |
| 1579 |
expectPong(t, cra) |
| 1580 |
|
| 1581 |
// We should not receive the request this time. |
| 1582 |
cb.parseAsync("PING\r\n") |
| 1583 |
expectPong(t, crb) |
| 1584 |
|
| 1585 |
// Now get an activation token such that it will work, but will expire. |
| 1586 |
barAC = jwt.NewAccountClaims(barPub) |
| 1587 |
serviceImport = &jwt.Import{Account: fooPub, Subject: "foo", Type: jwt.Service} |
| 1588 |
|
| 1589 |
now := time.Now() |
| 1590 |
activation := jwt.NewActivationClaims(barPub) |
| 1591 |
activation.ImportSubject = "foo" |
| 1592 |
activation.ImportType = jwt.Service |
| 1593 |
activation.IssuedAt = now.Add(-10 * time.Second).Unix() |
| 1594 |
activation.Expires = now.Add(time.Second).Round(time.Second).Unix() |
| 1595 |
actJWT, err := activation.Encode(fooKP) |
| 1596 |
if err != nil { |
| 1597 |
t.Fatalf("Error generating activation token: %v", err) |
| 1598 |
} |
| 1599 |
serviceImport.Token = actJWT |
| 1600 |
|
| 1601 |
barAC.Imports.Add(serviceImport) |
| 1602 |
barJWT, err = barAC.Encode(okp) |
| 1603 |
if err != nil { |
| 1604 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1605 |
} |
| 1606 |
addAccountToMemResolver(s, barPub, barJWT) |
| 1607 |
acc, _ = s.LookupAccount(barPub) |
| 1608 |
s.UpdateAccountClaims(acc, barAC) |
| 1609 |
|
| 1610 |
// Now it should work again. |
| 1611 |
// Send Another Request |
| 1612 |
ca.parseAsync("PUB foo 3\r\nhi2\r\nPING\r\n") |
| 1613 |
expectPong(t, cra) |
| 1614 |
|
| 1615 |
// We should receive the request. PING needed to flush. |
| 1616 |
cb.parseAsync("PING\r\n") |
| 1617 |
expectMsg(t, crb, "foo", "hi2") |
| 1618 |
|
| 1619 |
// Now wait for it to expire, then retry. |
| 1620 |
waitTime := time.Duration(activation.Expires-time.Now().Unix()) * time.Second |
| 1621 |
time.Sleep(waitTime + 250*time.Millisecond) |
| 1622 |
|
| 1623 |
// Send Another Request |
| 1624 |
ca.parseAsync("PUB foo 3\r\nhi3\r\nPING\r\n") |
| 1625 |
expectPong(t, cra) |
| 1626 |
|
| 1627 |
// We should NOT receive the request. PING needed to flush. |
| 1628 |
cb.parseAsync("PING\r\n") |
| 1629 |
expectPong(t, crb) |
| 1630 |
} |
| 1631 |
|
| 1632 |
func TestJWTAccountURLResolver(t *testing.T) { |
| 1633 |
for _, test := range []struct { |
| 1634 |
name string |
| 1635 |
useTLS bool |
| 1636 |
}{ |
| 1637 |
{"plain", false}, |
| 1638 |
{"tls", true}, |
| 1639 |
} { |
| 1640 |
t.Run(test.name, func(t *testing.T) { |
| 1641 |
kp, _ := nkeys.FromSeed(oSeed) |
| 1642 |
akp, _ := nkeys.CreateAccount() |
| 1643 |
apub, _ := akp.PublicKey() |
| 1644 |
nac := jwt.NewAccountClaims(apub) |
| 1645 |
ajwt, err := nac.Encode(kp) |
| 1646 |
if err != nil { |
| 1647 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1648 |
} |
| 1649 |
|
| 1650 |
hf := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 1651 |
w.Write([]byte(ajwt)) |
| 1652 |
}) |
| 1653 |
var ts *httptest.Server |
| 1654 |
if test.useTLS { |
| 1655 |
tc := &TLSConfigOpts{ |
| 1656 |
CertFile: "../test/configs/certs/server-cert.pem", |
| 1657 |
KeyFile: "../test/configs/certs/server-key.pem", |
| 1658 |
CaFile: "../test/configs/certs/ca.pem", |
| 1659 |
} |
| 1660 |
tlsConfig, err := GenTLSConfig(tc) |
| 1661 |
if err != nil { |
| 1662 |
t.Fatalf("Error generating tls config: %v", err) |
| 1663 |
} |
| 1664 |
ts = httptest.NewUnstartedServer(hf) |
| 1665 |
ts.TLS = tlsConfig |
| 1666 |
ts.StartTLS() |
| 1667 |
} else { |
| 1668 |
ts = httptest.NewServer(hf) |
| 1669 |
} |
| 1670 |
defer ts.Close() |
| 1671 |
|
| 1672 |
confTemplate := ` |
| 1673 |
operator: %s |
| 1674 |
listen: 127.0.0.1:-1 |
| 1675 |
resolver: URL("%s/ngs/v1/accounts/jwt/") |
| 1676 |
resolver_tls { |
| 1677 |
cert_file: "../test/configs/certs/client-cert.pem" |
| 1678 |
key_file: "../test/configs/certs/client-key.pem" |
| 1679 |
ca_file: "../test/configs/certs/ca.pem" |
| 1680 |
} |
| 1681 |
` |
| 1682 |
conf := createConfFile(t, []byte(fmt.Sprintf(confTemplate, ojwt, ts.URL))) |
| 1683 |
|
| 1684 |
s, opts := RunServerWithConfig(conf) |
| 1685 |
pub, _ := kp.PublicKey() |
| 1686 |
opts.TrustedKeys = []string{pub} |
| 1687 |
defer s.Shutdown() |
| 1688 |
|
| 1689 |
acc, _ := s.LookupAccount(apub) |
| 1690 |
if acc == nil { |
| 1691 |
t.Fatalf("Expected to receive an account") |
| 1692 |
} |
| 1693 |
if acc.Name != apub { |
| 1694 |
t.Fatalf("Account name did not match claim key") |
| 1695 |
} |
| 1696 |
}) |
| 1697 |
} |
| 1698 |
} |
| 1699 |
|
| 1700 |
func TestJWTAccountURLResolverTimeout(t *testing.T) { |
| 1701 |
kp, _ := nkeys.FromSeed(oSeed) |
| 1702 |
akp, _ := nkeys.CreateAccount() |
| 1703 |
apub, _ := akp.PublicKey() |
| 1704 |
nac := jwt.NewAccountClaims(apub) |
| 1705 |
ajwt, err := nac.Encode(kp) |
| 1706 |
if err != nil { |
| 1707 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1708 |
} |
| 1709 |
|
| 1710 |
basePath := "/ngs/v1/accounts/jwt/" |
| 1711 |
|
| 1712 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 1713 |
if r.URL.Path == basePath { |
| 1714 |
w.Write([]byte("ok")) |
| 1715 |
return |
| 1716 |
} |
| 1717 |
// Purposely be slow on account lookup. |
| 1718 |
time.Sleep(200 * time.Millisecond) |
| 1719 |
w.Write([]byte(ajwt)) |
| 1720 |
})) |
| 1721 |
defer ts.Close() |
| 1722 |
|
| 1723 |
confTemplate := ` |
| 1724 |
listen: 127.0.0.1:-1 |
| 1725 |
resolver: URL("%s%s") |
| 1726 |
` |
| 1727 |
conf := createConfFile(t, []byte(fmt.Sprintf(confTemplate, ts.URL, basePath))) |
| 1728 |
|
| 1729 |
s, opts := RunServerWithConfig(conf) |
| 1730 |
pub, _ := kp.PublicKey() |
| 1731 |
opts.TrustedKeys = []string{pub} |
| 1732 |
defer s.Shutdown() |
| 1733 |
|
| 1734 |
// Lower default timeout to speed-up test |
| 1735 |
s.AccountResolver().(*URLAccResolver).c.Timeout = 50 * time.Millisecond |
| 1736 |
|
| 1737 |
acc, _ := s.LookupAccount(apub) |
| 1738 |
if acc != nil { |
| 1739 |
t.Fatalf("Expected to not receive an account due to timeout") |
| 1740 |
} |
| 1741 |
} |
| 1742 |
|
| 1743 |
func TestJWTAccountURLResolverNoFetchOnReload(t *testing.T) { |
| 1744 |
kp, _ := nkeys.FromSeed(oSeed) |
| 1745 |
akp, _ := nkeys.CreateAccount() |
| 1746 |
apub, _ := akp.PublicKey() |
| 1747 |
nac := jwt.NewAccountClaims(apub) |
| 1748 |
ajwt, err := nac.Encode(kp) |
| 1749 |
if err != nil { |
| 1750 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1751 |
} |
| 1752 |
|
| 1753 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 1754 |
w.Write([]byte(ajwt)) |
| 1755 |
})) |
| 1756 |
defer ts.Close() |
| 1757 |
|
| 1758 |
confTemplate := ` |
| 1759 |
operator: %s |
| 1760 |
listen: 127.0.0.1:-1 |
| 1761 |
resolver: URL("%s/ngs/v1/accounts/jwt/") |
| 1762 |
` |
| 1763 |
conf := createConfFile(t, []byte(fmt.Sprintf(confTemplate, ojwt, ts.URL))) |
| 1764 |
|
| 1765 |
s, _ := RunServerWithConfig(conf) |
| 1766 |
defer s.Shutdown() |
| 1767 |
|
| 1768 |
acc, _ := s.LookupAccount(apub) |
| 1769 |
if acc == nil { |
| 1770 |
t.Fatalf("Expected to receive an account") |
| 1771 |
} |
| 1772 |
|
| 1773 |
// Reload would produce a DATA race during the DeepEqual check for the account resolver, |
| 1774 |
// so close the current one and we will create a new one that keeps track of fetch calls. |
| 1775 |
ts.Close() |
| 1776 |
|
| 1777 |
fetch := int32(0) |
| 1778 |
ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 1779 |
atomic.AddInt32(&fetch, 1) |
| 1780 |
w.Write([]byte(ajwt)) |
| 1781 |
})) |
| 1782 |
defer ts.Close() |
| 1783 |
|
| 1784 |
changeCurrentConfigContentWithNewContent(t, conf, []byte(fmt.Sprintf(confTemplate, ojwt, ts.URL))) |
| 1785 |
|
| 1786 |
if err := s.Reload(); err != nil { |
| 1787 |
t.Fatalf("Error on reload: %v", err) |
| 1788 |
} |
| 1789 |
if atomic.LoadInt32(&fetch) != 0 { |
| 1790 |
t.Fatalf("Fetch invoked during reload") |
| 1791 |
} |
| 1792 |
|
| 1793 |
// Now stop the resolver and make sure that on startup, we report URL resolver failure |
| 1794 |
s.Shutdown() |
| 1795 |
s = nil |
| 1796 |
ts.Close() |
| 1797 |
|
| 1798 |
opts := LoadConfig(conf) |
| 1799 |
if s, err := NewServer(opts); err == nil || !strings.Contains(err.Error(), "could not fetch") { |
| 1800 |
if s != nil { |
| 1801 |
s.Shutdown() |
| 1802 |
} |
| 1803 |
t.Fatalf("Expected error regarding account resolver, got %v", err) |
| 1804 |
} |
| 1805 |
} |
| 1806 |
|
| 1807 |
func TestJWTAccountURLResolverFetchFailureInServer1(t *testing.T) { |
| 1808 |
const subj = "test" |
| 1809 |
const crossAccSubj = "test" |
| 1810 |
// Create Exporting Account |
| 1811 |
expkp, _ := nkeys.CreateAccount() |
| 1812 |
exppub, _ := expkp.PublicKey() |
| 1813 |
expac := jwt.NewAccountClaims(exppub) |
| 1814 |
expac.Exports.Add(&jwt.Export{ |
| 1815 |
Subject: crossAccSubj, |
| 1816 |
Type: jwt.Stream, |
| 1817 |
}) |
| 1818 |
expjwt, err := expac.Encode(oKp) |
| 1819 |
if err != nil { |
| 1820 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1821 |
} |
| 1822 |
// Create importing Account |
| 1823 |
impkp, _ := nkeys.CreateAccount() |
| 1824 |
imppub, _ := impkp.PublicKey() |
| 1825 |
impac := jwt.NewAccountClaims(imppub) |
| 1826 |
impac.Imports.Add(&jwt.Import{ |
| 1827 |
Account: exppub, |
| 1828 |
Subject: crossAccSubj, |
| 1829 |
Type: jwt.Stream, |
| 1830 |
}) |
| 1831 |
impjwt, err := impac.Encode(oKp) |
| 1832 |
if err != nil { |
| 1833 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1834 |
} |
| 1835 |
// Simulate an account server that drops the first request to exppub |
| 1836 |
chanImpA := make(chan struct{}, 10) |
| 1837 |
defer close(chanImpA) |
| 1838 |
chanExpS := make(chan struct{}, 10) |
| 1839 |
defer close(chanExpS) |
| 1840 |
chanExpF := make(chan struct{}, 1) |
| 1841 |
defer close(chanExpF) |
| 1842 |
failureCnt := int32(0) |
| 1843 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 1844 |
if r.URL.Path == "/A/" { |
| 1845 |
// Server startup |
| 1846 |
w.Write(nil) |
| 1847 |
chanImpA <- struct{}{} |
| 1848 |
} else if r.URL.Path == "/A/"+imppub { |
| 1849 |
w.Write([]byte(impjwt)) |
| 1850 |
chanImpA <- struct{}{} |
| 1851 |
} else if r.URL.Path == "/A/"+exppub { |
| 1852 |
if atomic.AddInt32(&failureCnt, 1) <= 1 { |
| 1853 |
// skip the write to simulate the failure |
| 1854 |
chanExpF <- struct{}{} |
| 1855 |
} else { |
| 1856 |
w.Write([]byte(expjwt)) |
| 1857 |
chanExpS <- struct{}{} |
| 1858 |
} |
| 1859 |
} else { |
| 1860 |
t.Fatal("not expected") |
| 1861 |
} |
| 1862 |
})) |
| 1863 |
defer ts.Close() |
| 1864 |
// Create server |
| 1865 |
confA := createConfFile(t, []byte(fmt.Sprintf(` |
| 1866 |
listen: 127.0.0.1:-1 |
| 1867 |
operator: %s |
| 1868 |
resolver: URL("%s/A/") |
| 1869 |
`, ojwt, ts.URL))) |
| 1870 |
sA := RunServer(LoadConfig(confA)) |
| 1871 |
defer sA.Shutdown() |
| 1872 |
// server observed one fetch on startup |
| 1873 |
chanRecv(t, chanImpA, 10*time.Second) |
| 1874 |
// Create first client |
| 1875 |
ncA := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, impkp)) |
| 1876 |
defer ncA.Close() |
| 1877 |
// create a test subscription |
| 1878 |
subA, err := ncA.SubscribeSync(subj) |
| 1879 |
if err != nil { |
| 1880 |
t.Fatalf("Expected no error during subscribe: %v", err) |
| 1881 |
} |
| 1882 |
defer subA.Unsubscribe() |
| 1883 |
// Connect of client triggered a fetch of both accounts |
| 1884 |
// the fetch for the imported account will fail |
| 1885 |
chanRecv(t, chanImpA, 10*time.Second) |
| 1886 |
chanRecv(t, chanExpF, 10*time.Second) |
| 1887 |
// create second client for user exporting |
| 1888 |
ncB := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, expkp)) |
| 1889 |
defer ncB.Close() |
| 1890 |
chanRecv(t, chanExpS, 10*time.Second) |
| 1891 |
// Connect of client triggered another fetch, this time passing |
| 1892 |
checkSubInterest(t, sA, imppub, subj, 10*time.Second) |
| 1893 |
checkSubInterest(t, sA, exppub, crossAccSubj, 10*time.Second) // Will fail as a result of this issue |
| 1894 |
} |
| 1895 |
|
| 1896 |
func TestJWTAccountURLResolverFetchFailurePushReorder(t *testing.T) { |
| 1897 |
const subj = "test" |
| 1898 |
const crossAccSubj = "test" |
| 1899 |
// Create System Account |
| 1900 |
syskp, _ := nkeys.CreateAccount() |
| 1901 |
syspub, _ := syskp.PublicKey() |
| 1902 |
sysAc := jwt.NewAccountClaims(syspub) |
| 1903 |
sysjwt, err := sysAc.Encode(oKp) |
| 1904 |
if err != nil { |
| 1905 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1906 |
} |
| 1907 |
// Create Exporting Account |
| 1908 |
expkp, _ := nkeys.CreateAccount() |
| 1909 |
exppub, _ := expkp.PublicKey() |
| 1910 |
expac := jwt.NewAccountClaims(exppub) |
| 1911 |
expjwt1, err := expac.Encode(oKp) |
| 1912 |
if err != nil { |
| 1913 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1914 |
} |
| 1915 |
expac.Exports.Add(&jwt.Export{ |
| 1916 |
Subject: crossAccSubj, |
| 1917 |
Type: jwt.Stream, |
| 1918 |
}) |
| 1919 |
expjwt2, err := expac.Encode(oKp) |
| 1920 |
if err != nil { |
| 1921 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1922 |
} |
| 1923 |
// Create importing Account |
| 1924 |
impkp, _ := nkeys.CreateAccount() |
| 1925 |
imppub, _ := impkp.PublicKey() |
| 1926 |
impac := jwt.NewAccountClaims(imppub) |
| 1927 |
impac.Imports.Add(&jwt.Import{ |
| 1928 |
Account: exppub, |
| 1929 |
Subject: crossAccSubj, |
| 1930 |
Type: jwt.Stream, |
| 1931 |
}) |
| 1932 |
impjwt, err := impac.Encode(oKp) |
| 1933 |
if err != nil { |
| 1934 |
t.Fatalf("Error generating account JWT: %v", err) |
| 1935 |
} |
| 1936 |
// Simulate an account server that does not serve the updated jwt for exppub |
| 1937 |
chanImpA := make(chan struct{}, 10) |
| 1938 |
defer close(chanImpA) |
| 1939 |
chanExpS := make(chan struct{}, 10) |
| 1940 |
defer close(chanExpS) |
| 1941 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 1942 |
if r.URL.Path == "/A/" { |
| 1943 |
// Server startup |
| 1944 |
w.Write(nil) |
| 1945 |
chanImpA <- struct{}{} |
| 1946 |
} else if r.URL.Path == "/A/"+imppub { |
| 1947 |
w.Write([]byte(impjwt)) |
| 1948 |
chanImpA <- struct{}{} |
| 1949 |
} else if r.URL.Path == "/A/"+exppub { |
| 1950 |
// respond with jwt that does not have the export |
| 1951 |
// this simulates an ordering issue |
| 1952 |
w.Write([]byte(expjwt1)) |
| 1953 |
chanExpS <- struct{}{} |
| 1954 |
} else if r.URL.Path == "/A/"+syspub { |
| 1955 |
w.Write([]byte(sysjwt)) |
| 1956 |
} else { |
| 1957 |
t.Fatal("not expected") |
| 1958 |
} |
| 1959 |
})) |
| 1960 |
defer ts.Close() |
| 1961 |
confA := createConfFile(t, []byte(fmt.Sprintf(` |
| 1962 |
listen: 127.0.0.1:-1 |
| 1963 |
operator: %s |
| 1964 |
resolver: URL("%s/A/") |
| 1965 |
system_account: %s |
| 1966 |
`, ojwt, ts.URL, syspub))) |
| 1967 |
sA := RunServer(LoadConfig(confA)) |
| 1968 |
defer sA.Shutdown() |
| 1969 |
// server observed one fetch on startup |
| 1970 |
chanRecv(t, chanImpA, 10*time.Second) |
| 1971 |
// Create first client |
| 1972 |
ncA := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, impkp)) |
| 1973 |
defer ncA.Close() |
| 1974 |
// create a test subscription |
| 1975 |
subA, err := ncA.SubscribeSync(subj) |
| 1976 |
if err != nil { |
| 1977 |
t.Fatalf("Expected no error during subscribe: %v", err) |
| 1978 |
} |
| 1979 |
defer subA.Unsubscribe() |
| 1980 |
// Connect of client triggered a fetch of both accounts |
| 1981 |
// the fetch for the imported account will fail |
| 1982 |
chanRecv(t, chanImpA, 10*time.Second) |
| 1983 |
chanRecv(t, chanExpS, 10*time.Second) |
| 1984 |
// create second client for user exporting |
| 1985 |
ncB := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, expkp)) |
| 1986 |
defer ncB.Close() |
| 1987 |
// update expjwt2, this will correct the import issue |
| 1988 |
sysc := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, syskp)) |
| 1989 |
defer sysc.Close() |
| 1990 |
natsPub(t, sysc, fmt.Sprintf(accUpdateEventSubjNew, exppub), []byte(expjwt2)) |
| 1991 |
sysc.Flush() |
| 1992 |
// updating expjwt should cause this to pass |
| 1993 |
checkSubInterest(t, sA, imppub, subj, 10*time.Second) |
| 1994 |
checkSubInterest(t, sA, exppub, crossAccSubj, 10*time.Second) // Will fail as a result of this issue |
| 1995 |
} |
| 1996 |
|
| 1997 |
type captureDebugLogger struct { |
| 1998 |
DummyLogger |
| 1999 |
dbgCh chan string |
| 2000 |
} |
| 2001 |
|
| 2002 |
func (l *captureDebugLogger) Debugf(format string, v ...any) { |
| 2003 |
select { |
| 2004 |
case l.dbgCh <- fmt.Sprintf(format, v...): |
| 2005 |
default: |
| 2006 |
} |
| 2007 |
} |
| 2008 |
|
| 2009 |
func TestJWTAccountURLResolverPermanentFetchFailure(t *testing.T) { |
| 2010 |
const crossAccSubj = "test" |
| 2011 |
expkp, _ := nkeys.CreateAccount() |
| 2012 |
exppub, _ := expkp.PublicKey() |
| 2013 |
impkp, _ := nkeys.CreateAccount() |
| 2014 |
imppub, _ := impkp.PublicKey() |
| 2015 |
// Create System Account |
| 2016 |
syskp, _ := nkeys.CreateAccount() |
| 2017 |
syspub, _ := syskp.PublicKey() |
| 2018 |
sysAc := jwt.NewAccountClaims(syspub) |
| 2019 |
sysjwt, err := sysAc.Encode(oKp) |
| 2020 |
if err != nil { |
| 2021 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2022 |
} |
| 2023 |
// Create 2 Accounts. Each importing from the other, but NO matching export |
| 2024 |
expac := jwt.NewAccountClaims(exppub) |
| 2025 |
expac.Imports.Add(&jwt.Import{ |
| 2026 |
Account: imppub, |
| 2027 |
Subject: crossAccSubj, |
| 2028 |
Type: jwt.Stream, |
| 2029 |
}) |
| 2030 |
expjwt, err := expac.Encode(oKp) |
| 2031 |
if err != nil { |
| 2032 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2033 |
} |
| 2034 |
// Create importing Account |
| 2035 |
impac := jwt.NewAccountClaims(imppub) |
| 2036 |
impac.Imports.Add(&jwt.Import{ |
| 2037 |
Account: exppub, |
| 2038 |
Subject: crossAccSubj, |
| 2039 |
Type: jwt.Stream, |
| 2040 |
}) |
| 2041 |
impjwt, err := impac.Encode(oKp) |
| 2042 |
if err != nil { |
| 2043 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2044 |
} |
| 2045 |
// Simulate an account server that does not serve the updated jwt for exppub |
| 2046 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 2047 |
if r.URL.Path == "/A/" { |
| 2048 |
// Server startup |
| 2049 |
w.Write(nil) |
| 2050 |
} else if r.URL.Path == "/A/"+imppub { |
| 2051 |
w.Write([]byte(impjwt)) |
| 2052 |
} else if r.URL.Path == "/A/"+exppub { |
| 2053 |
w.Write([]byte(expjwt)) |
| 2054 |
} else if r.URL.Path == "/A/"+syspub { |
| 2055 |
w.Write([]byte(sysjwt)) |
| 2056 |
} else { |
| 2057 |
t.Fatal("not expected") |
| 2058 |
} |
| 2059 |
})) |
| 2060 |
defer ts.Close() |
| 2061 |
confA := createConfFile(t, []byte(fmt.Sprintf(` |
| 2062 |
listen: 127.0.0.1:-1 |
| 2063 |
operator: %s |
| 2064 |
resolver: URL("%s/A/") |
| 2065 |
system_account: %s |
| 2066 |
`, ojwt, ts.URL, syspub))) |
| 2067 |
o := LoadConfig(confA) |
| 2068 |
sA := RunServer(o) |
| 2069 |
defer sA.Shutdown() |
| 2070 |
l := &captureDebugLogger{dbgCh: make(chan string, 100)} // has enough space to not block |
| 2071 |
sA.SetLogger(l, true, false) |
| 2072 |
// Create clients |
| 2073 |
ncA := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, impkp)) |
| 2074 |
defer ncA.Close() |
| 2075 |
ncB := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, expkp)) |
| 2076 |
defer ncB.Close() |
| 2077 |
sysc := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, syskp)) |
| 2078 |
defer sysc.Close() |
| 2079 |
// push accounts |
| 2080 |
natsPub(t, sysc, fmt.Sprintf(accUpdateEventSubjNew, imppub), []byte(impjwt)) |
| 2081 |
natsPub(t, sysc, fmt.Sprintf(accUpdateEventSubjOld, exppub), []byte(expjwt)) |
| 2082 |
sysc.Flush() |
| 2083 |
importErrCnt := 0 |
| 2084 |
tmr := time.NewTimer(500 * time.Millisecond) |
| 2085 |
defer tmr.Stop() |
| 2086 |
for { |
| 2087 |
select { |
| 2088 |
case line := <-l.dbgCh: |
| 2089 |
if strings.HasPrefix(line, "Error adding stream import to account") { |
| 2090 |
importErrCnt++ |
| 2091 |
} |
| 2092 |
case <-tmr.C: |
| 2093 |
// connecting and updating, each cause 3 traces (2 + 1 on iteration) + 1 xtra fetch |
| 2094 |
if importErrCnt != 7 { |
| 2095 |
t.Fatalf("Expected 7 debug traces, got %d", importErrCnt) |
| 2096 |
} |
| 2097 |
return |
| 2098 |
} |
| 2099 |
} |
| 2100 |
} |
| 2101 |
|
| 2102 |
func TestJWTAccountURLResolverFetchFailureInCluster(t *testing.T) { |
| 2103 |
assertChanLen := func(x int, chans ...chan struct{}) { |
| 2104 |
t.Helper() |
| 2105 |
for _, c := range chans { |
| 2106 |
if len(c) != x { |
| 2107 |
t.Fatalf("length of channel is not %d", x) |
| 2108 |
} |
| 2109 |
} |
| 2110 |
} |
| 2111 |
const subj = ">" |
| 2112 |
const crossAccSubj = "test" |
| 2113 |
// Create Exporting Account |
| 2114 |
expkp, _ := nkeys.CreateAccount() |
| 2115 |
exppub, _ := expkp.PublicKey() |
| 2116 |
expac := jwt.NewAccountClaims(exppub) |
| 2117 |
expac.Exports.Add(&jwt.Export{ |
| 2118 |
Subject: crossAccSubj, |
| 2119 |
Type: jwt.Stream, |
| 2120 |
}) |
| 2121 |
expjwt, err := expac.Encode(oKp) |
| 2122 |
if err != nil { |
| 2123 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2124 |
} |
| 2125 |
// Create importing Account |
| 2126 |
impkp, _ := nkeys.CreateAccount() |
| 2127 |
imppub, _ := impkp.PublicKey() |
| 2128 |
impac := jwt.NewAccountClaims(imppub) |
| 2129 |
impac.Imports.Add(&jwt.Import{ |
| 2130 |
Account: exppub, |
| 2131 |
Subject: crossAccSubj, |
| 2132 |
Type: jwt.Stream, |
| 2133 |
}) |
| 2134 |
impac.Exports.Add(&jwt.Export{ |
| 2135 |
Subject: "srvc", |
| 2136 |
Type: jwt.Service, |
| 2137 |
}) |
| 2138 |
impjwt, err := impac.Encode(oKp) |
| 2139 |
if err != nil { |
| 2140 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2141 |
} |
| 2142 |
// Create User |
| 2143 |
nkp, _ := nkeys.CreateUser() |
| 2144 |
uSeed, _ := nkp.Seed() |
| 2145 |
upub, _ := nkp.PublicKey() |
| 2146 |
nuc := newJWTTestUserClaims() |
| 2147 |
nuc.Subject = upub |
| 2148 |
uJwt, err := nuc.Encode(impkp) |
| 2149 |
if err != nil { |
| 2150 |
t.Fatalf("Error generating user JWT: %v", err) |
| 2151 |
} |
| 2152 |
creds := genCredsFile(t, uJwt, uSeed) |
| 2153 |
// Simulate an account server that drops the first request to /B/acc |
| 2154 |
chanImpA := make(chan struct{}, 4) |
| 2155 |
defer close(chanImpA) |
| 2156 |
chanImpB := make(chan struct{}, 4) |
| 2157 |
defer close(chanImpB) |
| 2158 |
chanExpA := make(chan struct{}, 4) |
| 2159 |
defer close(chanExpA) |
| 2160 |
chanExpB := make(chan struct{}, 4) |
| 2161 |
defer close(chanExpB) |
| 2162 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 2163 |
if r.URL.Path == "/A/" { |
| 2164 |
// Server A startup |
| 2165 |
w.Write(nil) |
| 2166 |
chanImpA <- struct{}{} |
| 2167 |
} else if r.URL.Path == "/B/" { |
| 2168 |
// Server B startup |
| 2169 |
w.Write(nil) |
| 2170 |
chanImpB <- struct{}{} |
| 2171 |
} else if r.URL.Path == "/A/"+imppub { |
| 2172 |
// First Client connecting to Server A |
| 2173 |
w.Write([]byte(impjwt)) |
| 2174 |
chanImpA <- struct{}{} |
| 2175 |
} else if r.URL.Path == "/B/"+imppub { |
| 2176 |
// Second Client connecting to Server B |
| 2177 |
w.Write([]byte(impjwt)) |
| 2178 |
chanImpB <- struct{}{} |
| 2179 |
} else if r.URL.Path == "/A/"+exppub { |
| 2180 |
// First Client connecting to Server A |
| 2181 |
w.Write([]byte(expjwt)) |
| 2182 |
chanExpA <- struct{}{} |
| 2183 |
} else if r.URL.Path == "/B/"+exppub { |
| 2184 |
// Second Client connecting to Server B |
| 2185 |
w.Write([]byte(expjwt)) |
| 2186 |
chanExpB <- struct{}{} |
| 2187 |
} else { |
| 2188 |
t.Fatal("not expected") |
| 2189 |
} |
| 2190 |
})) |
| 2191 |
defer ts.Close() |
| 2192 |
// Create seed server A |
| 2193 |
confA := createConfFile(t, []byte(fmt.Sprintf(` |
| 2194 |
listen: 127.0.0.1:-1 |
| 2195 |
operator: %s |
| 2196 |
resolver: URL("%s/A/") |
| 2197 |
cluster { |
| 2198 |
name: clust |
| 2199 |
no_advertise: true |
| 2200 |
listen: 127.0.0.1:-1 |
| 2201 |
} |
| 2202 |
`, ojwt, ts.URL))) |
| 2203 |
sA := RunServer(LoadConfig(confA)) |
| 2204 |
defer sA.Shutdown() |
| 2205 |
// Create Server B (using no_advertise to prevent failover) |
| 2206 |
confB := createConfFile(t, []byte(fmt.Sprintf(` |
| 2207 |
listen: 127.0.0.1:-1 |
| 2208 |
operator: %s |
| 2209 |
resolver: URL("%s/B/") |
| 2210 |
cluster { |
| 2211 |
name: clust |
| 2212 |
no_advertise: true |
| 2213 |
listen: 127.0.0.1:-1 |
| 2214 |
routes [ |
| 2215 |
nats-route://127.0.0.1:%d |
| 2216 |
] |
| 2217 |
} |
| 2218 |
`, ojwt, ts.URL, sA.opts.Cluster.Port))) |
| 2219 |
sB := RunServer(LoadConfig(confB)) |
| 2220 |
defer sB.Shutdown() |
| 2221 |
// startup cluster |
| 2222 |
checkClusterFormed(t, sA, sB) |
| 2223 |
// Both server observed one fetch on startup |
| 2224 |
chanRecv(t, chanImpA, 10*time.Second) |
| 2225 |
chanRecv(t, chanImpB, 10*time.Second) |
| 2226 |
assertChanLen(0, chanImpA, chanImpB, chanExpA, chanExpB) |
| 2227 |
// Create first client, directly connects to A |
| 2228 |
urlA := fmt.Sprintf("nats://%s:%d", sA.opts.Host, sA.opts.Port) |
| 2229 |
ncA, err := nats.Connect(urlA, nats.UserCredentials(creds), |
| 2230 |
nats.DisconnectErrHandler(func(_ *nats.Conn, err error) { |
| 2231 |
if err != nil { |
| 2232 |
t.Fatal("error not expected in this test", err) |
| 2233 |
} |
| 2234 |
}), |
| 2235 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) { |
| 2236 |
t.Fatal("error not expected in this test", err) |
| 2237 |
}), |
| 2238 |
) |
| 2239 |
if err != nil { |
| 2240 |
t.Fatalf("Expected to connect, got %v %s", err, urlA) |
| 2241 |
} |
| 2242 |
defer ncA.Close() |
| 2243 |
// create a test subscription |
| 2244 |
subA, err := ncA.SubscribeSync(subj) |
| 2245 |
if err != nil { |
| 2246 |
t.Fatalf("Expected no error during subscribe: %v", err) |
| 2247 |
} |
| 2248 |
defer subA.Unsubscribe() |
| 2249 |
// Connect of client triggered a fetch by Server A |
| 2250 |
chanRecv(t, chanImpA, 10*time.Second) |
| 2251 |
chanRecv(t, chanExpA, 10*time.Second) |
| 2252 |
assertChanLen(0, chanImpA, chanImpB, chanExpA, chanExpB) |
| 2253 |
//time.Sleep(10 * time.Second) |
| 2254 |
// create second client, directly connect to B |
| 2255 |
urlB := fmt.Sprintf("nats://%s:%d", sB.opts.Host, sB.opts.Port) |
| 2256 |
ncB, err := nats.Connect(urlB, nats.UserCredentials(creds), nats.NoReconnect()) |
| 2257 |
if err != nil { |
| 2258 |
t.Fatalf("Expected to connect, got %v %s", err, urlB) |
| 2259 |
} |
| 2260 |
defer ncB.Close() |
| 2261 |
// Connect of client triggered a fetch by Server B |
| 2262 |
chanRecv(t, chanImpB, 10*time.Second) |
| 2263 |
chanRecv(t, chanExpB, 10*time.Second) |
| 2264 |
assertChanLen(0, chanImpA, chanImpB, chanExpA, chanExpB) |
| 2265 |
checkClusterFormed(t, sA, sB) |
| 2266 |
// the route subscription was lost due to the failed fetch |
| 2267 |
// Now we test if some recover mechanism is in play |
| 2268 |
checkSubInterest(t, sB, imppub, subj, 10*time.Second) // Will fail as a result of this issue |
| 2269 |
checkSubInterest(t, sB, exppub, crossAccSubj, 10*time.Second) // Will fail as a result of this issue |
| 2270 |
if err := ncB.Publish(subj, []byte("msg")); err != nil { |
| 2271 |
t.Fatalf("Expected to publish %v", err) |
| 2272 |
} |
| 2273 |
// expect the message from B to flow to A |
| 2274 |
if m, err := subA.NextMsg(10 * time.Second); err != nil { |
| 2275 |
t.Fatalf("Expected to receive a message %v", err) |
| 2276 |
} else if string(m.Data) != "msg" { |
| 2277 |
t.Fatalf("Expected to receive 'msg', got: %s", string(m.Data)) |
| 2278 |
} |
| 2279 |
assertChanLen(0, chanImpA, chanImpB, chanExpA, chanExpB) |
| 2280 |
} |
| 2281 |
|
| 2282 |
func TestJWTAccountURLResolverReturnDifferentOperator(t *testing.T) { |
| 2283 |
// Create a valid chain of op/acc/usr using a different operator |
| 2284 |
// This is so we can test if the server rejects this chain. |
| 2285 |
// Create Operator |
| 2286 |
op, _ := nkeys.CreateOperator() |
| 2287 |
// Create Account, this account is the one returned by the resolver |
| 2288 |
akp, _ := nkeys.CreateAccount() |
| 2289 |
apub, _ := akp.PublicKey() |
| 2290 |
nac := jwt.NewAccountClaims(apub) |
| 2291 |
ajwt, err := nac.Encode(op) |
| 2292 |
if err != nil { |
| 2293 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2294 |
} |
| 2295 |
// Create User |
| 2296 |
nkp, _ := nkeys.CreateUser() |
| 2297 |
uSeed, _ := nkp.Seed() |
| 2298 |
upub, _ := nkp.PublicKey() |
| 2299 |
nuc := newJWTTestUserClaims() |
| 2300 |
nuc.Subject = upub |
| 2301 |
uJwt, err := nuc.Encode(akp) |
| 2302 |
if err != nil { |
| 2303 |
t.Fatalf("Error generating user JWT: %v", err) |
| 2304 |
} |
| 2305 |
creds := genCredsFile(t, uJwt, uSeed) |
| 2306 |
// Simulate an account server that was hijacked/mis configured |
| 2307 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 2308 |
w.Write([]byte(ajwt)) |
| 2309 |
})) |
| 2310 |
defer ts.Close() |
| 2311 |
// Create Server |
| 2312 |
confA := createConfFile(t, []byte(fmt.Sprintf(` |
| 2313 |
listen: 127.0.0.1:-1 |
| 2314 |
operator: %s |
| 2315 |
resolver: URL("%s/A/") |
| 2316 |
`, ojwt, ts.URL))) |
| 2317 |
sA, _ := RunServerWithConfig(confA) |
| 2318 |
defer sA.Shutdown() |
| 2319 |
// Create first client, directly connects to A |
| 2320 |
urlA := fmt.Sprintf("nats://%s:%d", sA.opts.Host, sA.opts.Port) |
| 2321 |
if _, err := nats.Connect(urlA, nats.UserCredentials(creds), |
| 2322 |
nats.DisconnectErrHandler(func(_ *nats.Conn, err error) { |
| 2323 |
if err != nil { |
| 2324 |
t.Fatal("error not expected in this test", err) |
| 2325 |
} |
| 2326 |
}), |
| 2327 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) { |
| 2328 |
t.Fatal("error not expected in this test", err) |
| 2329 |
}), |
| 2330 |
); err == nil { |
| 2331 |
t.Fatal("Expected connect to fail") |
| 2332 |
} |
| 2333 |
// Test if the server has the account in memory. (shouldn't) |
| 2334 |
if v, ok := sA.accounts.Load(apub); ok { |
| 2335 |
t.Fatalf("Expected account to NOT be in memory: %v", v.(*Account)) |
| 2336 |
} |
| 2337 |
} |
| 2338 |
|
| 2339 |
func TestJWTUserSigningKey(t *testing.T) { |
| 2340 |
s := opTrustBasicSetup() |
| 2341 |
defer s.Shutdown() |
| 2342 |
|
| 2343 |
// Check to make sure we would have an authTimer |
| 2344 |
if !s.info.AuthRequired { |
| 2345 |
t.Fatalf("Expect the server to require auth") |
| 2346 |
} |
| 2347 |
|
| 2348 |
c, cr, _ := newClientForServer(s) |
| 2349 |
defer c.close() |
| 2350 |
// Don't send jwt field, should fail. |
| 2351 |
c.parseAsync("CONNECT {\"verbose\":true,\"pedantic\":true}\r\nPING\r\n") |
| 2352 |
l, _ := cr.ReadString('\n') |
| 2353 |
if !strings.HasPrefix(l, "-ERR ") { |
| 2354 |
t.Fatalf("Expected an error") |
| 2355 |
} |
| 2356 |
|
| 2357 |
okp, _ := nkeys.FromSeed(oSeed) |
| 2358 |
|
| 2359 |
// Create an account |
| 2360 |
akp, _ := nkeys.CreateAccount() |
| 2361 |
apub, _ := akp.PublicKey() |
| 2362 |
|
| 2363 |
// Create a signing key for the account |
| 2364 |
askp, _ := nkeys.CreateAccount() |
| 2365 |
aspub, _ := askp.PublicKey() |
| 2366 |
|
| 2367 |
nac := jwt.NewAccountClaims(apub) |
| 2368 |
ajwt, err := nac.Encode(okp) |
| 2369 |
if err != nil { |
| 2370 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2371 |
} |
| 2372 |
|
| 2373 |
// Create a client with the account signing key |
| 2374 |
c, cr, cs := createClientWithIssuer(t, s, askp, apub) |
| 2375 |
defer c.close() |
| 2376 |
|
| 2377 |
// PING needed to flush the +OK/-ERR to us. |
| 2378 |
// This should fail too since no account resolver is defined. |
| 2379 |
c.parseAsync(cs) |
| 2380 |
l, _ = cr.ReadString('\n') |
| 2381 |
if !strings.HasPrefix(l, "-ERR ") { |
| 2382 |
t.Fatalf("Expected an error") |
| 2383 |
} |
| 2384 |
|
| 2385 |
// Ok now let's walk through and make sure all is good. |
| 2386 |
// We will set the account resolver by hand to a memory resolver. |
| 2387 |
buildMemAccResolver(s) |
| 2388 |
addAccountToMemResolver(s, apub, ajwt) |
| 2389 |
|
| 2390 |
// Create a client with a signing key |
| 2391 |
c, cr, cs = createClientWithIssuer(t, s, askp, apub) |
| 2392 |
defer c.close() |
| 2393 |
// should fail because the signing key is not known |
| 2394 |
c.parseAsync(cs) |
| 2395 |
l, _ = cr.ReadString('\n') |
| 2396 |
if !strings.HasPrefix(l, "-ERR ") { |
| 2397 |
t.Fatalf("Expected an error: %v", l) |
| 2398 |
} |
| 2399 |
|
| 2400 |
// add a signing key |
| 2401 |
nac.SigningKeys.Add(aspub) |
| 2402 |
// update the memory resolver |
| 2403 |
acc, _ := s.LookupAccount(apub) |
| 2404 |
s.UpdateAccountClaims(acc, nac) |
| 2405 |
|
| 2406 |
// Create a client with a signing key |
| 2407 |
c, cr, cs = createClientWithIssuer(t, s, askp, apub) |
| 2408 |
defer c.close() |
| 2409 |
|
| 2410 |
// expect this to work |
| 2411 |
c.parseAsync(cs) |
| 2412 |
l, _ = cr.ReadString('\n') |
| 2413 |
if !strings.HasPrefix(l, "PONG") { |
| 2414 |
t.Fatalf("Expected a PONG, got %q", l) |
| 2415 |
} |
| 2416 |
|
| 2417 |
isClosed := func() bool { |
| 2418 |
c.mu.Lock() |
| 2419 |
defer c.mu.Unlock() |
| 2420 |
return c.isClosed() |
| 2421 |
} |
| 2422 |
|
| 2423 |
if isClosed() { |
| 2424 |
t.Fatal("expected client to be alive") |
| 2425 |
} |
| 2426 |
// remove the signing key should bounce client |
| 2427 |
nac.SigningKeys = nil |
| 2428 |
acc, _ = s.LookupAccount(apub) |
| 2429 |
s.UpdateAccountClaims(acc, nac) |
| 2430 |
|
| 2431 |
if !isClosed() { |
| 2432 |
t.Fatal("expected client to be gone") |
| 2433 |
} |
| 2434 |
} |
| 2435 |
|
| 2436 |
func TestJWTAccountImportSignerRemoved(t *testing.T) { |
| 2437 |
s := opTrustBasicSetup() |
| 2438 |
defer s.Shutdown() |
| 2439 |
buildMemAccResolver(s) |
| 2440 |
|
| 2441 |
okp, _ := nkeys.FromSeed(oSeed) |
| 2442 |
|
| 2443 |
// Exporter keys |
| 2444 |
srvKP, _ := nkeys.CreateAccount() |
| 2445 |
srvPK, _ := srvKP.PublicKey() |
| 2446 |
srvSignerKP, _ := nkeys.CreateAccount() |
| 2447 |
srvSignerPK, _ := srvSignerKP.PublicKey() |
| 2448 |
|
| 2449 |
// Importer keys |
| 2450 |
clientKP, _ := nkeys.CreateAccount() |
| 2451 |
clientPK, _ := clientKP.PublicKey() |
| 2452 |
|
| 2453 |
createSrvJwt := func(signingKeys ...string) (string, *jwt.AccountClaims) { |
| 2454 |
ac := jwt.NewAccountClaims(srvPK) |
| 2455 |
ac.SigningKeys.Add(signingKeys...) |
| 2456 |
ac.Exports.Add(&jwt.Export{Subject: "foo", Type: jwt.Service, TokenReq: true}) |
| 2457 |
ac.Exports.Add(&jwt.Export{Subject: "bar", Type: jwt.Stream, TokenReq: true}) |
| 2458 |
token, err := ac.Encode(okp) |
| 2459 |
if err != nil { |
| 2460 |
t.Fatalf("Error generating exporter JWT: %v", err) |
| 2461 |
} |
| 2462 |
return token, ac |
| 2463 |
} |
| 2464 |
|
| 2465 |
createImportToken := func(sub string, kind jwt.ExportType) string { |
| 2466 |
actC := jwt.NewActivationClaims(clientPK) |
| 2467 |
actC.IssuerAccount = srvPK |
| 2468 |
actC.ImportType = kind |
| 2469 |
actC.ImportSubject = jwt.Subject(sub) |
| 2470 |
token, err := actC.Encode(srvSignerKP) |
| 2471 |
if err != nil { |
| 2472 |
t.Fatal(err) |
| 2473 |
} |
| 2474 |
return token |
| 2475 |
} |
| 2476 |
|
| 2477 |
createClientJwt := func() string { |
| 2478 |
ac := jwt.NewAccountClaims(clientPK) |
| 2479 |
ac.Imports.Add(&jwt.Import{Account: srvPK, Subject: "foo", Type: jwt.Service, Token: createImportToken("foo", jwt.Service)}) |
| 2480 |
ac.Imports.Add(&jwt.Import{Account: srvPK, Subject: "bar", Type: jwt.Stream, Token: createImportToken("bar", jwt.Stream)}) |
| 2481 |
token, err := ac.Encode(okp) |
| 2482 |
if err != nil { |
| 2483 |
t.Fatalf("Error generating importer JWT: %v", err) |
| 2484 |
} |
| 2485 |
return token |
| 2486 |
} |
| 2487 |
|
| 2488 |
srvJWT, _ := createSrvJwt(srvSignerPK) |
| 2489 |
addAccountToMemResolver(s, srvPK, srvJWT) |
| 2490 |
|
| 2491 |
clientJWT := createClientJwt() |
| 2492 |
addAccountToMemResolver(s, clientPK, clientJWT) |
| 2493 |
|
| 2494 |
// Create a client that will send the request |
| 2495 |
client, clientReader, clientCS := createClient(t, s, clientKP) |
| 2496 |
defer client.close() |
| 2497 |
client.parseAsync(clientCS) |
| 2498 |
expectPong(t, clientReader) |
| 2499 |
|
| 2500 |
checkShadow := func(expected int) { |
| 2501 |
t.Helper() |
| 2502 |
client.mu.Lock() |
| 2503 |
defer client.mu.Unlock() |
| 2504 |
sub := client.subs["1"] |
| 2505 |
count := 0 |
| 2506 |
if sub != nil { |
| 2507 |
count = len(sub.shadow) |
| 2508 |
} |
| 2509 |
if count != expected { |
| 2510 |
t.Fatalf("Expected shadows to be %d, got %d", expected, count) |
| 2511 |
} |
| 2512 |
} |
| 2513 |
|
| 2514 |
checkShadow(0) |
| 2515 |
// Create the client that will respond to the requests. |
| 2516 |
srv, srvReader, srvCS := createClient(t, s, srvKP) |
| 2517 |
defer srv.close() |
| 2518 |
srv.parseAsync(srvCS) |
| 2519 |
expectPong(t, srvReader) |
| 2520 |
|
| 2521 |
// Create Subscriber. |
| 2522 |
srv.parseAsync("SUB foo 1\r\nPING\r\n") |
| 2523 |
expectPong(t, srvReader) |
| 2524 |
|
| 2525 |
// Send Request |
| 2526 |
client.parseAsync("PUB foo 2\r\nhi\r\nPING\r\n") |
| 2527 |
expectPong(t, clientReader) |
| 2528 |
|
| 2529 |
// We should receive the request. PING needed to flush. |
| 2530 |
srv.parseAsync("PING\r\n") |
| 2531 |
expectMsg(t, srvReader, "foo", "hi") |
| 2532 |
|
| 2533 |
client.parseAsync("SUB bar 1\r\nPING\r\n") |
| 2534 |
expectPong(t, clientReader) |
| 2535 |
checkShadow(1) |
| 2536 |
|
| 2537 |
srv.parseAsync("PUB bar 2\r\nhi\r\nPING\r\n") |
| 2538 |
expectPong(t, srvReader) |
| 2539 |
|
| 2540 |
// We should receive from stream. PING needed to flush. |
| 2541 |
client.parseAsync("PING\r\n") |
| 2542 |
expectMsg(t, clientReader, "bar", "hi") |
| 2543 |
|
| 2544 |
// Now update the exported service no signer |
| 2545 |
srvJWT, srvAC := createSrvJwt() |
| 2546 |
addAccountToMemResolver(s, srvPK, srvJWT) |
| 2547 |
acc, _ := s.LookupAccount(srvPK) |
| 2548 |
s.UpdateAccountClaims(acc, srvAC) |
| 2549 |
|
| 2550 |
// Send Another Request |
| 2551 |
client.parseAsync("PUB foo 2\r\nhi\r\nPING\r\n") |
| 2552 |
expectPong(t, clientReader) |
| 2553 |
|
| 2554 |
// We should not receive the request this time. |
| 2555 |
srv.parseAsync("PING\r\n") |
| 2556 |
expectPong(t, srvReader) |
| 2557 |
|
| 2558 |
// Publish on the stream |
| 2559 |
srv.parseAsync("PUB bar 2\r\nhi\r\nPING\r\n") |
| 2560 |
expectPong(t, srvReader) |
| 2561 |
|
| 2562 |
// We should not receive from the stream this time |
| 2563 |
client.parseAsync("PING\r\n") |
| 2564 |
expectPong(t, clientReader) |
| 2565 |
checkShadow(0) |
| 2566 |
} |
| 2567 |
|
| 2568 |
func TestJWTAccountImportSignerDeadlock(t *testing.T) { |
| 2569 |
s := opTrustBasicSetup() |
| 2570 |
defer s.Shutdown() |
| 2571 |
buildMemAccResolver(s) |
| 2572 |
|
| 2573 |
okp, _ := nkeys.FromSeed(oSeed) |
| 2574 |
|
| 2575 |
// Exporter keys |
| 2576 |
srvKP, _ := nkeys.CreateAccount() |
| 2577 |
srvPK, _ := srvKP.PublicKey() |
| 2578 |
srvSignerKP, _ := nkeys.CreateAccount() |
| 2579 |
srvSignerPK, _ := srvSignerKP.PublicKey() |
| 2580 |
|
| 2581 |
// Importer keys |
| 2582 |
clientKP, _ := nkeys.CreateAccount() |
| 2583 |
clientPK, _ := clientKP.PublicKey() |
| 2584 |
|
| 2585 |
createSrvJwt := func(signingKeys ...string) (string, *jwt.AccountClaims) { |
| 2586 |
ac := jwt.NewAccountClaims(srvPK) |
| 2587 |
ac.SigningKeys.Add(signingKeys...) |
| 2588 |
ac.Exports.Add(&jwt.Export{Subject: "foo", Type: jwt.Service, TokenReq: true}) |
| 2589 |
ac.Exports.Add(&jwt.Export{Subject: "bar", Type: jwt.Stream, TokenReq: true}) |
| 2590 |
token, err := ac.Encode(okp) |
| 2591 |
if err != nil { |
| 2592 |
t.Fatalf("Error generating exporter JWT: %v", err) |
| 2593 |
} |
| 2594 |
return token, ac |
| 2595 |
} |
| 2596 |
|
| 2597 |
createImportToken := func(sub string, kind jwt.ExportType) string { |
| 2598 |
actC := jwt.NewActivationClaims(clientPK) |
| 2599 |
actC.IssuerAccount = srvPK |
| 2600 |
actC.ImportType = kind |
| 2601 |
actC.ImportSubject = jwt.Subject(sub) |
| 2602 |
token, err := actC.Encode(srvSignerKP) |
| 2603 |
if err != nil { |
| 2604 |
t.Fatal(err) |
| 2605 |
} |
| 2606 |
return token |
| 2607 |
} |
| 2608 |
|
| 2609 |
createClientJwt := func() string { |
| 2610 |
ac := jwt.NewAccountClaims(clientPK) |
| 2611 |
ac.Imports.Add(&jwt.Import{Account: srvPK, Subject: "foo", Type: jwt.Service, Token: createImportToken("foo", jwt.Service)}) |
| 2612 |
ac.Imports.Add(&jwt.Import{Account: srvPK, Subject: "bar", Type: jwt.Stream, Token: createImportToken("bar", jwt.Stream)}) |
| 2613 |
token, err := ac.Encode(okp) |
| 2614 |
if err != nil { |
| 2615 |
t.Fatalf("Error generating importer JWT: %v", err) |
| 2616 |
} |
| 2617 |
return token |
| 2618 |
} |
| 2619 |
|
| 2620 |
srvJWT, _ := createSrvJwt(srvSignerPK) |
| 2621 |
addAccountToMemResolver(s, srvPK, srvJWT) |
| 2622 |
|
| 2623 |
clientJWT := createClientJwt() |
| 2624 |
addAccountToMemResolver(s, clientPK, clientJWT) |
| 2625 |
|
| 2626 |
acc, _ := s.LookupAccount(srvPK) |
| 2627 |
// Have a go routine that constantly gets/releases the acc's write lock. |
| 2628 |
// There was a bug that could cause AddServiceImportWithClaim to deadlock. |
| 2629 |
ch := make(chan bool, 1) |
| 2630 |
wg := sync.WaitGroup{} |
| 2631 |
wg.Add(1) |
| 2632 |
go func() { |
| 2633 |
defer wg.Done() |
| 2634 |
for { |
| 2635 |
select { |
| 2636 |
case <-ch: |
| 2637 |
return |
| 2638 |
default: |
| 2639 |
acc.mu.Lock() |
| 2640 |
acc.mu.Unlock() |
| 2641 |
time.Sleep(time.Millisecond) |
| 2642 |
} |
| 2643 |
} |
| 2644 |
}() |
| 2645 |
|
| 2646 |
// Create a client that will send the request |
| 2647 |
client, clientReader, clientCS := createClient(t, s, clientKP) |
| 2648 |
defer client.close() |
| 2649 |
client.parseAsync(clientCS) |
| 2650 |
expectPong(t, clientReader) |
| 2651 |
|
| 2652 |
close(ch) |
| 2653 |
wg.Wait() |
| 2654 |
} |
| 2655 |
|
| 2656 |
func TestJWTAccountImportWrongIssuerAccount(t *testing.T) { |
| 2657 |
s := opTrustBasicSetup() |
| 2658 |
defer s.Shutdown() |
| 2659 |
buildMemAccResolver(s) |
| 2660 |
|
| 2661 |
l := &captureErrorLogger{errCh: make(chan string, 2)} |
| 2662 |
s.SetLogger(l, false, false) |
| 2663 |
|
| 2664 |
okp, _ := nkeys.FromSeed(oSeed) |
| 2665 |
|
| 2666 |
// Exporter keys |
| 2667 |
srvKP, _ := nkeys.CreateAccount() |
| 2668 |
srvPK, _ := srvKP.PublicKey() |
| 2669 |
srvSignerKP, _ := nkeys.CreateAccount() |
| 2670 |
srvSignerPK, _ := srvSignerKP.PublicKey() |
| 2671 |
|
| 2672 |
// Importer keys |
| 2673 |
clientKP, _ := nkeys.CreateAccount() |
| 2674 |
clientPK, _ := clientKP.PublicKey() |
| 2675 |
|
| 2676 |
createSrvJwt := func(signingKeys ...string) (string, *jwt.AccountClaims) { |
| 2677 |
ac := jwt.NewAccountClaims(srvPK) |
| 2678 |
ac.SigningKeys.Add(signingKeys...) |
| 2679 |
ac.Exports.Add(&jwt.Export{Subject: "foo", Type: jwt.Service, TokenReq: true}) |
| 2680 |
ac.Exports.Add(&jwt.Export{Subject: "bar", Type: jwt.Stream, TokenReq: true}) |
| 2681 |
token, err := ac.Encode(okp) |
| 2682 |
if err != nil { |
| 2683 |
t.Fatalf("Error generating exporter JWT: %v", err) |
| 2684 |
} |
| 2685 |
return token, ac |
| 2686 |
} |
| 2687 |
|
| 2688 |
createImportToken := func(sub string, kind jwt.ExportType) string { |
| 2689 |
actC := jwt.NewActivationClaims(clientPK) |
| 2690 |
// Reference ourselves, which is wrong. |
| 2691 |
actC.IssuerAccount = clientPK |
| 2692 |
actC.ImportType = kind |
| 2693 |
actC.ImportSubject = jwt.Subject(sub) |
| 2694 |
token, err := actC.Encode(srvSignerKP) |
| 2695 |
if err != nil { |
| 2696 |
t.Fatal(err) |
| 2697 |
} |
| 2698 |
return token |
| 2699 |
} |
| 2700 |
|
| 2701 |
createClientJwt := func() string { |
| 2702 |
ac := jwt.NewAccountClaims(clientPK) |
| 2703 |
ac.Imports.Add(&jwt.Import{Account: srvPK, Subject: "foo", Type: jwt.Service, Token: createImportToken("foo", jwt.Service)}) |
| 2704 |
ac.Imports.Add(&jwt.Import{Account: srvPK, Subject: "bar", Type: jwt.Stream, Token: createImportToken("bar", jwt.Stream)}) |
| 2705 |
token, err := ac.Encode(okp) |
| 2706 |
if err != nil { |
| 2707 |
t.Fatalf("Error generating importer JWT: %v", err) |
| 2708 |
} |
| 2709 |
return token |
| 2710 |
} |
| 2711 |
|
| 2712 |
srvJWT, _ := createSrvJwt(srvSignerPK) |
| 2713 |
addAccountToMemResolver(s, srvPK, srvJWT) |
| 2714 |
|
| 2715 |
clientJWT := createClientJwt() |
| 2716 |
addAccountToMemResolver(s, clientPK, clientJWT) |
| 2717 |
|
| 2718 |
// Create a client that will send the request |
| 2719 |
client, clientReader, clientCS := createClient(t, s, clientKP) |
| 2720 |
defer client.close() |
| 2721 |
client.parseAsync(clientCS) |
| 2722 |
if l, _, err := clientReader.ReadLine(); err != nil { |
| 2723 |
t.Fatalf("Expected no Error, got: %v", err) |
| 2724 |
} else if !strings.Contains(string(l), "-ERR 'Authorization Violation'") { |
| 2725 |
t.Fatalf("Expected Error, got: %v", l) |
| 2726 |
} |
| 2727 |
} |
| 2728 |
|
| 2729 |
func TestJWTUserRevokedOnAccountUpdate(t *testing.T) { |
| 2730 |
nac := newJWTTestAccountClaims() |
| 2731 |
s, akp, c, cr := setupJWTTestWitAccountClaims(t, nac, "+OK") |
| 2732 |
defer s.Shutdown() |
| 2733 |
defer c.close() |
| 2734 |
|
| 2735 |
expectPong(t, cr) |
| 2736 |
|
| 2737 |
okp, _ := nkeys.FromSeed(oSeed) |
| 2738 |
apub, _ := akp.PublicKey() |
| 2739 |
|
| 2740 |
c.mu.Lock() |
| 2741 |
pub := c.user.Nkey |
| 2742 |
c.mu.Unlock() |
| 2743 |
|
| 2744 |
// Now revoke the user. |
| 2745 |
nac.Revoke(pub) |
| 2746 |
|
| 2747 |
ajwt, err := nac.Encode(okp) |
| 2748 |
if err != nil { |
| 2749 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2750 |
} |
| 2751 |
|
| 2752 |
// Update the account on the server. |
| 2753 |
addAccountToMemResolver(s, apub, ajwt) |
| 2754 |
acc, err := s.LookupAccount(apub) |
| 2755 |
if err != nil { |
| 2756 |
t.Fatalf("Error looking up the account: %v", err) |
| 2757 |
} |
| 2758 |
|
| 2759 |
// This is simulating a system update for the account claims. |
| 2760 |
go s.updateAccountWithClaimJWT(acc, ajwt) |
| 2761 |
|
| 2762 |
l, _ := cr.ReadString('\n') |
| 2763 |
if !strings.HasPrefix(l, "-ERR ") { |
| 2764 |
t.Fatalf("Expected an error") |
| 2765 |
} |
| 2766 |
if !strings.Contains(l, "Revoked") { |
| 2767 |
t.Fatalf("Expected 'Revoked' to be in the error") |
| 2768 |
} |
| 2769 |
} |
| 2770 |
|
| 2771 |
func TestJWTUserRevoked(t *testing.T) { |
| 2772 |
okp, _ := nkeys.FromSeed(oSeed) |
| 2773 |
|
| 2774 |
// Create a new user that we will make sure has been revoked. |
| 2775 |
nkp, _ := nkeys.CreateUser() |
| 2776 |
pub, _ := nkp.PublicKey() |
| 2777 |
nuc := jwt.NewUserClaims(pub) |
| 2778 |
|
| 2779 |
akp, _ := nkeys.CreateAccount() |
| 2780 |
apub, _ := akp.PublicKey() |
| 2781 |
nac := jwt.NewAccountClaims(apub) |
| 2782 |
// Revoke the user right away. |
| 2783 |
nac.Revoke(pub) |
| 2784 |
ajwt, err := nac.Encode(okp) |
| 2785 |
if err != nil { |
| 2786 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2787 |
} |
| 2788 |
|
| 2789 |
// Sign for the user. |
| 2790 |
jwt, err := nuc.Encode(akp) |
| 2791 |
if err != nil { |
| 2792 |
t.Fatalf("Error generating user JWT: %v", err) |
| 2793 |
} |
| 2794 |
|
| 2795 |
s := opTrustBasicSetup() |
| 2796 |
defer s.Shutdown() |
| 2797 |
buildMemAccResolver(s) |
| 2798 |
addAccountToMemResolver(s, apub, ajwt) |
| 2799 |
|
| 2800 |
c, cr, l := newClientForServer(s) |
| 2801 |
defer c.close() |
| 2802 |
|
| 2803 |
// Sign Nonce |
| 2804 |
var info nonceInfo |
| 2805 |
json.Unmarshal([]byte(l[5:]), &info) |
| 2806 |
sigraw, _ := nkp.Sign([]byte(info.Nonce)) |
| 2807 |
sig := base64.RawURLEncoding.EncodeToString(sigraw) |
| 2808 |
|
| 2809 |
// PING needed to flush the +OK/-ERR to us. |
| 2810 |
cs := fmt.Sprintf("CONNECT {\"jwt\":%q,\"sig\":\"%s\"}\r\nPING\r\n", jwt, sig) |
| 2811 |
|
| 2812 |
c.parseAsync(cs) |
| 2813 |
|
| 2814 |
l, _ = cr.ReadString('\n') |
| 2815 |
if !strings.HasPrefix(l, "-ERR ") { |
| 2816 |
t.Fatalf("Expected an error") |
| 2817 |
} |
| 2818 |
if !strings.Contains(l, "Authorization") { |
| 2819 |
t.Fatalf("Expected 'Revoked' to be in the error") |
| 2820 |
} |
| 2821 |
} |
| 2822 |
|
| 2823 |
// Test that an account update that revokes an import authorization cancels the import. |
| 2824 |
func TestJWTImportTokenRevokedAfter(t *testing.T) { |
| 2825 |
s := opTrustBasicSetup() |
| 2826 |
defer s.Shutdown() |
| 2827 |
buildMemAccResolver(s) |
| 2828 |
|
| 2829 |
okp, _ := nkeys.FromSeed(oSeed) |
| 2830 |
|
| 2831 |
// Create accounts and imports/exports. |
| 2832 |
fooKP, _ := nkeys.CreateAccount() |
| 2833 |
fooPub, _ := fooKP.PublicKey() |
| 2834 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 2835 |
|
| 2836 |
// Now create Exports. |
| 2837 |
export := &jwt.Export{Subject: "foo.private", Type: jwt.Stream, TokenReq: true} |
| 2838 |
|
| 2839 |
fooAC.Exports.Add(export) |
| 2840 |
fooJWT, err := fooAC.Encode(okp) |
| 2841 |
if err != nil { |
| 2842 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2843 |
} |
| 2844 |
|
| 2845 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 2846 |
|
| 2847 |
barKP, _ := nkeys.CreateAccount() |
| 2848 |
barPub, _ := barKP.PublicKey() |
| 2849 |
barAC := jwt.NewAccountClaims(barPub) |
| 2850 |
simport := &jwt.Import{Account: fooPub, Subject: "foo.private", Type: jwt.Stream} |
| 2851 |
|
| 2852 |
activation := jwt.NewActivationClaims(barPub) |
| 2853 |
activation.ImportSubject = "foo.private" |
| 2854 |
activation.ImportType = jwt.Stream |
| 2855 |
actJWT, err := activation.Encode(fooKP) |
| 2856 |
if err != nil { |
| 2857 |
t.Fatalf("Error generating activation token: %v", err) |
| 2858 |
} |
| 2859 |
|
| 2860 |
simport.Token = actJWT |
| 2861 |
barAC.Imports.Add(simport) |
| 2862 |
barJWT, err := barAC.Encode(okp) |
| 2863 |
if err != nil { |
| 2864 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2865 |
} |
| 2866 |
addAccountToMemResolver(s, barPub, barJWT) |
| 2867 |
|
| 2868 |
// Now revoke the export. |
| 2869 |
decoded, _ := jwt.DecodeActivationClaims(actJWT) |
| 2870 |
export.Revoke(decoded.Subject) |
| 2871 |
|
| 2872 |
fooJWT, err = fooAC.Encode(okp) |
| 2873 |
if err != nil { |
| 2874 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2875 |
} |
| 2876 |
|
| 2877 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 2878 |
|
| 2879 |
fooAcc, _ := s.LookupAccount(fooPub) |
| 2880 |
if fooAcc == nil { |
| 2881 |
t.Fatalf("Expected to retrieve the account") |
| 2882 |
} |
| 2883 |
|
| 2884 |
// Now lookup bar account and make sure it was revoked. |
| 2885 |
acc, _ := s.LookupAccount(barPub) |
| 2886 |
if acc == nil { |
| 2887 |
t.Fatalf("Expected to retrieve the account") |
| 2888 |
} |
| 2889 |
if les := len(acc.imports.streams); les != 0 { |
| 2890 |
t.Fatalf("Expected imports streams len of 0, got %d", les) |
| 2891 |
} |
| 2892 |
} |
| 2893 |
|
| 2894 |
// Test that an account update that revokes an import authorization cancels the import. |
| 2895 |
func TestJWTImportTokenRevokedBefore(t *testing.T) { |
| 2896 |
s := opTrustBasicSetup() |
| 2897 |
defer s.Shutdown() |
| 2898 |
buildMemAccResolver(s) |
| 2899 |
|
| 2900 |
okp, _ := nkeys.FromSeed(oSeed) |
| 2901 |
|
| 2902 |
// Create accounts and imports/exports. |
| 2903 |
fooKP, _ := nkeys.CreateAccount() |
| 2904 |
fooPub, _ := fooKP.PublicKey() |
| 2905 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 2906 |
|
| 2907 |
// Now create Exports. |
| 2908 |
export := &jwt.Export{Subject: "foo.private", Type: jwt.Stream, TokenReq: true} |
| 2909 |
|
| 2910 |
fooAC.Exports.Add(export) |
| 2911 |
|
| 2912 |
// Import account |
| 2913 |
barKP, _ := nkeys.CreateAccount() |
| 2914 |
barPub, _ := barKP.PublicKey() |
| 2915 |
barAC := jwt.NewAccountClaims(barPub) |
| 2916 |
simport := &jwt.Import{Account: fooPub, Subject: "foo.private", Type: jwt.Stream} |
| 2917 |
|
| 2918 |
activation := jwt.NewActivationClaims(barPub) |
| 2919 |
activation.ImportSubject = "foo.private" |
| 2920 |
activation.ImportType = jwt.Stream |
| 2921 |
actJWT, err := activation.Encode(fooKP) |
| 2922 |
if err != nil { |
| 2923 |
t.Fatalf("Error generating activation token: %v", err) |
| 2924 |
} |
| 2925 |
|
| 2926 |
simport.Token = actJWT |
| 2927 |
barAC.Imports.Add(simport) |
| 2928 |
|
| 2929 |
// Now revoke the export. |
| 2930 |
decoded, _ := jwt.DecodeActivationClaims(actJWT) |
| 2931 |
export.Revoke(decoded.Subject) |
| 2932 |
|
| 2933 |
fooJWT, err := fooAC.Encode(okp) |
| 2934 |
if err != nil { |
| 2935 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2936 |
} |
| 2937 |
|
| 2938 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 2939 |
|
| 2940 |
barJWT, err := barAC.Encode(okp) |
| 2941 |
if err != nil { |
| 2942 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2943 |
} |
| 2944 |
addAccountToMemResolver(s, barPub, barJWT) |
| 2945 |
|
| 2946 |
fooAcc, _ := s.LookupAccount(fooPub) |
| 2947 |
if fooAcc == nil { |
| 2948 |
t.Fatalf("Expected to retrieve the account") |
| 2949 |
} |
| 2950 |
|
| 2951 |
// Now lookup bar account and make sure it was revoked. |
| 2952 |
acc, _ := s.LookupAccount(barPub) |
| 2953 |
if acc == nil { |
| 2954 |
t.Fatalf("Expected to retrieve the account") |
| 2955 |
} |
| 2956 |
if les := len(acc.imports.streams); les != 0 { |
| 2957 |
t.Fatalf("Expected imports streams len of 0, got %d", les) |
| 2958 |
} |
| 2959 |
} |
| 2960 |
|
| 2961 |
func TestJWTCircularAccountServiceImport(t *testing.T) { |
| 2962 |
s := opTrustBasicSetup() |
| 2963 |
defer s.Shutdown() |
| 2964 |
buildMemAccResolver(s) |
| 2965 |
|
| 2966 |
okp, _ := nkeys.FromSeed(oSeed) |
| 2967 |
|
| 2968 |
// Create accounts |
| 2969 |
fooKP, _ := nkeys.CreateAccount() |
| 2970 |
fooPub, _ := fooKP.PublicKey() |
| 2971 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 2972 |
|
| 2973 |
barKP, _ := nkeys.CreateAccount() |
| 2974 |
barPub, _ := barKP.PublicKey() |
| 2975 |
barAC := jwt.NewAccountClaims(barPub) |
| 2976 |
|
| 2977 |
// Create service export/import for account foo |
| 2978 |
serviceExport := &jwt.Export{Subject: "foo", Type: jwt.Service, TokenReq: true} |
| 2979 |
serviceImport := &jwt.Import{Account: barPub, Subject: "bar", Type: jwt.Service} |
| 2980 |
|
| 2981 |
fooAC.Exports.Add(serviceExport) |
| 2982 |
fooAC.Imports.Add(serviceImport) |
| 2983 |
fooJWT, err := fooAC.Encode(okp) |
| 2984 |
if err != nil { |
| 2985 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2986 |
} |
| 2987 |
|
| 2988 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 2989 |
|
| 2990 |
// Create service export/import for account bar |
| 2991 |
serviceExport = &jwt.Export{Subject: "bar", Type: jwt.Service, TokenReq: true} |
| 2992 |
serviceImport = &jwt.Import{Account: fooPub, Subject: "foo", Type: jwt.Service} |
| 2993 |
|
| 2994 |
barAC.Exports.Add(serviceExport) |
| 2995 |
barAC.Imports.Add(serviceImport) |
| 2996 |
barJWT, err := barAC.Encode(okp) |
| 2997 |
if err != nil { |
| 2998 |
t.Fatalf("Error generating account JWT: %v", err) |
| 2999 |
} |
| 3000 |
|
| 3001 |
addAccountToMemResolver(s, barPub, barJWT) |
| 3002 |
|
| 3003 |
c, cr, cs := createClient(t, s, fooKP) |
| 3004 |
defer c.close() |
| 3005 |
|
| 3006 |
c.parseAsync(cs) |
| 3007 |
expectPong(t, cr) |
| 3008 |
|
| 3009 |
c.parseAsync("SUB foo 1\r\nPING\r\n") |
| 3010 |
expectPong(t, cr) |
| 3011 |
} |
| 3012 |
|
| 3013 |
// This test ensures that connected clients are properly evicted |
| 3014 |
// (no deadlock) if the max conns of an account has been lowered |
| 3015 |
// and the account is being updated (following expiration during |
| 3016 |
// a lookup). |
| 3017 |
func TestJWTAccountLimitsMaxConnsAfterExpired(t *testing.T) { |
| 3018 |
s := opTrustBasicSetup() |
| 3019 |
defer s.Shutdown() |
| 3020 |
buildMemAccResolver(s) |
| 3021 |
|
| 3022 |
okp, _ := nkeys.FromSeed(oSeed) |
| 3023 |
|
| 3024 |
// Create accounts and imports/exports. |
| 3025 |
fooKP, _ := nkeys.CreateAccount() |
| 3026 |
fooPub, _ := fooKP.PublicKey() |
| 3027 |
fooAC := jwt.NewAccountClaims(fooPub) |
| 3028 |
fooAC.Limits.Conn = 10 |
| 3029 |
fooJWT, err := fooAC.Encode(okp) |
| 3030 |
if err != nil { |
| 3031 |
t.Fatalf("Error generating account JWT: %v", err) |
| 3032 |
} |
| 3033 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 3034 |
|
| 3035 |
newClient := func(expPre string) *testAsyncClient { |
| 3036 |
t.Helper() |
| 3037 |
// Create a client. |
| 3038 |
c, cr, cs := createClient(t, s, fooKP) |
| 3039 |
c.parseAsync(cs) |
| 3040 |
l, _ := cr.ReadString('\n') |
| 3041 |
if !strings.HasPrefix(l, expPre) { |
| 3042 |
t.Fatalf("Expected a response starting with %q, got %q", expPre, l) |
| 3043 |
} |
| 3044 |
go func() { |
| 3045 |
for { |
| 3046 |
if _, _, err := cr.ReadLine(); err != nil { |
| 3047 |
return |
| 3048 |
} |
| 3049 |
} |
| 3050 |
}() |
| 3051 |
return c |
| 3052 |
} |
| 3053 |
|
| 3054 |
for i := 0; i < 4; i++ { |
| 3055 |
c := newClient("PONG") |
| 3056 |
defer c.close() |
| 3057 |
} |
| 3058 |
|
| 3059 |
// We will simulate that the account has expired. When |
| 3060 |
// a new client will connect, the server will do a lookup |
| 3061 |
// and find the account expired, which then will cause |
| 3062 |
// a fetch and a rebuild of the account. Since max conns |
| 3063 |
// is now lower, some clients should have been removed. |
| 3064 |
acc, _ := s.LookupAccount(fooPub) |
| 3065 |
acc.mu.Lock() |
| 3066 |
acc.expired.Store(true) |
| 3067 |
acc.updated = time.Now().UTC().Add(-2 * time.Second) // work around updating to quickly |
| 3068 |
acc.mu.Unlock() |
| 3069 |
|
| 3070 |
// Now update with new expiration and max connections lowered to 2 |
| 3071 |
fooAC.Limits.Conn = 2 |
| 3072 |
fooJWT, err = fooAC.Encode(okp) |
| 3073 |
if err != nil { |
| 3074 |
t.Fatalf("Error generating account JWT: %v", err) |
| 3075 |
} |
| 3076 |
addAccountToMemResolver(s, fooPub, fooJWT) |
| 3077 |
|
| 3078 |
// Cause the lookup that will detect that account was expired |
| 3079 |
// and rebuild it, and kick clients out. |
| 3080 |
c := newClient("-ERR ") |
| 3081 |
defer c.close() |
| 3082 |
|
| 3083 |
acc, _ = s.LookupAccount(fooPub) |
| 3084 |
checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { |
| 3085 |
acc.mu.RLock() |
| 3086 |
numClients := len(acc.clients) |
| 3087 |
acc.mu.RUnlock() |
| 3088 |
if numClients != 2 { |
| 3089 |
return fmt.Errorf("Should have 2 clients, got %v", numClients) |
| 3090 |
} |
| 3091 |
return nil |
| 3092 |
}) |
| 3093 |
} |
| 3094 |
|
| 3095 |
func TestJWTBearerToken(t *testing.T) { |
| 3096 |
okp, _ := nkeys.FromSeed(oSeed) |
| 3097 |
akp, _ := nkeys.CreateAccount() |
| 3098 |
apub, _ := akp.PublicKey() |
| 3099 |
nac := jwt.NewAccountClaims(apub) |
| 3100 |
ajwt, err := nac.Encode(okp) |
| 3101 |
if err != nil { |
| 3102 |
t.Fatalf("Error generating account JWT: %v", err) |
| 3103 |
} |
| 3104 |
|
| 3105 |
nkp, _ := nkeys.CreateUser() |
| 3106 |
pub, _ := nkp.PublicKey() |
| 3107 |
nuc := newJWTTestUserClaims() |
| 3108 |
nuc.Subject = pub |
| 3109 |
// Set bearer token. |
| 3110 |
nuc.BearerToken = true |
| 3111 |
jwt, err := nuc.Encode(akp) |
| 3112 |
if err != nil { |
| 3113 |
t.Fatalf("Error generating user JWT: %v", err) |
| 3114 |
} |
| 3115 |
|
| 3116 |
s := opTrustBasicSetup() |
| 3117 |
defer s.Shutdown() |
| 3118 |
buildMemAccResolver(s) |
| 3119 |
addAccountToMemResolver(s, apub, ajwt) |
| 3120 |
|
| 3121 |
c, cr, _ := newClientForServer(s) |
| 3122 |
defer c.close() |
| 3123 |
|
| 3124 |
// Skip nonce signature... |
| 3125 |
|
| 3126 |
// PING needed to flush the +OK/-ERR to us. |
| 3127 |
cs := fmt.Sprintf("CONNECT {\"jwt\":%q,\"verbose\":true,\"pedantic\":true}\r\nPING\r\n", jwt) |
| 3128 |
wg := sync.WaitGroup{} |
| 3129 |
wg.Add(1) |
| 3130 |
go func() { |
| 3131 |
c.parse([]byte(cs)) |
| 3132 |
wg.Done() |
| 3133 |
}() |
| 3134 |
l, _ := cr.ReadString('\n') |
| 3135 |
if !strings.HasPrefix(l, "+OK") { |
| 3136 |
t.Fatalf("Expected +OK, got %s", l) |
| 3137 |
} |
| 3138 |
wg.Wait() |
| 3139 |
} |
| 3140 |
|
| 3141 |
func TestJWTBearerWithIssuerSameAsAccountToken(t *testing.T) { |
| 3142 |
okp, _ := nkeys.FromSeed(oSeed) |
| 3143 |
akp, _ := nkeys.CreateAccount() |
| 3144 |
apub, _ := akp.PublicKey() |
| 3145 |
nac := jwt.NewAccountClaims(apub) |
| 3146 |
ajwt, err := nac.Encode(okp) |
| 3147 |
if err != nil { |
| 3148 |
t.Fatalf("Error generating account JWT: %v", err) |
| 3149 |
} |
| 3150 |
|
| 3151 |
nkp, _ := nkeys.CreateUser() |
| 3152 |
pub, _ := nkp.PublicKey() |
| 3153 |
nuc := newJWTTestUserClaims() |
| 3154 |
// we are setting the issuer account here to trigger verification |
| 3155 |
// of the issuer - the account has no signing keys, but the issuer |
| 3156 |
// account is set to the public key of the account which should be OK. |
| 3157 |
nuc.IssuerAccount = apub |
| 3158 |
nuc.Subject = pub |
| 3159 |
// Set bearer token. |
| 3160 |
nuc.BearerToken = true |
| 3161 |
jwt, err := nuc.Encode(akp) |
| 3162 |
if err != nil { |
| 3163 |
t.Fatalf("Error generating user JWT: %v", err) |
| 3164 |
} |
| 3165 |
|
| 3166 |
s := opTrustBasicSetup() |
| 3167 |
defer s.Shutdown() |
| 3168 |
buildMemAccResolver(s) |
| 3169 |
addAccountToMemResolver(s, apub, ajwt) |
| 3170 |
|
| 3171 |
c, cr, _ := newClientForServer(s) |
| 3172 |
defer c.close() |
| 3173 |
|
| 3174 |
// Skip nonce signature... |
| 3175 |
|
| 3176 |
// PING needed to flush the +OK/-ERR to us. |
| 3177 |
cs := fmt.Sprintf("CONNECT {\"jwt\":%q,\"verbose\":true,\"pedantic\":true}\r\nPING\r\n", jwt) |
| 3178 |
wg := sync.WaitGroup{} |
| 3179 |
wg.Add(1) |
| 3180 |
go func() { |
| 3181 |
c.parse([]byte(cs)) |
| 3182 |
wg.Done() |
| 3183 |
}() |
| 3184 |
l, _ := cr.ReadString('\n') |
| 3185 |
if !strings.HasPrefix(l, "+OK") { |
| 3186 |
t.Fatalf("Expected +OK, got %s", l) |
| 3187 |
} |
| 3188 |
wg.Wait() |
| 3189 |
} |
| 3190 |
|
| 3191 |
func TestJWTBearerWithBadIssuerToken(t *testing.T) { |
| 3192 |
okp, _ := nkeys.FromSeed(oSeed) |
| 3193 |
akp, _ := nkeys.CreateAccount() |
| 3194 |
apub, _ := akp.PublicKey() |
| 3195 |
nac := jwt.NewAccountClaims(apub) |
| 3196 |
ajwt, err := nac.Encode(okp) |
| 3197 |
if err != nil { |
| 3198 |
t.Fatalf("Error generating account JWT: %v", err) |
| 3199 |
} |
| 3200 |
|
| 3201 |
nkp, _ := nkeys.CreateUser() |
| 3202 |
pub, _ := nkp.PublicKey() |
| 3203 |
nuc := newJWTTestUserClaims() |
| 3204 |
bakp, _ := nkeys.CreateAccount() |
| 3205 |
bapub, _ := bakp.PublicKey() |
| 3206 |
nuc.IssuerAccount = bapub |
| 3207 |
nuc.Subject = pub |
| 3208 |
// Set bearer token. |
| 3209 |
nuc.BearerToken = true |
| 3210 |
jwt, err := nuc.Encode(akp) |
| 3211 |
if err != nil { |
| 3212 |
t.Fatalf("Error generating user JWT: %v", err) |
| 3213 |
} |
| 3214 |
|
| 3215 |
s := opTrustBasicSetup() |
| 3216 |
defer s.Shutdown() |
| 3217 |
buildMemAccResolver(s) |
| 3218 |
addAccountToMemResolver(s, apub, ajwt) |
| 3219 |
|
| 3220 |
c, cr, _ := newClientForServer(s) |
| 3221 |
defer c.close() |
| 3222 |
|
| 3223 |
// Skip nonce signature... |
| 3224 |
|
| 3225 |
// PING needed to flush the +OK/-ERR to us. |
| 3226 |
cs := fmt.Sprintf("CONNECT {\"jwt\":%q,\"verbose\":true,\"pedantic\":true}\r\nPING\r\n", jwt) |
| 3227 |
wg := sync.WaitGroup{} |
| 3228 |
wg.Add(1) |
| 3229 |
go func() { |
| 3230 |
c.parse([]byte(cs)) |
| 3231 |
wg.Done() |
| 3232 |
}() |
| 3233 |
l, _ := cr.ReadString('\n') |
| 3234 |
if !strings.HasPrefix(l, "-ERR") { |
| 3235 |
t.Fatalf("Expected -ERR, got %s", l) |
| 3236 |
} |
| 3237 |
wg.Wait() |
| 3238 |
} |
| 3239 |
|
| 3240 |
func TestJWTExpiredUserCredentialsRenewal(t *testing.T) { |
| 3241 |
createTmpFile := func(t *testing.T, content []byte) string { |
| 3242 |
t.Helper() |
| 3243 |
conf := createTempFile(t, _EMPTY_) |
| 3244 |
fName := conf.Name() |
| 3245 |
conf.Close() |
| 3246 |
if err := os.WriteFile(fName, content, 0666); err != nil { |
| 3247 |
t.Fatalf("Error writing conf file: %v", err) |
| 3248 |
} |
| 3249 |
return fName |
| 3250 |
} |
| 3251 |
waitTime := func(ch chan bool, timeout time.Duration) error { |
| 3252 |
select { |
| 3253 |
case <-ch: |
| 3254 |
return nil |
| 3255 |
case <-time.After(timeout): |
| 3256 |
} |
| 3257 |
return errors.New("timeout") |
| 3258 |
} |
| 3259 |
|
| 3260 |
okp, _ := nkeys.FromSeed(oSeed) |
| 3261 |
akp, err := nkeys.CreateAccount() |
| 3262 |
if err != nil { |
| 3263 |
t.Fatalf("Error generating account") |
| 3264 |
} |
| 3265 |
aPub, _ := akp.PublicKey() |
| 3266 |
nac := jwt.NewAccountClaims(aPub) |
| 3267 |
aJwt, err := nac.Encode(okp) |
| 3268 |
if err != nil { |
| 3269 |
t.Fatalf("Error generating account JWT: %v", err) |
| 3270 |
} |
| 3271 |
|
| 3272 |
kp, _ := nkeys.FromSeed(oSeed) |
| 3273 |
oPub, _ := kp.PublicKey() |
| 3274 |
opts := defaultServerOptions |
| 3275 |
opts.TrustedKeys = []string{oPub} |
| 3276 |
s := RunServer(&opts) |
| 3277 |
if s == nil { |
| 3278 |
t.Fatal("Server did not start") |
| 3279 |
} |
| 3280 |
defer s.Shutdown() |
| 3281 |
buildMemAccResolver(s) |
| 3282 |
addAccountToMemResolver(s, aPub, aJwt) |
| 3283 |
|
| 3284 |
nkp, _ := nkeys.CreateUser() |
| 3285 |
pub, _ := nkp.PublicKey() |
| 3286 |
uSeed, _ := nkp.Seed() |
| 3287 |
nuc := newJWTTestUserClaims() |
| 3288 |
nuc.Subject = pub |
| 3289 |
nuc.Expires = time.Now().Add(time.Second).Unix() |
| 3290 |
uJwt, err := nuc.Encode(akp) |
| 3291 |
if err != nil { |
| 3292 |
t.Fatalf("Error generating user JWT: %v", err) |
| 3293 |
} |
| 3294 |
|
| 3295 |
creds, err := jwt.FormatUserConfig(uJwt, uSeed) |
| 3296 |
if err != nil { |
| 3297 |
t.Fatalf("Error encoding credentials: %v", err) |
| 3298 |
} |
| 3299 |
chainedFile := createTmpFile(t, creds) |
| 3300 |
|
| 3301 |
rch := make(chan bool) |
| 3302 |
|
| 3303 |
url := fmt.Sprintf("nats://%s:%d", s.opts.Host, s.opts.Port) |
| 3304 |
nc, err := nats.Connect(url, |
| 3305 |
nats.UserCredentials(chainedFile), |
| 3306 |
nats.ReconnectWait(25*time.Millisecond), |
| 3307 |
nats.ReconnectJitter(0, 0), |
| 3308 |
nats.MaxReconnects(2), |
| 3309 |
nats.ErrorHandler(noOpErrHandler), |
| 3310 |
nats.ReconnectHandler(func(nc *nats.Conn) { |
| 3311 |
rch <- true |
| 3312 |
}), |
| 3313 |
) |
| 3314 |
if err != nil { |
| 3315 |
t.Fatalf("Expected to connect, got %v %s", err, url) |
| 3316 |
} |
| 3317 |
defer nc.Close() |
| 3318 |
|
| 3319 |
// Place new credentials underneath. |
| 3320 |
nuc.Expires = time.Now().Add(30 * time.Second).Unix() |
| 3321 |
uJwt, err = nuc.Encode(akp) |
| 3322 |
if err != nil { |
| 3323 |
t.Fatalf("Error encoding user jwt: %v", err) |
| 3324 |
} |
| 3325 |
creds, err = jwt.FormatUserConfig(uJwt, uSeed) |
| 3326 |
if err != nil { |
| 3327 |
t.Fatalf("Error encoding credentials: %v", err) |
| 3328 |
} |
| 3329 |
if err := os.WriteFile(chainedFile, creds, 0666); err != nil { |
| 3330 |
t.Fatalf("Error writing conf file: %v", err) |
| 3331 |
} |
| 3332 |
|
| 3333 |
// Make sure we get disconnected and reconnected first. |
| 3334 |
if err := waitTime(rch, 2*time.Second); err != nil { |
| 3335 |
t.Fatal("Should have reconnected.") |
| 3336 |
} |
| 3337 |
|
| 3338 |
// We should not have been closed. |
| 3339 |
if nc.IsClosed() { |
| 3340 |
t.Fatal("Got disconnected when we should have reconnected.") |
| 3341 |
} |
| 3342 |
|
| 3343 |
// Check that we clear the lastErr that can cause the disconnect. |
| 3344 |
// Our reconnect CB will happen before the clear. So check after a bit. |
| 3345 |
time.Sleep(50 * time.Millisecond) |
| 3346 |
if nc.LastError() != nil { |
| 3347 |
t.Fatalf("Expected lastErr to be cleared, got %q", nc.LastError()) |
| 3348 |
} |
| 3349 |
} |
| 3350 |
|
| 3351 |
func updateJwt(t *testing.T, url string, creds string, jwt string, respCnt int) int { |
| 3352 |
t.Helper() |
| 3353 |
require_NextMsg := func(sub *nats.Subscription) bool { |
| 3354 |
t.Helper() |
| 3355 |
msg := natsNexMsg(t, sub, time.Second) |
| 3356 |
content := make(map[string]any) |
| 3357 |
json.Unmarshal(msg.Data, &content) |
| 3358 |
if _, ok := content["data"]; ok { |
| 3359 |
return true |
| 3360 |
} |
| 3361 |
return false |
| 3362 |
} |
| 3363 |
c := natsConnect(t, url, nats.UserCredentials(creds), |
| 3364 |
nats.DisconnectErrHandler(func(_ *nats.Conn, err error) { |
| 3365 |
if err != nil { |
| 3366 |
t.Fatal("error not expected in this test", err) |
| 3367 |
} |
| 3368 |
}), |
| 3369 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) { |
| 3370 |
t.Fatal("error not expected in this test", err) |
| 3371 |
}), |
| 3372 |
) |
| 3373 |
defer c.Close() |
| 3374 |
resp := c.NewRespInbox() |
| 3375 |
sub := natsSubSync(t, c, resp) |
| 3376 |
err := sub.AutoUnsubscribe(respCnt) |
| 3377 |
require_NoError(t, err) |
| 3378 |
require_NoError(t, c.PublishRequest(accClaimsReqSubj, resp, []byte(jwt))) |
| 3379 |
passCnt := 0 |
| 3380 |
for i := 0; i < respCnt; i++ { |
| 3381 |
if require_NextMsg(sub) { |
| 3382 |
passCnt++ |
| 3383 |
} |
| 3384 |
} |
| 3385 |
return passCnt |
| 3386 |
} |
| 3387 |
|
| 3388 |
func require_JWTAbsent(t *testing.T, dir string, pub string) { |
| 3389 |
t.Helper() |
| 3390 |
_, err := os.Stat(filepath.Join(dir, pub+".jwt")) |
| 3391 |
require_Error(t, err) |
| 3392 |
require_True(t, os.IsNotExist(err)) |
| 3393 |
} |
| 3394 |
|
| 3395 |
func require_JWTPresent(t *testing.T, dir string, pub string) { |
| 3396 |
t.Helper() |
| 3397 |
_, err := os.Stat(filepath.Join(dir, pub+".jwt")) |
| 3398 |
require_NoError(t, err) |
| 3399 |
} |
| 3400 |
|
| 3401 |
func require_JWTEqual(t *testing.T, dir string, pub string, jwt string) { |
| 3402 |
t.Helper() |
| 3403 |
content, err := os.ReadFile(filepath.Join(dir, pub+".jwt")) |
| 3404 |
require_NoError(t, err) |
| 3405 |
require_Equal(t, string(content), jwt) |
| 3406 |
} |
| 3407 |
|
| 3408 |
func createTempFile(t testing.TB, prefix string) *os.File { |
| 3409 |
t.Helper() |
| 3410 |
tempDir := t.TempDir() |
| 3411 |
f, err := os.CreateTemp(tempDir, prefix) |
| 3412 |
require_NoError(t, err) |
| 3413 |
return f |
| 3414 |
} |
| 3415 |
|
| 3416 |
func removeDir(t testing.TB, dir string) { |
| 3417 |
t.Helper() |
| 3418 |
if err := os.RemoveAll(dir); err != nil { |
| 3419 |
t.Fatal(err) |
| 3420 |
} |
| 3421 |
} |
| 3422 |
|
| 3423 |
func removeFile(t testing.TB, p string) { |
| 3424 |
t.Helper() |
| 3425 |
if err := os.Remove(p); err != nil { |
| 3426 |
t.Fatal(err) |
| 3427 |
} |
| 3428 |
} |
| 3429 |
|
| 3430 |
func writeJWT(t *testing.T, dir string, pub string, jwt string) { |
| 3431 |
t.Helper() |
| 3432 |
err := os.WriteFile(filepath.Join(dir, pub+".jwt"), []byte(jwt), 0644) |
| 3433 |
require_NoError(t, err) |
| 3434 |
} |
| 3435 |
|
| 3436 |
func TestJWTAccountNATSResolverFetch(t *testing.T) { |
| 3437 |
origEventsHBInterval := eventsHBInterval |
| 3438 |
eventsHBInterval = 50 * time.Millisecond // speed up eventing |
| 3439 |
defer func() { eventsHBInterval = origEventsHBInterval }() |
| 3440 |
require_NoLocalOrRemoteConnections := func(account string, srvs ...*Server) { |
| 3441 |
t.Helper() |
| 3442 |
for _, srv := range srvs { |
| 3443 |
if acc, ok := srv.accounts.Load(account); ok { |
| 3444 |
checkAccClientsCount(t, acc.(*Account), 0) |
| 3445 |
} |
| 3446 |
} |
| 3447 |
} |
| 3448 |
// After each connection check, require_XConnection and connect assures that |
| 3449 |
// listed server have no connections for the account used |
| 3450 |
require_1Connection := func(url, creds, acc string, srvs ...*Server) { |
| 3451 |
t.Helper() |
| 3452 |
func() { |
| 3453 |
t.Helper() |
| 3454 |
c := natsConnect(t, url, nats.UserCredentials(creds)) |
| 3455 |
defer c.Close() |
| 3456 |
if _, err := nats.Connect(url, nats.UserCredentials(creds)); err == nil { |
| 3457 |
t.Fatal("Second connection was supposed to fail due to limits") |
| 3458 |
} else if !strings.Contains(err.Error(), ErrTooManyAccountConnections.Error()) { |
| 3459 |
t.Fatal("Second connection was supposed to fail with too many conns") |
| 3460 |
} |
| 3461 |
}() |
| 3462 |
require_NoLocalOrRemoteConnections(acc, srvs...) |
| 3463 |
} |
| 3464 |
require_2Connection := func(url, creds, acc string, srvs ...*Server) { |
| 3465 |
t.Helper() |
| 3466 |
func() { |
| 3467 |
t.Helper() |
| 3468 |
c1 := natsConnect(t, url, nats.UserCredentials(creds)) |
| 3469 |
defer c1.Close() |
| 3470 |
c2 := natsConnect(t, url, nats.UserCredentials(creds)) |
| 3471 |
defer c2.Close() |
| 3472 |
if _, err := nats.Connect(url, nats.UserCredentials(creds)); err == nil { |
| 3473 |
t.Fatal("Third connection was supposed to fail due to limits") |
| 3474 |
} else if !strings.Contains(err.Error(), ErrTooManyAccountConnections.Error()) { |
| 3475 |
t.Fatal("Third connection was supposed to fail with too many conns") |
| 3476 |
} |
| 3477 |
}() |
| 3478 |
require_NoLocalOrRemoteConnections(acc, srvs...) |
| 3479 |
} |
| 3480 |
connect := func(url string, credsfile string, acc string, srvs ...*Server) { |
| 3481 |
t.Helper() |
| 3482 |
nc := natsConnect(t, url, nats.UserCredentials(credsfile), nats.Timeout(5*time.Second)) |
| 3483 |
nc.Close() |
| 3484 |
require_NoLocalOrRemoteConnections(acc, srvs...) |
| 3485 |
} |
| 3486 |
createAccountAndUser := func(limit bool, done chan struct{}, pubKey, jwt1, jwt2, creds *string) { |
| 3487 |
t.Helper() |
| 3488 |
kp, _ := nkeys.CreateAccount() |
| 3489 |
*pubKey, _ = kp.PublicKey() |
| 3490 |
claim := jwt.NewAccountClaims(*pubKey) |
| 3491 |
if limit { |
| 3492 |
claim.Limits.Conn = 1 |
| 3493 |
} |
| 3494 |
var err error |
| 3495 |
*jwt1, err = claim.Encode(oKp) |
| 3496 |
require_NoError(t, err) |
| 3497 |
// need to assure that create time differs (resolution is sec) |
| 3498 |
time.Sleep(time.Millisecond * 1100) |
| 3499 |
// create updated claim allowing more connections |
| 3500 |
if limit { |
| 3501 |
claim.Limits.Conn = 2 |
| 3502 |
} |
| 3503 |
*jwt2, err = claim.Encode(oKp) |
| 3504 |
require_NoError(t, err) |
| 3505 |
ukp, _ := nkeys.CreateUser() |
| 3506 |
seed, _ := ukp.Seed() |
| 3507 |
upub, _ := ukp.PublicKey() |
| 3508 |
uclaim := newJWTTestUserClaims() |
| 3509 |
uclaim.Subject = upub |
| 3510 |
ujwt, err := uclaim.Encode(kp) |
| 3511 |
require_NoError(t, err) |
| 3512 |
*creds = genCredsFile(t, ujwt, seed) |
| 3513 |
done <- struct{}{} |
| 3514 |
} |
| 3515 |
// Create Accounts and corresponding user creds. Do so concurrently to speed up the test |
| 3516 |
doneChan := make(chan struct{}, 5) |
| 3517 |
defer close(doneChan) |
| 3518 |
var syspub, sysjwt, dummy1, sysCreds string |
| 3519 |
go createAccountAndUser(false, doneChan, &syspub, &sysjwt, &dummy1, &sysCreds) |
| 3520 |
var apub, ajwt1, ajwt2, aCreds string |
| 3521 |
go createAccountAndUser(true, doneChan, &apub, &ajwt1, &ajwt2, &aCreds) |
| 3522 |
var bpub, bjwt1, bjwt2, bCreds string |
| 3523 |
go createAccountAndUser(true, doneChan, &bpub, &bjwt1, &bjwt2, &bCreds) |
| 3524 |
var cpub, cjwt1, cjwt2, cCreds string |
| 3525 |
go createAccountAndUser(true, doneChan, &cpub, &cjwt1, &cjwt2, &cCreds) |
| 3526 |
var dpub, djwt1, dummy2, dCreds string // extra user used later in the test in order to test limits |
| 3527 |
go createAccountAndUser(true, doneChan, &dpub, &djwt1, &dummy2, &dCreds) |
| 3528 |
for i := 0; i < cap(doneChan); i++ { |
| 3529 |
<-doneChan |
| 3530 |
} |
| 3531 |
// Create one directory for each server |
| 3532 |
dirA := t.TempDir() |
| 3533 |
dirB := t.TempDir() |
| 3534 |
dirC := t.TempDir() |
| 3535 |
// simulate a restart of the server by storing files in them |
| 3536 |
// Server A/B will completely sync, so after startup each server |
| 3537 |
// will contain the union off all stored/configured jwt |
| 3538 |
// Server C will send out lookup requests for jwt it does not store itself |
| 3539 |
writeJWT(t, dirA, apub, ajwt1) |
| 3540 |
writeJWT(t, dirB, bpub, bjwt1) |
| 3541 |
writeJWT(t, dirC, cpub, cjwt1) |
| 3542 |
// Create seed server A (using no_advertise to prevent fail over) |
| 3543 |
confA := createConfFile(t, []byte(fmt.Sprintf(` |
| 3544 |
listen: 127.0.0.1:-1 |
| 3545 |
server_name: srv-A |
| 3546 |
operator: %s |
| 3547 |
system_account: %s |
| 3548 |
resolver: { |
| 3549 |
type: full |
| 3550 |
dir: '%s' |
| 3551 |
interval: "200ms" |
| 3552 |
limit: 4 |
| 3553 |
} |
| 3554 |
resolver_preload: { |
| 3555 |
%s: %s |
| 3556 |
} |
| 3557 |
cluster { |
| 3558 |
name: clust |
| 3559 |
listen: 127.0.0.1:-1 |
| 3560 |
no_advertise: true |
| 3561 |
} |
| 3562 |
`, ojwt, syspub, dirA, cpub, cjwt1))) |
| 3563 |
sA, _ := RunServerWithConfig(confA) |
| 3564 |
defer sA.Shutdown() |
| 3565 |
// during startup resolver_preload causes the directory to contain data |
| 3566 |
require_JWTPresent(t, dirA, cpub) |
| 3567 |
// Create Server B (using no_advertise to prevent fail over) |
| 3568 |
confB := createConfFile(t, []byte(fmt.Sprintf(` |
| 3569 |
listen: 127.0.0.1:-1 |
| 3570 |
server_name: srv-B |
| 3571 |
operator: %s |
| 3572 |
system_account: %s |
| 3573 |
resolver: { |
| 3574 |
type: full |
| 3575 |
|
| 3576 |
dir: '%s' |
| 3577 |
interval: "200ms" |
| 3578 |
limit: 4 |
| 3579 |
} |
| 3580 |
cluster { |
| 3581 |
name: clust |
| 3582 |
listen: 127.0.0.1:-1 |
| 3583 |
no_advertise: true |
| 3584 |
routes [ |
| 3585 |
nats-route://127.0.0.1:%d |
| 3586 |
] |
| 3587 |
} |
| 3588 |
`, ojwt, syspub, dirB, sA.opts.Cluster.Port))) |
| 3589 |
sB, _ := RunServerWithConfig(confB) |
| 3590 |
defer sB.Shutdown() |
| 3591 |
// Create Server C (using no_advertise to prevent fail over) |
| 3592 |
fmtC := ` |
| 3593 |
listen: 127.0.0.1:-1 |
| 3594 |
server_name: srv-C |
| 3595 |
operator: %s |
| 3596 |
system_account: %s |
| 3597 |
resolver: { |
| 3598 |
type: cache |
| 3599 |
dir: '%s' |
| 3600 |
ttl: "%dms" |
| 3601 |
limit: 4 |
| 3602 |
} |
| 3603 |
cluster { |
| 3604 |
name: clust |
| 3605 |
listen: 127.0.0.1:-1 |
| 3606 |
no_advertise: true |
| 3607 |
routes [ |
| 3608 |
nats-route://127.0.0.1:%d |
| 3609 |
] |
| 3610 |
} |
| 3611 |
` |
| 3612 |
confClongTTL := createConfFile(t, []byte(fmt.Sprintf(fmtC, ojwt, syspub, dirC, 10000, sA.opts.Cluster.Port))) |
| 3613 |
confCshortTTL := createConfFile(t, []byte(fmt.Sprintf(fmtC, ojwt, syspub, dirC, 1000, sA.opts.Cluster.Port))) |
| 3614 |
sC, _ := RunServerWithConfig(confClongTTL) // use long ttl to assure it is not kicking |
| 3615 |
defer sC.Shutdown() |
| 3616 |
// startup cluster |
| 3617 |
checkClusterFormed(t, sA, sB, sC) |
| 3618 |
time.Sleep(500 * time.Millisecond) // wait for the protocol to converge |
| 3619 |
// Check all accounts |
| 3620 |
require_JWTPresent(t, dirA, apub) // was already present on startup |
| 3621 |
require_JWTPresent(t, dirB, apub) // was copied from server A |
| 3622 |
require_JWTAbsent(t, dirC, apub) |
| 3623 |
require_JWTPresent(t, dirA, bpub) // was copied from server B |
| 3624 |
require_JWTPresent(t, dirB, bpub) // was already present on startup |
| 3625 |
require_JWTAbsent(t, dirC, bpub) |
| 3626 |
require_JWTPresent(t, dirA, cpub) // was present in preload |
| 3627 |
require_JWTPresent(t, dirB, cpub) // was copied from server A |
| 3628 |
require_JWTPresent(t, dirC, cpub) // was already present on startup |
| 3629 |
// This is to test that connecting to it still works |
| 3630 |
require_JWTAbsent(t, dirA, syspub) |
| 3631 |
require_JWTAbsent(t, dirB, syspub) |
| 3632 |
require_JWTAbsent(t, dirC, syspub) |
| 3633 |
// system account client can connect to every server |
| 3634 |
connect(sA.ClientURL(), sysCreds, "") |
| 3635 |
connect(sB.ClientURL(), sysCreds, "") |
| 3636 |
connect(sC.ClientURL(), sysCreds, "") |
| 3637 |
checkClusterFormed(t, sA, sB, sC) |
| 3638 |
// upload system account and require a response from each server |
| 3639 |
passCnt := updateJwt(t, sA.ClientURL(), sysCreds, sysjwt, 3) |
| 3640 |
require_True(t, passCnt == 3) |
| 3641 |
require_JWTPresent(t, dirA, syspub) // was just received |
| 3642 |
require_JWTPresent(t, dirB, syspub) // was just received |
| 3643 |
require_JWTPresent(t, dirC, syspub) // was just received |
| 3644 |
// Only files missing are in C, which is only caching |
| 3645 |
connect(sC.ClientURL(), aCreds, apub, sA, sB, sC) |
| 3646 |
connect(sC.ClientURL(), bCreds, bpub, sA, sB, sC) |
| 3647 |
require_JWTPresent(t, dirC, apub) // was looked up form A or B |
| 3648 |
require_JWTPresent(t, dirC, bpub) // was looked up from A or B |
| 3649 |
// Check limits and update jwt B connecting to server A |
| 3650 |
for port, v := range map[string]struct{ pub, jwt, creds string }{ |
| 3651 |
sB.ClientURL(): {bpub, bjwt2, bCreds}, |
| 3652 |
sC.ClientURL(): {cpub, cjwt2, cCreds}, |
| 3653 |
} { |
| 3654 |
require_1Connection(sA.ClientURL(), v.creds, v.pub, sA, sB, sC) |
| 3655 |
require_1Connection(sB.ClientURL(), v.creds, v.pub, sA, sB, sC) |
| 3656 |
require_1Connection(sC.ClientURL(), v.creds, v.pub, sA, sB, sC) |
| 3657 |
passCnt := updateJwt(t, port, sysCreds, v.jwt, 3) |
| 3658 |
require_True(t, passCnt == 3) |
| 3659 |
require_2Connection(sA.ClientURL(), v.creds, v.pub, sA, sB, sC) |
| 3660 |
require_2Connection(sB.ClientURL(), v.creds, v.pub, sA, sB, sC) |
| 3661 |
require_2Connection(sC.ClientURL(), v.creds, v.pub, sA, sB, sC) |
| 3662 |
require_JWTEqual(t, dirA, v.pub, v.jwt) |
| 3663 |
require_JWTEqual(t, dirB, v.pub, v.jwt) |
| 3664 |
require_JWTEqual(t, dirC, v.pub, v.jwt) |
| 3665 |
} |
| 3666 |
// Simulates A having missed an update |
| 3667 |
// shutting B down as it has it will directly connect to A and connect right away |
| 3668 |
sB.Shutdown() |
| 3669 |
writeJWT(t, dirB, apub, ajwt2) // this will be copied to server A |
| 3670 |
sB, _ = RunServerWithConfig(confB) |
| 3671 |
defer sB.Shutdown() |
| 3672 |
checkClusterFormed(t, sA, sB, sC) |
| 3673 |
time.Sleep(500 * time.Millisecond) // wait for the protocol to converge |
| 3674 |
// Restart server C. this is a workaround to force C to do a lookup in the absence of account cleanup |
| 3675 |
sC.Shutdown() |
| 3676 |
sC, _ = RunServerWithConfig(confClongTTL) //TODO remove this once we clean up accounts |
| 3677 |
defer sC.Shutdown() |
| 3678 |
require_JWTEqual(t, dirA, apub, ajwt2) // was copied from server B |
| 3679 |
require_JWTEqual(t, dirB, apub, ajwt2) // was restarted with this |
| 3680 |
require_JWTEqual(t, dirC, apub, ajwt1) // still contains old cached value |
| 3681 |
require_2Connection(sA.ClientURL(), aCreds, apub, sA, sB, sC) |
| 3682 |
require_2Connection(sB.ClientURL(), aCreds, apub, sA, sB, sC) |
| 3683 |
require_1Connection(sC.ClientURL(), aCreds, apub, sA, sB, sC) |
| 3684 |
// Restart server C. this is a workaround to force C to do a lookup in the absence of account cleanup |
| 3685 |
sC.Shutdown() |
| 3686 |
sC, _ = RunServerWithConfig(confCshortTTL) //TODO remove this once we clean up accounts |
| 3687 |
defer sC.Shutdown() |
| 3688 |
require_JWTEqual(t, dirC, apub, ajwt1) // still contains old cached value |
| 3689 |
checkClusterFormed(t, sA, sB, sC) |
| 3690 |
// Force next connect to do a lookup exceeds ttl |
| 3691 |
fname := filepath.Join(dirC, apub+".jwt") |
| 3692 |
checkFor(t, 2*time.Second, 100*time.Millisecond, func() error { |
| 3693 |
_, err := os.Stat(fname) |
| 3694 |
if os.IsNotExist(err) { |
| 3695 |
return nil |
| 3696 |
} |
| 3697 |
return fmt.Errorf("File not removed in time") |
| 3698 |
}) |
| 3699 |
connect(sC.ClientURL(), aCreds, apub, sA, sB, sC) // When lookup happens |
| 3700 |
require_JWTEqual(t, dirC, apub, ajwt2) // was looked up form A or B |
| 3701 |
require_2Connection(sC.ClientURL(), aCreds, apub, sA, sB, sC) |
| 3702 |
// Test exceeding limit. For the exclusive directory resolver, limit is a stop gap measure. |
| 3703 |
// It is not expected to be hit. When hit the administrator is supposed to take action. |
| 3704 |
passCnt = updateJwt(t, sA.ClientURL(), sysCreds, djwt1, 3) |
| 3705 |
require_True(t, passCnt == 1) // Only Server C updated |
| 3706 |
for _, srv := range []*Server{sA, sB, sC} { |
| 3707 |
if a, ok := srv.accounts.Load(syspub); ok { |
| 3708 |
acc := a.(*Account) |
| 3709 |
checkFor(t, time.Second, 20*time.Millisecond, func() error { |
| 3710 |
acc.mu.Lock() |
| 3711 |
defer acc.mu.Unlock() |
| 3712 |
if acc.ctmr != nil { |
| 3713 |
return fmt.Errorf("Timer still exists") |
| 3714 |
} |
| 3715 |
return nil |
| 3716 |
}) |
| 3717 |
} |
| 3718 |
} |
| 3719 |
} |
| 3720 |
|
| 3721 |
func TestJWTAccountNATSResolverCrossClusterFetch(t *testing.T) { |
| 3722 |
connect := func(url string, credsfile string) { |
| 3723 |
t.Helper() |
| 3724 |
nc := natsConnect(t, url, nats.UserCredentials(credsfile)) |
| 3725 |
nc.Close() |
| 3726 |
} |
| 3727 |
createAccountAndUser := func(done chan struct{}, pubKey, jwt1, jwt2, creds *string) { |
| 3728 |
t.Helper() |
| 3729 |
kp, _ := nkeys.CreateAccount() |
| 3730 |
*pubKey, _ = kp.PublicKey() |
| 3731 |
claim := jwt.NewAccountClaims(*pubKey) |
| 3732 |
var err error |
| 3733 |
*jwt1, err = claim.Encode(oKp) |
| 3734 |
require_NoError(t, err) |
| 3735 |
// need to assure that create time differs (resolution is sec) |
| 3736 |
time.Sleep(time.Millisecond * 1100) |
| 3737 |
// create updated claim |
| 3738 |
claim.Tags.Add("tag") |
| 3739 |
*jwt2, err = claim.Encode(oKp) |
| 3740 |
require_NoError(t, err) |
| 3741 |
ukp, _ := nkeys.CreateUser() |
| 3742 |
seed, _ := ukp.Seed() |
| 3743 |
upub, _ := ukp.PublicKey() |
| 3744 |
uclaim := newJWTTestUserClaims() |
| 3745 |
uclaim.Subject = upub |
| 3746 |
ujwt, err := uclaim.Encode(kp) |
| 3747 |
require_NoError(t, err) |
| 3748 |
*creds = genCredsFile(t, ujwt, seed) |
| 3749 |
done <- struct{}{} |
| 3750 |
} |
| 3751 |
// Create Accounts and corresponding user creds. Do so concurrently to speed up the test |
| 3752 |
doneChan := make(chan struct{}, 3) |
| 3753 |
defer close(doneChan) |
| 3754 |
var syspub, sysjwt, dummy1, sysCreds string |
| 3755 |
go createAccountAndUser(doneChan, &syspub, &sysjwt, &dummy1, &sysCreds) |
| 3756 |
var apub, ajwt1, ajwt2, aCreds string |
| 3757 |
go createAccountAndUser(doneChan, &apub, &ajwt1, &ajwt2, &aCreds) |
| 3758 |
var bpub, bjwt1, bjwt2, bCreds string |
| 3759 |
go createAccountAndUser(doneChan, &bpub, &bjwt1, &bjwt2, &bCreds) |
| 3760 |
for i := 0; i < cap(doneChan); i++ { |
| 3761 |
<-doneChan |
| 3762 |
} |
| 3763 |
// Create one directory for each server |
| 3764 |
dirAA := t.TempDir() |
| 3765 |
dirAB := t.TempDir() |
| 3766 |
dirBA := t.TempDir() |
| 3767 |
dirBB := t.TempDir() |
| 3768 |
// simulate a restart of the server by storing files in them |
| 3769 |
// Server AA & AB will completely sync |
| 3770 |
// Server BA & BB will completely sync |
| 3771 |
// Be aware that no syncing will occur between cluster |
| 3772 |
writeJWT(t, dirAA, apub, ajwt1) |
| 3773 |
writeJWT(t, dirBA, bpub, bjwt1) |
| 3774 |
// Create seed server A (using no_advertise to prevent fail over) |
| 3775 |
confAA := createConfFile(t, []byte(fmt.Sprintf(` |
| 3776 |
listen: 127.0.0.1:-1 |
| 3777 |
server_name: srv-A-A |
| 3778 |
operator: %s |
| 3779 |
system_account: %s |
| 3780 |
resolver: { |
| 3781 |
type: full |
| 3782 |
dir: '%s' |
| 3783 |
interval: "200ms" |
| 3784 |
} |
| 3785 |
gateway: { |
| 3786 |
name: "clust-A" |
| 3787 |
listen: 127.0.0.1:-1 |
| 3788 |
} |
| 3789 |
cluster { |
| 3790 |
name: clust-A |
| 3791 |
listen: 127.0.0.1:-1 |
| 3792 |
no_advertise: true |
| 3793 |
} |
| 3794 |
`, ojwt, syspub, dirAA))) |
| 3795 |
sAA, _ := RunServerWithConfig(confAA) |
| 3796 |
defer sAA.Shutdown() |
| 3797 |
// Create Server B (using no_advertise to prevent fail over) |
| 3798 |
confAB := createConfFile(t, []byte(fmt.Sprintf(` |
| 3799 |
listen: 127.0.0.1:-1 |
| 3800 |
server_name: srv-A-B |
| 3801 |
operator: %s |
| 3802 |
system_account: %s |
| 3803 |
resolver: { |
| 3804 |
type: full |
| 3805 |
dir: '%s' |
| 3806 |
interval: "200ms" |
| 3807 |
} |
| 3808 |
gateway: { |
| 3809 |
name: "clust-A" |
| 3810 |
listen: 127.0.0.1:-1 |
| 3811 |
} |
| 3812 |
cluster { |
| 3813 |
name: clust-A |
| 3814 |
listen: 127.0.0.1:-1 |
| 3815 |
no_advertise: true |
| 3816 |
routes [ |
| 3817 |
nats-route://127.0.0.1:%d |
| 3818 |
] |
| 3819 |
} |
| 3820 |
`, ojwt, syspub, dirAB, sAA.opts.Cluster.Port))) |
| 3821 |
sAB, _ := RunServerWithConfig(confAB) |
| 3822 |
defer sAB.Shutdown() |
| 3823 |
// Create Server C (using no_advertise to prevent fail over) |
| 3824 |
confBA := createConfFile(t, []byte(fmt.Sprintf(` |
| 3825 |
listen: 127.0.0.1:-1 |
| 3826 |
server_name: srv-B-A |
| 3827 |
operator: %s |
| 3828 |
system_account: %s |
| 3829 |
resolver: { |
| 3830 |
type: full |
| 3831 |
dir: '%s' |
| 3832 |
interval: "200ms" |
| 3833 |
} |
| 3834 |
gateway: { |
| 3835 |
name: "clust-B" |
| 3836 |
listen: 127.0.0.1:-1 |
| 3837 |
gateways: [ |
| 3838 |
{name: "clust-A", url: "nats://127.0.0.1:%d"}, |
| 3839 |
] |
| 3840 |
} |
| 3841 |
cluster { |
| 3842 |
name: clust-B |
| 3843 |
listen: 127.0.0.1:-1 |
| 3844 |
no_advertise: true |
| 3845 |
} |
| 3846 |
`, ojwt, syspub, dirBA, sAA.opts.Gateway.Port))) |
| 3847 |
sBA, _ := RunServerWithConfig(confBA) |
| 3848 |
defer sBA.Shutdown() |
| 3849 |
// Create Server BA (using no_advertise to prevent fail over) |
| 3850 |
confBB := createConfFile(t, []byte(fmt.Sprintf(` |
| 3851 |
listen: 127.0.0.1:-1 |
| 3852 |
server_name: srv-B-B |
| 3853 |
operator: %s |
| 3854 |
system_account: %s |
| 3855 |
resolver: { |
| 3856 |
type: full |
| 3857 |
dir: '%s' |
| 3858 |
interval: "200ms" |
| 3859 |
} |
| 3860 |
cluster { |
| 3861 |
name: clust-B |
| 3862 |
listen: 127.0.0.1:-1 |
| 3863 |
no_advertise: true |
| 3864 |
routes [ |
| 3865 |
nats-route://127.0.0.1:%d |
| 3866 |
] |
| 3867 |
} |
| 3868 |
gateway: { |
| 3869 |
name: "clust-B" |
| 3870 |
listen: 127.0.0.1:-1 |
| 3871 |
gateways: [ |
| 3872 |
{name: "clust-A", url: "nats://127.0.0.1:%d"}, |
| 3873 |
] |
| 3874 |
} |
| 3875 |
`, ojwt, syspub, dirBB, sBA.opts.Cluster.Port, sAA.opts.Cluster.Port))) |
| 3876 |
sBB, _ := RunServerWithConfig(confBB) |
| 3877 |
defer sBB.Shutdown() |
| 3878 |
// Assert topology |
| 3879 |
checkClusterFormed(t, sAA, sAB) |
| 3880 |
checkClusterFormed(t, sBA, sBB) |
| 3881 |
waitForOutboundGateways(t, sAA, 1, 5*time.Second) |
| 3882 |
waitForOutboundGateways(t, sAB, 1, 5*time.Second) |
| 3883 |
waitForOutboundGateways(t, sBA, 1, 5*time.Second) |
| 3884 |
waitForOutboundGateways(t, sBB, 1, 5*time.Second) |
| 3885 |
time.Sleep(500 * time.Millisecond) // wait for the protocol to converge |
| 3886 |
updateJwt(t, sAA.ClientURL(), sysCreds, sysjwt, 4) // update system account jwt on all server |
| 3887 |
require_JWTEqual(t, dirAA, syspub, sysjwt) // assure this update made it to every server |
| 3888 |
require_JWTEqual(t, dirAB, syspub, sysjwt) // assure this update made it to every server |
| 3889 |
require_JWTEqual(t, dirBA, syspub, sysjwt) // assure this update made it to every server |
| 3890 |
require_JWTEqual(t, dirBB, syspub, sysjwt) // assure this update made it to every server |
| 3891 |
require_JWTAbsent(t, dirAA, bpub) // assure that jwt are not synced across cluster |
| 3892 |
require_JWTAbsent(t, dirAB, bpub) // assure that jwt are not synced across cluster |
| 3893 |
require_JWTAbsent(t, dirBA, apub) // assure that jwt are not synced across cluster |
| 3894 |
require_JWTAbsent(t, dirBB, apub) // assure that jwt are not synced across cluster |
| 3895 |
connect(sAA.ClientURL(), aCreds) // connect to cluster where jwt was initially stored |
| 3896 |
connect(sAB.ClientURL(), aCreds) // connect to cluster where jwt was initially stored |
| 3897 |
connect(sBA.ClientURL(), bCreds) // connect to cluster where jwt was initially stored |
| 3898 |
connect(sBB.ClientURL(), bCreds) // connect to cluster where jwt was initially stored |
| 3899 |
time.Sleep(500 * time.Millisecond) // wait for the protocol to (NOT) converge |
| 3900 |
require_JWTAbsent(t, dirAA, bpub) // assure that jwt are still not synced across cluster |
| 3901 |
require_JWTAbsent(t, dirAB, bpub) // assure that jwt are still not synced across cluster |
| 3902 |
require_JWTAbsent(t, dirBA, apub) // assure that jwt are still not synced across cluster |
| 3903 |
require_JWTAbsent(t, dirBB, apub) // assure that jwt are still not synced across cluster |
| 3904 |
// We have verified that account B does not exist in cluster A, neither does account A in cluster B |
| 3905 |
// Despite that clients from account B can connect to server A, same for account A in cluster B |
| 3906 |
connect(sAA.ClientURL(), bCreds) // connect to cluster where jwt was not initially stored |
| 3907 |
connect(sAB.ClientURL(), bCreds) // connect to cluster where jwt was not initially stored |
| 3908 |
connect(sBA.ClientURL(), aCreds) // connect to cluster where jwt was not initially stored |
| 3909 |
connect(sBB.ClientURL(), aCreds) // connect to cluster where jwt was not initially stored |
| 3910 |
require_JWTEqual(t, dirAA, bpub, bjwt1) // assure that now jwt used in connect is stored |
| 3911 |
require_JWTEqual(t, dirAB, bpub, bjwt1) // assure that now jwt used in connect is stored |
| 3912 |
require_JWTEqual(t, dirBA, apub, ajwt1) // assure that now jwt used in connect is stored |
| 3913 |
require_JWTEqual(t, dirBB, apub, ajwt1) // assure that now jwt used in connect is stored |
| 3914 |
updateJwt(t, sAA.ClientURL(), sysCreds, bjwt2, 4) // update bjwt, expect updates from everywhere |
| 3915 |
updateJwt(t, sBA.ClientURL(), sysCreds, ajwt2, 4) // update ajwt, expect updates from everywhere |
| 3916 |
require_JWTEqual(t, dirAA, bpub, bjwt2) // assure that jwt got updated accordingly |
| 3917 |
require_JWTEqual(t, dirAB, bpub, bjwt2) // assure that jwt got updated accordingly |
| 3918 |
require_JWTEqual(t, dirBA, apub, ajwt2) // assure that jwt got updated accordingly |
| 3919 |
require_JWTEqual(t, dirBB, apub, ajwt2) // assure that jwt got updated accordingly |
| 3920 |
} |
| 3921 |
|
| 3922 |
func newTimeRange(start time.Time, dur time.Duration) jwt.TimeRange { |
| 3923 |
return jwt.TimeRange{Start: start.Format("15:04:05"), End: start.Add(dur).Format("15:04:05")} |
| 3924 |
} |
| 3925 |
|
| 3926 |
func createUserWithLimit(t *testing.T, accKp nkeys.KeyPair, expiration time.Time, limits func(*jwt.UserPermissionLimits)) string { |
| 3927 |
t.Helper() |
| 3928 |
ukp, _ := nkeys.CreateUser() |
| 3929 |
seed, _ := ukp.Seed() |
| 3930 |
upub, _ := ukp.PublicKey() |
| 3931 |
uclaim := newJWTTestUserClaims() |
| 3932 |
uclaim.Subject = upub |
| 3933 |
if limits != nil { |
| 3934 |
limits(&uclaim.UserPermissionLimits) |
| 3935 |
} |
| 3936 |
if !expiration.IsZero() { |
| 3937 |
uclaim.Expires = expiration.Unix() |
| 3938 |
} |
| 3939 |
vr := jwt.ValidationResults{} |
| 3940 |
uclaim.Validate(&vr) |
| 3941 |
require_Len(t, len(vr.Errors()), 0) |
| 3942 |
ujwt, err := uclaim.Encode(accKp) |
| 3943 |
require_NoError(t, err) |
| 3944 |
return genCredsFile(t, ujwt, seed) |
| 3945 |
} |
| 3946 |
|
| 3947 |
func TestJWTUserLimits(t *testing.T) { |
| 3948 |
// helper for time |
| 3949 |
inAnHour := time.Now().Add(time.Hour) |
| 3950 |
inTwoHours := time.Now().Add(2 * time.Hour) |
| 3951 |
doNotExpire := time.Now().AddDate(1, 0, 0) |
| 3952 |
// create account |
| 3953 |
kp, _ := nkeys.CreateAccount() |
| 3954 |
aPub, _ := kp.PublicKey() |
| 3955 |
claim := jwt.NewAccountClaims(aPub) |
| 3956 |
aJwt, err := claim.Encode(oKp) |
| 3957 |
require_NoError(t, err) |
| 3958 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 3959 |
listen: 127.0.0.1:-1 |
| 3960 |
operator: %s |
| 3961 |
resolver: MEM |
| 3962 |
resolver_preload: { |
| 3963 |
%s: %s |
| 3964 |
} |
| 3965 |
`, ojwt, aPub, aJwt))) |
| 3966 |
sA, _ := RunServerWithConfig(conf) |
| 3967 |
defer sA.Shutdown() |
| 3968 |
for _, v := range []struct { |
| 3969 |
pass bool |
| 3970 |
f func(*jwt.UserPermissionLimits) |
| 3971 |
}{ |
| 3972 |
{true, nil}, |
| 3973 |
{false, func(j *jwt.UserPermissionLimits) { j.Src.Set("8.8.8.8/8") }}, |
| 3974 |
{true, func(j *jwt.UserPermissionLimits) { j.Src.Set("8.8.8.8/0") }}, |
| 3975 |
{true, func(j *jwt.UserPermissionLimits) { j.Src.Set("127.0.0.1/8") }}, |
| 3976 |
{true, func(j *jwt.UserPermissionLimits) { j.Src.Set("8.8.8.8/8,127.0.0.1/8") }}, |
| 3977 |
{false, func(j *jwt.UserPermissionLimits) { j.Src.Set("8.8.8.8/8,9.9.9.9/8") }}, |
| 3978 |
{true, func(j *jwt.UserPermissionLimits) { j.Times = append(j.Times, newTimeRange(time.Now(), time.Hour)) }}, |
| 3979 |
{false, func(j *jwt.UserPermissionLimits) { |
| 3980 |
j.Times = append(j.Times, newTimeRange(time.Now().Add(time.Hour), time.Hour)) |
| 3981 |
}}, |
| 3982 |
{true, func(j *jwt.UserPermissionLimits) { |
| 3983 |
j.Times = append(j.Times, newTimeRange(inAnHour, time.Hour), newTimeRange(time.Now(), time.Hour)) |
| 3984 |
}}, // last one is within range |
| 3985 |
{false, func(j *jwt.UserPermissionLimits) { |
| 3986 |
j.Times = append(j.Times, newTimeRange(inAnHour, time.Hour), newTimeRange(inTwoHours, time.Hour)) |
| 3987 |
}}, // out of range |
| 3988 |
{false, func(j *jwt.UserPermissionLimits) { |
| 3989 |
j.Times = append(j.Times, newTimeRange(inAnHour, 3*time.Hour), newTimeRange(inTwoHours, 2*time.Hour)) |
| 3990 |
}}, // overlapping [a[]b] out of range*/ |
| 3991 |
{false, func(j *jwt.UserPermissionLimits) { |
| 3992 |
j.Times = append(j.Times, newTimeRange(inAnHour, 3*time.Hour), newTimeRange(inTwoHours, time.Hour)) |
| 3993 |
}}, // overlapping [a[b]] out of range |
| 3994 |
// next day tests where end < begin |
| 3995 |
{true, func(j *jwt.UserPermissionLimits) { j.Times = append(j.Times, newTimeRange(time.Now(), 25*time.Hour)) }}, |
| 3996 |
{true, func(j *jwt.UserPermissionLimits) { j.Times = append(j.Times, newTimeRange(time.Now(), -time.Hour)) }}, |
| 3997 |
} { |
| 3998 |
t.Run("", func(t *testing.T) { |
| 3999 |
creds := createUserWithLimit(t, kp, doNotExpire, v.f) |
| 4000 |
if c, err := nats.Connect(sA.ClientURL(), nats.UserCredentials(creds)); err == nil { |
| 4001 |
c.Close() |
| 4002 |
if !v.pass { |
| 4003 |
t.Fatalf("Expected failure got none") |
| 4004 |
} |
| 4005 |
} else if v.pass { |
| 4006 |
t.Fatalf("Expected success got %v", err) |
| 4007 |
} else if !strings.Contains(err.Error(), "Authorization Violation") { |
| 4008 |
t.Fatalf("Expected error other than %v", err) |
| 4009 |
} |
| 4010 |
}) |
| 4011 |
} |
| 4012 |
} |
| 4013 |
|
| 4014 |
func TestJWTTimeExpiration(t *testing.T) { |
| 4015 |
validFor := 1500 * time.Millisecond |
| 4016 |
validRange := 500 * time.Millisecond |
| 4017 |
doNotExpire := time.Now().AddDate(1, 0, 0) |
| 4018 |
// create account |
| 4019 |
kp, _ := nkeys.CreateAccount() |
| 4020 |
aPub, _ := kp.PublicKey() |
| 4021 |
claim := jwt.NewAccountClaims(aPub) |
| 4022 |
aJwt, err := claim.Encode(oKp) |
| 4023 |
require_NoError(t, err) |
| 4024 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 4025 |
listen: 127.0.0.1:-1 |
| 4026 |
operator: %s |
| 4027 |
resolver: MEM |
| 4028 |
resolver_preload: { |
| 4029 |
%s: %s |
| 4030 |
} |
| 4031 |
`, ojwt, aPub, aJwt))) |
| 4032 |
sA, _ := RunServerWithConfig(conf) |
| 4033 |
defer sA.Shutdown() |
| 4034 |
for _, l := range []string{"", "Europe/Berlin", "America/New_York"} { |
| 4035 |
t.Run("simple expiration "+l, func(t *testing.T) { |
| 4036 |
start := time.Now() |
| 4037 |
creds := createUserWithLimit(t, kp, doNotExpire, func(j *jwt.UserPermissionLimits) { |
| 4038 |
if l == _EMPTY_ { |
| 4039 |
j.Times = []jwt.TimeRange{newTimeRange(start, validFor)} |
| 4040 |
} else { |
| 4041 |
loc, err := time.LoadLocation(l) |
| 4042 |
require_NoError(t, err) |
| 4043 |
j.Times = []jwt.TimeRange{newTimeRange(start.In(loc), validFor)} |
| 4044 |
j.Locale = l |
| 4045 |
} |
| 4046 |
}) |
| 4047 |
disconnectChan := make(chan struct{}) |
| 4048 |
defer close(disconnectChan) |
| 4049 |
errChan := make(chan struct{}) |
| 4050 |
defer close(errChan) |
| 4051 |
c := natsConnect(t, sA.ClientURL(), |
| 4052 |
nats.UserCredentials(creds), |
| 4053 |
nats.DisconnectErrHandler(func(conn *nats.Conn, err error) { |
| 4054 |
if err != io.EOF { |
| 4055 |
return |
| 4056 |
} |
| 4057 |
disconnectChan <- struct{}{} |
| 4058 |
}), |
| 4059 |
nats.ErrorHandler(func(conn *nats.Conn, s *nats.Subscription, err error) { |
| 4060 |
if err != nats.ErrAuthExpired { |
| 4061 |
return |
| 4062 |
} |
| 4063 |
now := time.Now() |
| 4064 |
stop := start.Add(validFor) |
| 4065 |
// assure event happens within a second of stop |
| 4066 |
if stop.Add(-validRange).Before(stop) && now.Before(stop.Add(validRange)) { |
| 4067 |
errChan <- struct{}{} |
| 4068 |
} |
| 4069 |
})) |
| 4070 |
defer c.Close() |
| 4071 |
chanRecv(t, errChan, 10*time.Second) |
| 4072 |
chanRecv(t, disconnectChan, 10*time.Second) |
| 4073 |
require_True(t, c.IsReconnecting()) |
| 4074 |
require_False(t, c.IsConnected()) |
| 4075 |
}) |
| 4076 |
} |
| 4077 |
t.Run("double expiration", func(t *testing.T) { |
| 4078 |
start1 := time.Now() |
| 4079 |
start2 := start1.Add(2 * validFor) |
| 4080 |
creds := createUserWithLimit(t, kp, doNotExpire, func(j *jwt.UserPermissionLimits) { |
| 4081 |
j.Times = []jwt.TimeRange{newTimeRange(start1, validFor), newTimeRange(start2, validFor)} |
| 4082 |
}) |
| 4083 |
errChan := make(chan struct{}) |
| 4084 |
defer close(errChan) |
| 4085 |
reConnectChan := make(chan struct{}) |
| 4086 |
defer close(reConnectChan) |
| 4087 |
c := natsConnect(t, sA.ClientURL(), |
| 4088 |
nats.UserCredentials(creds), |
| 4089 |
nats.ReconnectHandler(func(conn *nats.Conn) { |
| 4090 |
reConnectChan <- struct{}{} |
| 4091 |
}), |
| 4092 |
nats.ErrorHandler(func(conn *nats.Conn, s *nats.Subscription, err error) { |
| 4093 |
if err != nats.ErrAuthExpired { |
| 4094 |
return |
| 4095 |
} |
| 4096 |
now := time.Now() |
| 4097 |
stop := start1.Add(validFor) |
| 4098 |
// assure event happens within a second of stop |
| 4099 |
if stop.Add(-validRange).Before(stop) && now.Before(stop.Add(validRange)) { |
| 4100 |
errChan <- struct{}{} |
| 4101 |
return |
| 4102 |
} |
| 4103 |
stop = start2.Add(validFor) |
| 4104 |
// assure event happens within a second of stop |
| 4105 |
if stop.Add(-validRange).Before(stop) && now.Before(stop.Add(validRange)) { |
| 4106 |
errChan <- struct{}{} |
| 4107 |
} |
| 4108 |
})) |
| 4109 |
defer c.Close() |
| 4110 |
chanRecv(t, errChan, 10*time.Second) |
| 4111 |
chanRecv(t, reConnectChan, 10*time.Second) |
| 4112 |
require_False(t, c.IsReconnecting()) |
| 4113 |
require_True(t, c.IsConnected()) |
| 4114 |
chanRecv(t, errChan, 10*time.Second) |
| 4115 |
}) |
| 4116 |
t.Run("lower jwt expiration overwrites time", func(t *testing.T) { |
| 4117 |
start := time.Now() |
| 4118 |
creds := createUserWithLimit(t, kp, start.Add(validFor), func(j *jwt.UserPermissionLimits) { j.Times = []jwt.TimeRange{newTimeRange(start, 2*validFor)} }) |
| 4119 |
disconnectChan := make(chan struct{}) |
| 4120 |
defer close(disconnectChan) |
| 4121 |
errChan := make(chan struct{}) |
| 4122 |
defer close(errChan) |
| 4123 |
c := natsConnect(t, sA.ClientURL(), |
| 4124 |
nats.UserCredentials(creds), |
| 4125 |
nats.DisconnectErrHandler(func(conn *nats.Conn, err error) { |
| 4126 |
if err != io.EOF { |
| 4127 |
return |
| 4128 |
} |
| 4129 |
disconnectChan <- struct{}{} |
| 4130 |
}), |
| 4131 |
nats.ErrorHandler(func(conn *nats.Conn, s *nats.Subscription, err error) { |
| 4132 |
if err != nats.ErrAuthExpired { |
| 4133 |
return |
| 4134 |
} |
| 4135 |
now := time.Now() |
| 4136 |
stop := start.Add(validFor) |
| 4137 |
// assure event happens within a second of stop |
| 4138 |
if stop.Add(-validRange).Before(stop) && now.Before(stop.Add(validRange)) { |
| 4139 |
errChan <- struct{}{} |
| 4140 |
} |
| 4141 |
})) |
| 4142 |
defer c.Close() |
| 4143 |
chanRecv(t, errChan, 10*time.Second) |
| 4144 |
chanRecv(t, disconnectChan, 10*time.Second) |
| 4145 |
require_True(t, c.IsReconnecting()) |
| 4146 |
require_False(t, c.IsConnected()) |
| 4147 |
}) |
| 4148 |
} |
| 4149 |
|
| 4150 |
func TestJWTValidateTimesAt(t *testing.T) { |
| 4151 |
at := func(h, m, s int) time.Time { |
| 4152 |
Y, M, D := time.Now().Date() |
| 4153 |
return time.Date(Y, M, D, h, m, s, 0, time.UTC) |
| 4154 |
} |
| 4155 |
for _, tc := range []struct { |
| 4156 |
name string |
| 4157 |
now time.Time |
| 4158 |
timeRanges []jwt.TimeRange |
| 4159 |
allowed bool |
| 4160 |
remaining time.Duration |
| 4161 |
}{ |
| 4162 |
{ |
| 4163 |
name: "inside window", |
| 4164 |
now: at(14, 30, 0), |
| 4165 |
timeRanges: []jwt.TimeRange{{Start: "09:00:00", End: "17:00:00"}}, |
| 4166 |
allowed: true, |
| 4167 |
remaining: 2*time.Hour + 30*time.Minute, |
| 4168 |
}, |
| 4169 |
{ |
| 4170 |
name: "before window", |
| 4171 |
now: at(8, 0, 0), |
| 4172 |
timeRanges: []jwt.TimeRange{{Start: "09:00:00", End: "17:00:00"}}, |
| 4173 |
allowed: false, |
| 4174 |
remaining: time.Duration(0), |
| 4175 |
}, |
| 4176 |
{ |
| 4177 |
name: "after window", |
| 4178 |
now: at(18, 0, 0), |
| 4179 |
timeRanges: []jwt.TimeRange{{Start: "09:00:00", End: "17:00:00"}}, |
| 4180 |
allowed: false, |
| 4181 |
remaining: time.Duration(0), |
| 4182 |
}, |
| 4183 |
{ |
| 4184 |
name: "cross midnight inside window before midnight", |
| 4185 |
now: at(23, 30, 0), |
| 4186 |
timeRanges: []jwt.TimeRange{{Start: "22:00:00", End: "06:00:00"}}, |
| 4187 |
allowed: true, |
| 4188 |
remaining: 6*time.Hour + 30*time.Minute, |
| 4189 |
}, |
| 4190 |
{ |
| 4191 |
name: "cross midnight inside window after midnight", |
| 4192 |
now: at(5, 0, 0), |
| 4193 |
timeRanges: []jwt.TimeRange{{Start: "22:00:00", End: "06:00:00"}}, |
| 4194 |
allowed: true, |
| 4195 |
remaining: 1 * time.Hour, |
| 4196 |
}, |
| 4197 |
{ |
| 4198 |
name: "cross midnight before window", |
| 4199 |
now: at(21, 0, 0), |
| 4200 |
timeRanges: []jwt.TimeRange{{Start: "22:00:00", End: "06:00:00"}}, |
| 4201 |
allowed: false, |
| 4202 |
remaining: time.Duration(0), |
| 4203 |
}, |
| 4204 |
{ |
| 4205 |
name: "cross midnight after window", |
| 4206 |
now: at(7, 0, 0), |
| 4207 |
timeRanges: []jwt.TimeRange{{Start: "22:00:00", End: "06:00:00"}}, |
| 4208 |
allowed: false, |
| 4209 |
remaining: time.Duration(0), |
| 4210 |
}, |
| 4211 |
{ |
| 4212 |
name: "overlap after midnight", |
| 4213 |
now: at(1, 0, 0), |
| 4214 |
timeRanges: []jwt.TimeRange{ |
| 4215 |
{Start: "22:00:00", End: "06:00:00"}, |
| 4216 |
{Start: "00:00:00", End: "08:00:00"}, |
| 4217 |
}, |
| 4218 |
allowed: true, |
| 4219 |
remaining: 7 * time.Hour, |
| 4220 |
}, |
| 4221 |
{ |
| 4222 |
name: "overlap after midnight reversed order", |
| 4223 |
now: at(1, 0, 0), |
| 4224 |
timeRanges: []jwt.TimeRange{ |
| 4225 |
{Start: "00:00:00", End: "08:00:00"}, |
| 4226 |
{Start: "22:00:00", End: "06:00:00"}, |
| 4227 |
}, |
| 4228 |
allowed: true, |
| 4229 |
remaining: 7 * time.Hour, |
| 4230 |
}, |
| 4231 |
} { |
| 4232 |
t.Run(tc.name, func(t *testing.T) { |
| 4233 |
claims := newJWTTestUserClaims() |
| 4234 |
claims.Locale = "UTC" |
| 4235 |
claims.Times = tc.timeRanges |
| 4236 |
allowed, remaining := validateTimesAt(claims, tc.now) |
| 4237 |
|
| 4238 |
require_Equal(t, allowed, tc.allowed) |
| 4239 |
require_Equal(t, remaining, tc.remaining) |
| 4240 |
}) |
| 4241 |
} |
| 4242 |
} |
| 4243 |
|
| 4244 |
func NewJwtAccountClaim(name string) (nkeys.KeyPair, string, *jwt.AccountClaims) { |
| 4245 |
sysKp, _ := nkeys.CreateAccount() |
| 4246 |
sysPub, _ := sysKp.PublicKey() |
| 4247 |
claim := jwt.NewAccountClaims(sysPub) |
| 4248 |
claim.Name = name |
| 4249 |
return sysKp, sysPub, claim |
| 4250 |
} |
| 4251 |
|
| 4252 |
func TestJWTSysImportForDifferentAccount(t *testing.T) { |
| 4253 |
_, sysPub, sysClaim := NewJwtAccountClaim("SYS") |
| 4254 |
sysClaim.Exports.Add(&jwt.Export{ |
| 4255 |
Type: jwt.Service, |
| 4256 |
Subject: "$SYS.REQ.ACCOUNT.*.INFO", |
| 4257 |
}) |
| 4258 |
sysJwt, err := sysClaim.Encode(oKp) |
| 4259 |
require_NoError(t, err) |
| 4260 |
|
| 4261 |
// create account |
| 4262 |
aKp, aPub, claim := NewJwtAccountClaim("A") |
| 4263 |
claim.Imports.Add(&jwt.Import{ |
| 4264 |
Type: jwt.Service, |
| 4265 |
Subject: "$SYS.REQ.ACCOUNT.*.INFO", |
| 4266 |
LocalSubject: "COMMON.ADVISORY.SYS.REQ.ACCOUNT.*.INFO", |
| 4267 |
Account: sysPub, |
| 4268 |
}) |
| 4269 |
aJwt, err := claim.Encode(oKp) |
| 4270 |
require_NoError(t, err) |
| 4271 |
|
| 4272 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 4273 |
listen: 127.0.0.1:-1 |
| 4274 |
operator: %s |
| 4275 |
system_account: %s |
| 4276 |
resolver: MEM |
| 4277 |
resolver_preload: { |
| 4278 |
%s: %s |
| 4279 |
%s: %s |
| 4280 |
} |
| 4281 |
`, ojwt, sysPub, sysPub, sysJwt, aPub, aJwt))) |
| 4282 |
sA, _ := RunServerWithConfig(conf) |
| 4283 |
defer sA.Shutdown() |
| 4284 |
|
| 4285 |
nc := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, aKp)) |
| 4286 |
defer nc.Close() |
| 4287 |
// user for account a requests for a different account, the system account |
| 4288 |
m, err := nc.Request(fmt.Sprintf("COMMON.ADVISORY.SYS.REQ.ACCOUNT.%s.INFO", sysPub), nil, time.Second) |
| 4289 |
require_NoError(t, err) |
| 4290 |
resp := &ServerAPIResponse{} |
| 4291 |
require_NoError(t, json.Unmarshal(m.Data, resp)) |
| 4292 |
require_True(t, resp.Error == nil) |
| 4293 |
} |
| 4294 |
|
| 4295 |
func TestJWTSysImportFromNothing(t *testing.T) { |
| 4296 |
_, sysPub, sysClaim := NewJwtAccountClaim("SYS") |
| 4297 |
sysJwt, err := sysClaim.Encode(oKp) |
| 4298 |
require_NoError(t, err) |
| 4299 |
|
| 4300 |
// create account |
| 4301 |
aKp, aPub, claim := NewJwtAccountClaim("A") |
| 4302 |
claim.Imports.Add(&jwt.Import{ |
| 4303 |
Type: jwt.Service, |
| 4304 |
// fails as it's not for own account, but system account |
| 4305 |
Subject: jwt.Subject(fmt.Sprintf("$SYS.REQ.ACCOUNT.%s.CONNZ", sysPub)), |
| 4306 |
LocalSubject: "fail1", |
| 4307 |
Account: sysPub, |
| 4308 |
}) |
| 4309 |
claim.Imports.Add(&jwt.Import{ |
| 4310 |
Type: jwt.Service, |
| 4311 |
// fails as it's not for own account but all accounts |
| 4312 |
Subject: "$SYS.REQ.ACCOUNT.*.CONNZ", |
| 4313 |
LocalSubject: "fail2.*", |
| 4314 |
Account: sysPub, |
| 4315 |
}) |
| 4316 |
claim.Imports.Add(&jwt.Import{ |
| 4317 |
Type: jwt.Service, |
| 4318 |
Subject: jwt.Subject(fmt.Sprintf("$SYS.REQ.ACCOUNT.%s.CONNZ", aPub)), |
| 4319 |
LocalSubject: "pass", |
| 4320 |
Account: sysPub, |
| 4321 |
}) |
| 4322 |
aJwt, err := claim.Encode(oKp) |
| 4323 |
require_NoError(t, err) |
| 4324 |
|
| 4325 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 4326 |
listen: 127.0.0.1:-1 |
| 4327 |
operator: %s |
| 4328 |
system_account: %s |
| 4329 |
resolver: MEM |
| 4330 |
resolver_preload: { |
| 4331 |
%s: %s |
| 4332 |
%s: %s |
| 4333 |
} |
| 4334 |
`, ojwt, sysPub, sysPub, sysJwt, aPub, aJwt))) |
| 4335 |
sA, _ := RunServerWithConfig(conf) |
| 4336 |
defer sA.Shutdown() |
| 4337 |
|
| 4338 |
nc := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, aKp)) |
| 4339 |
defer nc.Close() |
| 4340 |
// user for account a requests for a different account, the system account |
| 4341 |
_, err = nc.Request("pass", nil, time.Second) |
| 4342 |
require_NoError(t, err) |
| 4343 |
// default import |
| 4344 |
_, err = nc.Request("$SYS.REQ.ACCOUNT.PING.CONNZ", nil, time.Second) |
| 4345 |
require_NoError(t, err) |
| 4346 |
_, err = nc.Request("fail1", nil, time.Second) |
| 4347 |
require_Error(t, err) |
| 4348 |
require_Contains(t, err.Error(), "no responders") |
| 4349 |
// fails even for own account, as the import itself is bad |
| 4350 |
_, err = nc.Request("fail2."+aPub, nil, time.Second) |
| 4351 |
require_Error(t, err) |
| 4352 |
require_Contains(t, err.Error(), "no responders") |
| 4353 |
} |
| 4354 |
|
| 4355 |
func TestJWTSysImportOverwritePublic(t *testing.T) { |
| 4356 |
_, sysPub, sysClaim := NewJwtAccountClaim("SYS") |
| 4357 |
// this changes the export permissions to allow for requests for every account |
| 4358 |
sysClaim.Exports.Add(&jwt.Export{ |
| 4359 |
Type: jwt.Service, |
| 4360 |
Subject: "$SYS.REQ.ACCOUNT.*.>", |
| 4361 |
}) |
| 4362 |
sysJwt, err := sysClaim.Encode(oKp) |
| 4363 |
require_NoError(t, err) |
| 4364 |
|
| 4365 |
// create account |
| 4366 |
aKp, aPub, claim := NewJwtAccountClaim("A") |
| 4367 |
claim.Imports.Add(&jwt.Import{ |
| 4368 |
Type: jwt.Service, |
| 4369 |
Subject: jwt.Subject(fmt.Sprintf("$SYS.REQ.ACCOUNT.%s.CONNZ", sysPub)), |
| 4370 |
LocalSubject: "pass1", |
| 4371 |
Account: sysPub, |
| 4372 |
}) |
| 4373 |
claim.Imports.Add(&jwt.Import{ |
| 4374 |
Type: jwt.Service, |
| 4375 |
Subject: jwt.Subject(fmt.Sprintf("$SYS.REQ.ACCOUNT.%s.CONNZ", aPub)), |
| 4376 |
LocalSubject: "pass2", |
| 4377 |
Account: sysPub, |
| 4378 |
}) |
| 4379 |
claim.Imports.Add(&jwt.Import{ |
| 4380 |
Type: jwt.Service, |
| 4381 |
Subject: "$SYS.REQ.ACCOUNT.*.CONNZ", |
| 4382 |
LocalSubject: "pass3.*", |
| 4383 |
Account: sysPub, |
| 4384 |
}) |
| 4385 |
aJwt, err := claim.Encode(oKp) |
| 4386 |
require_NoError(t, err) |
| 4387 |
|
| 4388 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 4389 |
listen: 127.0.0.1:-1 |
| 4390 |
operator: %s |
| 4391 |
system_account: %s |
| 4392 |
resolver: MEM |
| 4393 |
resolver_preload: { |
| 4394 |
%s: %s |
| 4395 |
%s: %s |
| 4396 |
} |
| 4397 |
`, ojwt, sysPub, sysPub, sysJwt, aPub, aJwt))) |
| 4398 |
sA, _ := RunServerWithConfig(conf) |
| 4399 |
defer sA.Shutdown() |
| 4400 |
|
| 4401 |
nc := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, aKp)) |
| 4402 |
defer nc.Close() |
| 4403 |
// user for account a requests for a different account, the system account |
| 4404 |
_, err = nc.Request("pass1", nil, time.Second) |
| 4405 |
require_NoError(t, err) |
| 4406 |
_, err = nc.Request("pass2", nil, time.Second) |
| 4407 |
require_NoError(t, err) |
| 4408 |
_, err = nc.Request("pass3."+sysPub, nil, time.Second) |
| 4409 |
require_NoError(t, err) |
| 4410 |
_, err = nc.Request("pass3."+aPub, nil, time.Second) |
| 4411 |
require_NoError(t, err) |
| 4412 |
_, err = nc.Request("pass3.PING", nil, time.Second) |
| 4413 |
require_NoError(t, err) |
| 4414 |
} |
| 4415 |
|
| 4416 |
func TestJWTSysImportOverwriteToken(t *testing.T) { |
| 4417 |
_, sysPub, sysClaim := NewJwtAccountClaim("SYS") |
| 4418 |
// this changes the export permissions in a way that the internal imports can't satisfy |
| 4419 |
sysClaim.Exports.Add(&jwt.Export{ |
| 4420 |
Type: jwt.Service, |
| 4421 |
Subject: "$SYS.REQ.>", |
| 4422 |
TokenReq: true, |
| 4423 |
}) |
| 4424 |
|
| 4425 |
sysJwt, err := sysClaim.Encode(oKp) |
| 4426 |
require_NoError(t, err) |
| 4427 |
|
| 4428 |
// create account |
| 4429 |
aKp, aPub, claim := NewJwtAccountClaim("A") |
| 4430 |
aJwt, err := claim.Encode(oKp) |
| 4431 |
require_NoError(t, err) |
| 4432 |
|
| 4433 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 4434 |
listen: 127.0.0.1:-1 |
| 4435 |
operator: %s |
| 4436 |
system_account: %s |
| 4437 |
resolver: MEM |
| 4438 |
resolver_preload: { |
| 4439 |
%s: %s |
| 4440 |
%s: %s |
| 4441 |
} |
| 4442 |
`, ojwt, sysPub, sysPub, sysJwt, aPub, aJwt))) |
| 4443 |
sA, _ := RunServerWithConfig(conf) |
| 4444 |
defer sA.Shutdown() |
| 4445 |
|
| 4446 |
nc := natsConnect(t, sA.ClientURL(), createUserCreds(t, nil, aKp)) |
| 4447 |
defer nc.Close() |
| 4448 |
// make sure the internal import still got added |
| 4449 |
_, err = nc.Request("$SYS.REQ.ACCOUNT.PING.CONNZ", nil, time.Second) |
| 4450 |
require_NoError(t, err) |
| 4451 |
} |
| 4452 |
|
| 4453 |
func TestJWTLimits(t *testing.T) { |
| 4454 |
doNotExpire := time.Now().AddDate(1, 0, 0) |
| 4455 |
// create account |
| 4456 |
kp, _ := nkeys.CreateAccount() |
| 4457 |
aPub, _ := kp.PublicKey() |
| 4458 |
claim := jwt.NewAccountClaims(aPub) |
| 4459 |
aJwt, err := claim.Encode(oKp) |
| 4460 |
require_NoError(t, err) |
| 4461 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 4462 |
listen: 127.0.0.1:-1 |
| 4463 |
operator: %s |
| 4464 |
resolver: MEM |
| 4465 |
resolver_preload: { |
| 4466 |
%s: %s |
| 4467 |
} |
| 4468 |
`, ojwt, aPub, aJwt))) |
| 4469 |
sA, _ := RunServerWithConfig(conf) |
| 4470 |
defer sA.Shutdown() |
| 4471 |
errChan := make(chan struct{}) |
| 4472 |
defer close(errChan) |
| 4473 |
t.Run("subs", func(t *testing.T) { |
| 4474 |
creds := createUserWithLimit(t, kp, doNotExpire, func(j *jwt.UserPermissionLimits) { j.Subs = 1 }) |
| 4475 |
c := natsConnect(t, sA.ClientURL(), nats.UserCredentials(creds), |
| 4476 |
nats.ErrorHandler(func(conn *nats.Conn, s *nats.Subscription, err error) { |
| 4477 |
if e := conn.LastError(); e != nil && strings.Contains(e.Error(), "maximum subscriptions exceeded") { |
| 4478 |
errChan <- struct{}{} |
| 4479 |
} |
| 4480 |
}), |
| 4481 |
) |
| 4482 |
defer c.Close() |
| 4483 |
if _, err := c.Subscribe("foo", func(msg *nats.Msg) {}); err != nil { |
| 4484 |
t.Fatalf("couldn't subscribe: %v", err) |
| 4485 |
} |
| 4486 |
if _, err = c.Subscribe("bar", func(msg *nats.Msg) {}); err != nil { |
| 4487 |
t.Fatalf("expected error got: %v", err) |
| 4488 |
} |
| 4489 |
chanRecv(t, errChan, time.Second) |
| 4490 |
}) |
| 4491 |
t.Run("payload", func(t *testing.T) { |
| 4492 |
creds := createUserWithLimit(t, kp, doNotExpire, func(j *jwt.UserPermissionLimits) { j.Payload = 5 }) |
| 4493 |
c := natsConnect(t, sA.ClientURL(), nats.UserCredentials(creds)) |
| 4494 |
defer c.Close() |
| 4495 |
if err := c.Flush(); err != nil { |
| 4496 |
t.Fatalf("flush failed %v", err) |
| 4497 |
} |
| 4498 |
if err := c.Publish("foo", []byte("world")); err != nil { |
| 4499 |
t.Fatalf("couldn't publish: %v", err) |
| 4500 |
} |
| 4501 |
if err := c.Publish("foo", []byte("worldX")); err != nats.ErrMaxPayload { |
| 4502 |
t.Fatalf("couldn't publish: %v", err) |
| 4503 |
} |
| 4504 |
}) |
| 4505 |
} |
| 4506 |
|
| 4507 |
func TestJWTTemplates(t *testing.T) { |
| 4508 |
kp, _ := nkeys.CreateAccount() |
| 4509 |
aPub, _ := kp.PublicKey() |
| 4510 |
ukp, _ := nkeys.CreateUser() |
| 4511 |
upub, _ := ukp.PublicKey() |
| 4512 |
uclaim := newJWTTestUserClaims() |
| 4513 |
uclaim.Name = "myname" |
| 4514 |
uclaim.Subject = upub |
| 4515 |
uclaim.SetScoped(true) |
| 4516 |
uclaim.IssuerAccount = aPub |
| 4517 |
uclaim.Tags.Add("foo:foo1") |
| 4518 |
uclaim.Tags.Add("foo:foo2") |
| 4519 |
uclaim.Tags.Add("bar:bar1") |
| 4520 |
uclaim.Tags.Add("bar:bar2") |
| 4521 |
uclaim.Tags.Add("bar:bar3") |
| 4522 |
|
| 4523 |
lim := jwt.UserPermissionLimits{} |
| 4524 |
lim.Pub.Allow.Add("{{tag(foo)}}.none.{{tag(bar)}}") |
| 4525 |
lim.Pub.Deny.Add("{{tag(foo)}}.{{account-tag(acc)}}") |
| 4526 |
lim.Sub.Allow.Add("{{tag(NOT_THERE)}}") // expect to not emit this |
| 4527 |
lim.Sub.Deny.Add("foo.{{name()}}.{{subject()}}.{{account-name()}}.{{account-subject()}}.bar") |
| 4528 |
acc := &Account{nameTag: "accname", tags: []string{"acc:acc1", "acc:acc2"}} |
| 4529 |
|
| 4530 |
resLim, err := processUserPermissionsTemplate(lim, uclaim, acc) |
| 4531 |
require_NoError(t, err) |
| 4532 |
|
| 4533 |
test := func(expectedSubjects []string, res jwt.StringList) { |
| 4534 |
t.Helper() |
| 4535 |
require_True(t, len(res) == len(expectedSubjects)) |
| 4536 |
for _, expetedSubj := range expectedSubjects { |
| 4537 |
require_True(t, res.Contains(expetedSubj)) |
| 4538 |
} |
| 4539 |
} |
| 4540 |
|
| 4541 |
test(resLim.Pub.Allow, []string{"foo1.none.bar1", "foo1.none.bar2", "foo1.none.bar3", |
| 4542 |
"foo2.none.bar1", "foo2.none.bar2", "foo2.none.bar3"}) |
| 4543 |
|
| 4544 |
test(resLim.Pub.Deny, []string{"foo1.acc1", "foo1.acc2", "foo2.acc1", "foo2.acc2"}) |
| 4545 |
|
| 4546 |
require_True(t, len(resLim.Sub.Allow) == 0) |
| 4547 |
require_True(t, len(resLim.Sub.Deny) == 2) |
| 4548 |
require_Contains(t, resLim.Sub.Deny[0], fmt.Sprintf("foo.myname.%s.accname.%s.bar", upub, aPub)) |
| 4549 |
// added in to compensate for sub allow not resolving |
| 4550 |
require_Contains(t, resLim.Sub.Deny[1], ">") |
| 4551 |
|
| 4552 |
lim.Pub.Deny.Add("{{tag(NOT_THERE)}}") |
| 4553 |
_, err = processUserPermissionsTemplate(lim, uclaim, acc) |
| 4554 |
require_Error(t, err) |
| 4555 |
require_Contains(t, err.Error(), "generated invalid subject") |
| 4556 |
} |
| 4557 |
|
| 4558 |
func TestJWTInLineTemplates(t *testing.T) { |
| 4559 |
kp, _ := nkeys.CreateAccount() |
| 4560 |
aPub, _ := kp.PublicKey() |
| 4561 |
ukp, _ := nkeys.CreateUser() |
| 4562 |
upub, _ := ukp.PublicKey() |
| 4563 |
uclaim := newJWTTestUserClaims() |
| 4564 |
uclaim.Name = "myname" |
| 4565 |
uclaim.Subject = upub |
| 4566 |
uclaim.SetScoped(true) |
| 4567 |
uclaim.IssuerAccount = aPub |
| 4568 |
uclaim.Tags.Add("bucket:a") |
| 4569 |
|
| 4570 |
lim := jwt.UserPermissionLimits{} |
| 4571 |
lim.Pub.Allow.Add("$JS.API.STREAM.INFO.KV_{{tag(bucket)}}") |
| 4572 |
acc := &Account{nameTag: "accname", tags: []string{"acc:acc1", "acc:acc2"}} |
| 4573 |
|
| 4574 |
resLim, err := processUserPermissionsTemplate(lim, uclaim, acc) |
| 4575 |
require_NoError(t, err) |
| 4576 |
|
| 4577 |
test := func(expectedSubjects []string, res jwt.StringList) { |
| 4578 |
t.Helper() |
| 4579 |
require_True(t, len(res) == len(expectedSubjects)) |
| 4580 |
for _, expetedSubj := range expectedSubjects { |
| 4581 |
require_True(t, res.Contains(expetedSubj)) |
| 4582 |
} |
| 4583 |
} |
| 4584 |
|
| 4585 |
test(resLim.Pub.Allow, []string{"$JS.API.STREAM.INFO.KV_a"}) |
| 4586 |
} |
| 4587 |
|
| 4588 |
func TestJWTTemplateGoodTagAfterBadTag(t *testing.T) { |
| 4589 |
kp, _ := nkeys.CreateAccount() |
| 4590 |
aPub, _ := kp.PublicKey() |
| 4591 |
ukp, _ := nkeys.CreateUser() |
| 4592 |
upub, _ := ukp.PublicKey() |
| 4593 |
uclaim := newJWTTestUserClaims() |
| 4594 |
uclaim.Name = "myname" |
| 4595 |
uclaim.Subject = upub |
| 4596 |
uclaim.SetScoped(true) |
| 4597 |
uclaim.IssuerAccount = aPub |
| 4598 |
uclaim.Tags.Add("foo:foo1") |
| 4599 |
|
| 4600 |
lim := jwt.UserPermissionLimits{} |
| 4601 |
lim.Pub.Deny.Add("{{tag(NOT_THERE)}}.{{tag(foo)}}") |
| 4602 |
acc := &Account{nameTag: "accname", tags: []string{"acc:acc1", "acc:acc2"}} |
| 4603 |
|
| 4604 |
_, err := processUserPermissionsTemplate(lim, uclaim, acc) |
| 4605 |
require_Error(t, err) |
| 4606 |
require_Contains(t, err.Error(), "generated invalid subject") |
| 4607 |
} |
| 4608 |
|
| 4609 |
func TestJWTLimitsTemplate(t *testing.T) { |
| 4610 |
kp, _ := nkeys.CreateAccount() |
| 4611 |
aPub, _ := kp.PublicKey() |
| 4612 |
claim := jwt.NewAccountClaims(aPub) |
| 4613 |
aSignScopedKp, aSignScopedPub := createKey(t) |
| 4614 |
signer := jwt.NewUserScope() |
| 4615 |
signer.Key = aSignScopedPub |
| 4616 |
signer.Template.Pub.Deny.Add("denied") |
| 4617 |
signer.Template.Pub.Allow.Add("foo.{{name()}}") |
| 4618 |
signer.Template.Sub.Allow.Add("foo.{{name()}}") |
| 4619 |
claim.SigningKeys.AddScopedSigner(signer) |
| 4620 |
aJwt, err := claim.Encode(oKp) |
| 4621 |
require_NoError(t, err) |
| 4622 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 4623 |
listen: 127.0.0.1:-1 |
| 4624 |
operator: %s |
| 4625 |
resolver: MEM |
| 4626 |
resolver_preload: { |
| 4627 |
%s: %s |
| 4628 |
} |
| 4629 |
`, ojwt, aPub, aJwt))) |
| 4630 |
sA, _ := RunServerWithConfig(conf) |
| 4631 |
defer sA.Shutdown() |
| 4632 |
errChan := make(chan struct{}) |
| 4633 |
defer close(errChan) |
| 4634 |
|
| 4635 |
ukp, _ := nkeys.CreateUser() |
| 4636 |
seed, _ := ukp.Seed() |
| 4637 |
upub, _ := ukp.PublicKey() |
| 4638 |
uclaim := newJWTTestUserClaims() |
| 4639 |
uclaim.Name = "myname" |
| 4640 |
uclaim.Subject = upub |
| 4641 |
uclaim.SetScoped(true) |
| 4642 |
uclaim.IssuerAccount = aPub |
| 4643 |
|
| 4644 |
ujwt, err := uclaim.Encode(aSignScopedKp) |
| 4645 |
require_NoError(t, err) |
| 4646 |
creds := genCredsFile(t, ujwt, seed) |
| 4647 |
|
| 4648 |
t.Run("pass", func(t *testing.T) { |
| 4649 |
c := natsConnect(t, sA.ClientURL(), nats.UserCredentials(creds)) |
| 4650 |
defer c.Close() |
| 4651 |
sub, err := c.SubscribeSync("foo.myname") |
| 4652 |
require_NoError(t, err) |
| 4653 |
require_NoError(t, c.Flush()) |
| 4654 |
require_NoError(t, c.Publish("foo.myname", nil)) |
| 4655 |
_, err = sub.NextMsg(time.Second) |
| 4656 |
require_NoError(t, err) |
| 4657 |
}) |
| 4658 |
t.Run("fail", func(t *testing.T) { |
| 4659 |
c := natsConnect(t, sA.ClientURL(), nats.UserCredentials(creds), |
| 4660 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) { |
| 4661 |
if strings.Contains(err.Error(), `Permissions Violation for Publish to "foo.othername"`) { |
| 4662 |
errChan <- struct{}{} |
| 4663 |
} |
| 4664 |
})) |
| 4665 |
defer c.Close() |
| 4666 |
require_NoError(t, c.Publish("foo.othername", nil)) |
| 4667 |
select { |
| 4668 |
case <-errChan: |
| 4669 |
case <-time.After(time.Second * 2): |
| 4670 |
require_True(t, false) |
| 4671 |
} |
| 4672 |
}) |
| 4673 |
} |
| 4674 |
|
| 4675 |
func TestJWTNoOperatorMode(t *testing.T) { |
| 4676 |
for _, login := range []bool{true, false} { |
| 4677 |
t.Run("", func(t *testing.T) { |
| 4678 |
opts := DefaultOptions() |
| 4679 |
if login { |
| 4680 |
opts.Users = append(opts.Users, &User{Username: "u", Password: "pwd"}) |
| 4681 |
} |
| 4682 |
sA := RunServer(opts) |
| 4683 |
defer sA.Shutdown() |
| 4684 |
kp, _ := nkeys.CreateAccount() |
| 4685 |
creds := createUserWithLimit(t, kp, time.Now().Add(time.Hour), nil) |
| 4686 |
url := sA.ClientURL() |
| 4687 |
if login { |
| 4688 |
url = fmt.Sprintf("nats://u:pwd@%s:%d", sA.opts.Host, sA.opts.Port) |
| 4689 |
} |
| 4690 |
c := natsConnect(t, url, nats.UserCredentials(creds)) |
| 4691 |
defer c.Close() |
| 4692 |
sA.mu.Lock() |
| 4693 |
defer sA.mu.Unlock() |
| 4694 |
if len(sA.clients) != 1 { |
| 4695 |
t.Fatalf("Expected exactly one client") |
| 4696 |
} |
| 4697 |
for _, v := range sA.clients { |
| 4698 |
if v.opts.JWT != "" { |
| 4699 |
t.Fatalf("Expected no jwt %v", v.opts.JWT) |
| 4700 |
} |
| 4701 |
} |
| 4702 |
}) |
| 4703 |
} |
| 4704 |
} |
| 4705 |
|
| 4706 |
func TestJWTUserRevocation(t *testing.T) { |
| 4707 |
test := func(all bool) { |
| 4708 |
createAccountAndUser := func(done chan struct{}, pubKey, jwt1, jwt2, creds1, creds2 *string) { |
| 4709 |
t.Helper() |
| 4710 |
kp, _ := nkeys.CreateAccount() |
| 4711 |
*pubKey, _ = kp.PublicKey() |
| 4712 |
claim := jwt.NewAccountClaims(*pubKey) |
| 4713 |
var err error |
| 4714 |
*jwt1, err = claim.Encode(oKp) |
| 4715 |
require_NoError(t, err) |
| 4716 |
|
| 4717 |
ukp, _ := nkeys.CreateUser() |
| 4718 |
seed, _ := ukp.Seed() |
| 4719 |
upub, _ := ukp.PublicKey() |
| 4720 |
uclaim := newJWTTestUserClaims() |
| 4721 |
uclaim.Subject = upub |
| 4722 |
|
| 4723 |
ujwt1, err := uclaim.Encode(kp) |
| 4724 |
require_NoError(t, err) |
| 4725 |
*creds1 = genCredsFile(t, ujwt1, seed) |
| 4726 |
|
| 4727 |
// create updated claim need to assure that issue time differs |
| 4728 |
if all { |
| 4729 |
claim.Revoke(jwt.All) // revokes all jwt from now on |
| 4730 |
} else { |
| 4731 |
claim.Revoke(upub) // revokes this jwt from now on |
| 4732 |
} |
| 4733 |
time.Sleep(time.Millisecond * 1100) |
| 4734 |
*jwt2, err = claim.Encode(oKp) |
| 4735 |
require_NoError(t, err) |
| 4736 |
|
| 4737 |
ujwt2, err := uclaim.Encode(kp) |
| 4738 |
require_NoError(t, err) |
| 4739 |
*creds2 = genCredsFile(t, ujwt2, seed) |
| 4740 |
|
| 4741 |
done <- struct{}{} |
| 4742 |
} |
| 4743 |
// Create Accounts and corresponding revoked and non revoked user creds. Do so concurrently to speed up the test |
| 4744 |
doneChan := make(chan struct{}, 2) |
| 4745 |
defer close(doneChan) |
| 4746 |
var syspub, sysjwt, dummy1, sysCreds, dummyCreds string |
| 4747 |
go createAccountAndUser(doneChan, &syspub, &sysjwt, &dummy1, &sysCreds, &dummyCreds) |
| 4748 |
var apub, ajwt1, ajwt2, aCreds1, aCreds2 string |
| 4749 |
go createAccountAndUser(doneChan, &apub, &ajwt1, &ajwt2, &aCreds1, &aCreds2) |
| 4750 |
for i := 0; i < cap(doneChan); i++ { |
| 4751 |
<-doneChan |
| 4752 |
} |
| 4753 |
dirSrv := t.TempDir() |
| 4754 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 4755 |
listen: 127.0.0.1:-1 |
| 4756 |
operator: %s |
| 4757 |
system_account: %s |
| 4758 |
resolver: { |
| 4759 |
type: full |
| 4760 |
dir: '%s' |
| 4761 |
} |
| 4762 |
`, ojwt, syspub, dirSrv))) |
| 4763 |
srv, _ := RunServerWithConfig(conf) |
| 4764 |
defer srv.Shutdown() |
| 4765 |
updateJwt(t, srv.ClientURL(), sysCreds, sysjwt, 1) // update system account jwt |
| 4766 |
updateJwt(t, srv.ClientURL(), sysCreds, ajwt1, 1) // set account jwt without revocation |
| 4767 |
ncSys := natsConnect(t, srv.ClientURL(), nats.UserCredentials(sysCreds), nats.Name("conn name")) |
| 4768 |
defer ncSys.Close() |
| 4769 |
ncChan := make(chan *nats.Msg, 10) |
| 4770 |
defer close(ncChan) |
| 4771 |
sub, _ := ncSys.ChanSubscribe(fmt.Sprintf(disconnectEventSubj, apub), ncChan) // observe disconnect message |
| 4772 |
defer sub.Unsubscribe() |
| 4773 |
// use credentials that will be revoked ans assure that the connection will be disconnected |
| 4774 |
nc := natsConnect(t, srv.ClientURL(), nats.UserCredentials(aCreds1), |
| 4775 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) { |
| 4776 |
if err != nil && strings.Contains(err.Error(), "authentication revoked") { |
| 4777 |
doneChan <- struct{}{} |
| 4778 |
} |
| 4779 |
}), |
| 4780 |
) |
| 4781 |
defer nc.Close() |
| 4782 |
// update account jwt to contain revocation |
| 4783 |
if updateJwt(t, srv.ClientURL(), sysCreds, ajwt2, 1) != 1 { |
| 4784 |
t.Fatalf("Expected jwt update to pass") |
| 4785 |
} |
| 4786 |
// assure that nc got disconnected due to the revocation |
| 4787 |
select { |
| 4788 |
case <-doneChan: |
| 4789 |
case <-time.After(time.Second): |
| 4790 |
t.Fatalf("Expected connection to have failed") |
| 4791 |
} |
| 4792 |
m := <-ncChan |
| 4793 |
require_Len(t, strings.Count(string(m.Data), apub), 3) |
| 4794 |
require_True(t, strings.Contains(string(m.Data), `"jwt":"eyJ0`)) |
| 4795 |
// try again with old credentials. Expected to fail |
| 4796 |
if nc1, err := nats.Connect(srv.ClientURL(), nats.UserCredentials(aCreds1)); err == nil { |
| 4797 |
nc1.Close() |
| 4798 |
t.Fatalf("Expected revoked credentials to fail") |
| 4799 |
} |
| 4800 |
// Assure new creds pass |
| 4801 |
nc2 := natsConnect(t, srv.ClientURL(), nats.UserCredentials(aCreds2)) |
| 4802 |
defer nc2.Close() |
| 4803 |
} |
| 4804 |
t.Run("specific-key", func(t *testing.T) { |
| 4805 |
test(false) |
| 4806 |
}) |
| 4807 |
t.Run("all-key", func(t *testing.T) { |
| 4808 |
test(true) |
| 4809 |
}) |
| 4810 |
} |
| 4811 |
|
| 4812 |
func TestJWTActivationRevocation(t *testing.T) { |
| 4813 |
test := func(all bool) { |
| 4814 |
sysKp, syspub := createKey(t) |
| 4815 |
sysJwt := encodeClaim(t, jwt.NewAccountClaims(syspub), syspub) |
| 4816 |
sysCreds := newUser(t, sysKp) |
| 4817 |
|
| 4818 |
aExpKp, aExpPub := createKey(t) |
| 4819 |
aExpClaim := jwt.NewAccountClaims(aExpPub) |
| 4820 |
aExpClaim.Name = "Export" |
| 4821 |
aExpClaim.Exports.Add(&jwt.Export{ |
| 4822 |
Subject: "foo", |
| 4823 |
Type: jwt.Stream, |
| 4824 |
TokenReq: true, |
| 4825 |
}) |
| 4826 |
aExp1Jwt := encodeClaim(t, aExpClaim, aExpPub) |
| 4827 |
aExpCreds := newUser(t, aExpKp) |
| 4828 |
|
| 4829 |
aImpKp, aImpPub := createKey(t) |
| 4830 |
|
| 4831 |
ac := &jwt.ActivationClaims{} |
| 4832 |
ac.Subject = aImpPub |
| 4833 |
ac.ImportSubject = "foo" |
| 4834 |
ac.ImportType = jwt.Stream |
| 4835 |
token, err := ac.Encode(aExpKp) |
| 4836 |
require_NoError(t, err) |
| 4837 |
|
| 4838 |
revPubKey := aImpPub |
| 4839 |
if all { |
| 4840 |
revPubKey = jwt.All |
| 4841 |
} |
| 4842 |
|
| 4843 |
aExpClaim.Exports[0].RevokeAt(revPubKey, time.Now()) |
| 4844 |
aExp2Jwt := encodeClaim(t, aExpClaim, aExpPub) |
| 4845 |
|
| 4846 |
aExpClaim.Exports[0].ClearRevocation(revPubKey) |
| 4847 |
aExp3Jwt := encodeClaim(t, aExpClaim, aExpPub) |
| 4848 |
|
| 4849 |
aImpClaim := jwt.NewAccountClaims(aImpPub) |
| 4850 |
aImpClaim.Name = "Import" |
| 4851 |
aImpClaim.Imports.Add(&jwt.Import{ |
| 4852 |
Subject: "foo", |
| 4853 |
Type: jwt.Stream, |
| 4854 |
Account: aExpPub, |
| 4855 |
Token: token, |
| 4856 |
}) |
| 4857 |
aImpJwt := encodeClaim(t, aImpClaim, aImpPub) |
| 4858 |
aImpCreds := newUser(t, aImpKp) |
| 4859 |
|
| 4860 |
dirSrv := t.TempDir() |
| 4861 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 4862 |
listen: 127.0.0.1:-1 |
| 4863 |
operator: %s |
| 4864 |
system_account: %s |
| 4865 |
resolver: { |
| 4866 |
type: full |
| 4867 |
dir: '%s' |
| 4868 |
} |
| 4869 |
`, ojwt, syspub, dirSrv))) |
| 4870 |
|
| 4871 |
t.Run("token-expired-on-connect", func(t *testing.T) { |
| 4872 |
srv, _ := RunServerWithConfig(conf) |
| 4873 |
defer srv.Shutdown() |
| 4874 |
defer removeDir(t, dirSrv) // clean jwt directory |
| 4875 |
|
| 4876 |
updateJwt(t, srv.ClientURL(), sysCreds, sysJwt, 1) // update system account jwt |
| 4877 |
updateJwt(t, srv.ClientURL(), sysCreds, aExp2Jwt, 1) // set account jwt without revocation |
| 4878 |
updateJwt(t, srv.ClientURL(), sysCreds, aImpJwt, 1) |
| 4879 |
|
| 4880 |
ncExp1 := natsConnect(t, srv.ClientURL(), nats.UserCredentials(aExpCreds)) |
| 4881 |
defer ncExp1.Close() |
| 4882 |
|
| 4883 |
ncImp := natsConnect(t, srv.ClientURL(), nats.UserCredentials(aImpCreds)) |
| 4884 |
defer ncImp.Close() |
| 4885 |
|
| 4886 |
sub, err := ncImp.SubscribeSync("foo") |
| 4887 |
require_NoError(t, err) |
| 4888 |
require_NoError(t, ncImp.Flush()) |
| 4889 |
require_NoError(t, ncExp1.Publish("foo", []byte("1"))) |
| 4890 |
_, err = sub.NextMsg(time.Second) |
| 4891 |
require_Error(t, err) |
| 4892 |
require_Equal(t, err.Error(), "nats: timeout") |
| 4893 |
}) |
| 4894 |
|
| 4895 |
t.Run("token-expired-on-update", func(t *testing.T) { |
| 4896 |
srv, _ := RunServerWithConfig(conf) |
| 4897 |
defer srv.Shutdown() |
| 4898 |
defer removeDir(t, dirSrv) // clean jwt directory |
| 4899 |
|
| 4900 |
updateJwt(t, srv.ClientURL(), sysCreds, sysJwt, 1) // update system account jwt |
| 4901 |
updateJwt(t, srv.ClientURL(), sysCreds, aExp1Jwt, 1) // set account jwt without revocation |
| 4902 |
updateJwt(t, srv.ClientURL(), sysCreds, aImpJwt, 1) |
| 4903 |
|
| 4904 |
ncExp1 := natsConnect(t, srv.ClientURL(), nats.UserCredentials(aExpCreds)) |
| 4905 |
defer ncExp1.Close() |
| 4906 |
|
| 4907 |
ncImp := natsConnect(t, srv.ClientURL(), nats.UserCredentials(aImpCreds)) |
| 4908 |
defer ncImp.Close() |
| 4909 |
|
| 4910 |
sub, err := ncImp.SubscribeSync("foo") |
| 4911 |
require_NoError(t, err) |
| 4912 |
require_NoError(t, ncImp.Flush()) |
| 4913 |
require_NoError(t, ncExp1.Publish("foo", []byte("1"))) |
| 4914 |
m1, err := sub.NextMsg(time.Second) |
| 4915 |
require_NoError(t, err) |
| 4916 |
require_Equal(t, string(m1.Data), "1") |
| 4917 |
|
| 4918 |
updateJwt(t, srv.ClientURL(), sysCreds, aExp2Jwt, 1) // set account jwt with revocation |
| 4919 |
|
| 4920 |
require_NoError(t, ncExp1.Publish("foo", []byte("2"))) |
| 4921 |
_, err = sub.NextMsg(time.Second) |
| 4922 |
require_Error(t, err) |
| 4923 |
require_Equal(t, err.Error(), "nats: timeout") |
| 4924 |
|
| 4925 |
updateJwt(t, srv.ClientURL(), sysCreds, aExp3Jwt, 1) // set account with revocation cleared |
| 4926 |
|
| 4927 |
require_NoError(t, ncExp1.Publish("foo", []byte("3"))) |
| 4928 |
m2, err := sub.NextMsg(time.Second) |
| 4929 |
require_NoError(t, err) |
| 4930 |
require_Equal(t, string(m2.Data), "3") |
| 4931 |
}) |
| 4932 |
} |
| 4933 |
t.Run("specific-key", func(t *testing.T) { |
| 4934 |
test(false) |
| 4935 |
}) |
| 4936 |
t.Run("all-key", func(t *testing.T) { |
| 4937 |
test(true) |
| 4938 |
}) |
| 4939 |
} |
| 4940 |
|
| 4941 |
func TestJWTAccountFetchTimeout(t *testing.T) { |
| 4942 |
createAccountAndUser := func(pubKey, jwt1, creds1 *string) { |
| 4943 |
t.Helper() |
| 4944 |
kp, _ := nkeys.CreateAccount() |
| 4945 |
*pubKey, _ = kp.PublicKey() |
| 4946 |
claim := jwt.NewAccountClaims(*pubKey) |
| 4947 |
var err error |
| 4948 |
*jwt1, err = claim.Encode(oKp) |
| 4949 |
require_NoError(t, err) |
| 4950 |
ukp, _ := nkeys.CreateUser() |
| 4951 |
seed, _ := ukp.Seed() |
| 4952 |
upub, _ := ukp.PublicKey() |
| 4953 |
uclaim := newJWTTestUserClaims() |
| 4954 |
uclaim.Subject = upub |
| 4955 |
ujwt1, err := uclaim.Encode(kp) |
| 4956 |
require_NoError(t, err) |
| 4957 |
*creds1 = genCredsFile(t, ujwt1, seed) |
| 4958 |
} |
| 4959 |
for _, cfg := range []string{ |
| 4960 |
`type: full`, |
| 4961 |
`type: cache`, |
| 4962 |
} { |
| 4963 |
t.Run("", func(t *testing.T) { |
| 4964 |
var syspub, sysjwt, sysCreds string |
| 4965 |
createAccountAndUser(&syspub, &sysjwt, &sysCreds) |
| 4966 |
var apub, ajwt1, aCreds1 string |
| 4967 |
createAccountAndUser(&apub, &ajwt1, &aCreds1) |
| 4968 |
dirSrv := t.TempDir() |
| 4969 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 4970 |
listen: 127.0.0.1:-1 |
| 4971 |
operator: %s |
| 4972 |
system_account: %s |
| 4973 |
resolver: { |
| 4974 |
%s |
| 4975 |
timeout: "100ms" |
| 4976 |
dir: '%s' |
| 4977 |
} |
| 4978 |
`, ojwt, syspub, cfg, dirSrv))) |
| 4979 |
srv, _ := RunServerWithConfig(conf) |
| 4980 |
defer srv.Shutdown() |
| 4981 |
updateJwt(t, srv.ClientURL(), sysCreds, sysjwt, 1) // update system account jwt |
| 4982 |
start := time.Now() |
| 4983 |
nc, err := nats.Connect(srv.ClientURL(), nats.UserCredentials(aCreds1)) |
| 4984 |
if err == nil { |
| 4985 |
t.Fatal("expected an error, got none") |
| 4986 |
} else if !strings.Contains(err.Error(), "Authorization Violation") { |
| 4987 |
t.Fatalf("expected an authorization violation, got: %v", err) |
| 4988 |
} |
| 4989 |
if time.Since(start) > 300*time.Millisecond { |
| 4990 |
t.Fatal("expected timeout earlier") |
| 4991 |
} |
| 4992 |
defer nc.Close() |
| 4993 |
}) |
| 4994 |
} |
| 4995 |
} |
| 4996 |
|
| 4997 |
func TestJWTAccountOps(t *testing.T) { |
| 4998 |
op, _ := nkeys.CreateOperator() |
| 4999 |
opPk, _ := op.PublicKey() |
| 5000 |
sk, _ := nkeys.CreateOperator() |
| 5001 |
skPk, _ := sk.PublicKey() |
| 5002 |
opClaim := jwt.NewOperatorClaims(opPk) |
| 5003 |
opClaim.SigningKeys.Add(skPk) |
| 5004 |
opJwt, err := opClaim.Encode(op) |
| 5005 |
require_NoError(t, err) |
| 5006 |
createAccountAndUser := func(pubKey, jwt1, creds1 *string) { |
| 5007 |
t.Helper() |
| 5008 |
kp, _ := nkeys.CreateAccount() |
| 5009 |
*pubKey, _ = kp.PublicKey() |
| 5010 |
claim := jwt.NewAccountClaims(*pubKey) |
| 5011 |
var err error |
| 5012 |
*jwt1, err = claim.Encode(sk) |
| 5013 |
require_NoError(t, err) |
| 5014 |
|
| 5015 |
ukp, _ := nkeys.CreateUser() |
| 5016 |
seed, _ := ukp.Seed() |
| 5017 |
upub, _ := ukp.PublicKey() |
| 5018 |
uclaim := newJWTTestUserClaims() |
| 5019 |
uclaim.Subject = upub |
| 5020 |
|
| 5021 |
ujwt1, err := uclaim.Encode(kp) |
| 5022 |
require_NoError(t, err) |
| 5023 |
*creds1 = genCredsFile(t, ujwt1, seed) |
| 5024 |
} |
| 5025 |
generateRequest := func(accs []string, kp nkeys.KeyPair) []byte { |
| 5026 |
t.Helper() |
| 5027 |
opk, _ := kp.PublicKey() |
| 5028 |
c := jwt.NewGenericClaims(opk) |
| 5029 |
c.Data["accounts"] = accs |
| 5030 |
cJwt, err := c.Encode(kp) |
| 5031 |
if err != nil { |
| 5032 |
t.Fatalf("Expected no error %v", err) |
| 5033 |
} |
| 5034 |
return []byte(cJwt) |
| 5035 |
} |
| 5036 |
for _, cfg := range []string{ |
| 5037 |
`type: full |
| 5038 |
allow_delete: true`, |
| 5039 |
`type: cache`, |
| 5040 |
} { |
| 5041 |
t.Run("", func(t *testing.T) { |
| 5042 |
var syspub, sysjwt, sysCreds string |
| 5043 |
createAccountAndUser(&syspub, &sysjwt, &sysCreds) |
| 5044 |
var apub, ajwt1, aCreds1 string |
| 5045 |
createAccountAndUser(&apub, &ajwt1, &aCreds1) |
| 5046 |
dirSrv := t.TempDir() |
| 5047 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 5048 |
listen: 127.0.0.1:-1 |
| 5049 |
operator: %s |
| 5050 |
system_account: %s |
| 5051 |
resolver: { |
| 5052 |
%s |
| 5053 |
dir: '%s' |
| 5054 |
} |
| 5055 |
`, opJwt, syspub, cfg, dirSrv))) |
| 5056 |
disconnectErrChan := make(chan struct{}, 1) |
| 5057 |
defer close(disconnectErrChan) |
| 5058 |
srv, _ := RunServerWithConfig(conf) |
| 5059 |
defer srv.Shutdown() |
| 5060 |
updateJwt(t, srv.ClientURL(), sysCreds, sysjwt, 1) // update system account jwt |
| 5061 |
// push jwt (for full resolver) |
| 5062 |
updateJwt(t, srv.ClientURL(), sysCreds, ajwt1, 1) // set jwt |
| 5063 |
nc := natsConnect(t, srv.ClientURL(), nats.UserCredentials(sysCreds)) |
| 5064 |
defer nc.Close() |
| 5065 |
// simulate nas resolver in case of a lookup request (cache) |
| 5066 |
nc.Subscribe(fmt.Sprintf(accLookupReqSubj, apub), func(msg *nats.Msg) { |
| 5067 |
msg.Respond([]byte(ajwt1)) |
| 5068 |
}) |
| 5069 |
// connect so there is a reason to cache the request and so disconnect can be observed |
| 5070 |
ncA := natsConnect(t, srv.ClientURL(), nats.UserCredentials(aCreds1), nats.NoReconnect(), |
| 5071 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) { |
| 5072 |
if err != nil && strings.Contains(err.Error(), "account authentication expired") { |
| 5073 |
disconnectErrChan <- struct{}{} |
| 5074 |
} |
| 5075 |
})) |
| 5076 |
defer ncA.Close() |
| 5077 |
resp, err := nc.Request(accListReqSubj, nil, time.Second) |
| 5078 |
require_NoError(t, err) |
| 5079 |
require_True(t, strings.Contains(string(resp.Data), apub)) |
| 5080 |
require_True(t, strings.Contains(string(resp.Data), syspub)) |
| 5081 |
// delete nothing |
| 5082 |
resp, err = nc.Request(accDeleteReqSubj, generateRequest([]string{}, op), time.Second) |
| 5083 |
require_NoError(t, err) |
| 5084 |
require_True(t, strings.Contains(string(resp.Data), `"message":"deleted 0 accounts"`)) |
| 5085 |
// issue delete, twice to also delete a non existing account |
| 5086 |
// also switch which key used to sign the request |
| 5087 |
for i := 0; i < 2; i++ { |
| 5088 |
resp, err = nc.Request(accDeleteReqSubj, generateRequest([]string{apub}, sk), time.Second) |
| 5089 |
require_NoError(t, err) |
| 5090 |
require_True(t, strings.Contains(string(resp.Data), `"message":"deleted 1 accounts"`)) |
| 5091 |
resp, err = nc.Request(accListReqSubj, nil, time.Second) |
| 5092 |
require_False(t, strings.Contains(string(resp.Data), apub)) |
| 5093 |
require_True(t, strings.Contains(string(resp.Data), syspub)) |
| 5094 |
require_NoError(t, err) |
| 5095 |
if i > 0 { |
| 5096 |
continue |
| 5097 |
} |
| 5098 |
select { |
| 5099 |
case <-disconnectErrChan: |
| 5100 |
case <-time.After(time.Second): |
| 5101 |
t.Fatal("Callback not executed") |
| 5102 |
} |
| 5103 |
} |
| 5104 |
}) |
| 5105 |
} |
| 5106 |
} |
| 5107 |
|
| 5108 |
func createKey(t *testing.T) (nkeys.KeyPair, string) { |
| 5109 |
t.Helper() |
| 5110 |
kp, _ := nkeys.CreateAccount() |
| 5111 |
syspub, _ := kp.PublicKey() |
| 5112 |
return kp, syspub |
| 5113 |
} |
| 5114 |
|
| 5115 |
func encodeClaim(t *testing.T, claim *jwt.AccountClaims, _ string) string { |
| 5116 |
t.Helper() |
| 5117 |
theJWT, err := claim.Encode(oKp) |
| 5118 |
require_NoError(t, err) |
| 5119 |
return theJWT |
| 5120 |
} |
| 5121 |
|
| 5122 |
// returns user creds |
| 5123 |
func newUserEx(t *testing.T, accKp nkeys.KeyPair, scoped bool, issuerAccount string) string { |
| 5124 |
ukp, _ := nkeys.CreateUser() |
| 5125 |
seed, _ := ukp.Seed() |
| 5126 |
upub, _ := ukp.PublicKey() |
| 5127 |
uclaim := newJWTTestUserClaims() |
| 5128 |
uclaim.Subject = upub |
| 5129 |
uclaim.SetScoped(scoped) |
| 5130 |
if issuerAccount != _EMPTY_ { |
| 5131 |
uclaim.IssuerAccount = issuerAccount |
| 5132 |
} |
| 5133 |
ujwt, err := uclaim.Encode(accKp) |
| 5134 |
require_NoError(t, err) |
| 5135 |
return genCredsFile(t, ujwt, seed) |
| 5136 |
} |
| 5137 |
|
| 5138 |
// returns user creds |
| 5139 |
func newUser(t *testing.T, accKp nkeys.KeyPair) string { |
| 5140 |
return newUserEx(t, accKp, false, "") |
| 5141 |
} |
| 5142 |
|
| 5143 |
func TestJWTHeader(t *testing.T) { |
| 5144 |
sysKp, syspub := createKey(t) |
| 5145 |
sysJwt := encodeClaim(t, jwt.NewAccountClaims(syspub), syspub) |
| 5146 |
sysCreds := newUser(t, sysKp) |
| 5147 |
|
| 5148 |
test := func(share bool) { |
| 5149 |
aExpKp, aExpPub := createKey(t) |
| 5150 |
aExpClaim := jwt.NewAccountClaims(aExpPub) |
| 5151 |
aExpClaim.Exports.Add(&jwt.Export{ |
| 5152 |
Name: "test", |
| 5153 |
Subject: "srvc", |
| 5154 |
Type: jwt.Service, |
| 5155 |
TokenReq: false, |
| 5156 |
Latency: &jwt.ServiceLatency{ |
| 5157 |
Sampling: jwt.Headers, |
| 5158 |
Results: "res", |
| 5159 |
}, |
| 5160 |
}) |
| 5161 |
aExpJwt := encodeClaim(t, aExpClaim, aExpPub) |
| 5162 |
aExpCreds := newUser(t, aExpKp) |
| 5163 |
|
| 5164 |
aImpKp, aImpPub := createKey(t) |
| 5165 |
aImpClaim := jwt.NewAccountClaims(aImpPub) |
| 5166 |
aImpClaim.Imports.Add(&jwt.Import{ |
| 5167 |
Name: "test", |
| 5168 |
Subject: "srvc", |
| 5169 |
Account: aExpPub, |
| 5170 |
Type: jwt.Service, |
| 5171 |
Share: share, |
| 5172 |
}) |
| 5173 |
aImpJwt := encodeClaim(t, aImpClaim, aImpPub) |
| 5174 |
aImpCreds := newUser(t, aImpKp) |
| 5175 |
|
| 5176 |
dirSrv := t.TempDir() |
| 5177 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 5178 |
listen: 127.0.0.1:-1 |
| 5179 |
operator: %s |
| 5180 |
system_account: %s |
| 5181 |
resolver: { |
| 5182 |
type: full |
| 5183 |
dir: '%s' |
| 5184 |
} |
| 5185 |
`, ojwt, syspub, dirSrv))) |
| 5186 |
srv, _ := RunServerWithConfig(conf) |
| 5187 |
defer srv.Shutdown() |
| 5188 |
updateJwt(t, srv.ClientURL(), sysCreds, sysJwt, 1) // update system account jwt |
| 5189 |
updateJwt(t, srv.ClientURL(), sysCreds, aExpJwt, 1) |
| 5190 |
updateJwt(t, srv.ClientURL(), sysCreds, aImpJwt, 1) |
| 5191 |
|
| 5192 |
expNc := natsConnect(t, srv.ClientURL(), nats.UserCredentials(aExpCreds)) |
| 5193 |
defer expNc.Close() |
| 5194 |
resChan := make(chan *nats.Msg, 1) |
| 5195 |
expNc.ChanSubscribe("res", resChan) |
| 5196 |
sub, err := expNc.Subscribe("srvc", func(msg *nats.Msg) { |
| 5197 |
msg.Respond(nil) |
| 5198 |
}) |
| 5199 |
require_NoError(t, err) |
| 5200 |
defer sub.Unsubscribe() |
| 5201 |
|
| 5202 |
impNc := natsConnect(t, srv.ClientURL(), nats.UserCredentials(aImpCreds)) |
| 5203 |
defer impNc.Close() |
| 5204 |
// send request w/o header |
| 5205 |
_, err = impNc.Request("srvc", []byte("msg1"), time.Second) |
| 5206 |
require_NoError(t, err) |
| 5207 |
require_True(t, len(resChan) == 0) |
| 5208 |
|
| 5209 |
_, err = impNc.RequestMsg(&nats.Msg{ |
| 5210 |
Subject: "srvc", Data: []byte("msg2"), Header: nats.Header{ |
| 5211 |
"X-B3-Sampled": []string{"1"}, |
| 5212 |
"Share": []string{"Me"}}}, time.Second) |
| 5213 |
require_NoError(t, err) |
| 5214 |
select { |
| 5215 |
case <-time.After(time.Second): |
| 5216 |
t.Fatalf("should have received a response") |
| 5217 |
case m := <-resChan: |
| 5218 |
obj := map[string]any{} |
| 5219 |
err = json.Unmarshal(m.Data, &obj) |
| 5220 |
require_NoError(t, err) |
| 5221 |
// test if shared is honored |
| 5222 |
reqInfo := obj["requestor"].(map[string]any) |
| 5223 |
// fields always set |
| 5224 |
require_True(t, reqInfo["acc"] != nil) |
| 5225 |
require_True(t, reqInfo["rtt"] != nil) |
| 5226 |
|
| 5227 |
// fields only set when shared |
| 5228 |
_, ok1 := reqInfo["lang"] |
| 5229 |
_, ok2 := reqInfo["ver"] |
| 5230 |
_, ok3 := reqInfo["host"] |
| 5231 |
_, ok4 := reqInfo["start"] |
| 5232 |
if !share { |
| 5233 |
ok1 = !ok1 |
| 5234 |
ok2 = !ok2 |
| 5235 |
ok3 = !ok3 |
| 5236 |
ok4 = !ok4 |
| 5237 |
} |
| 5238 |
require_True(t, ok1) |
| 5239 |
require_True(t, ok2) |
| 5240 |
require_True(t, ok3) |
| 5241 |
require_True(t, ok4) |
| 5242 |
|
| 5243 |
} |
| 5244 |
require_True(t, len(resChan) == 0) |
| 5245 |
} |
| 5246 |
test(true) |
| 5247 |
test(false) |
| 5248 |
} |
| 5249 |
|
| 5250 |
func TestJWTAccountImportsWithWildcardSupport(t *testing.T) { |
| 5251 |
test := func(aExpPub, aExpJwt, aExpCreds, aImpPub, aImpJwt, aImpCreds string, jsEnabled bool, exSubExpect, exPub, imReq, imSubExpect string) { |
| 5252 |
t.Helper() |
| 5253 |
|
| 5254 |
var jsSetting string |
| 5255 |
if jsEnabled { |
| 5256 |
jsSetting = "jetstream: {max_mem_store: 10Mb, max_file_store: 10Mb}" |
| 5257 |
} |
| 5258 |
|
| 5259 |
_, aSysPub := createKey(t) |
| 5260 |
aSysClaim := jwt.NewAccountClaims(aSysPub) |
| 5261 |
aSysJwt := encodeClaim(t, aSysClaim, aSysPub) |
| 5262 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 5263 |
port: -1 |
| 5264 |
operator = %s |
| 5265 |
resolver = MEMORY |
| 5266 |
resolver_preload = { |
| 5267 |
%s : "%s" |
| 5268 |
%s : "%s" |
| 5269 |
%s : "%s" |
| 5270 |
} |
| 5271 |
system_account: %s |
| 5272 |
%s |
| 5273 |
`, ojwt, aExpPub, aExpJwt, aImpPub, aImpJwt, aSysPub, aSysJwt, aSysPub, jsSetting))) |
| 5274 |
|
| 5275 |
s, opts := RunServerWithConfig(cf) |
| 5276 |
defer s.Shutdown() |
| 5277 |
|
| 5278 |
ncExp := natsConnect(t, fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port), nats.UserCredentials(aExpCreds)) |
| 5279 |
defer ncExp.Close() |
| 5280 |
|
| 5281 |
ncImp := natsConnect(t, fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port), nats.UserCredentials(aImpCreds)) |
| 5282 |
defer ncImp.Close() |
| 5283 |
|
| 5284 |
// Create subscriber for the service endpoint in foo. |
| 5285 |
_, err := ncExp.Subscribe(exSubExpect, func(m *nats.Msg) { |
| 5286 |
m.Respond([]byte("yes!")) |
| 5287 |
}) |
| 5288 |
require_NoError(t, err) |
| 5289 |
ncExp.Flush() |
| 5290 |
|
| 5291 |
// Now test service import. |
| 5292 |
if resp, err := ncImp.Request(imReq, []byte("yes?"), time.Second); err != nil { |
| 5293 |
t.Fatalf("Expected a response to request %s got: %v", imReq, err) |
| 5294 |
} else if string(resp.Data) != "yes!" { |
| 5295 |
t.Fatalf("Expected a response of %q, got %q", "yes!", resp.Data) |
| 5296 |
} |
| 5297 |
subBar, err := ncImp.SubscribeSync(imSubExpect) |
| 5298 |
require_NoError(t, err) |
| 5299 |
ncImp.Flush() |
| 5300 |
|
| 5301 |
ncExp.Publish(exPub, []byte("event!")) |
| 5302 |
|
| 5303 |
if m, err := subBar.NextMsg(time.Second); err != nil { |
| 5304 |
t.Fatalf("Expected a stream message got %v", err) |
| 5305 |
} else if string(m.Data) != "event!" { |
| 5306 |
t.Fatalf("Expected a response of %q, got %q", "event!", m.Data) |
| 5307 |
} |
| 5308 |
} |
| 5309 |
createExporter := func() (string, string, string) { |
| 5310 |
t.Helper() |
| 5311 |
aExpKp, aExpPub := createKey(t) |
| 5312 |
aExpClaim := jwt.NewAccountClaims(aExpPub) |
| 5313 |
aExpClaim.Name = "Export" |
| 5314 |
aExpClaim.Exports.Add(&jwt.Export{ |
| 5315 |
Subject: "$request.*.$in.*.>", |
| 5316 |
Type: jwt.Service, |
| 5317 |
}, &jwt.Export{ |
| 5318 |
Subject: "$events.*.$in.*.>", |
| 5319 |
Type: jwt.Stream, |
| 5320 |
}) |
| 5321 |
aExpJwt := encodeClaim(t, aExpClaim, aExpPub) |
| 5322 |
aExpCreds := newUser(t, aExpKp) |
| 5323 |
return aExpPub, aExpJwt, aExpCreds |
| 5324 |
} |
| 5325 |
t.Run("To", func(t *testing.T) { |
| 5326 |
aExpPub, aExpJwt, aExpCreds := createExporter() |
| 5327 |
aImpKp, aImpPub := createKey(t) |
| 5328 |
aImpClaim := jwt.NewAccountClaims(aImpPub) |
| 5329 |
aImpClaim.Name = "Import" |
| 5330 |
aImpClaim.Imports.Add(&jwt.Import{ |
| 5331 |
Subject: "my.request.*.*.>", |
| 5332 |
Type: jwt.Service, |
| 5333 |
To: "$request.*.$in.*.>", // services have local and remote switched between Subject and To |
| 5334 |
Account: aExpPub, |
| 5335 |
}, &jwt.Import{ |
| 5336 |
Subject: "$events.*.$in.*.>", |
| 5337 |
Type: jwt.Stream, |
| 5338 |
To: "prefix", |
| 5339 |
Account: aExpPub, |
| 5340 |
}) |
| 5341 |
aImpJwt := encodeClaim(t, aImpClaim, aImpPub) |
| 5342 |
aImpCreds := newUser(t, aImpKp) |
| 5343 |
test(aExpPub, aExpJwt, aExpCreds, aImpPub, aImpJwt, aImpCreds, false, |
| 5344 |
"$request.1.$in.2.bar", "$events.1.$in.2.bar", |
| 5345 |
"my.request.1.2.bar", "prefix.$events.1.$in.2.bar") |
| 5346 |
}) |
| 5347 |
t.Run("LocalSubject-No-Reorder", func(t *testing.T) { |
| 5348 |
aExpPub, aExpJwt, aExpCreds := createExporter() |
| 5349 |
aImpKp, aImpPub := createKey(t) |
| 5350 |
aImpClaim := jwt.NewAccountClaims(aImpPub) |
| 5351 |
aImpClaim.Name = "Import" |
| 5352 |
aImpClaim.Imports.Add(&jwt.Import{ |
| 5353 |
Subject: "$request.*.$in.*.>", |
| 5354 |
Type: jwt.Service, |
| 5355 |
LocalSubject: "my.request.*.*.>", |
| 5356 |
Account: aExpPub, |
| 5357 |
}, &jwt.Import{ |
| 5358 |
Subject: "$events.*.$in.*.>", |
| 5359 |
Type: jwt.Stream, |
| 5360 |
LocalSubject: "my.events.*.*.>", |
| 5361 |
Account: aExpPub, |
| 5362 |
}) |
| 5363 |
aImpJwt := encodeClaim(t, aImpClaim, aImpPub) |
| 5364 |
aImpCreds := newUser(t, aImpKp) |
| 5365 |
test(aExpPub, aExpJwt, aExpCreds, aImpPub, aImpJwt, aImpCreds, false, |
| 5366 |
"$request.1.$in.2.bar", "$events.1.$in.2.bar", |
| 5367 |
"my.request.1.2.bar", "my.events.1.2.bar") |
| 5368 |
}) |
| 5369 |
t.Run("LocalSubject-Reorder", func(t *testing.T) { |
| 5370 |
for _, jsEnabled := range []bool{false, true} { |
| 5371 |
t.Run(fmt.Sprintf("%t", jsEnabled), func(t *testing.T) { |
| 5372 |
aExpPub, aExpJwt, aExpCreds := createExporter() |
| 5373 |
aImpKp, aImpPub := createKey(t) |
| 5374 |
aImpClaim := jwt.NewAccountClaims(aImpPub) |
| 5375 |
aImpClaim.Name = "Import" |
| 5376 |
aImpClaim.Imports.Add(&jwt.Import{ |
| 5377 |
Subject: "$request.*.$in.*.>", |
| 5378 |
Type: jwt.Service, |
| 5379 |
LocalSubject: "my.request.$2.$1.>", |
| 5380 |
Account: aExpPub, |
| 5381 |
}, &jwt.Import{ |
| 5382 |
Subject: "$events.*.$in.*.>", |
| 5383 |
Type: jwt.Stream, |
| 5384 |
LocalSubject: "my.events.$2.$1.>", |
| 5385 |
Account: aExpPub, |
| 5386 |
}) |
| 5387 |
aImpJwt := encodeClaim(t, aImpClaim, aImpPub) |
| 5388 |
aImpCreds := newUser(t, aImpKp) |
| 5389 |
test(aExpPub, aExpJwt, aExpCreds, aImpPub, aImpJwt, aImpCreds, jsEnabled, |
| 5390 |
"$request.2.$in.1.bar", "$events.1.$in.2.bar", |
| 5391 |
"my.request.1.2.bar", "my.events.2.1.bar") |
| 5392 |
}) |
| 5393 |
} |
| 5394 |
}) |
| 5395 |
} |
| 5396 |
|
| 5397 |
func TestJWTAccountTokenImportMisuse(t *testing.T) { |
| 5398 |
sysKp, syspub := createKey(t) |
| 5399 |
sysJwt := encodeClaim(t, jwt.NewAccountClaims(syspub), syspub) |
| 5400 |
sysCreds := newUser(t, sysKp) |
| 5401 |
|
| 5402 |
aExpKp, aExpPub := createKey(t) |
| 5403 |
aExpClaim := jwt.NewAccountClaims(aExpPub) |
| 5404 |
aExpClaim.Name = "Export" |
| 5405 |
aExpClaim.Exports.Add(&jwt.Export{ |
| 5406 |
Subject: "$events.*.$in.*.>", |
| 5407 |
Type: jwt.Stream, |
| 5408 |
TokenReq: true, |
| 5409 |
}, &jwt.Export{ |
| 5410 |
Subject: "foo", |
| 5411 |
Type: jwt.Stream, |
| 5412 |
TokenReq: true, |
| 5413 |
}) |
| 5414 |
aExpJwt := encodeClaim(t, aExpClaim, aExpPub) |
| 5415 |
|
| 5416 |
createImportingAccountClaim := func(aImpKp nkeys.KeyPair, aExpPub string, ac *jwt.ActivationClaims) (string, string) { |
| 5417 |
t.Helper() |
| 5418 |
token, err := ac.Encode(aExpKp) |
| 5419 |
require_NoError(t, err) |
| 5420 |
|
| 5421 |
aImpPub, err := aImpKp.PublicKey() |
| 5422 |
require_NoError(t, err) |
| 5423 |
aImpClaim := jwt.NewAccountClaims(aImpPub) |
| 5424 |
aImpClaim.Name = "Import" |
| 5425 |
aImpClaim.Imports.Add(&jwt.Import{ |
| 5426 |
Subject: "$events.*.$in.*.>", |
| 5427 |
Type: jwt.Stream, |
| 5428 |
Account: aExpPub, |
| 5429 |
Token: token, |
| 5430 |
}) |
| 5431 |
aImpJwt := encodeClaim(t, aImpClaim, aImpPub) |
| 5432 |
aImpCreds := newUser(t, aImpKp) |
| 5433 |
return aImpJwt, aImpCreds |
| 5434 |
} |
| 5435 |
|
| 5436 |
testConnect := func(aExpPub, aExpJwt, aImpPub, aImpJwt, aImpCreds string) { |
| 5437 |
t.Helper() |
| 5438 |
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 5439 |
if r.URL.Path == "/A/" { |
| 5440 |
// Server startup |
| 5441 |
w.Write(nil) |
| 5442 |
} else if r.URL.Path == "/A/"+aExpPub { |
| 5443 |
w.Write([]byte(aExpJwt)) |
| 5444 |
} else if r.URL.Path == "/A/"+aImpPub { |
| 5445 |
w.Write([]byte(aImpJwt)) |
| 5446 |
} else { |
| 5447 |
t.Fatal("not expected") |
| 5448 |
} |
| 5449 |
})) |
| 5450 |
defer ts.Close() |
| 5451 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 5452 |
listen: 127.0.0.1:-1 |
| 5453 |
operator: %s |
| 5454 |
resolver: URL("%s/A/") |
| 5455 |
`, ojwt, ts.URL))) |
| 5456 |
|
| 5457 |
s, opts := RunServerWithConfig(cf) |
| 5458 |
defer s.Shutdown() |
| 5459 |
|
| 5460 |
ncImp, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port), nats.UserCredentials(aImpCreds)) |
| 5461 |
require_Error(t, err) // misuse needs to result in an error |
| 5462 |
defer ncImp.Close() |
| 5463 |
} |
| 5464 |
|
| 5465 |
testNatsResolver := func(aImpJwt string) { |
| 5466 |
t.Helper() |
| 5467 |
dirSrv := t.TempDir() |
| 5468 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 5469 |
listen: 127.0.0.1:-1 |
| 5470 |
operator: %s |
| 5471 |
system_account: %s |
| 5472 |
resolver: { |
| 5473 |
type: full |
| 5474 |
dir: '%s' |
| 5475 |
} |
| 5476 |
`, ojwt, syspub, dirSrv))) |
| 5477 |
|
| 5478 |
s, _ := RunServerWithConfig(cf) |
| 5479 |
defer s.Shutdown() |
| 5480 |
|
| 5481 |
require_True(t, updateJwt(t, s.ClientURL(), sysCreds, sysJwt, 1) == 1) |
| 5482 |
require_True(t, updateJwt(t, s.ClientURL(), sysCreds, aExpJwt, 1) == 1) |
| 5483 |
require_True(t, updateJwt(t, s.ClientURL(), sysCreds, aImpJwt, 1) == 0) // assure this did not succeed |
| 5484 |
} |
| 5485 |
|
| 5486 |
t.Run("wrong-account", func(t *testing.T) { |
| 5487 |
aImpKp, aImpPub := createKey(t) |
| 5488 |
ac := &jwt.ActivationClaims{} |
| 5489 |
_, ac.Subject = createKey(t) // on purpose issue this token for another account |
| 5490 |
ac.ImportSubject = "$events.*.$in.*.>" |
| 5491 |
ac.ImportType = jwt.Stream |
| 5492 |
|
| 5493 |
aImpJwt, aImpCreds := createImportingAccountClaim(aImpKp, aExpPub, ac) |
| 5494 |
testConnect(aExpPub, aExpJwt, aImpPub, aImpJwt, aImpCreds) |
| 5495 |
testNatsResolver(aImpJwt) |
| 5496 |
}) |
| 5497 |
|
| 5498 |
t.Run("different-subject", func(t *testing.T) { |
| 5499 |
aImpKp, aImpPub := createKey(t) |
| 5500 |
ac := &jwt.ActivationClaims{} |
| 5501 |
ac.Subject = aImpPub |
| 5502 |
ac.ImportSubject = "foo" // on purpose use a subject from another export |
| 5503 |
ac.ImportType = jwt.Stream |
| 5504 |
|
| 5505 |
aImpJwt, aImpCreds := createImportingAccountClaim(aImpKp, aExpPub, ac) |
| 5506 |
testConnect(aExpPub, aExpJwt, aImpPub, aImpJwt, aImpCreds) |
| 5507 |
testNatsResolver(aImpJwt) |
| 5508 |
}) |
| 5509 |
|
| 5510 |
t.Run("non-existing-subject", func(t *testing.T) { |
| 5511 |
aImpKp, aImpPub := createKey(t) |
| 5512 |
ac := &jwt.ActivationClaims{} |
| 5513 |
ac.Subject = aImpPub |
| 5514 |
ac.ImportSubject = "does-not-exist-or-from-different-export" // on purpose use a non exported subject |
| 5515 |
ac.ImportType = jwt.Stream |
| 5516 |
|
| 5517 |
aImpJwt, aImpCreds := createImportingAccountClaim(aImpKp, aExpPub, ac) |
| 5518 |
testConnect(aExpPub, aExpJwt, aImpPub, aImpJwt, aImpCreds) |
| 5519 |
testNatsResolver(aImpJwt) |
| 5520 |
}) |
| 5521 |
} |
| 5522 |
|
| 5523 |
func TestJWTResponseThreshold(t *testing.T) { |
| 5524 |
respThresh := 20 * time.Millisecond |
| 5525 |
aExpKp, aExpPub := createKey(t) |
| 5526 |
aExpClaim := jwt.NewAccountClaims(aExpPub) |
| 5527 |
aExpClaim.Name = "Export" |
| 5528 |
aExpClaim.Exports.Add(&jwt.Export{ |
| 5529 |
Subject: "srvc", |
| 5530 |
Type: jwt.Service, |
| 5531 |
ResponseThreshold: respThresh, |
| 5532 |
}) |
| 5533 |
aExpJwt := encodeClaim(t, aExpClaim, aExpPub) |
| 5534 |
aExpCreds := newUser(t, aExpKp) |
| 5535 |
|
| 5536 |
aImpKp, aImpPub := createKey(t) |
| 5537 |
aImpClaim := jwt.NewAccountClaims(aImpPub) |
| 5538 |
aImpClaim.Name = "Import" |
| 5539 |
aImpClaim.Imports.Add(&jwt.Import{ |
| 5540 |
Subject: "srvc", |
| 5541 |
Type: jwt.Service, |
| 5542 |
Account: aExpPub, |
| 5543 |
}) |
| 5544 |
aImpJwt := encodeClaim(t, aImpClaim, aImpPub) |
| 5545 |
aImpCreds := newUser(t, aImpKp) |
| 5546 |
|
| 5547 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 5548 |
port: -1 |
| 5549 |
operator = %s |
| 5550 |
resolver = MEMORY |
| 5551 |
resolver_preload = { |
| 5552 |
%s : "%s" |
| 5553 |
%s : "%s" |
| 5554 |
} |
| 5555 |
`, ojwt, aExpPub, aExpJwt, aImpPub, aImpJwt))) |
| 5556 |
|
| 5557 |
s, opts := RunServerWithConfig(cf) |
| 5558 |
defer s.Shutdown() |
| 5559 |
|
| 5560 |
ncExp := natsConnect(t, fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port), nats.UserCredentials(aExpCreds)) |
| 5561 |
defer ncExp.Close() |
| 5562 |
|
| 5563 |
ncImp := natsConnect(t, fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port), nats.UserCredentials(aImpCreds)) |
| 5564 |
defer ncImp.Close() |
| 5565 |
|
| 5566 |
delayChan := make(chan time.Duration, 1) |
| 5567 |
|
| 5568 |
// Create subscriber for the service endpoint in foo. |
| 5569 |
_, err := ncExp.Subscribe("srvc", func(m *nats.Msg) { |
| 5570 |
time.Sleep(<-delayChan) |
| 5571 |
m.Respond([]byte("yes!")) |
| 5572 |
}) |
| 5573 |
require_NoError(t, err) |
| 5574 |
ncExp.Flush() |
| 5575 |
|
| 5576 |
t.Run("No-Timeout", func(t *testing.T) { |
| 5577 |
delayChan <- respThresh / 2 |
| 5578 |
if resp, err := ncImp.Request("srvc", []byte("yes?"), 4*respThresh); err != nil { |
| 5579 |
t.Fatalf("Expected a response to request srvc got: %v", err) |
| 5580 |
} else if string(resp.Data) != "yes!" { |
| 5581 |
t.Fatalf("Expected a response of %q, got %q", "yes!", resp.Data) |
| 5582 |
} |
| 5583 |
}) |
| 5584 |
t.Run("Timeout", func(t *testing.T) { |
| 5585 |
delayChan <- 2 * respThresh |
| 5586 |
if _, err := ncImp.Request("srvc", []byte("yes?"), 4*respThresh); err == nil || err != nats.ErrTimeout { |
| 5587 |
t.Fatalf("Expected a timeout") |
| 5588 |
} |
| 5589 |
}) |
| 5590 |
} |
| 5591 |
|
| 5592 |
func TestJWTJetStreamTiers(t *testing.T) { |
| 5593 |
sysKp, syspub := createKey(t) |
| 5594 |
sysJwt := encodeClaim(t, jwt.NewAccountClaims(syspub), syspub) |
| 5595 |
sysCreds := newUser(t, sysKp) |
| 5596 |
|
| 5597 |
accKp, accPub := createKey(t) |
| 5598 |
accClaim := jwt.NewAccountClaims(accPub) |
| 5599 |
accClaim.Name = "acc" |
| 5600 |
accClaim.Limits.JetStreamTieredLimits["R1"] = jwt.JetStreamLimits{ |
| 5601 |
DiskStorage: 1100, MemoryStorage: 0, Consumer: 2, Streams: 2} |
| 5602 |
accJwt1 := encodeClaim(t, accClaim, accPub) |
| 5603 |
accCreds := newUser(t, accKp) |
| 5604 |
|
| 5605 |
start := time.Now() |
| 5606 |
|
| 5607 |
storeDir := t.TempDir() |
| 5608 |
|
| 5609 |
dirSrv := t.TempDir() |
| 5610 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 5611 |
listen: 127.0.0.1:-1 |
| 5612 |
server_name: s1 |
| 5613 |
jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'} |
| 5614 |
leaf { |
| 5615 |
listen: 127.0.0.1:-1 |
| 5616 |
} |
| 5617 |
operator: %s |
| 5618 |
system_account: %s |
| 5619 |
resolver: { |
| 5620 |
type: full |
| 5621 |
dir: '%s' |
| 5622 |
} |
| 5623 |
`, storeDir, ojwt, syspub, dirSrv))) |
| 5624 |
|
| 5625 |
s, _ := RunServerWithConfig(cf) |
| 5626 |
defer s.Shutdown() |
| 5627 |
|
| 5628 |
updateJwt(t, s.ClientURL(), sysCreds, sysJwt, 1) |
| 5629 |
updateJwt(t, s.ClientURL(), sysCreds, accJwt1, 1) |
| 5630 |
|
| 5631 |
nc := natsConnect(t, s.ClientURL(), nats.UserCredentials(accCreds)) |
| 5632 |
defer nc.Close() |
| 5633 |
|
| 5634 |
js, err := nc.JetStream() |
| 5635 |
require_NoError(t, err) |
| 5636 |
|
| 5637 |
// Test tiers up to stream limits |
| 5638 |
_, err = js.AddStream(&nats.StreamConfig{Name: "testR1-1", Replicas: 1, Subjects: []string{"testR1-1"}}) |
| 5639 |
require_NoError(t, err) |
| 5640 |
_, err = js.AddStream(&nats.StreamConfig{Name: "testR1-2", Replicas: 1, Subjects: []string{"testR1-2"}}) |
| 5641 |
require_NoError(t, err) |
| 5642 |
|
| 5643 |
// Test exceeding tiered stream limit |
| 5644 |
_, err = js.AddStream(&nats.StreamConfig{Name: "testR1-3", Replicas: 1, Subjects: []string{"testR1-3"}}) |
| 5645 |
require_Error(t, err) |
| 5646 |
require_Equal(t, err.Error(), "nats: maximum number of streams reached") |
| 5647 |
|
| 5648 |
// Test tiers up to consumer limits |
| 5649 |
_, err = js.AddConsumer("testR1-1", &nats.ConsumerConfig{Durable: "dur1", AckPolicy: nats.AckExplicitPolicy}) |
| 5650 |
require_NoError(t, err) |
| 5651 |
_, err = js.AddConsumer("testR1-1", &nats.ConsumerConfig{Durable: "dur3", AckPolicy: nats.AckExplicitPolicy}) |
| 5652 |
require_NoError(t, err) |
| 5653 |
|
| 5654 |
// test exceeding tiered consumer limits |
| 5655 |
_, err = js.AddConsumer("testR1-1", &nats.ConsumerConfig{Durable: "dur4", AckPolicy: nats.AckExplicitPolicy}) |
| 5656 |
require_Error(t, err) |
| 5657 |
require_Equal(t, err.Error(), "nats: maximum consumers limit reached") |
| 5658 |
_, err = js.AddConsumer("testR1-1", &nats.ConsumerConfig{Durable: "dur5", AckPolicy: nats.AckExplicitPolicy}) |
| 5659 |
require_Error(t, err) |
| 5660 |
require_Equal(t, err.Error(), "nats: maximum consumers limit reached") |
| 5661 |
|
| 5662 |
// test tiered storage limit |
| 5663 |
msg := [512]byte{} |
| 5664 |
_, err = js.Publish("testR1-1", msg[:]) |
| 5665 |
require_NoError(t, err) |
| 5666 |
_, err = js.Publish("testR1-2", msg[:]) |
| 5667 |
require_NoError(t, err) |
| 5668 |
|
| 5669 |
ainfo, err := js.AccountInfo() |
| 5670 |
require_NoError(t, err) |
| 5671 |
require_Equal(t, ainfo.Tiers["R1"].Store, 1100) |
| 5672 |
|
| 5673 |
// test exceeding tiered storage limit |
| 5674 |
_, err = js.Publish("testR1-1", []byte("1")) |
| 5675 |
require_Error(t, err) |
| 5676 |
require_Equal(t, err.Error(), "nats: resource limits exceeded for account") |
| 5677 |
|
| 5678 |
// Check that storage has not increased after the rejected publish. |
| 5679 |
ainfo, err = js.AccountInfo() |
| 5680 |
require_NoError(t, err) |
| 5681 |
require_Equal(t, ainfo.Tiers["R1"].Store, 1100) |
| 5682 |
|
| 5683 |
time.Sleep(time.Second - time.Since(start)) // make sure the time stamp changes |
| 5684 |
accClaim.Limits.JetStreamTieredLimits["R1"] = jwt.JetStreamLimits{ |
| 5685 |
DiskStorage: 1650, MemoryStorage: 0, Consumer: 1, Streams: 3} |
| 5686 |
accJwt2 := encodeClaim(t, accClaim, accPub) |
| 5687 |
updateJwt(t, s.ClientURL(), sysCreds, accJwt2, 1) |
| 5688 |
|
| 5689 |
// test same sequence as before, add stream, fail add stream, add consumer, fail add consumer, publish, fail publish |
| 5690 |
_, err = js.AddStream(&nats.StreamConfig{Name: "testR1-3", Replicas: 1, Subjects: []string{"testR1-3"}}) |
| 5691 |
require_NoError(t, err) |
| 5692 |
_, err = js.AddStream(&nats.StreamConfig{Name: "testR1-4", Replicas: 1, Subjects: []string{"testR1-4"}}) |
| 5693 |
require_Error(t, err) |
| 5694 |
require_Equal(t, err.Error(), "nats: maximum number of streams reached") |
| 5695 |
_, err = js.AddConsumer("testR1-3", &nats.ConsumerConfig{Durable: "dur6", AckPolicy: nats.AckExplicitPolicy}) |
| 5696 |
require_NoError(t, err) |
| 5697 |
_, err = js.AddConsumer("testR1-3", &nats.ConsumerConfig{Durable: "dur7", AckPolicy: nats.AckExplicitPolicy}) |
| 5698 |
require_Error(t, err) |
| 5699 |
require_Equal(t, err.Error(), "nats: maximum consumers limit reached") |
| 5700 |
|
| 5701 |
// At this point it will be exactly at the DiskStorage limit so it should not fail. |
| 5702 |
_, err = js.Publish("testR1-3", msg[:]) |
| 5703 |
require_NoError(t, err) |
| 5704 |
ainfo, err = js.AccountInfo() |
| 5705 |
require_NoError(t, err) |
| 5706 |
require_Equal(t, ainfo.Tiers["R1"].Store, 1650) |
| 5707 |
|
| 5708 |
_, err = js.Publish("testR1-3", []byte("1")) |
| 5709 |
require_Error(t, err) |
| 5710 |
require_Equal(t, err.Error(), "nats: resource limits exceeded for account") |
| 5711 |
|
| 5712 |
// Should remain at the same usage. |
| 5713 |
ainfo, err = js.AccountInfo() |
| 5714 |
require_NoError(t, err) |
| 5715 |
require_Equal(t, ainfo.Tiers["R1"].Store, 1650) |
| 5716 |
} |
| 5717 |
|
| 5718 |
func TestJWTJetStreamMaxAckPending(t *testing.T) { |
| 5719 |
sysKp, syspub := createKey(t) |
| 5720 |
sysJwt := encodeClaim(t, jwt.NewAccountClaims(syspub), syspub) |
| 5721 |
sysCreds := newUser(t, sysKp) |
| 5722 |
|
| 5723 |
accKp, accPub := createKey(t) |
| 5724 |
accClaim := jwt.NewAccountClaims(accPub) |
| 5725 |
accClaim.Name = "acc" |
| 5726 |
accClaim.Limits.JetStreamTieredLimits["R1"] = jwt.JetStreamLimits{ |
| 5727 |
DiskStorage: jwt.NoLimit, MemoryStorage: jwt.NoLimit, |
| 5728 |
Consumer: jwt.NoLimit, Streams: jwt.NoLimit, MaxAckPending: int64(1000), |
| 5729 |
} |
| 5730 |
accJwt1 := encodeClaim(t, accClaim, accPub) |
| 5731 |
accCreds := newUser(t, accKp) |
| 5732 |
|
| 5733 |
start := time.Now() |
| 5734 |
|
| 5735 |
storeDir := t.TempDir() |
| 5736 |
|
| 5737 |
dirSrv := t.TempDir() |
| 5738 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 5739 |
listen: 127.0.0.1:-1 |
| 5740 |
server_name: s1 |
| 5741 |
jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'} |
| 5742 |
leaf { |
| 5743 |
listen: 127.0.0.1:-1 |
| 5744 |
} |
| 5745 |
operator: %s |
| 5746 |
system_account: %s |
| 5747 |
resolver: { |
| 5748 |
type: full |
| 5749 |
dir: '%s' |
| 5750 |
} |
| 5751 |
`, storeDir, ojwt, syspub, dirSrv))) |
| 5752 |
|
| 5753 |
s, _ := RunServerWithConfig(cf) |
| 5754 |
defer s.Shutdown() |
| 5755 |
|
| 5756 |
updateJwt(t, s.ClientURL(), sysCreds, sysJwt, 1) |
| 5757 |
updateJwt(t, s.ClientURL(), sysCreds, accJwt1, 1) |
| 5758 |
|
| 5759 |
nc := natsConnect(t, s.ClientURL(), nats.UserCredentials(accCreds)) |
| 5760 |
defer nc.Close() |
| 5761 |
|
| 5762 |
js, err := nc.JetStream() |
| 5763 |
require_NoError(t, err) |
| 5764 |
|
| 5765 |
_, err = js.AddStream(&nats.StreamConfig{Name: "foo", Replicas: 1}) |
| 5766 |
require_NoError(t, err) |
| 5767 |
|
| 5768 |
_, err = js.AddConsumer("foo", &nats.ConsumerConfig{ |
| 5769 |
Durable: "dur1", AckPolicy: nats.AckAllPolicy, MaxAckPending: 2000}) |
| 5770 |
require_Error(t, err) |
| 5771 |
require_Equal(t, err.Error(), "nats: consumer max ack pending exceeds system limit of 1000") |
| 5772 |
|
| 5773 |
ci, err := js.AddConsumer("foo", &nats.ConsumerConfig{ |
| 5774 |
Durable: "dur2", AckPolicy: nats.AckAllPolicy, MaxAckPending: 500}) |
| 5775 |
require_NoError(t, err) |
| 5776 |
require_True(t, ci.Config.MaxAckPending == 500) |
| 5777 |
|
| 5778 |
_, err = js.UpdateConsumer("foo", &nats.ConsumerConfig{ |
| 5779 |
Durable: "dur2", AckPolicy: nats.AckAllPolicy, MaxAckPending: 2000}) |
| 5780 |
require_Error(t, err) |
| 5781 |
require_Equal(t, err.Error(), "nats: consumer max ack pending exceeds system limit of 1000") |
| 5782 |
|
| 5783 |
time.Sleep(time.Second - time.Since(start)) // make sure the time stamp changes |
| 5784 |
accClaim.Limits.JetStreamTieredLimits["R1"] = jwt.JetStreamLimits{ |
| 5785 |
DiskStorage: jwt.NoLimit, MemoryStorage: jwt.NoLimit, Consumer: jwt.NoLimit, |
| 5786 |
Streams: jwt.NoLimit, MaxAckPending: int64(2000)} |
| 5787 |
accJwt2 := encodeClaim(t, accClaim, accPub) |
| 5788 |
updateJwt(t, s.ClientURL(), sysCreds, accJwt2, 1) |
| 5789 |
|
| 5790 |
ci, err = js.UpdateConsumer("foo", &nats.ConsumerConfig{ |
| 5791 |
Durable: "dur2", AckPolicy: nats.AckAllPolicy, MaxAckPending: 2000}) |
| 5792 |
require_NoError(t, err) |
| 5793 |
require_True(t, ci.Config.MaxAckPending == 2000) |
| 5794 |
} |
| 5795 |
|
| 5796 |
func TestJWTJetStreamMaxStore(t *testing.T) { |
| 5797 |
sysKp, syspub := createKey(t) |
| 5798 |
sysJwt := encodeClaim(t, jwt.NewAccountClaims(syspub), syspub) |
| 5799 |
sysCreds := newUser(t, sysKp) |
| 5800 |
|
| 5801 |
accKp, accPub := createKey(t) |
| 5802 |
accClaim := jwt.NewAccountClaims(accPub) |
| 5803 |
accClaim.Name = "acc" |
| 5804 |
accClaim.Limits.JetStreamTieredLimits["R1"] = jwt.JetStreamLimits{ |
| 5805 |
DiskStorage: 1024, MemoryStorage: jwt.NoLimit, |
| 5806 |
Consumer: jwt.NoLimit, Streams: jwt.NoLimit, |
| 5807 |
DiskMaxStreamBytes: 1024, MaxBytesRequired: false, |
| 5808 |
} |
| 5809 |
accJwt1 := encodeClaim(t, accClaim, accPub) |
| 5810 |
accCreds := newUser(t, accKp) |
| 5811 |
|
| 5812 |
start := time.Now() |
| 5813 |
|
| 5814 |
storeDir := t.TempDir() |
| 5815 |
|
| 5816 |
dirSrv := t.TempDir() |
| 5817 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 5818 |
listen: 127.0.0.1:-1 |
| 5819 |
server_name: s1 |
| 5820 |
jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'} |
| 5821 |
leaf { |
| 5822 |
listen: 127.0.0.1:-1 |
| 5823 |
} |
| 5824 |
operator: %s |
| 5825 |
system_account: %s |
| 5826 |
resolver: { |
| 5827 |
type: full |
| 5828 |
dir: '%s' |
| 5829 |
} |
| 5830 |
`, storeDir, ojwt, syspub, dirSrv))) |
| 5831 |
|
| 5832 |
s, _ := RunServerWithConfig(cf) |
| 5833 |
defer s.Shutdown() |
| 5834 |
|
| 5835 |
updateJwt(t, s.ClientURL(), sysCreds, sysJwt, 1) |
| 5836 |
updateJwt(t, s.ClientURL(), sysCreds, accJwt1, 1) |
| 5837 |
|
| 5838 |
nc := natsConnect(t, s.ClientURL(), nats.UserCredentials(accCreds)) |
| 5839 |
defer nc.Close() |
| 5840 |
|
| 5841 |
js, err := nc.JetStream() |
| 5842 |
require_NoError(t, err) |
| 5843 |
|
| 5844 |
_, err = js.AddStream(&nats.StreamConfig{Name: "foo", Replicas: 1, MaxBytes: 2048}) |
| 5845 |
require_Error(t, err, NewJSStorageResourcesExceededError()) |
| 5846 |
_, err = js.AddStream(&nats.StreamConfig{Name: "foo", Replicas: 1, MaxBytes: 1024}) |
| 5847 |
require_NoError(t, err) |
| 5848 |
|
| 5849 |
msg := [900]byte{} |
| 5850 |
_, err = js.Publish("foo", msg[:]) |
| 5851 |
require_NoError(t, err) |
| 5852 |
_, err = js.Publish("foo", msg[:]) // exceeds storage limit |
| 5853 |
require_Error(t, err) |
| 5854 |
require_Equal(t, err.Error(), "nats: resource limits exceeded for account") |
| 5855 |
|
| 5856 |
time.Sleep(time.Second - time.Since(start)) // make sure the time stamp changes |
| 5857 |
accClaim.Limits.JetStreamTieredLimits["R1"] = jwt.JetStreamLimits{ |
| 5858 |
DiskStorage: 3072, MemoryStorage: jwt.NoLimit, Consumer: jwt.NoLimit, Streams: jwt.NoLimit, |
| 5859 |
DiskMaxStreamBytes: 2048, MaxBytesRequired: true} |
| 5860 |
accJwt2 := encodeClaim(t, accClaim, accPub) |
| 5861 |
updateJwt(t, s.ClientURL(), sysCreds, accJwt2, 1) |
| 5862 |
|
| 5863 |
_, err = js.AddStream(&nats.StreamConfig{Name: "bar", Replicas: 1, MaxBytes: 3000}) |
| 5864 |
require_Error(t, err, NewJSStorageResourcesExceededError()) |
| 5865 |
_, err = js.AddStream(&nats.StreamConfig{Name: "bar", Replicas: 1, MaxBytes: 2048}) |
| 5866 |
require_NoError(t, err) |
| 5867 |
|
| 5868 |
ainfo, err := js.AccountInfo() |
| 5869 |
require_NoError(t, err) |
| 5870 |
require_Equal(t, ainfo.Tiers["R1"].Store, 933) |
| 5871 |
|
| 5872 |
// This should be exactly at the limit of the account. |
| 5873 |
_, err = js.Publish("foo", []byte(strings.Repeat("A", 991))) |
| 5874 |
require_NoError(t, err) |
| 5875 |
ainfo, err = js.AccountInfo() |
| 5876 |
require_NoError(t, err) |
| 5877 |
require_Equal(t, ainfo.Tiers["R1"].Store, 1024) |
| 5878 |
_, err = js.Publish("bar", []byte(strings.Repeat("A", 2015))) |
| 5879 |
require_NoError(t, err) |
| 5880 |
ainfo, err = js.AccountInfo() |
| 5881 |
require_NoError(t, err) |
| 5882 |
require_Equal(t, ainfo.Tiers["R1"].Store, 3072) |
| 5883 |
|
| 5884 |
// Exceed storage limit. |
| 5885 |
_, err = js.Publish("bar", []byte("1")) |
| 5886 |
require_Error(t, err) |
| 5887 |
require_Equal(t, err.Error(), "nats: resource limits exceeded for account") |
| 5888 |
|
| 5889 |
// Confirm no changes after rejected publish. |
| 5890 |
ainfo, err = js.AccountInfo() |
| 5891 |
require_NoError(t, err) |
| 5892 |
require_Equal(t, ainfo.Tiers["R1"].Store, 3072) |
| 5893 |
|
| 5894 |
// test disabling max bytes required |
| 5895 |
_, err = js.UpdateStream(&nats.StreamConfig{Name: "bar", Replicas: 1}) |
| 5896 |
require_Error(t, err) |
| 5897 |
require_Equal(t, err.Error(), "nats: account requires a stream config to have max bytes set") |
| 5898 |
} |
| 5899 |
|
| 5900 |
func TestJWTQueuePermissions(t *testing.T) { |
| 5901 |
aExpKp, aExpPub := createKey(t) |
| 5902 |
aExpClaim := jwt.NewAccountClaims(aExpPub) |
| 5903 |
aExpJwt := encodeClaim(t, aExpClaim, aExpPub) |
| 5904 |
newUser := func(t *testing.T, permType string) string { |
| 5905 |
ukp, _ := nkeys.CreateUser() |
| 5906 |
seed, _ := ukp.Seed() |
| 5907 |
upub, _ := ukp.PublicKey() |
| 5908 |
uclaim := newJWTTestUserClaims() |
| 5909 |
uclaim.Subject = upub |
| 5910 |
switch permType { |
| 5911 |
case "allow": |
| 5912 |
uclaim.Permissions.Sub.Allow.Add("foo.> *.dev") |
| 5913 |
case "deny": |
| 5914 |
uclaim.Permissions.Sub.Deny.Add("foo.> *.dev") |
| 5915 |
} |
| 5916 |
ujwt, err := uclaim.Encode(aExpKp) |
| 5917 |
require_NoError(t, err) |
| 5918 |
return genCredsFile(t, ujwt, seed) |
| 5919 |
} |
| 5920 |
confFileName := createConfFile(t, []byte(fmt.Sprintf(` |
| 5921 |
port: -1 |
| 5922 |
operator = %s |
| 5923 |
resolver = MEMORY |
| 5924 |
resolver_preload = { |
| 5925 |
%s : %s |
| 5926 |
}`, ojwt, aExpPub, aExpJwt))) |
| 5927 |
opts, err := ProcessConfigFile(confFileName) |
| 5928 |
if err != nil { |
| 5929 |
t.Fatalf("Received unexpected error %s", err) |
| 5930 |
} |
| 5931 |
opts.NoLog, opts.NoSigs = true, true |
| 5932 |
errChan := make(chan error, 1) |
| 5933 |
defer close(errChan) |
| 5934 |
s := RunServer(opts) |
| 5935 |
defer s.Shutdown() |
| 5936 |
|
| 5937 |
for _, test := range []struct { |
| 5938 |
permType string |
| 5939 |
queue string |
| 5940 |
errExpected bool |
| 5941 |
}{ |
| 5942 |
{"allow", "queue.dev", false}, |
| 5943 |
{"allow", "", true}, |
| 5944 |
{"allow", "bad", true}, |
| 5945 |
{"deny", "", false}, |
| 5946 |
{"deny", "queue.dev", true}, |
| 5947 |
} { |
| 5948 |
t.Run(test.permType+test.queue, func(t *testing.T) { |
| 5949 |
usrCreds := newUser(t, test.permType) |
| 5950 |
nc, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", opts.Port), |
| 5951 |
nats.ErrorHandler(func(conn *nats.Conn, s *nats.Subscription, err error) { |
| 5952 |
errChan <- err |
| 5953 |
}), |
| 5954 |
nats.UserCredentials(usrCreds)) |
| 5955 |
if err != nil { |
| 5956 |
t.Fatalf("No error expected: %v", err) |
| 5957 |
} |
| 5958 |
defer nc.Close() |
| 5959 |
if test.queue == "" { |
| 5960 |
if _, err := nc.Subscribe("foo.bar", func(msg *nats.Msg) {}); err != nil { |
| 5961 |
t.Fatalf("no error expected: %v", err) |
| 5962 |
} |
| 5963 |
} else { |
| 5964 |
if _, err := nc.QueueSubscribe("foo.bar", test.queue, func(msg *nats.Msg) {}); err != nil { |
| 5965 |
t.Fatalf("no error expected: %v", err) |
| 5966 |
} |
| 5967 |
} |
| 5968 |
nc.Flush() |
| 5969 |
select { |
| 5970 |
case err := <-errChan: |
| 5971 |
if !test.errExpected { |
| 5972 |
t.Fatalf("Expected no error, got %v", err) |
| 5973 |
} |
| 5974 |
if !strings.Contains(err.Error(), `Permissions Violation for Subscription to "foo.bar"`) { |
| 5975 |
t.Fatalf("error %v", err) |
| 5976 |
} |
| 5977 |
case <-time.After(150 * time.Millisecond): |
| 5978 |
if test.errExpected { |
| 5979 |
t.Fatal("Expected an error") |
| 5980 |
} |
| 5981 |
} |
| 5982 |
}) |
| 5983 |
|
| 5984 |
} |
| 5985 |
} |
| 5986 |
|
| 5987 |
func TestJWTScopedSigningKeys(t *testing.T) { |
| 5988 |
sysKp, syspub := createKey(t) |
| 5989 |
sysJwt := encodeClaim(t, jwt.NewAccountClaims(syspub), syspub) |
| 5990 |
sysCreds := newUser(t, sysKp) |
| 5991 |
|
| 5992 |
_, aExpPub := createKey(t) |
| 5993 |
accClaim := jwt.NewAccountClaims(aExpPub) |
| 5994 |
accClaim.Name = "acc" |
| 5995 |
|
| 5996 |
aSignNonScopedKp, aSignNonScopedPub := createKey(t) |
| 5997 |
accClaim.SigningKeys.Add(aSignNonScopedPub) |
| 5998 |
|
| 5999 |
aSignScopedKp, aSignScopedPub := createKey(t) |
| 6000 |
signer := jwt.NewUserScope() |
| 6001 |
signer.Key = aSignScopedPub |
| 6002 |
signer.Template.Pub.Deny.Add("denied") |
| 6003 |
signer.Template.Payload = 5 |
| 6004 |
signer.Template.AllowedConnectionTypes.Add(jwt.ConnectionTypeStandard) |
| 6005 |
accClaim.SigningKeys.AddScopedSigner(signer) |
| 6006 |
accJwt := encodeClaim(t, accClaim, aExpPub) |
| 6007 |
|
| 6008 |
aNonScopedCreds := newUserEx(t, aSignNonScopedKp, false, aExpPub) |
| 6009 |
aBadScopedCreds := newUserEx(t, aSignScopedKp, false, aExpPub) |
| 6010 |
aScopedCreds := newUserEx(t, aSignScopedKp, true, aExpPub) |
| 6011 |
|
| 6012 |
dirSrv := t.TempDir() |
| 6013 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 6014 |
listen: 127.0.0.1:-1 |
| 6015 |
operator: %s |
| 6016 |
system_account: %s |
| 6017 |
resolver: { |
| 6018 |
type: full |
| 6019 |
dir: '%s' |
| 6020 |
} |
| 6021 |
websocket { |
| 6022 |
listen: 127.0.0.1:-1 |
| 6023 |
no_tls: true |
| 6024 |
} |
| 6025 |
`, ojwt, syspub, dirSrv))) |
| 6026 |
s, opts := RunServerWithConfig(cf) |
| 6027 |
defer s.Shutdown() |
| 6028 |
|
| 6029 |
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port) |
| 6030 |
wsUrl := fmt.Sprintf("ws://%s:%d", opts.Websocket.Host, opts.Websocket.Port) |
| 6031 |
errChan := make(chan error, 1) |
| 6032 |
defer close(errChan) |
| 6033 |
awaitError := func(expected bool) { |
| 6034 |
t.Helper() |
| 6035 |
select { |
| 6036 |
case err := <-errChan: |
| 6037 |
if !expected { |
| 6038 |
t.Fatalf("Expected no error, got %v", err) |
| 6039 |
} |
| 6040 |
case <-time.After(150 * time.Millisecond): |
| 6041 |
if expected { |
| 6042 |
t.Fatal("Expected an error") |
| 6043 |
} |
| 6044 |
} |
| 6045 |
} |
| 6046 |
errHdlr := nats.ErrorHandler(func(conn *nats.Conn, s *nats.Subscription, err error) { |
| 6047 |
errChan <- err |
| 6048 |
}) |
| 6049 |
if updateJwt(t, url, sysCreds, sysJwt, 1) != 1 { |
| 6050 |
t.Error("Expected update to pass") |
| 6051 |
} else if updateJwt(t, url, sysCreds, accJwt, 1) != 1 { |
| 6052 |
t.Error("Expected update to pass") |
| 6053 |
} |
| 6054 |
t.Run("bad-scoped-signing-key", func(t *testing.T) { |
| 6055 |
_, err := nats.Connect(url, nats.UserCredentials(aBadScopedCreds)) |
| 6056 |
require_Error(t, err) |
| 6057 |
}) |
| 6058 |
t.Run("regular-signing-key", func(t *testing.T) { |
| 6059 |
nc := natsConnect(t, url, nats.UserCredentials(aNonScopedCreds), errHdlr) |
| 6060 |
defer nc.Close() |
| 6061 |
nc.Flush() |
| 6062 |
err := nc.Publish("denied", nil) |
| 6063 |
require_NoError(t, err) |
| 6064 |
nc.Flush() |
| 6065 |
awaitError(false) |
| 6066 |
}) |
| 6067 |
t.Run("scoped-signing-key-client-side", func(t *testing.T) { |
| 6068 |
nc := natsConnect(t, url, nats.UserCredentials(aScopedCreds), errHdlr) |
| 6069 |
defer nc.Close() |
| 6070 |
nc.Flush() |
| 6071 |
err := nc.Publish("too-long", []byte("way.too.long.for.payload.limit")) |
| 6072 |
require_Error(t, err) |
| 6073 |
require_True(t, strings.Contains(err.Error(), ErrMaxPayload.Error())) |
| 6074 |
}) |
| 6075 |
t.Run("scoped-signing-key-server-side", func(t *testing.T) { |
| 6076 |
nc := natsConnect(t, url, nats.UserCredentials(aScopedCreds), errHdlr) |
| 6077 |
defer nc.Close() |
| 6078 |
nc.Flush() |
| 6079 |
err := nc.Publish("denied", nil) |
| 6080 |
require_NoError(t, err) |
| 6081 |
nc.Flush() |
| 6082 |
awaitError(true) |
| 6083 |
}) |
| 6084 |
t.Run("scoped-signing-key-allowed-conn-types", func(t *testing.T) { |
| 6085 |
_, err := nats.Connect(wsUrl, nats.UserCredentials(aScopedCreds)) |
| 6086 |
require_Error(t, err) |
| 6087 |
}) |
| 6088 |
t.Run("scoped-signing-key-reload", func(t *testing.T) { |
| 6089 |
reconChan := make(chan struct{}, 1) |
| 6090 |
defer close(reconChan) |
| 6091 |
msgChan := make(chan *nats.Msg, 2) |
| 6092 |
defer close(msgChan) |
| 6093 |
nc := natsConnect(t, url, nats.UserCredentials(aScopedCreds), errHdlr, |
| 6094 |
nats.DisconnectErrHandler(func(conn *nats.Conn, err error) { |
| 6095 |
if err != nil { |
| 6096 |
errChan <- err |
| 6097 |
} |
| 6098 |
}), |
| 6099 |
nats.ReconnectHandler(func(conn *nats.Conn) { |
| 6100 |
reconChan <- struct{}{} |
| 6101 |
}), |
| 6102 |
nats.ReconnectWait(100*time.Millisecond), |
| 6103 |
) |
| 6104 |
defer nc.Close() |
| 6105 |
_, err := nc.ChanSubscribe("denied", msgChan) |
| 6106 |
require_NoError(t, err) |
| 6107 |
nc.Flush() |
| 6108 |
err = nc.Publish("denied", nil) |
| 6109 |
require_NoError(t, err) |
| 6110 |
awaitError(true) |
| 6111 |
require_Len(t, len(msgChan), 0) |
| 6112 |
// Alter scoped permissions and update |
| 6113 |
signer.Template.Payload = -1 |
| 6114 |
signer.Template.Pub.Deny.Remove("denied") |
| 6115 |
signer.Template.AllowedConnectionTypes.Add(jwt.ConnectionTypeWebsocket) |
| 6116 |
accClaim.SigningKeys.AddScopedSigner(signer) |
| 6117 |
accUpdatedJwt := encodeClaim(t, accClaim, aExpPub) |
| 6118 |
if updateJwt(t, url, sysCreds, accUpdatedJwt, 1) != 1 { |
| 6119 |
t.Error("Expected update to pass") |
| 6120 |
} |
| 6121 |
// disconnect triggered by update |
| 6122 |
awaitError(true) |
| 6123 |
<-reconChan |
| 6124 |
nc.Flush() |
| 6125 |
err = nc.Publish("denied", []byte("way.too.long.for.old.payload.limit")) |
| 6126 |
require_NoError(t, err) |
| 6127 |
awaitError(false) |
| 6128 |
msg := <-msgChan |
| 6129 |
require_Equal(t, string(msg.Data), "way.too.long.for.old.payload.limit") |
| 6130 |
require_Len(t, len(msgChan), 0) |
| 6131 |
nc.Close() |
| 6132 |
nc, err = nats.Connect(wsUrl, nats.UserCredentials(aScopedCreds)) |
| 6133 |
require_NoError(t, err) |
| 6134 |
nc.Flush() |
| 6135 |
defer nc.Close() |
| 6136 |
}) |
| 6137 |
require_Len(t, len(errChan), 0) |
| 6138 |
} |
| 6139 |
|
| 6140 |
func TestJWTStrictSigningKeys(t *testing.T) { |
| 6141 |
newAccount := func(opKp nkeys.KeyPair) (nkeys.KeyPair, nkeys.KeyPair, string, *jwt.AccountClaims, string) { |
| 6142 |
accId, err := nkeys.CreateAccount() |
| 6143 |
require_NoError(t, err) |
| 6144 |
accIdPub, err := accId.PublicKey() |
| 6145 |
require_NoError(t, err) |
| 6146 |
|
| 6147 |
accSig, err := nkeys.CreateAccount() |
| 6148 |
require_NoError(t, err) |
| 6149 |
accSigPub, err := accSig.PublicKey() |
| 6150 |
require_NoError(t, err) |
| 6151 |
|
| 6152 |
aClaim := jwt.NewAccountClaims(accIdPub) |
| 6153 |
aClaim.SigningKeys.Add(accSigPub) |
| 6154 |
theJwt, err := aClaim.Encode(opKp) |
| 6155 |
require_NoError(t, err) |
| 6156 |
return accId, accSig, accIdPub, aClaim, theJwt |
| 6157 |
} |
| 6158 |
|
| 6159 |
opId, err := nkeys.CreateOperator() |
| 6160 |
require_NoError(t, err) |
| 6161 |
opIdPub, err := opId.PublicKey() |
| 6162 |
require_NoError(t, err) |
| 6163 |
|
| 6164 |
opSig, err := nkeys.CreateOperator() |
| 6165 |
require_NoError(t, err) |
| 6166 |
opSigPub, err := opSig.PublicKey() |
| 6167 |
require_NoError(t, err) |
| 6168 |
|
| 6169 |
aBadBadKp, aBadGoodKp, aBadPub, _, aBadJwt := newAccount(opId) |
| 6170 |
aGoodBadKp, aGoodGoodKp, aGoodPub, _, aGoodJwt := newAccount(opSig) |
| 6171 |
_, aSysKp, aSysPub, _, aSysJwt := newAccount(opSig) |
| 6172 |
|
| 6173 |
oClaim := jwt.NewOperatorClaims(opIdPub) |
| 6174 |
oClaim.StrictSigningKeyUsage = true |
| 6175 |
oClaim.SigningKeys.Add(opSigPub) |
| 6176 |
oClaim.SystemAccount = aSysPub |
| 6177 |
oJwt, err := oClaim.Encode(opId) |
| 6178 |
require_NoError(t, err) |
| 6179 |
|
| 6180 |
uBadBadCreds := newUserEx(t, aBadBadKp, false, aBadPub) |
| 6181 |
uBadGoodCreds := newUserEx(t, aBadGoodKp, false, aBadPub) |
| 6182 |
uGoodBadCreds := newUserEx(t, aGoodBadKp, false, aGoodPub) |
| 6183 |
uGoodGoodCreds := newUserEx(t, aGoodGoodKp, false, aGoodPub) |
| 6184 |
uSysCreds := newUserEx(t, aSysKp, false, aSysPub) |
| 6185 |
|
| 6186 |
connectTest := func(url string) { |
| 6187 |
for _, test := range []struct { |
| 6188 |
creds string |
| 6189 |
fail bool |
| 6190 |
}{ |
| 6191 |
{uBadBadCreds, true}, |
| 6192 |
{uBadGoodCreds, true}, |
| 6193 |
{uGoodBadCreds, true}, |
| 6194 |
{uGoodGoodCreds, false}, |
| 6195 |
} { |
| 6196 |
nc, err := nats.Connect(url, nats.UserCredentials(test.creds)) |
| 6197 |
nc.Close() |
| 6198 |
if test.fail { |
| 6199 |
require_Error(t, err) |
| 6200 |
} else { |
| 6201 |
require_NoError(t, err) |
| 6202 |
} |
| 6203 |
} |
| 6204 |
} |
| 6205 |
|
| 6206 |
t.Run("resolver", func(t *testing.T) { |
| 6207 |
dirSrv := t.TempDir() |
| 6208 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 6209 |
port: -1 |
| 6210 |
operator = %s |
| 6211 |
resolver: { |
| 6212 |
type: full |
| 6213 |
dir: '%s' |
| 6214 |
} |
| 6215 |
resolver_preload = { |
| 6216 |
%s : "%s" |
| 6217 |
} |
| 6218 |
`, oJwt, dirSrv, aSysPub, aSysJwt))) |
| 6219 |
s, _ := RunServerWithConfig(cf) |
| 6220 |
defer s.Shutdown() |
| 6221 |
url := s.ClientURL() |
| 6222 |
if updateJwt(t, url, uSysCreds, aBadJwt, 1) != 0 { |
| 6223 |
t.Fatal("Expected negative response") |
| 6224 |
} |
| 6225 |
if updateJwt(t, url, uSysCreds, aGoodJwt, 1) != 1 { |
| 6226 |
t.Fatal("Expected positive response") |
| 6227 |
} |
| 6228 |
connectTest(url) |
| 6229 |
}) |
| 6230 |
|
| 6231 |
t.Run("mem-resolver", func(t *testing.T) { |
| 6232 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 6233 |
port: -1 |
| 6234 |
operator = %s |
| 6235 |
resolver: MEMORY |
| 6236 |
resolver_preload = { |
| 6237 |
%s : "%s" |
| 6238 |
%s : "%s" |
| 6239 |
%s : "%s" |
| 6240 |
} |
| 6241 |
`, oJwt, aSysPub, aSysJwt, aBadPub, aBadJwt, aGoodPub, aGoodJwt))) |
| 6242 |
s, _ := RunServerWithConfig(cf) |
| 6243 |
defer s.Shutdown() |
| 6244 |
connectTest(s.ClientURL()) |
| 6245 |
}) |
| 6246 |
} |
| 6247 |
|
| 6248 |
func TestJWTAccountProtectedImport(t *testing.T) { |
| 6249 |
srvFmt := ` |
| 6250 |
port: -1 |
| 6251 |
operator = %s |
| 6252 |
resolver: MEMORY |
| 6253 |
resolver_preload = { |
| 6254 |
%s : "%s" |
| 6255 |
%s : "%s" |
| 6256 |
} ` |
| 6257 |
setupAccounts := func(pass bool) (nkeys.KeyPair, string, string, string, nkeys.KeyPair, string, string, string, string) { |
| 6258 |
// Create accounts and imports/exports. |
| 6259 |
exportKP, _ := nkeys.CreateAccount() |
| 6260 |
exportPub, _ := exportKP.PublicKey() |
| 6261 |
exportAC := jwt.NewAccountClaims(exportPub) |
| 6262 |
exportAC.Exports.Add(&jwt.Export{Subject: "service.*", Type: jwt.Service, AccountTokenPosition: 2}) |
| 6263 |
exportAC.Exports.Add(&jwt.Export{Subject: "stream.*", Type: jwt.Stream, AccountTokenPosition: 2}) |
| 6264 |
exportJWT, err := exportAC.Encode(oKp) |
| 6265 |
require_NoError(t, err) |
| 6266 |
// create alternative exporter jwt without account token pos set |
| 6267 |
exportAC.Exports = jwt.Exports{} |
| 6268 |
exportAC.Exports.Add(&jwt.Export{Subject: "service.*", Type: jwt.Service}) |
| 6269 |
exportAC.Exports.Add(&jwt.Export{Subject: "stream.*", Type: jwt.Stream}) |
| 6270 |
exportJWTNoPos, err := exportAC.Encode(oKp) |
| 6271 |
require_NoError(t, err) |
| 6272 |
|
| 6273 |
importKP, _ := nkeys.CreateAccount() |
| 6274 |
importPub, _ := importKP.PublicKey() |
| 6275 |
importAc := jwt.NewAccountClaims(importPub) |
| 6276 |
srvcSub, strmSub := "service.foo", "stream.foo" |
| 6277 |
if pass { |
| 6278 |
srvcSub = fmt.Sprintf("service.%s", importPub) |
| 6279 |
strmSub = fmt.Sprintf("stream.%s", importPub) |
| 6280 |
} |
| 6281 |
importAc.Imports.Add(&jwt.Import{Account: exportPub, Subject: jwt.Subject(srvcSub), Type: jwt.Service}) |
| 6282 |
importAc.Imports.Add(&jwt.Import{Account: exportPub, Subject: jwt.Subject(strmSub), Type: jwt.Stream}) |
| 6283 |
importJWT, err := importAc.Encode(oKp) |
| 6284 |
require_NoError(t, err) |
| 6285 |
|
| 6286 |
return exportKP, exportPub, exportJWT, exportJWTNoPos, importKP, importPub, importJWT, srvcSub, strmSub |
| 6287 |
} |
| 6288 |
t.Run("pass", func(t *testing.T) { |
| 6289 |
exportKp, exportPub, exportJWT, _, importKp, importPub, importJWT, srvcSub, strmSub := setupAccounts(true) |
| 6290 |
cf := createConfFile(t, []byte(fmt.Sprintf(srvFmt, ojwt, exportPub, exportJWT, importPub, importJWT))) |
| 6291 |
s, _ := RunServerWithConfig(cf) |
| 6292 |
defer s.Shutdown() |
| 6293 |
ncExp := natsConnect(t, s.ClientURL(), createUserCreds(t, s, exportKp)) |
| 6294 |
defer ncExp.Close() |
| 6295 |
ncImp := natsConnect(t, s.ClientURL(), createUserCreds(t, s, importKp)) |
| 6296 |
defer ncImp.Close() |
| 6297 |
t.Run("service", func(t *testing.T) { |
| 6298 |
sub, err := ncExp.Subscribe("service.*", func(msg *nats.Msg) { |
| 6299 |
msg.Respond([]byte("world")) |
| 6300 |
}) |
| 6301 |
defer sub.Unsubscribe() |
| 6302 |
require_NoError(t, err) |
| 6303 |
ncExp.Flush() |
| 6304 |
msg, err := ncImp.Request(srvcSub, []byte("hello"), time.Second) |
| 6305 |
require_NoError(t, err) |
| 6306 |
require_Equal(t, string(msg.Data), "world") |
| 6307 |
}) |
| 6308 |
t.Run("stream", func(t *testing.T) { |
| 6309 |
msgChan := make(chan *nats.Msg, 4) |
| 6310 |
defer close(msgChan) |
| 6311 |
sub, err := ncImp.ChanSubscribe(strmSub, msgChan) |
| 6312 |
defer sub.Unsubscribe() |
| 6313 |
require_NoError(t, err) |
| 6314 |
ncImp.Flush() |
| 6315 |
err = ncExp.Publish("stream.foo", []byte("hello")) |
| 6316 |
require_NoError(t, err) |
| 6317 |
err = ncExp.Publish(strmSub, []byte("hello")) |
| 6318 |
require_NoError(t, err) |
| 6319 |
msg := <-msgChan |
| 6320 |
require_Equal(t, string(msg.Data), "hello") |
| 6321 |
require_True(t, len(msgChan) == 0) |
| 6322 |
}) |
| 6323 |
}) |
| 6324 |
t.Run("fail", func(t *testing.T) { |
| 6325 |
exportKp, exportPub, exportJWT, _, importKp, importPub, importJWT, srvcSub, strmSub := setupAccounts(false) |
| 6326 |
cf := createConfFile(t, []byte(fmt.Sprintf(srvFmt, ojwt, exportPub, exportJWT, importPub, importJWT))) |
| 6327 |
s, _ := RunServerWithConfig(cf) |
| 6328 |
defer s.Shutdown() |
| 6329 |
ncExp := natsConnect(t, s.ClientURL(), createUserCreds(t, s, exportKp)) |
| 6330 |
defer ncExp.Close() |
| 6331 |
ncImp := natsConnect(t, s.ClientURL(), createUserCreds(t, s, importKp)) |
| 6332 |
defer ncImp.Close() |
| 6333 |
t.Run("service", func(t *testing.T) { |
| 6334 |
sub, err := ncExp.Subscribe("service.*", func(msg *nats.Msg) { |
| 6335 |
msg.Respond([]byte("world")) |
| 6336 |
}) |
| 6337 |
defer sub.Unsubscribe() |
| 6338 |
require_NoError(t, err) |
| 6339 |
ncExp.Flush() |
| 6340 |
_, err = ncImp.Request(srvcSub, []byte("hello"), time.Second) |
| 6341 |
require_Error(t, err) |
| 6342 |
require_Contains(t, err.Error(), "no responders available for request") |
| 6343 |
}) |
| 6344 |
t.Run("stream", func(t *testing.T) { |
| 6345 |
msgChan := make(chan *nats.Msg, 4) |
| 6346 |
defer close(msgChan) |
| 6347 |
_, err := ncImp.ChanSubscribe(strmSub, msgChan) |
| 6348 |
require_NoError(t, err) |
| 6349 |
ncImp.Flush() |
| 6350 |
err = ncExp.Publish("stream.foo", []byte("hello")) |
| 6351 |
require_NoError(t, err) |
| 6352 |
err = ncExp.Publish(strmSub, []byte("hello")) |
| 6353 |
require_NoError(t, err) |
| 6354 |
select { |
| 6355 |
case <-msgChan: |
| 6356 |
t.Fatal("did not expect a message") |
| 6357 |
case <-time.After(250 * time.Millisecond): |
| 6358 |
} |
| 6359 |
require_True(t, len(msgChan) == 0) |
| 6360 |
}) |
| 6361 |
}) |
| 6362 |
t.Run("reload-off-2-on", func(t *testing.T) { |
| 6363 |
exportKp, exportPub, exportJWTOn, exportJWTOff, importKp, _, importJWT, srvcSub, strmSub := setupAccounts(false) |
| 6364 |
dirSrv := t.TempDir() |
| 6365 |
// set up system account. Relying bootstrapping system account to not create JWT |
| 6366 |
sysAcc, err := nkeys.CreateAccount() |
| 6367 |
require_NoError(t, err) |
| 6368 |
sysPub, err := sysAcc.PublicKey() |
| 6369 |
require_NoError(t, err) |
| 6370 |
sysUsrCreds := newUserEx(t, sysAcc, false, sysPub) |
| 6371 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 6372 |
port: -1 |
| 6373 |
operator = %s |
| 6374 |
system_account = %s |
| 6375 |
resolver: { |
| 6376 |
type: full |
| 6377 |
dir: '%s' |
| 6378 |
}`, ojwt, sysPub, dirSrv))) |
| 6379 |
s, _ := RunServerWithConfig(cf) |
| 6380 |
defer s.Shutdown() |
| 6381 |
updateJwt(t, s.ClientURL(), sysUsrCreds, importJWT, 1) |
| 6382 |
updateJwt(t, s.ClientURL(), sysUsrCreds, exportJWTOff, 1) |
| 6383 |
ncExp := natsConnect(t, s.ClientURL(), createUserCreds(t, s, exportKp)) |
| 6384 |
defer ncExp.Close() |
| 6385 |
ncImp := natsConnect(t, s.ClientURL(), createUserCreds(t, s, importKp)) |
| 6386 |
defer ncImp.Close() |
| 6387 |
msgChan := make(chan *nats.Msg, 4) |
| 6388 |
defer close(msgChan) |
| 6389 |
// ensure service passes |
| 6390 |
subSrvc, err := ncExp.Subscribe("service.*", func(msg *nats.Msg) { |
| 6391 |
msg.Respond([]byte("world")) |
| 6392 |
}) |
| 6393 |
defer subSrvc.Unsubscribe() |
| 6394 |
require_NoError(t, err) |
| 6395 |
ncExp.Flush() |
| 6396 |
respMst, err := ncImp.Request(srvcSub, []byte("hello"), time.Second) |
| 6397 |
require_NoError(t, err) |
| 6398 |
require_Equal(t, string(respMst.Data), "world") |
| 6399 |
// ensure stream passes |
| 6400 |
subStrm, err := ncImp.ChanSubscribe(strmSub, msgChan) |
| 6401 |
defer subStrm.Unsubscribe() |
| 6402 |
require_NoError(t, err) |
| 6403 |
ncImp.Flush() |
| 6404 |
err = ncExp.Publish(strmSub, []byte("hello")) |
| 6405 |
require_NoError(t, err) |
| 6406 |
msg := <-msgChan |
| 6407 |
require_Equal(t, string(msg.Data), "hello") |
| 6408 |
require_True(t, len(msgChan) == 0) |
| 6409 |
|
| 6410 |
updateJwt(t, s.ClientURL(), sysUsrCreds, exportJWTOn, 1) |
| 6411 |
|
| 6412 |
// ensure service fails |
| 6413 |
_, err = ncImp.Request(srvcSub, []byte("hello"), time.Second) |
| 6414 |
require_Error(t, err, nats.ErrNoResponders) |
| 6415 |
s.AccountResolver().Store(exportPub, exportJWTOn) |
| 6416 |
// ensure stream fails |
| 6417 |
err = ncExp.Publish(strmSub, []byte("hello")) |
| 6418 |
require_NoError(t, err) |
| 6419 |
select { |
| 6420 |
case <-msgChan: |
| 6421 |
t.Fatal("did not expect a message") |
| 6422 |
case <-time.After(250 * time.Millisecond): |
| 6423 |
} |
| 6424 |
require_True(t, len(msgChan) == 0) |
| 6425 |
}) |
| 6426 |
} |
| 6427 |
|
| 6428 |
// Headers are ignored in claims update, but passing them should not cause error. |
| 6429 |
func TestJWTClaimsUpdateWithHeaders(t *testing.T) { |
| 6430 |
skp, spub := createKey(t) |
| 6431 |
newUser(t, skp) |
| 6432 |
|
| 6433 |
sclaim := jwt.NewAccountClaims(spub) |
| 6434 |
encodeClaim(t, sclaim, spub) |
| 6435 |
|
| 6436 |
akp, apub := createKey(t) |
| 6437 |
newUser(t, akp) |
| 6438 |
claim := jwt.NewAccountClaims(apub) |
| 6439 |
jwtClaim := encodeClaim(t, claim, apub) |
| 6440 |
|
| 6441 |
dirSrv := t.TempDir() |
| 6442 |
|
| 6443 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 6444 |
listen: 127.0.0.1:-1 |
| 6445 |
operator: %s |
| 6446 |
system_account: %s |
| 6447 |
resolver: { |
| 6448 |
type: full |
| 6449 |
dir: '%s' |
| 6450 |
allow_delete: true |
| 6451 |
} |
| 6452 |
`, ojwt, spub, dirSrv))) |
| 6453 |
|
| 6454 |
s, _ := RunServerWithConfig(conf) |
| 6455 |
defer s.Shutdown() |
| 6456 |
|
| 6457 |
type zapi struct { |
| 6458 |
Server *ServerInfo |
| 6459 |
Data *Connz |
| 6460 |
Error *ApiError |
| 6461 |
} |
| 6462 |
|
| 6463 |
sc := natsConnect(t, s.ClientURL(), createUserCreds(t, s, skp)) |
| 6464 |
defer sc.Close() |
| 6465 |
// Pass claims update with headers. |
| 6466 |
msg := &nats.Msg{ |
| 6467 |
Subject: "$SYS.REQ.CLAIMS.UPDATE", |
| 6468 |
Data: []byte(jwtClaim), |
| 6469 |
Header: map[string][]string{"key": {"value"}}, |
| 6470 |
} |
| 6471 |
resp, err := sc.RequestMsg(msg, time.Second) |
| 6472 |
if err != nil { |
| 6473 |
t.Fatalf("Unexpected error: %v", err) |
| 6474 |
} |
| 6475 |
var cz zapi |
| 6476 |
if err := json.Unmarshal(resp.Data, &cz); err != nil { |
| 6477 |
t.Fatalf("Unexpected error: %v", err) |
| 6478 |
} |
| 6479 |
if cz.Error != nil { |
| 6480 |
t.Fatalf("Unexpected error: %+v", cz.Error) |
| 6481 |
} |
| 6482 |
|
| 6483 |
// Pass claims delete with headers. |
| 6484 |
opk, err := oKp.PublicKey() |
| 6485 |
require_NoError(t, err) |
| 6486 |
c := jwt.NewGenericClaims(opk) |
| 6487 |
c.Data["accounts"] = []string{apub} |
| 6488 |
djwt, err := c.Encode(oKp) |
| 6489 |
require_NoError(t, err) |
| 6490 |
msg.Subject = "$SYS.REQ.CLAIMS.DELETE" |
| 6491 |
msg.Data = []byte(djwt) |
| 6492 |
resp, err = sc.RequestMsg(msg, time.Second) |
| 6493 |
if err != nil { |
| 6494 |
t.Fatalf("Unexpected error: %v", err) |
| 6495 |
} |
| 6496 |
cz = zapi{} |
| 6497 |
if err := json.Unmarshal(resp.Data, &cz); err != nil { |
| 6498 |
t.Fatalf("Unexpected error: %v", err) |
| 6499 |
} |
| 6500 |
if cz.Error != nil { |
| 6501 |
t.Fatalf("Unexpected error: %+v", cz.Error) |
| 6502 |
} |
| 6503 |
} |
| 6504 |
|
| 6505 |
func TestJWTMappings(t *testing.T) { |
| 6506 |
sysKp, syspub := createKey(t) |
| 6507 |
sysJwt := encodeClaim(t, jwt.NewAccountClaims(syspub), syspub) |
| 6508 |
sysCreds := newUser(t, sysKp) |
| 6509 |
|
| 6510 |
// create two jwt, one with and one without mapping |
| 6511 |
aKp, aPub := createKey(t) |
| 6512 |
aClaim := jwt.NewAccountClaims(aPub) |
| 6513 |
aJwtNoM := encodeClaim(t, aClaim, aPub) |
| 6514 |
aClaim.AddMapping("foo1", jwt.WeightedMapping{Subject: "bar1"}) |
| 6515 |
aJwtMap1 := encodeClaim(t, aClaim, aPub) |
| 6516 |
|
| 6517 |
aClaim.Mappings = map[jwt.Subject][]jwt.WeightedMapping{} |
| 6518 |
aClaim.AddMapping("foo2", jwt.WeightedMapping{Subject: "bar2"}) |
| 6519 |
aJwtMap2 := encodeClaim(t, aClaim, aPub) |
| 6520 |
|
| 6521 |
dirSrv := t.TempDir() |
| 6522 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 6523 |
listen: 127.0.0.1:-1 |
| 6524 |
operator: %s |
| 6525 |
system_account: %s |
| 6526 |
resolver: { |
| 6527 |
type: full |
| 6528 |
dir: '%s' |
| 6529 |
} |
| 6530 |
`, ojwt, syspub, dirSrv))) |
| 6531 |
srv, _ := RunServerWithConfig(conf) |
| 6532 |
defer srv.Shutdown() |
| 6533 |
updateJwt(t, srv.ClientURL(), sysCreds, sysJwt, 1) // update system account jwt |
| 6534 |
|
| 6535 |
test := func(pub, sub string, fail bool) { |
| 6536 |
t.Helper() |
| 6537 |
nc := natsConnect(t, srv.ClientURL(), createUserCreds(t, srv, aKp)) |
| 6538 |
defer nc.Close() |
| 6539 |
s, err := nc.SubscribeSync(sub) |
| 6540 |
require_NoError(t, err) |
| 6541 |
nc.Flush() |
| 6542 |
err = nc.Publish(pub, nil) |
| 6543 |
require_NoError(t, err) |
| 6544 |
_, err = s.NextMsg(500 * time.Millisecond) |
| 6545 |
switch { |
| 6546 |
case fail && err == nil: |
| 6547 |
t.Fatal("expected error, got none") |
| 6548 |
case !fail && err != nil: |
| 6549 |
t.Fatalf("expected no error, got %v", err) |
| 6550 |
} |
| 6551 |
} |
| 6552 |
|
| 6553 |
// turn mappings on |
| 6554 |
require_Len(t, 1, updateJwt(t, srv.ClientURL(), sysCreds, aJwtMap1, 1)) |
| 6555 |
test("foo1", "bar1", false) |
| 6556 |
// alter mappings |
| 6557 |
require_Len(t, 1, updateJwt(t, srv.ClientURL(), sysCreds, aJwtMap2, 1)) |
| 6558 |
test("foo1", "bar1", true) |
| 6559 |
test("foo2", "bar2", false) |
| 6560 |
// turn mappings off |
| 6561 |
require_Len(t, 1, updateJwt(t, srv.ClientURL(), sysCreds, aJwtNoM, 1)) |
| 6562 |
test("foo2", "bar2", true) |
| 6563 |
} |
| 6564 |
|
| 6565 |
func TestJWTOperatorPinnedAccounts(t *testing.T) { |
| 6566 |
kps, pubs, jwts := [4]nkeys.KeyPair{}, [4]string{}, [4]string{} |
| 6567 |
for i := 0; i < 4; i++ { |
| 6568 |
kps[i], pubs[i] = createKey(t) |
| 6569 |
jwts[i] = encodeClaim(t, jwt.NewAccountClaims(pubs[i]), pubs[i]) |
| 6570 |
} |
| 6571 |
// create system account user credentials, index 0 is handled as system account |
| 6572 |
newUser(t, kps[0]) |
| 6573 |
|
| 6574 |
cfgCommon := fmt.Sprintf(` |
| 6575 |
listen: 127.0.0.1:-1 |
| 6576 |
operator: %s |
| 6577 |
system_account: %s |
| 6578 |
resolver: MEM |
| 6579 |
resolver_preload: { |
| 6580 |
%s:%s |
| 6581 |
%s:%s |
| 6582 |
%s:%s |
| 6583 |
%s:%s |
| 6584 |
}`, ojwt, pubs[0], pubs[0], jwts[0], pubs[1], jwts[1], pubs[2], jwts[2], pubs[3], jwts[3]) |
| 6585 |
cfgFmt := cfgCommon + ` |
| 6586 |
resolver_pinned_accounts: [%s, %s] |
| 6587 |
` |
| 6588 |
conf := createConfFile(t, []byte(fmt.Sprintf(cfgFmt, pubs[1], pubs[2]))) |
| 6589 |
srv, _ := RunServerWithConfig(conf) |
| 6590 |
defer srv.Shutdown() |
| 6591 |
|
| 6592 |
connectPass := func(keys ...nkeys.KeyPair) { |
| 6593 |
for _, kp := range keys { |
| 6594 |
nc, err := nats.Connect(srv.ClientURL(), createUserCreds(t, srv, kp)) |
| 6595 |
require_NoError(t, err) |
| 6596 |
defer nc.Close() |
| 6597 |
} |
| 6598 |
} |
| 6599 |
var pinnedFail uint64 |
| 6600 |
connectFail := func(key nkeys.KeyPair) { |
| 6601 |
_, err := nats.Connect(srv.ClientURL(), createUserCreds(t, srv, key)) |
| 6602 |
require_Error(t, err) |
| 6603 |
require_Contains(t, err.Error(), "Authorization Violation") |
| 6604 |
v, err := srv.Varz(&VarzOptions{}) |
| 6605 |
require_NoError(t, err) |
| 6606 |
require_True(t, pinnedFail+1 == v.PinnedAccountFail) |
| 6607 |
pinnedFail = v.PinnedAccountFail |
| 6608 |
} |
| 6609 |
|
| 6610 |
connectPass(kps[0], kps[1], kps[2]) // make sure user from accounts listed and system account (index 0) work |
| 6611 |
connectFail(kps[3]) // make sure the other user does not work |
| 6612 |
// reload and test again |
| 6613 |
reloadUpdateConfig(t, srv, conf, fmt.Sprintf(cfgFmt, pubs[2], pubs[3])) |
| 6614 |
connectPass(kps[0], kps[2], kps[3]) // make sure user from accounts listed and system account (index 0) work |
| 6615 |
connectFail(kps[1]) // make sure the other user does not work |
| 6616 |
// completely disable and test again |
| 6617 |
reloadUpdateConfig(t, srv, conf, cfgCommon) |
| 6618 |
connectPass(kps[0], kps[1], kps[2], kps[3]) // make sure every account and system account (index 0) can connect |
| 6619 |
// re-enable and test again |
| 6620 |
reloadUpdateConfig(t, srv, conf, fmt.Sprintf(cfgFmt, pubs[2], pubs[3])) |
| 6621 |
connectPass(kps[0], kps[2], kps[3]) // make sure user from accounts listed and system account (index 0) work |
| 6622 |
connectFail(kps[1]) // make sure the other user does not work |
| 6623 |
} |
| 6624 |
|
| 6625 |
func TestJWTNoSystemAccountButNatsResolver(t *testing.T) { |
| 6626 |
dirSrv := t.TempDir() |
| 6627 |
for _, resType := range []string{"full", "cache"} { |
| 6628 |
t.Run(resType, func(t *testing.T) { |
| 6629 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 6630 |
listen: 127.0.0.1:-1 |
| 6631 |
operator: %s |
| 6632 |
resolver: { |
| 6633 |
type: %s |
| 6634 |
dir: '%s' |
| 6635 |
}`, ojwt, resType, dirSrv))) |
| 6636 |
opts := LoadConfig(conf) |
| 6637 |
s, err := NewServer(opts) |
| 6638 |
// Since the server cannot be stopped, since it did not start, |
| 6639 |
// let's manually close the account resolver to avoid leaking go routines. |
| 6640 |
opts.AccountResolver.Close() |
| 6641 |
s.Shutdown() |
| 6642 |
require_Error(t, err) |
| 6643 |
require_Contains(t, err.Error(), "the system account needs to be specified in configuration or the operator jwt") |
| 6644 |
}) |
| 6645 |
} |
| 6646 |
} |
| 6647 |
|
| 6648 |
func TestJWTAccountConnzAccessAfterClaimUpdate(t *testing.T) { |
| 6649 |
skp, spub := createKey(t) |
| 6650 |
newUser(t, skp) |
| 6651 |
|
| 6652 |
sclaim := jwt.NewAccountClaims(spub) |
| 6653 |
sclaim.AddMapping("foo.bar", jwt.WeightedMapping{Subject: "foo.baz"}) |
| 6654 |
sjwt := encodeClaim(t, sclaim, spub) |
| 6655 |
|
| 6656 |
// create two jwt, one with and one without mapping |
| 6657 |
akp, apub := createKey(t) |
| 6658 |
newUser(t, akp) |
| 6659 |
claim := jwt.NewAccountClaims(apub) |
| 6660 |
jwt1 := encodeClaim(t, claim, apub) |
| 6661 |
claim.AddMapping("foo.bar", jwt.WeightedMapping{Subject: "foo.baz"}) |
| 6662 |
jwt2 := encodeClaim(t, claim, apub) |
| 6663 |
|
| 6664 |
dirSrv := t.TempDir() |
| 6665 |
|
| 6666 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 6667 |
listen: 127.0.0.1:-1 |
| 6668 |
operator: %s |
| 6669 |
system_account: %s |
| 6670 |
resolver: { |
| 6671 |
type: full |
| 6672 |
dir: '%s' |
| 6673 |
} |
| 6674 |
`, ojwt, spub, dirSrv))) |
| 6675 |
|
| 6676 |
s, _ := RunServerWithConfig(conf) |
| 6677 |
defer s.Shutdown() |
| 6678 |
|
| 6679 |
type zapi struct { |
| 6680 |
Server *ServerInfo |
| 6681 |
Data *Connz |
| 6682 |
Error *ApiError |
| 6683 |
} |
| 6684 |
|
| 6685 |
updateJWT := func(jwt string) { |
| 6686 |
t.Helper() |
| 6687 |
sc := natsConnect(t, s.ClientURL(), createUserCreds(t, s, skp)) |
| 6688 |
defer sc.Close() |
| 6689 |
resp, err := sc.Request("$SYS.REQ.CLAIMS.UPDATE", []byte(jwt), time.Second) |
| 6690 |
if err != nil { |
| 6691 |
t.Fatalf("Unexpected error: %v", err) |
| 6692 |
} |
| 6693 |
var cz zapi |
| 6694 |
if err := json.Unmarshal(resp.Data, &cz); err != nil { |
| 6695 |
t.Fatalf("Unexpected error: %v", err) |
| 6696 |
} |
| 6697 |
if cz.Error != nil { |
| 6698 |
t.Fatalf("Unexpected error: %+v", cz.Error) |
| 6699 |
} |
| 6700 |
} |
| 6701 |
|
| 6702 |
updateJWT(jwt1) |
| 6703 |
|
| 6704 |
nc := natsConnect(t, s.ClientURL(), createUserCreds(t, s, akp)) |
| 6705 |
defer nc.Close() |
| 6706 |
|
| 6707 |
doRequest := func() { |
| 6708 |
t.Helper() |
| 6709 |
resp, err := nc.Request("$SYS.REQ.SERVER.PING.CONNZ", nil, time.Second) |
| 6710 |
if err != nil { |
| 6711 |
t.Fatalf("Unexpected error: %v", err) |
| 6712 |
} |
| 6713 |
var cz zapi |
| 6714 |
if err := json.Unmarshal(resp.Data, &cz); err != nil { |
| 6715 |
t.Fatalf("Unexpected error: %v", err) |
| 6716 |
} |
| 6717 |
if cz.Error != nil { |
| 6718 |
t.Fatalf("Unexpected error: %+v", cz.Error) |
| 6719 |
} |
| 6720 |
} |
| 6721 |
|
| 6722 |
doRequest() |
| 6723 |
updateJWT(jwt2) |
| 6724 |
// If we accidentally wipe the system import this will fail with no responders. |
| 6725 |
doRequest() |
| 6726 |
// Now test updating system account. |
| 6727 |
updateJWT(sjwt) |
| 6728 |
// If export was wiped this would fail with timeout. |
| 6729 |
doRequest() |
| 6730 |
} |
| 6731 |
|
| 6732 |
func TestJWTAccountWeightedMappingInSuperCluster(t *testing.T) { |
| 6733 |
skp, spub := createKey(t) |
| 6734 |
sysClaim := jwt.NewAccountClaims(spub) |
| 6735 |
sysClaim.Name = "SYS" |
| 6736 |
sysCreds := newUser(t, skp) |
| 6737 |
|
| 6738 |
akp, apub := createKey(t) |
| 6739 |
aUsr := createUserCreds(t, nil, akp) |
| 6740 |
claim := jwt.NewAccountClaims(apub) |
| 6741 |
aJwtMap := encodeClaim(t, claim, apub) |
| 6742 |
|
| 6743 |
// We are using the createJetStreamSuperClusterWithTemplateAndModHook() |
| 6744 |
// helper, but this test is not about JetStream... |
| 6745 |
tmpl := ` |
| 6746 |
listen: 127.0.0.1:-1 |
| 6747 |
server_name: %s |
| 6748 |
jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'} |
| 6749 |
cluster { |
| 6750 |
name: %s |
| 6751 |
listen: 127.0.0.1:%d |
| 6752 |
routes = [%s] |
| 6753 |
} |
| 6754 |
` |
| 6755 |
|
| 6756 |
sc := createJetStreamSuperClusterWithTemplateAndModHook(t, tmpl, 3, 3, |
| 6757 |
func(serverName, clusterName, storeDir, conf string) string { |
| 6758 |
dirSrv := t.TempDir() |
| 6759 |
return fmt.Sprintf(`%s |
| 6760 |
operator: %s |
| 6761 |
system_account: %s |
| 6762 |
resolver: { |
| 6763 |
type: full |
| 6764 |
dir: '%s' |
| 6765 |
} |
| 6766 |
`, conf, ojwt, spub, dirSrv) |
| 6767 |
}, nil) |
| 6768 |
defer sc.shutdown() |
| 6769 |
|
| 6770 |
// Update from C2 |
| 6771 |
require_Len(t, 1, updateJwt(t, sc.clusterForName("C2").randomServer().ClientURL(), sysCreds, aJwtMap, 1)) |
| 6772 |
|
| 6773 |
// We will connect our services in the C3 cluster. |
| 6774 |
nc1 := natsConnect(t, sc.clusterForName("C3").randomServer().ClientURL(), aUsr) |
| 6775 |
defer nc1.Close() |
| 6776 |
nc2 := natsConnect(t, sc.clusterForName("C3").randomServer().ClientURL(), aUsr) |
| 6777 |
defer nc2.Close() |
| 6778 |
|
| 6779 |
natsSub(t, nc1, "foo", func(m *nats.Msg) { |
| 6780 |
m.Respond([]byte("foo")) |
| 6781 |
}) |
| 6782 |
natsSub(t, nc1, "bar.v1", func(m *nats.Msg) { |
| 6783 |
m.Respond([]byte("v1")) |
| 6784 |
}) |
| 6785 |
natsSub(t, nc2, "bar.v2", func(m *nats.Msg) { |
| 6786 |
m.Respond([]byte("v2")) |
| 6787 |
}) |
| 6788 |
natsFlush(t, nc1) |
| 6789 |
natsFlush(t, nc2) |
| 6790 |
|
| 6791 |
// Now we will update the account to add weighted subject mapping |
| 6792 |
claim.Mappings = map[jwt.Subject][]jwt.WeightedMapping{} |
| 6793 |
// Start with foo->bar.v2 at 40%, the server will auto-add foo->foo at 60%. |
| 6794 |
wm := []jwt.WeightedMapping{{Subject: "bar.v2", Weight: 40}} |
| 6795 |
claim.AddMapping("foo", wm...) |
| 6796 |
aJwtMap = encodeClaim(t, claim, apub) |
| 6797 |
|
| 6798 |
// We will update from C2 |
| 6799 |
require_Len(t, 1, updateJwt(t, sc.clusterForName("C2").randomServer().ClientURL(), sysCreds, aJwtMap, 1)) |
| 6800 |
|
| 6801 |
time.Sleep(time.Second) |
| 6802 |
|
| 6803 |
// And we will publish from C1 |
| 6804 |
nc := natsConnect(t, sc.clusterForName("C1").randomServer().ClientURL(), aUsr) |
| 6805 |
defer nc.Close() |
| 6806 |
|
| 6807 |
var foo, v1, v2 int |
| 6808 |
pubAndCount := func() { |
| 6809 |
for i := 0; i < 1000; i++ { |
| 6810 |
msg, err := nc.Request("foo", []byte("req"), 500*time.Millisecond) |
| 6811 |
if err != nil { |
| 6812 |
continue |
| 6813 |
} |
| 6814 |
switch string(msg.Data) { |
| 6815 |
case "foo": |
| 6816 |
foo++ |
| 6817 |
case "v1": |
| 6818 |
v1++ |
| 6819 |
case "v2": |
| 6820 |
v2++ |
| 6821 |
} |
| 6822 |
} |
| 6823 |
} |
| 6824 |
pubAndCount() |
| 6825 |
if foo < 550 || foo > 650 { |
| 6826 |
t.Fatalf("Expected foo to receive 60%%, got %v/1000", foo) |
| 6827 |
} |
| 6828 |
if v1 != 0 { |
| 6829 |
t.Fatalf("Expected v1 to receive no message, got %v/1000", v1) |
| 6830 |
} |
| 6831 |
if v2 < 350 || v2 > 450 { |
| 6832 |
t.Fatalf("Expected v2 to receive 40%%, got %v/1000", v2) |
| 6833 |
} |
| 6834 |
|
| 6835 |
// Now send a new update with foo-> bar.v2(40) and bar.v1(60). |
| 6836 |
// The auto-add of "foo" should no longer be used by the server. |
| 6837 |
wm = []jwt.WeightedMapping{ |
| 6838 |
{Subject: "bar.v2", Weight: 40}, |
| 6839 |
{Subject: "bar.v1", Weight: 60}, |
| 6840 |
} |
| 6841 |
claim.AddMapping("foo", wm...) |
| 6842 |
aJwtMap = encodeClaim(t, claim, apub) |
| 6843 |
|
| 6844 |
// We will update from C2 |
| 6845 |
require_Len(t, 1, updateJwt(t, sc.clusterForName("C2").randomServer().ClientURL(), sysCreds, aJwtMap, 1)) |
| 6846 |
|
| 6847 |
time.Sleep(time.Second) |
| 6848 |
|
| 6849 |
foo, v1, v2 = 0, 0, 0 |
| 6850 |
pubAndCount() |
| 6851 |
if foo != 0 { |
| 6852 |
t.Fatalf("Expected foo to receive no message, got %v/1000", foo) |
| 6853 |
} |
| 6854 |
if v1 < 550 || v1 > 650 { |
| 6855 |
t.Fatalf("Expected v1 to receive 60%%, got %v/1000", v1) |
| 6856 |
} |
| 6857 |
if v2 < 350 || v2 > 450 { |
| 6858 |
t.Fatalf("Expected v2 to receive 40%%, got %v/1000", v2) |
| 6859 |
} |
| 6860 |
} |
| 6861 |
|
| 6862 |
func TestJWTServerOperatorModeNoAuthRequired(t *testing.T) { |
| 6863 |
_, spub := createKey(t) |
| 6864 |
sysClaim := jwt.NewAccountClaims(spub) |
| 6865 |
sysClaim.Name = "$SYS" |
| 6866 |
sysJwt, err := sysClaim.Encode(oKp) |
| 6867 |
require_NoError(t, err) |
| 6868 |
|
| 6869 |
akp, apub := createKey(t) |
| 6870 |
accClaim := jwt.NewAccountClaims(apub) |
| 6871 |
accClaim.Name = "TEST" |
| 6872 |
accJwt, err := accClaim.Encode(oKp) |
| 6873 |
require_NoError(t, err) |
| 6874 |
|
| 6875 |
ukp, _ := nkeys.CreateUser() |
| 6876 |
seed, _ := ukp.Seed() |
| 6877 |
upub, _ := ukp.PublicKey() |
| 6878 |
nuc := jwt.NewUserClaims(upub) |
| 6879 |
ujwt, err := nuc.Encode(akp) |
| 6880 |
require_NoError(t, err) |
| 6881 |
creds := genCredsFile(t, ujwt, seed) |
| 6882 |
|
| 6883 |
dirSrv := t.TempDir() |
| 6884 |
|
| 6885 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 6886 |
listen: 127.0.0.1:-1 |
| 6887 |
server_name: srv-A |
| 6888 |
operator: %s |
| 6889 |
system_account: %s |
| 6890 |
resolver: { |
| 6891 |
type: full |
| 6892 |
dir: '%s' |
| 6893 |
interval: "200ms" |
| 6894 |
limit: 4 |
| 6895 |
} |
| 6896 |
resolver_preload: { |
| 6897 |
%s: %s |
| 6898 |
%s: %s |
| 6899 |
} |
| 6900 |
`, ojwt, spub, dirSrv, spub, sysJwt, apub, accJwt))) |
| 6901 |
|
| 6902 |
s, _ := RunServerWithConfig(conf) |
| 6903 |
defer s.Shutdown() |
| 6904 |
|
| 6905 |
nc := natsConnect(t, s.ClientURL(), nats.UserCredentials(creds)) |
| 6906 |
defer nc.Close() |
| 6907 |
|
| 6908 |
require_True(t, nc.AuthRequired()) |
| 6909 |
} |
| 6910 |
|
| 6911 |
func TestJWTServerOperatorModeUserInfoExpiration(t *testing.T) { |
| 6912 |
_, spub := createKey(t) |
| 6913 |
sysClaim := jwt.NewAccountClaims(spub) |
| 6914 |
sysClaim.Name = "$SYS" |
| 6915 |
sysJwt, err := sysClaim.Encode(oKp) |
| 6916 |
require_NoError(t, err) |
| 6917 |
|
| 6918 |
akp, apub := createKey(t) |
| 6919 |
accClaim := jwt.NewAccountClaims(apub) |
| 6920 |
accClaim.Name = "TEST" |
| 6921 |
accJwt, err := accClaim.Encode(oKp) |
| 6922 |
require_NoError(t, err) |
| 6923 |
|
| 6924 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 6925 |
listen: 127.0.0.1:-1 |
| 6926 |
operator: %s |
| 6927 |
system_account: %s |
| 6928 |
resolver: MEM |
| 6929 |
resolver_preload: { |
| 6930 |
%s: %s |
| 6931 |
%s: %s |
| 6932 |
} |
| 6933 |
`, ojwt, spub, apub, accJwt, spub, sysJwt))) |
| 6934 |
defer removeFile(t, conf) |
| 6935 |
|
| 6936 |
s, _ := RunServerWithConfig(conf) |
| 6937 |
defer s.Shutdown() |
| 6938 |
|
| 6939 |
expires := time.Now().Add(time.Minute) |
| 6940 |
creds := createUserWithLimit(t, akp, expires, func(j *jwt.UserPermissionLimits) {}) |
| 6941 |
|
| 6942 |
nc := natsConnect(t, s.ClientURL(), nats.UserCredentials(creds)) |
| 6943 |
defer nc.Close() |
| 6944 |
|
| 6945 |
resp, err := nc.Request("$SYS.REQ.USER.INFO", nil, time.Second) |
| 6946 |
require_NoError(t, err) |
| 6947 |
now := time.Now() |
| 6948 |
|
| 6949 |
response := ServerAPIResponse{Data: &UserInfo{}} |
| 6950 |
err = json.Unmarshal(resp.Data, &response) |
| 6951 |
require_NoError(t, err) |
| 6952 |
|
| 6953 |
userInfo := response.Data.(*UserInfo) |
| 6954 |
require_True(t, userInfo.Expires != 0) |
| 6955 |
|
| 6956 |
// We need to round the expiration time to the second because the server |
| 6957 |
// will truncate the expiration time to the second. |
| 6958 |
expiresDurRounded := expires.Sub(now).Truncate(time.Second) |
| 6959 |
|
| 6960 |
// Checking range to avoid flaky tests where the expiration time is |
| 6961 |
// off by a couple of seconds. |
| 6962 |
require_True(t, expiresDurRounded >= userInfo.Expires-2*time.Second && expiresDurRounded <= userInfo.Expires+2*time.Second) |
| 6963 |
} |
| 6964 |
|
| 6965 |
func TestJWTAccountNATSResolverWrongCreds(t *testing.T) { |
| 6966 |
require_NoLocalOrRemoteConnections := func(account string, srvs ...*Server) { |
| 6967 |
t.Helper() |
| 6968 |
for _, srv := range srvs { |
| 6969 |
if acc, ok := srv.accounts.Load(account); ok { |
| 6970 |
checkAccClientsCount(t, acc.(*Account), 0) |
| 6971 |
} |
| 6972 |
} |
| 6973 |
} |
| 6974 |
connect := func(url string, credsfile string, acc string, srvs ...*Server) { |
| 6975 |
t.Helper() |
| 6976 |
nc := natsConnect(t, url, nats.UserCredentials(credsfile), nats.Timeout(5*time.Second)) |
| 6977 |
nc.Close() |
| 6978 |
require_NoLocalOrRemoteConnections(acc, srvs...) |
| 6979 |
} |
| 6980 |
createAccountAndUser := func(pubKey, jwt1, jwt2, creds *string) { |
| 6981 |
t.Helper() |
| 6982 |
kp, _ := nkeys.CreateAccount() |
| 6983 |
*pubKey, _ = kp.PublicKey() |
| 6984 |
claim := jwt.NewAccountClaims(*pubKey) |
| 6985 |
var err error |
| 6986 |
*jwt1, err = claim.Encode(oKp) |
| 6987 |
require_NoError(t, err) |
| 6988 |
*jwt2, err = claim.Encode(oKp) |
| 6989 |
require_NoError(t, err) |
| 6990 |
ukp, _ := nkeys.CreateUser() |
| 6991 |
seed, _ := ukp.Seed() |
| 6992 |
upub, _ := ukp.PublicKey() |
| 6993 |
uclaim := newJWTTestUserClaims() |
| 6994 |
uclaim.Subject = upub |
| 6995 |
ujwt, err := uclaim.Encode(kp) |
| 6996 |
require_NoError(t, err) |
| 6997 |
*creds = genCredsFile(t, ujwt, seed) |
| 6998 |
} |
| 6999 |
// Create Accounts and corresponding user creds. |
| 7000 |
var syspub, sysjwt, dummy1, sysCreds string |
| 7001 |
createAccountAndUser(&syspub, &sysjwt, &dummy1, &sysCreds) |
| 7002 |
|
| 7003 |
var apub, ajwt1, ajwt2, aCreds string |
| 7004 |
createAccountAndUser(&apub, &ajwt1, &ajwt2, &aCreds) |
| 7005 |
|
| 7006 |
var bpub, bjwt1, bjwt2, bCreds string |
| 7007 |
createAccountAndUser(&bpub, &bjwt1, &bjwt2, &bCreds) |
| 7008 |
|
| 7009 |
// The one that is going to be missing. |
| 7010 |
var cpub, cjwt1, cjwt2, cCreds string |
| 7011 |
createAccountAndUser(&cpub, &cjwt1, &cjwt2, &cCreds) |
| 7012 |
// Create one directory for each server |
| 7013 |
dirA := t.TempDir() |
| 7014 |
dirB := t.TempDir() |
| 7015 |
dirC := t.TempDir() |
| 7016 |
|
| 7017 |
// Store accounts on servers A and B, then let C sync on its own. |
| 7018 |
writeJWT(t, dirA, apub, ajwt1) |
| 7019 |
writeJWT(t, dirB, bpub, bjwt1) |
| 7020 |
|
| 7021 |
///////////////////////////////////////// |
| 7022 |
// // |
| 7023 |
// Server A: has creds from client A // |
| 7024 |
// // |
| 7025 |
///////////////////////////////////////// |
| 7026 |
confA := createConfFile(t, []byte(fmt.Sprintf(` |
| 7027 |
listen: 127.0.0.1:-1 |
| 7028 |
server_name: srv-A |
| 7029 |
operator: %s |
| 7030 |
system_account: %s |
| 7031 |
debug: true |
| 7032 |
resolver: { |
| 7033 |
type: full |
| 7034 |
dir: '%s' |
| 7035 |
allow_delete: true |
| 7036 |
timeout: "1.5s" |
| 7037 |
interval: "200ms" |
| 7038 |
} |
| 7039 |
resolver_preload: { |
| 7040 |
%s: %s |
| 7041 |
} |
| 7042 |
cluster { |
| 7043 |
name: clust |
| 7044 |
listen: 127.0.0.1:-1 |
| 7045 |
no_advertise: true |
| 7046 |
} |
| 7047 |
`, ojwt, syspub, dirA, apub, ajwt1))) |
| 7048 |
sA, _ := RunServerWithConfig(confA) |
| 7049 |
defer sA.Shutdown() |
| 7050 |
require_JWTPresent(t, dirA, apub) |
| 7051 |
|
| 7052 |
///////////////////////////////////////// |
| 7053 |
// // |
| 7054 |
// Server B: has creds from client B // |
| 7055 |
// // |
| 7056 |
///////////////////////////////////////// |
| 7057 |
confB := createConfFile(t, []byte(fmt.Sprintf(` |
| 7058 |
listen: 127.0.0.1:-1 |
| 7059 |
server_name: srv-B |
| 7060 |
operator: %s |
| 7061 |
system_account: %s |
| 7062 |
resolver: { |
| 7063 |
type: full |
| 7064 |
dir: '%s' |
| 7065 |
allow_delete: true |
| 7066 |
timeout: "1.5s" |
| 7067 |
interval: "200ms" |
| 7068 |
} |
| 7069 |
cluster { |
| 7070 |
name: clust |
| 7071 |
listen: 127.0.0.1:-1 |
| 7072 |
no_advertise: true |
| 7073 |
routes [ |
| 7074 |
nats-route://127.0.0.1:%d |
| 7075 |
] |
| 7076 |
} |
| 7077 |
`, ojwt, syspub, dirB, sA.opts.Cluster.Port))) |
| 7078 |
sB, _ := RunServerWithConfig(confB) |
| 7079 |
defer sB.Shutdown() |
| 7080 |
|
| 7081 |
///////////////////////////////////////// |
| 7082 |
// // |
| 7083 |
// Server C: has no creds // |
| 7084 |
// // |
| 7085 |
///////////////////////////////////////// |
| 7086 |
fmtC := ` |
| 7087 |
listen: 127.0.0.1:-1 |
| 7088 |
server_name: srv-C |
| 7089 |
operator: %s |
| 7090 |
system_account: %s |
| 7091 |
resolver: { |
| 7092 |
type: full |
| 7093 |
dir: '%s' |
| 7094 |
allow_delete: true |
| 7095 |
timeout: "1.5s" |
| 7096 |
interval: "200ms" |
| 7097 |
} |
| 7098 |
cluster { |
| 7099 |
name: clust |
| 7100 |
listen: 127.0.0.1:-1 |
| 7101 |
no_advertise: true |
| 7102 |
routes [ |
| 7103 |
nats-route://127.0.0.1:%d |
| 7104 |
] |
| 7105 |
} |
| 7106 |
` |
| 7107 |
confClongTTL := createConfFile(t, []byte(fmt.Sprintf(fmtC, ojwt, syspub, dirC, sA.opts.Cluster.Port))) |
| 7108 |
sC, _ := RunServerWithConfig(confClongTTL) // use long ttl to assure it is not kicking |
| 7109 |
defer sC.Shutdown() |
| 7110 |
|
| 7111 |
// startup cluster |
| 7112 |
checkClusterFormed(t, sA, sB, sC) |
| 7113 |
time.Sleep(1 * time.Second) // wait for the protocol to converge |
| 7114 |
// // Check all accounts |
| 7115 |
require_JWTPresent(t, dirA, apub) // was already present on startup |
| 7116 |
require_JWTPresent(t, dirB, apub) // was copied from server A |
| 7117 |
require_JWTPresent(t, dirA, bpub) // was copied from server B |
| 7118 |
require_JWTPresent(t, dirB, bpub) // was already present on startup |
| 7119 |
|
| 7120 |
// There should be no state about the missing account. |
| 7121 |
require_JWTAbsent(t, dirA, cpub) |
| 7122 |
require_JWTAbsent(t, dirB, cpub) |
| 7123 |
require_JWTAbsent(t, dirC, cpub) |
| 7124 |
|
| 7125 |
// system account client can connect to every server |
| 7126 |
connect(sA.ClientURL(), sysCreds, "") |
| 7127 |
connect(sB.ClientURL(), sysCreds, "") |
| 7128 |
connect(sC.ClientURL(), sysCreds, "") |
| 7129 |
|
| 7130 |
// A and B clients can connect to any server. |
| 7131 |
connect(sA.ClientURL(), aCreds, "") |
| 7132 |
connect(sB.ClientURL(), aCreds, "") |
| 7133 |
connect(sC.ClientURL(), aCreds, "") |
| 7134 |
connect(sA.ClientURL(), bCreds, "") |
| 7135 |
connect(sB.ClientURL(), bCreds, "") |
| 7136 |
connect(sC.ClientURL(), bCreds, "") |
| 7137 |
|
| 7138 |
// Check that trying to connect with bad credentials should not hang until the fetch timeout |
| 7139 |
// and instead return a faster response when an account is not found. |
| 7140 |
_, err := nats.Connect(sC.ClientURL(), nats.UserCredentials(cCreds), nats.Timeout(500*time.Second)) |
| 7141 |
if err != nil && !errors.Is(err, nats.ErrAuthorization) { |
| 7142 |
t.Fatalf("Expected auth error: %v", err) |
| 7143 |
} |
| 7144 |
} |
| 7145 |
|
| 7146 |
// Issue 5480: https://github.com/nats-io/nats-server/issues/5480 |
| 7147 |
func TestJWTImportsOnServerRestartAndClientsReconnect(t *testing.T) { |
| 7148 |
type namedCreds struct { |
| 7149 |
name string |
| 7150 |
creds nats.Option |
| 7151 |
} |
| 7152 |
preload := make(map[string]string) |
| 7153 |
users := make(map[string]*namedCreds) |
| 7154 |
|
| 7155 |
// sys account |
| 7156 |
_, sysAcc, sysAccClaim := NewJwtAccountClaim("sys") |
| 7157 |
sysAccJWT, err := sysAccClaim.Encode(oKp) |
| 7158 |
require_NoError(t, err) |
| 7159 |
preload[sysAcc] = sysAccJWT |
| 7160 |
|
| 7161 |
// main account, other accounts will import from this. |
| 7162 |
mainAccKP, mainAcc, mainAccClaim := NewJwtAccountClaim("main") |
| 7163 |
mainAccClaim.Exports.Add(&jwt.Export{ |
| 7164 |
Type: jwt.Stream, |
| 7165 |
Subject: "city.>", |
| 7166 |
}) |
| 7167 |
|
| 7168 |
// main account user |
| 7169 |
mainUserClaim := jwt.NewUserClaims("publisher") |
| 7170 |
mainUserClaim.Permissions = jwt.Permissions{ |
| 7171 |
Pub: jwt.Permission{ |
| 7172 |
Allow: []string{"city.>"}, |
| 7173 |
}, |
| 7174 |
} |
| 7175 |
mainCreds := createUserCredsEx(t, mainUserClaim, mainAccKP) |
| 7176 |
|
| 7177 |
// The main account will be importing from all other accounts. |
| 7178 |
maxAccounts := 100 |
| 7179 |
for i := 0; i < maxAccounts; i++ { |
| 7180 |
name := fmt.Sprintf("secondary-%d", i) |
| 7181 |
accKP, acc, accClaim := NewJwtAccountClaim(name) |
| 7182 |
|
| 7183 |
accClaim.Exports.Add(&jwt.Export{ |
| 7184 |
Type: jwt.Stream, |
| 7185 |
Subject: "internal.*", |
| 7186 |
}) |
| 7187 |
accClaim.Imports.Add(&jwt.Import{ |
| 7188 |
Type: jwt.Stream, |
| 7189 |
Subject: jwt.Subject(fmt.Sprintf("city.%d-1.*", i)), |
| 7190 |
Account: mainAcc, |
| 7191 |
}) |
| 7192 |
|
| 7193 |
// main account imports from the secondary accounts |
| 7194 |
mainAccClaim.Imports.Add(&jwt.Import{ |
| 7195 |
Type: jwt.Stream, |
| 7196 |
Subject: jwt.Subject(fmt.Sprintf("internal.%d", i)), |
| 7197 |
Account: acc, |
| 7198 |
}) |
| 7199 |
|
| 7200 |
accJWT, err := accClaim.Encode(oKp) |
| 7201 |
require_NoError(t, err) |
| 7202 |
preload[acc] = accJWT |
| 7203 |
|
| 7204 |
userClaim := jwt.NewUserClaims("subscriber") |
| 7205 |
userClaim.Permissions = jwt.Permissions{ |
| 7206 |
Sub: jwt.Permission{ |
| 7207 |
Allow: []string{"city.>", "internal.*"}, |
| 7208 |
}, |
| 7209 |
Pub: jwt.Permission{ |
| 7210 |
Allow: []string{"internal.*"}, |
| 7211 |
}, |
| 7212 |
} |
| 7213 |
userCreds := createUserCredsEx(t, userClaim, accKP) |
| 7214 |
users[acc] = &namedCreds{name, userCreds} |
| 7215 |
} |
| 7216 |
mainAccJWT, err := mainAccClaim.Encode(oKp) |
| 7217 |
require_NoError(t, err) |
| 7218 |
preload[mainAcc] = mainAccJWT |
| 7219 |
|
| 7220 |
// Start the server with the preload. |
| 7221 |
resolverPreload, err := json.Marshal(preload) |
| 7222 |
require_NoError(t, err) |
| 7223 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 7224 |
listen: 127.0.0.1:4747 |
| 7225 |
http: 127.0.0.1:8222 |
| 7226 |
operator: %s |
| 7227 |
system_account: %s |
| 7228 |
resolver: MEM |
| 7229 |
resolver_preload: %s |
| 7230 |
`, ojwt, sysAcc, string(resolverPreload)))) |
| 7231 |
s, _ := RunServerWithConfig(conf) |
| 7232 |
defer s.Shutdown() |
| 7233 |
|
| 7234 |
// Have a connection ready for each one of the accounts. |
| 7235 |
type namedSub struct { |
| 7236 |
name string |
| 7237 |
sub *nats.Subscription |
| 7238 |
} |
| 7239 |
subs := make(map[string]*namedSub) |
| 7240 |
for acc, user := range users { |
| 7241 |
nc := natsConnect(t, s.ClientURL(), user.creds, |
| 7242 |
// Make the clients attempt to reconnect too fast, |
| 7243 |
// changing this to be above ~200ms mitigates the issue. |
| 7244 |
nats.ReconnectWait(15*time.Millisecond), |
| 7245 |
nats.Name(user.name), |
| 7246 |
nats.MaxReconnects(-1), |
| 7247 |
) |
| 7248 |
defer nc.Close() |
| 7249 |
|
| 7250 |
sub, err := nc.SubscribeSync("city.>") |
| 7251 |
require_NoError(t, err) |
| 7252 |
subs[acc] = &namedSub{user.name, sub} |
| 7253 |
} |
| 7254 |
|
| 7255 |
nc := natsConnect(t, s.ClientURL(), mainCreds, nats.ReconnectWait(15*time.Millisecond), nats.MaxReconnects(-1)) |
| 7256 |
defer nc.Close() |
| 7257 |
|
| 7258 |
send := func(t *testing.T) { |
| 7259 |
t.Helper() |
| 7260 |
for i := 0; i < maxAccounts; i++ { |
| 7261 |
nc.Publish(fmt.Sprintf("city.%d-1.A4BDB048-69DC-4F10-916C-2B998249DC11", i), []byte(fmt.Sprintf("test:%d", i))) |
| 7262 |
} |
| 7263 |
nc.Flush() |
| 7264 |
} |
| 7265 |
|
| 7266 |
ctx, done := context.WithCancel(context.Background()) |
| 7267 |
defer done() |
| 7268 |
go func() { |
| 7269 |
for range time.NewTicker(200 * time.Millisecond).C { |
| 7270 |
select { |
| 7271 |
case <-ctx.Done(): |
| 7272 |
return |
| 7273 |
default: |
| 7274 |
} |
| 7275 |
send(t) |
| 7276 |
} |
| 7277 |
}() |
| 7278 |
|
| 7279 |
receive := func(t *testing.T) { |
| 7280 |
t.Helper() |
| 7281 |
received := 0 |
| 7282 |
for _, nsub := range subs { |
| 7283 |
// Drain first any pending messages. |
| 7284 |
pendingMsgs, _, _ := nsub.sub.Pending() |
| 7285 |
for i, _ := 0, 0; i < pendingMsgs; i++ { |
| 7286 |
nsub.sub.NextMsg(500 * time.Millisecond) |
| 7287 |
} |
| 7288 |
|
| 7289 |
_, err = nsub.sub.NextMsg(500 * time.Millisecond) |
| 7290 |
if err != nil { |
| 7291 |
t.Logf("WRN: Failed to receive message on account %q: %v", nsub.name, err) |
| 7292 |
} else { |
| 7293 |
received++ |
| 7294 |
} |
| 7295 |
} |
| 7296 |
if received < (maxAccounts / 2) { |
| 7297 |
t.Fatalf("Too many missed messages after restart. Received %d", received) |
| 7298 |
} |
| 7299 |
} |
| 7300 |
receive(t) |
| 7301 |
time.Sleep(1 * time.Second) |
| 7302 |
|
| 7303 |
restart := func(t *testing.T) *Server { |
| 7304 |
t.Helper() |
| 7305 |
s.Shutdown() |
| 7306 |
s.WaitForShutdown() |
| 7307 |
s, _ = RunServerWithConfig(conf) |
| 7308 |
|
| 7309 |
hctx, hcancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 7310 |
defer hcancel() |
| 7311 |
for range time.NewTicker(2 * time.Second).C { |
| 7312 |
select { |
| 7313 |
case <-hctx.Done(): |
| 7314 |
t.Logf("WRN: Timed out waiting for healthz from %s", s) |
| 7315 |
default: |
| 7316 |
} |
| 7317 |
|
| 7318 |
status := s.healthz(nil) |
| 7319 |
if status.StatusCode == 200 { |
| 7320 |
return s |
| 7321 |
} |
| 7322 |
} |
| 7323 |
return nil |
| 7324 |
} |
| 7325 |
|
| 7326 |
// Takes a few restarts for issue to show up. |
| 7327 |
for i := 0; i < 5; i++ { |
| 7328 |
s := restart(t) |
| 7329 |
defer s.Shutdown() |
| 7330 |
time.Sleep(2 * time.Second) |
| 7331 |
receive(t) |
| 7332 |
} |
| 7333 |
} |
| 7334 |
|
| 7335 |
func TestDefaultSentinelUser(t *testing.T) { |
| 7336 |
var err error |
| 7337 |
preload := make(map[string]string) |
| 7338 |
|
| 7339 |
_, sysPub, sysAC := NewJwtAccountClaim("SYS") |
| 7340 |
preload[sysPub], err = sysAC.Encode(oKp) |
| 7341 |
require_NoError(t, err) |
| 7342 |
|
| 7343 |
aKP, aPub, aAC := NewJwtAccountClaim("A") |
| 7344 |
aScopedKP, err := nkeys.CreateAccount() |
| 7345 |
require_NoError(t, err) |
| 7346 |
aScopedPK, err := aScopedKP.PublicKey() |
| 7347 |
require_NoError(t, err) |
| 7348 |
|
| 7349 |
sentinelScope := jwt.NewUserScope() |
| 7350 |
sentinelScope.Key = aScopedPK |
| 7351 |
sentinelScope.Role = "sentinel" |
| 7352 |
sentinelScope.Description = "Sentinel Role" |
| 7353 |
sentinelScope.Template = jwt.UserPermissionLimits{ |
| 7354 |
BearerToken: true, |
| 7355 |
Permissions: jwt.Permissions{ |
| 7356 |
Pub: jwt.Permission{Deny: []string{">"}}, |
| 7357 |
Sub: jwt.Permission{Deny: []string{">"}}, |
| 7358 |
}, |
| 7359 |
} |
| 7360 |
aAC.SigningKeys.AddScopedSigner(sentinelScope) |
| 7361 |
|
| 7362 |
preload[aPub], err = aAC.Encode(oKp) |
| 7363 |
require_NoError(t, err) |
| 7364 |
|
| 7365 |
preloadConfig, err := json.MarshalIndent(preload, "", " ") |
| 7366 |
require_NoError(t, err) |
| 7367 |
|
| 7368 |
// test that the user will be rejected |
| 7369 |
conf := createConfFile(t, []byte(fmt.Sprintf(` |
| 7370 |
listen: 127.0.0.1:4747 |
| 7371 |
operator: %s |
| 7372 |
system_account: %s |
| 7373 |
resolver: MEM |
| 7374 |
resolver_preload: %s |
| 7375 |
`, ojwt, sysPub, preloadConfig))) |
| 7376 |
|
| 7377 |
ns, _ := RunServerWithConfig(conf) |
| 7378 |
defer ns.Shutdown() |
| 7379 |
_, err = nats.Connect(ns.ClientURL(), nats.MaxReconnects(0)) |
| 7380 |
require_Error(t, err) |
| 7381 |
require_True(t, errors.Is(err, nats.ErrAuthorization)) |
| 7382 |
ns.Shutdown() |
| 7383 |
|
| 7384 |
// test that user can connect |
| 7385 |
uKP, err := nkeys.CreateUser() |
| 7386 |
require_NoError(t, err) |
| 7387 |
uPub, err := uKP.PublicKey() |
| 7388 |
require_NoError(t, err) |
| 7389 |
uc := jwt.NewUserClaims(uPub) |
| 7390 |
uc.BearerToken = false |
| 7391 |
uc.Name = "sentinel" |
| 7392 |
sentinelToken, err := uc.Encode(aKP) |
| 7393 |
require_NoError(t, err) |
| 7394 |
conf = createConfFile(t, []byte(fmt.Sprintf(` |
| 7395 |
listen: 127.0.0.1:4747 |
| 7396 |
operator: %s |
| 7397 |
system_account: %s |
| 7398 |
resolver: MEM |
| 7399 |
resolver_preload: %s |
| 7400 |
default_sentinel: %s |
| 7401 |
`, ojwt, sysPub, preloadConfig, sentinelToken))) |
| 7402 |
|
| 7403 |
// test non-bearer sentinel is rejected |
| 7404 |
opts, err := ProcessConfigFile(conf) |
| 7405 |
require_NoError(t, err) |
| 7406 |
_, err = NewServer(opts) |
| 7407 |
require_Error(t, err, fmt.Errorf("default sentinel must be a bearer token")) |
| 7408 |
|
| 7409 |
// correct and start server |
| 7410 |
uc.BearerToken = true |
| 7411 |
sentinelToken, err = uc.Encode(aKP) |
| 7412 |
require_NoError(t, err) |
| 7413 |
conf = createConfFile(t, []byte(fmt.Sprintf(` |
| 7414 |
listen: 127.0.0.1:4747 |
| 7415 |
operator: %s |
| 7416 |
system_account: %s |
| 7417 |
resolver: MEM |
| 7418 |
resolver_preload: %s |
| 7419 |
default_sentinel: %s |
| 7420 |
`, ojwt, sysPub, preloadConfig, sentinelToken))) |
| 7421 |
|
| 7422 |
ns, _ = RunServerWithConfig(conf) |
| 7423 |
nc, err := nats.Connect(ns.ClientURL()) |
| 7424 |
require_NoError(t, err) |
| 7425 |
defer nc.Close() |
| 7426 |
|
| 7427 |
r, err := nc.Request("$SYS.REQ.USER.INFO", nil, time.Second*5) |
| 7428 |
require_NoError(t, err) |
| 7429 |
type SR struct { |
| 7430 |
Data UserInfo `json:"data"` |
| 7431 |
} |
| 7432 |
var ui SR |
| 7433 |
require_NoError(t, json.Unmarshal(r.Data, &ui)) |
| 7434 |
require_Equal(t, ui.Data.UserID, uPub) |
| 7435 |
ns.Shutdown() |
| 7436 |
|
| 7437 |
// now lets make a sentinel that is a scoped user with bearer token |
| 7438 |
uc = jwt.NewUserClaims(uPub) |
| 7439 |
uc.IssuerAccount = aPub |
| 7440 |
uc.UserPermissionLimits = jwt.UserPermissionLimits{} |
| 7441 |
|
| 7442 |
sentinelToken, err = uc.Encode(aScopedKP) |
| 7443 |
require_NoError(t, err) |
| 7444 |
conf = createConfFile(t, []byte(fmt.Sprintf(` |
| 7445 |
listen: 127.0.0.1:4747 |
| 7446 |
operator: %s |
| 7447 |
system_account: %s |
| 7448 |
resolver: MEM |
| 7449 |
resolver_preload: %s |
| 7450 |
default_sentinel: %s |
| 7451 |
`, ojwt, sysPub, preloadConfig, sentinelToken))) |
| 7452 |
ns, _ = RunServerWithConfig(conf) |
| 7453 |
defer ns.Shutdown() |
| 7454 |
nc, err = nats.Connect(ns.ClientURL()) |
| 7455 |
require_NoError(t, err) |
| 7456 |
defer nc.Close() |
| 7457 |
|
| 7458 |
} |
| 7459 |
|
| 7460 |
func TestJWTUpdateAccountClaimsStreamAndServiceImportDeadlock(t *testing.T) { |
| 7461 |
for _, exportType := range []jwt.ExportType{jwt.Stream, jwt.Service} { |
| 7462 |
t.Run(exportType.String(), func(t *testing.T) { |
| 7463 |
s := opTrustBasicSetup() |
| 7464 |
defer s.Shutdown() |
| 7465 |
buildMemAccResolver(s) |
| 7466 |
|
| 7467 |
// Get operator. |
| 7468 |
okp, err := nkeys.FromSeed(oSeed) |
| 7469 |
require_NoError(t, err) |
| 7470 |
|
| 7471 |
type Acc struct { |
| 7472 |
pub string |
| 7473 |
ac *jwt.AccountClaims |
| 7474 |
a *Account |
| 7475 |
c *client |
| 7476 |
} |
| 7477 |
|
| 7478 |
// Create accounts. |
| 7479 |
var accs []*Acc |
| 7480 |
numAccounts := 10 |
| 7481 |
for i := 0; i < numAccounts; i++ { |
| 7482 |
aKp, err := nkeys.CreateAccount() |
| 7483 |
require_NoError(t, err) |
| 7484 |
aPub, err := aKp.PublicKey() |
| 7485 |
require_NoError(t, err) |
| 7486 |
aAC := jwt.NewAccountClaims(aPub) |
| 7487 |
aJWT, err := aAC.Encode(okp) |
| 7488 |
require_NoError(t, err) |
| 7489 |
addAccountToMemResolver(s, aPub, aJWT) |
| 7490 |
|
| 7491 |
aAcc, err := s.LookupAccount(aPub) |
| 7492 |
require_NoError(t, err) |
| 7493 |
|
| 7494 |
aAcc.mu.Lock() |
| 7495 |
c := aAcc.internalClient() |
| 7496 |
aAcc.mu.Unlock() |
| 7497 |
aAcc.addClient(c) |
| 7498 |
|
| 7499 |
accs = append(accs, &Acc{aPub, aAC, aAcc, c}) |
| 7500 |
} |
| 7501 |
|
| 7502 |
addImportExport := func(i int, acc *Acc) { |
| 7503 |
localSubject := fmt.Sprintf("%s.%d", acc.pub, i) |
| 7504 |
acc.ac.Exports.Add(&jwt.Export{Subject: jwt.Subject(localSubject), Type: exportType}) |
| 7505 |
for _, oAcc := range accs { |
| 7506 |
if acc.pub == oAcc.pub { |
| 7507 |
continue |
| 7508 |
} |
| 7509 |
externalSubject := fmt.Sprintf("%s.%d", oAcc.pub, i) |
| 7510 |
acc.ac.Imports.Add(&jwt.Import{Account: oAcc.pub, Subject: jwt.Subject(externalSubject), Type: exportType}) |
| 7511 |
} |
| 7512 |
} |
| 7513 |
test := func(i int) { |
| 7514 |
var start sync.WaitGroup |
| 7515 |
var release sync.WaitGroup |
| 7516 |
var finish sync.WaitGroup |
| 7517 |
start.Add(numAccounts) |
| 7518 |
release.Add(1) |
| 7519 |
finish.Add(numAccounts) |
| 7520 |
|
| 7521 |
// Add imports/exports to both accounts and update in parallel, should not deadlock. |
| 7522 |
for _, acc := range accs { |
| 7523 |
acc := acc |
| 7524 |
go func() { |
| 7525 |
defer finish.Done() |
| 7526 |
addImportExport(i, acc) |
| 7527 |
jwt, err := acc.ac.Encode(okp) |
| 7528 |
addAccountToMemResolver(s, acc.pub, jwt) |
| 7529 |
start.Done() |
| 7530 |
require_NoError(t, err) |
| 7531 |
|
| 7532 |
release.Wait() |
| 7533 |
s.UpdateAccountClaims(acc.a, acc.ac) |
| 7534 |
}() |
| 7535 |
} |
| 7536 |
|
| 7537 |
start.Wait() |
| 7538 |
|
| 7539 |
// Lock all clients, once we release below we'll get all claim updates |
| 7540 |
// in the same place after initial checks. |
| 7541 |
for _, acc := range accs { |
| 7542 |
acc.c.mu.Lock() |
| 7543 |
} |
| 7544 |
release.Done() |
| 7545 |
|
| 7546 |
// Wait some time for them to reach that point and be blocked on the client lock. |
| 7547 |
time.Sleep(time.Second) |
| 7548 |
for _, acc := range accs { |
| 7549 |
acc.c.mu.Unlock() |
| 7550 |
} |
| 7551 |
|
| 7552 |
// Eventually all goroutines should finish. |
| 7553 |
finish.Wait() |
| 7554 |
} |
| 7555 |
|
| 7556 |
// Repeat test multiple times, increasing the amount of imports/exports along the way. |
| 7557 |
for i := 0; i < 30; i++ { |
| 7558 |
test(i) |
| 7559 |
} |
| 7560 |
}) |
| 7561 |
} |
| 7562 |
} |
| 7563 |
|
| 7564 |
func TestJWTJetStreamClientsExcludedForMaxConnsUpdate(t *testing.T) { |
| 7565 |
sysKp, syspub := createKey(t) |
| 7566 |
sysJwt := encodeClaim(t, jwt.NewAccountClaims(syspub), syspub) |
| 7567 |
sysCreds := newUser(t, sysKp) |
| 7568 |
|
| 7569 |
accKp, accPub := createKey(t) |
| 7570 |
accClaim := jwt.NewAccountClaims(accPub) |
| 7571 |
accClaim.Name = "acc" |
| 7572 |
accClaim.Limits.JetStreamTieredLimits["R1"] = jwt.JetStreamLimits{ |
| 7573 |
DiskStorage: 1100, MemoryStorage: 0, Consumer: 2, Streams: 2} |
| 7574 |
accClaim.Limits.Conn = 5 |
| 7575 |
accJwt1 := encodeClaim(t, accClaim, accPub) |
| 7576 |
accCreds := newUser(t, accKp) |
| 7577 |
|
| 7578 |
storeDir := t.TempDir() |
| 7579 |
|
| 7580 |
dirSrv := t.TempDir() |
| 7581 |
cf := createConfFile(t, []byte(fmt.Sprintf(` |
| 7582 |
listen: 127.0.0.1:-1 |
| 7583 |
server_name: s1 |
| 7584 |
jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'} |
| 7585 |
leaf { |
| 7586 |
listen: 127.0.0.1:-1 |
| 7587 |
} |
| 7588 |
operator: %s |
| 7589 |
system_account: %s |
| 7590 |
resolver: { |
| 7591 |
type: full |
| 7592 |
dir: '%s' |
| 7593 |
} |
| 7594 |
`, storeDir, ojwt, syspub, dirSrv))) |
| 7595 |
|
| 7596 |
s, _ := RunServerWithConfig(cf) |
| 7597 |
defer s.Shutdown() |
| 7598 |
|
| 7599 |
updateJwt(t, s.ClientURL(), sysCreds, sysJwt, 1) |
| 7600 |
updateJwt(t, s.ClientURL(), sysCreds, accJwt1, 1) |
| 7601 |
|
| 7602 |
nc, js := jsClientConnectURL(t, s.ClientURL(), nats.UserCredentials(accCreds)) |
| 7603 |
defer nc.Close() |
| 7604 |
|
| 7605 |
_, err := js.AddStream(&nats.StreamConfig{Name: "TEST", Replicas: 1, Subjects: []string{"foo"}}) |
| 7606 |
require_NoError(t, err) |
| 7607 |
|
| 7608 |
_, err = js.Publish("foo", nil) |
| 7609 |
require_NoError(t, err) |
| 7610 |
|
| 7611 |
accClaim.Limits.Conn = 1 |
| 7612 |
accJwt1 = encodeClaim(t, accClaim, accPub) |
| 7613 |
updateJwt(t, s.ClientURL(), sysCreds, accJwt1, 1) |
| 7614 |
|
| 7615 |
// Manually reconnect. |
| 7616 |
nc.Close() |
| 7617 |
nc, js = jsClientConnectURL(t, s.ClientURL(), nats.UserCredentials(accCreds)) |
| 7618 |
defer nc.Close() |
| 7619 |
|
| 7620 |
_, err = js.Publish("foo", nil) |
| 7621 |
require_NoError(t, err) |
| 7622 |
} |
| 7623 |
|
| 7624 |
func TestJWTClusterUserInfoContainsPermissions(t *testing.T) { |
| 7625 |
tmpl := ` |
| 7626 |
listen: 127.0.0.1:-1 |
| 7627 |
server_name: %s |
| 7628 |
jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'} |
| 7629 |
cluster { |
| 7630 |
name: %s |
| 7631 |
listen: 127.0.0.1:%d |
| 7632 |
routes = [%s] |
| 7633 |
} |
| 7634 |
` |
| 7635 |
opFrag := ` |
| 7636 |
operator: %s |
| 7637 |
system_account: %s |
| 7638 |
resolver: { type: MEM } |
| 7639 |
resolver_preload = { |
| 7640 |
%s : %s |
| 7641 |
%s : %s |
| 7642 |
} |
| 7643 |
` |
| 7644 |
|
| 7645 |
_, syspub := createKey(t) |
| 7646 |
sysJwt := encodeClaim(t, jwt.NewAccountClaims(syspub), syspub) |
| 7647 |
|
| 7648 |
accKp, aExpPub := createKey(t) |
| 7649 |
accClaim := jwt.NewAccountClaims(aExpPub) |
| 7650 |
accClaim.DefaultPermissions.Sub = jwt.Permission{ |
| 7651 |
Deny: []string{"foo"}, |
| 7652 |
} |
| 7653 |
accJwt := encodeClaim(t, accClaim, aExpPub) |
| 7654 |
accCreds := newUser(t, accKp) |
| 7655 |
|
| 7656 |
template := tmpl + fmt.Sprintf(opFrag, ojwt, syspub, syspub, sysJwt, aExpPub, accJwt) |
| 7657 |
c := createJetStreamClusterWithTemplate(t, template, "R3S", 3) |
| 7658 |
defer c.shutdown() |
| 7659 |
|
| 7660 |
// Since it's a bit of a race whether the local server responds via the |
| 7661 |
// service import before a remote server does, we need to keep trying. |
| 7662 |
// In 1000 attempts it is quite easy to reproduce the problem. |
| 7663 |
test := func() { |
| 7664 |
nc, _ := jsClientConnect(t, c.randomServer(), nats.UserCredentials(accCreds)) |
| 7665 |
defer nc.Close() |
| 7666 |
|
| 7667 |
resp, err := nc.Request(userDirectInfoSubj, nil, time.Second) |
| 7668 |
require_NoError(t, err) |
| 7669 |
|
| 7670 |
response := ServerAPIResponse{Data: &UserInfo{}} |
| 7671 |
require_NoError(t, json.Unmarshal(resp.Data, &response)) |
| 7672 |
|
| 7673 |
userInfo := response.Data.(*UserInfo) |
| 7674 |
require_NotNil(t, userInfo.Permissions) |
| 7675 |
} |
| 7676 |
for range 1000 { |
| 7677 |
test() |
| 7678 |
} |
| 7679 |
} |
| 7680 |
|
| 7681 |
func TestJWTAccountLimitsOverflowInt32(t *testing.T) { |
| 7682 |
// Without clamping, int32 truncation of values > MaxInt32 causes: |
| 7683 |
// - mleafs/mconns wrapping to negative, triggering panics in |
| 7684 |
// updateRemoteServer (slice bounds out of range) and rejecting |
| 7685 |
// all connections. |
| 7686 |
fooAC := newJWTTestAccountClaims() |
| 7687 |
fooAC.Limits.Conn = math.MaxInt32 + 1 |
| 7688 |
fooAC.Limits.LeafNodeConn = math.MaxInt32 + 1 |
| 7689 |
fooAC.Limits.Subs = math.MaxInt32 + 1 |
| 7690 |
fooAC.Limits.Payload = math.MaxInt32 + 1 |
| 7691 |
|
| 7692 |
s, fooKP, c, _ := setupJWTTestWitAccountClaims(t, fooAC, "+OK") |
| 7693 |
defer s.Shutdown() |
| 7694 |
defer c.close() |
| 7695 |
|
| 7696 |
fooPub, _ := fooKP.PublicKey() |
| 7697 |
fooAcc, _ := s.LookupAccount(fooPub) |
| 7698 |
fooAcc.mu.RLock() |
| 7699 |
mconns := fooAcc.mconns |
| 7700 |
mleafs := fooAcc.mleafs |
| 7701 |
msubs := fooAcc.msubs |
| 7702 |
mpay := fooAcc.mpay |
| 7703 |
fooAcc.mu.RUnlock() |
| 7704 |
|
| 7705 |
// All account limits should be clamped to math.MaxInt32. |
| 7706 |
if mconns != math.MaxInt32 { |
| 7707 |
t.Fatalf("Expected account mconns to be MaxInt32 (%d), got %d", math.MaxInt32, mconns) |
| 7708 |
} |
| 7709 |
if mleafs != math.MaxInt32 { |
| 7710 |
t.Fatalf("Expected account mleafs to be MaxInt32 (%d), got %d", math.MaxInt32, mleafs) |
| 7711 |
} |
| 7712 |
if msubs != math.MaxInt32 { |
| 7713 |
t.Fatalf("Expected account msubs to be MaxInt32 (%d), got %d", math.MaxInt32, msubs) |
| 7714 |
} |
| 7715 |
if mpay != math.MaxInt32 { |
| 7716 |
t.Fatalf("Expected account mpay to be MaxInt32 (%d), got %d", math.MaxInt32, mpay) |
| 7717 |
} |
| 7718 |
|
| 7719 |
// Simulate a remote server update — without clamping this panics with: |
| 7720 |
// panic: runtime error: slice bounds out of range [2147483648:0] |
| 7721 |
clients := fooAcc.updateRemoteServer(&AccountNumConns{ |
| 7722 |
Server: ServerInfo{ |
| 7723 |
ID: "fake-server-1", |
| 7724 |
Name: "fake-nats-1", |
| 7725 |
}, |
| 7726 |
AccountStat: AccountStat{ |
| 7727 |
Account: fooPub, |
| 7728 |
Conns: 1, |
| 7729 |
LeafNodes: 1, |
| 7730 |
}, |
| 7731 |
}) |
| 7732 |
if len(clients) != 0 { |
| 7733 |
t.Fatalf("Expected no clients to disconnect, got %d", len(clients)) |
| 7734 |
} |
| 7735 |
} |
| 7736 |
|
| 7737 |
func TestJWTUserLimitsOverflowInt32SubPub(t *testing.T) { |
| 7738 |
t.Run("Subs", func(t *testing.T) { |
| 7739 |
nuc := newJWTTestUserClaims() |
| 7740 |
// Without clamping, int32(math.MaxInt32+1) wraps to MinInt32, |
| 7741 |
// making subsAtLimit() always true and blocking all subscriptions. |
| 7742 |
nuc.Limits.Subs = math.MaxInt32 + 1 |
| 7743 |
s, c, cr := setupJWTTestWithUserClaims(t, nuc, "+OK") |
| 7744 |
defer s.Shutdown() |
| 7745 |
defer c.close() |
| 7746 |
|
| 7747 |
expectPong(t, cr) |
| 7748 |
|
| 7749 |
// With clamping, subscriptions should succeed. |
| 7750 |
// Before, this would have been `-ERR 'maximum subscriptions exceeded` |
| 7751 |
c.parseAsync("SUB foo 1\r\nPING\r\n") |
| 7752 |
l, _ := cr.ReadString('\n') |
| 7753 |
if !strings.HasPrefix(l, "+OK") { |
| 7754 |
t.Fatalf("Expected +OK, got %q", l) |
| 7755 |
} |
| 7756 |
}) |
| 7757 |
|
| 7758 |
t.Run("Payload", func(t *testing.T) { |
| 7759 |
nuc := newJWTTestUserClaims() |
| 7760 |
// Without clamping, int32(math.MaxInt32+1) wraps to MinInt32, |
| 7761 |
// making int64(size) > int64(negative) always true and rejecting |
| 7762 |
// all publishes and closing the connection. |
| 7763 |
nuc.Limits.Payload = math.MaxInt32 + 1 |
| 7764 |
s, c, cr := setupJWTTestWithUserClaims(t, nuc, "+OK") |
| 7765 |
defer s.Shutdown() |
| 7766 |
defer c.close() |
| 7767 |
|
| 7768 |
expectPong(t, cr) |
| 7769 |
|
| 7770 |
// With clamping, publish should succeed. |
| 7771 |
// Before, this would have caused `-ERR 'Maximum Payload Violation'` |
| 7772 |
// then disconnect the client. |
| 7773 |
c.parseAsync("PUB baz 5\r\nhello\r\nPING\r\n") |
| 7774 |
l, _ := cr.ReadString('\n') |
| 7775 |
if !strings.HasPrefix(l, "+OK") { |
| 7776 |
t.Fatalf("Expected +OK, got %q", l) |
| 7777 |
} |
| 7778 |
}) |
| 7779 |
|
| 7780 |
t.Run("ScopedSigningKey", func(t *testing.T) { |
| 7781 |
// Without clamping in the scoped signing key path (client.go |
| 7782 |
// userScope.Template.Limits), int32 truncation of values > |
| 7783 |
// MaxInt32 would wrap to negative and reject all subs/publishes. |
| 7784 |
akp, _ := nkeys.CreateAccount() |
| 7785 |
apub, _ := akp.PublicKey() |
| 7786 |
nac := jwt.NewAccountClaims(apub) |
| 7787 |
|
| 7788 |
// Create a scoped signing key with overflow limits. |
| 7789 |
skp, _ := nkeys.CreateAccount() |
| 7790 |
spub, _ := skp.PublicKey() |
| 7791 |
scope := jwt.NewUserScope() |
| 7792 |
scope.Key = spub |
| 7793 |
scope.Template.Limits.Subs = math.MaxInt32 + 1 |
| 7794 |
scope.Template.Limits.Payload = math.MaxInt32 + 1 |
| 7795 |
nac.SigningKeys.AddScopedSigner(scope) |
| 7796 |
|
| 7797 |
ajwt, err := nac.Encode(oKp) |
| 7798 |
require_NoError(t, err) |
| 7799 |
|
| 7800 |
// Create user signed by the scoped signing key. |
| 7801 |
// SetScoped(true) clears UserPermissionLimits so the |
| 7802 |
// scope template is used instead of user claims. |
| 7803 |
ukp, _ := nkeys.CreateUser() |
| 7804 |
upub, _ := ukp.PublicKey() |
| 7805 |
nuc := jwt.NewUserClaims(upub) |
| 7806 |
nuc.IssuerAccount = apub |
| 7807 |
nuc.SetScoped(true) |
| 7808 |
ujwt, err := nuc.Encode(skp) |
| 7809 |
require_NoError(t, err) |
| 7810 |
|
| 7811 |
s := opTrustBasicSetup() |
| 7812 |
defer s.Shutdown() |
| 7813 |
buildMemAccResolver(s) |
| 7814 |
addAccountToMemResolver(s, apub, ajwt) |
| 7815 |
|
| 7816 |
c, cr, l := newClientForServer(s) |
| 7817 |
defer c.close() |
| 7818 |
|
| 7819 |
var info nonceInfo |
| 7820 |
json.Unmarshal([]byte(l[5:]), &info) |
| 7821 |
sigraw, _ := ukp.Sign([]byte(info.Nonce)) |
| 7822 |
sig := base64.RawURLEncoding.EncodeToString(sigraw) |
| 7823 |
|
| 7824 |
cs := fmt.Sprintf("CONNECT {\"jwt\":%q,\"sig\":\"%s\",\"verbose\":true,\"pedantic\":true}\r\nPING\r\n", ujwt, sig) |
| 7825 |
wg := sync.WaitGroup{} |
| 7826 |
wg.Add(1) |
| 7827 |
go func() { |
| 7828 |
c.parse([]byte(cs)) |
| 7829 |
wg.Done() |
| 7830 |
}() |
| 7831 |
l, _ = cr.ReadString('\n') |
| 7832 |
if !strings.HasPrefix(l, "+OK") { |
| 7833 |
t.Fatalf("Expected +OK on CONNECT, got %q", l) |
| 7834 |
} |
| 7835 |
wg.Wait() |
| 7836 |
expectPong(t, cr) |
| 7837 |
|
| 7838 |
// SUB must succeed — without clamping, msubs overflows to |
| 7839 |
// negative and subsAtLimit() always returns true. |
| 7840 |
c.parseAsync("SUB foo 1\r\nPING\r\n") |
| 7841 |
l, _ = cr.ReadString('\n') |
| 7842 |
if !strings.HasPrefix(l, "+OK") { |
| 7843 |
t.Fatalf("Expected +OK on SUB, got %q", l) |
| 7844 |
} |
| 7845 |
expectPong(t, cr) |
| 7846 |
|
| 7847 |
// PUB must succeed — without clamping, mpay overflows to |
| 7848 |
// negative and the payload check always triggers. |
| 7849 |
c.parseAsync("PUB baz 5\r\nhello\r\nPING\r\n") |
| 7850 |
l, _ = cr.ReadString('\n') |
| 7851 |
if !strings.HasPrefix(l, "+OK") { |
| 7852 |
t.Fatalf("Expected +OK on PUB, got %q", l) |
| 7853 |
} |
| 7854 |
}) |
| 7855 |
} |