Debian Codegraph @

server/accounts.go

raw
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 "bytes"
18 "cmp"
19 "encoding/hex"
20 "errors"
21 "fmt"
22 "io"
23 "io/fs"
24 "math"
25 "math/rand"
26 "net/http"
27 "net/textproto"
28 "reflect"
29 "slices"
30 "strconv"
31 "strings"
32 "sync"
33 "sync/atomic"
34 "time"
35
36 "github.com/nats-io/jwt/v2"
37 "github.com/nats-io/nats-server/v2/internal/fastrand"
38 "github.com/nats-io/nkeys"
39 "github.com/nats-io/nuid"
40 )
41
42 // For backwards compatibility with NATS < 2.0, users who are not explicitly defined into an
43 // account will be grouped in the default global account.
44 const globalAccountName = DEFAULT_GLOBAL_ACCOUNT
45
46 const defaultMaxSubLimitReportThreshold = int64(2 * time.Second)
47
48 var maxSubLimitReportThreshold = defaultMaxSubLimitReportThreshold
49
50 // Account are subject namespace definitions. By default no messages are shared between accounts.
51 // You can share via Exports and Imports of Streams and Services.
52 type Account struct {
53 // Total stats for the account.
54 stats struct {
55 sync.Mutex
56 stats // Totals
57 gw stats // Gateways
58 rt stats // Routes
59 ln stats // Leafnodes
60 }
61
62 gwReplyMapping
63 Name string
64 Nkey string
65 Issuer string
66 claimJWT string
67 updated time.Time
68 mu sync.RWMutex
69 smu sync.Mutex // serializes route interest updates
70 sl *Sublist
71 ic *client
72 sq *sendq
73 isid uint64
74 etmr *time.Timer
75 ctmr *time.Timer
76 strack map[string]sconns
77 nrclients int32
78 sysclients int32
79 nleafs int32
80 nrleafs int32
81 clients map[*client]struct{}
82 rm map[string]int32
83 lws map[string]int32 // per key, last rm[key] sent to routes; used to dedup sends
84 usersRevoked map[string]int64
85 mappings []*mapping
86 hasMapped atomic.Bool
87 lmu sync.RWMutex
88 lleafs []*client
89 leafClusters map[string]uint64
90 imports importMap
91 exports exportMap
92 js *jsAccount
93 jsLimits map[string]JetStreamAccountLimits
94 nrgAccount string
95 limits
96 expired atomic.Bool
97 incomplete bool
98 signingKeys map[string]jwt.Scope
99 extAuth *jwt.ExternalAuthorization
100 srv *Server // server this account is registered with (possibly nil)
101 lds string // loop detection subject for leaf nodes
102 siReply []byte // service reply prefix, will form wildcard subscription.
103 eventIds *nuid.NUID
104 eventIdsMu sync.Mutex
105 defaultPerms *Permissions
106 tags jwt.TagList
107 nameTag string
108 lastLimErr int64
109 routePoolIdx int
110 // If the trace destination is specified and a message with a traceParentHdr
111 // is received, and has the least significant bit of the last token set to 1,
112 // then if traceDestSampling is > 0 and < 100, a random value will be selected
113 // and if it falls between 0 and that value, message tracing will be triggered.
114 traceDest string
115 traceDestSampling int
116 // Guarantee that only one goroutine can be running either checkJetStreamMigrate
117 // or clearObserverState at a given time for this account to prevent interleaving.
118 jscmMu sync.Mutex
119 }
120
121 const (
122 accDedicatedRoute = -1
123 accTransitioningToDedicatedRoute = -2
124 )
125
126 // Account based limits.
127 type limits struct {
128 mpay int32
129 msubs int32
130 mconns int32
131 mleafs int32
132 disallowBearer bool
133 }
134
135 // Used to track remote clients and leafnodes per remote server.
136 type sconns struct {
137 conns int32
138 leafs int32
139 }
140
141 // clampInt64ToInt32 safely converts an int64 limit to int32,
142 // clamping values to the [math.MinInt32, math.MaxInt32] range.
143 func clampInt64ToInt32(v int64) int32 {
144 return int32(max(math.MinInt32, min(math.MaxInt32, v)))
145 }
146
147 // Import stream mapping struct
148 type streamImport struct {
149 acc *Account
150 from string
151 to string
152 tr *subjectTransform
153 rtr *subjectTransform
154 claim *jwt.Import
155 usePub bool
156 invalid bool
157 // This is `allow_trace` and when true and message tracing is happening,
158 // we will trace egresses past the account boundary, if `false`, we stop
159 // at the account boundary.
160 atrc bool
161 }
162
163 const ClientInfoHdr = "Nats-Request-Info"
164
165 // Import service mapping struct
166 type serviceImport struct {
167 acc *Account
168 claim *jwt.Import
169 se *serviceExport
170 sid []byte
171 from string
172 to string
173 tr *subjectTransform
174 ts int64
175 rt ServiceRespType
176 latency *serviceLatency
177 m1 *ServiceLatency
178 rc *client
179 mt *msgTrace
180 usePub bool
181 response bool
182 invalid bool
183 share bool
184 tracking bool
185 didDeliver bool
186 atrc bool // allow trace (got from service export)
187 trackingHdr http.Header // header from request
188 }
189
190 // This is used to record when we create a mapping for implicit service
191 // imports. We use this to clean up entries that are not singletons when
192 // we detect that interest is no longer present. The key to the map will
193 // be the actual interest. We record the mapped subject and the account.
194 type serviceRespEntry struct {
195 acc *Account
196 msub string
197 }
198
199 // rrIndexThreshold is the number of outstanding responses sharing a single
200 // reply subject above which we build an index for constant time removal.
201 // Reply subjects are normally unique per request, so the overwhelming majority
202 // of entries stay a one element list and never allocate the index.
203 const rrIndexThreshold = 16
204
205 // respEntries holds the outstanding response entries for one reply subject.
206 // The list is authoritative and unordered; idx, when present, maps a response
207 // subject to its position in the list. Once allocated the index is kept for as
208 // long as the reply subject has any entry left, since a subject that has been
209 // shared once tends to be shared again.
210 //
211 // This is held by value in importMap.rrMap, so mutating it means writing it
212 // back under its key. Add and remove entries through importMap.addRespEntry
213 // and importMap.removeRespEntry, which keep that write back in one place,
214 // rather than calling the methods below directly.
215 type respEntries struct {
216 list []*serviceRespEntry
217 idx map[string]int
218 }
219
220 // add appends an entry, building or maintaining the index as needed.
221 func (re *respEntries) add(sre *serviceRespEntry) {
222 re.list = append(re.list, sre)
223 if re.idx != nil {
224 re.idx[sre.msub] = len(re.list) - 1
225 return
226 }
227 if len(re.list) > rrIndexThreshold {
228 re.idx = make(map[string]int, len(re.list))
229 for i, e := range re.list {
230 re.idx[e.msub] = i
231 }
232 }
233 }
234
235 // remove drops the entry for msub, in constant time once indexed.
236 func (re *respEntries) remove(msub string) {
237 i := -1
238 if re.idx != nil {
239 var ok bool
240 if i, ok = re.idx[msub]; !ok {
241 return
242 }
243 delete(re.idx, msub)
244 } else {
245 for j, e := range re.list {
246 if e.msub == msub {
247 i = j
248 break
249 }
250 }
251 if i < 0 {
252 return
253 }
254 }
255 // Swap with the last entry so removal does not shift the whole list.
256 last := len(re.list) - 1
257 if i != last {
258 moved := re.list[last]
259 re.list[i] = moved
260 if re.idx != nil {
261 re.idx[moved.msub] = i
262 }
263 }
264 re.list[last] = nil
265 re.list = re.list[:last]
266 }
267
268 // ServiceRespType represents the types of service request response types.
269 type ServiceRespType uint8
270
271 // Service response types. Defaults to a singleton.
272 const (
273 Singleton ServiceRespType = iota
274 Streamed
275 Chunked
276 )
277
278 // String helper.
279 func (rt ServiceRespType) String() string {
280 switch rt {
281 case Singleton:
282 return "Singleton"
283 case Streamed:
284 return "Streamed"
285 case Chunked:
286 return "Chunked"
287 }
288 return "Unknown ServiceResType"
289 }
290
291 // exportAuth holds configured approvals or boolean indicating an
292 // auth token is required for import.
293 type exportAuth struct {
294 tokenReq bool
295 accountPos uint
296 approved map[string]*Account
297 actsRevoked map[string]int64
298 }
299
300 // streamExport
301 type streamExport struct {
302 exportAuth
303 }
304
305 // serviceExport holds additional information for exported services.
306 type serviceExport struct {
307 exportAuth
308 acc *Account
309 respType ServiceRespType
310 latency *serviceLatency
311 rtmr *time.Timer
312 respThresh time.Duration
313 // This is `allow_trace` and when true and message tracing is happening,
314 // when processing a service import we will go through account boundary
315 // and trace egresses on that other account. If `false`, we stop at the
316 // account boundary.
317 atrc bool
318 }
319
320 // Used to track service latency.
321 type serviceLatency struct {
322 sampling int8 // percentage from 1-100 or 0 to indicate triggered by header
323 subject string
324 }
325
326 // exportMap tracks the exported streams and services.
327 type exportMap struct {
328 streams map[string]*streamExport
329 services map[string]*serviceExport
330 responses map[string]*serviceImport
331 }
332
333 // importMap tracks the imported streams and services.
334 // For services we will also track the response mappings as well.
335 type importMap struct {
336 streams []*streamImport
337 services map[string][]*serviceImport
338 rrMap map[string]respEntries
339 }
340
341 // addRespEntry records an outstanding response entry under reply.
342 // Lock should be held on the owning account.
343 func (im *importMap) addRespEntry(reply string, sre *serviceRespEntry) {
344 if im.rrMap == nil {
345 im.rrMap = make(map[string]respEntries)
346 }
347 re := im.rrMap[reply]
348 re.add(sre)
349 im.rrMap[reply] = re
350 }
351
352 // removeRespEntry drops the outstanding response entry for msub under reply,
353 // dropping the reply subject itself once its last entry goes.
354 // Lock should be held on the owning account.
355 func (im *importMap) removeRespEntry(reply, msub string) {
356 re, ok := im.rrMap[reply]
357 if !ok {
358 return
359 }
360 re.remove(msub)
361 if len(re.list) == 0 {
362 delete(im.rrMap, reply)
363 } else {
364 im.rrMap[reply] = re
365 }
366 }
367
368 // NewAccount creates a new unlimited account with the given name.
369 func NewAccount(name string) *Account {
370 a := &Account{
371 Name: name,
372 limits: limits{-1, -1, -1, -1, false},
373 eventIds: nuid.New(),
374 }
375 return a
376 }
377
378 func (a *Account) String() string {
379 return a.Name
380 }
381
382 func (a *Account) setTraceDest(dest string) {
383 a.mu.Lock()
384 a.traceDest = dest
385 a.mu.Unlock()
386 }
387
388 func (a *Account) getTraceDestAndSampling() (string, int) {
389 a.mu.RLock()
390 dest := a.traceDest
391 sampling := a.traceDestSampling
392 a.mu.RUnlock()
393 return dest, sampling
394 }
395
396 // Used to create shallow copies of accounts for transfer
397 // from opts to real accounts in server struct.
398 // Account `na` write lock is expected to be held on entry
399 // while account `a` is the one from the Options struct
400 // being loaded/reloaded and do not need locking.
401 func (a *Account) shallowCopy(na *Account) {
402 na.Nkey = a.Nkey
403 na.Issuer = a.Issuer
404 na.traceDest, na.traceDestSampling = a.traceDest, a.traceDestSampling
405 na.nrgAccount = a.nrgAccount
406
407 if a.imports.streams != nil {
408 na.imports.streams = make([]*streamImport, 0, len(a.imports.streams))
409 for _, v := range a.imports.streams {
410 si := *v
411 na.imports.streams = append(na.imports.streams, &si)
412 }
413 }
414 if a.imports.services != nil {
415 na.imports.services = make(map[string][]*serviceImport)
416 for k, v := range a.imports.services {
417 sis := make([]*serviceImport, 0, len(v))
418 for _, si := range v {
419 csi := *si
420 sis = append(sis, &csi)
421 }
422 na.imports.services[k] = sis
423 }
424 }
425 if a.exports.streams != nil {
426 na.exports.streams = make(map[string]*streamExport)
427 for k, v := range a.exports.streams {
428 if v != nil {
429 se := *v
430 na.exports.streams[k] = &se
431 } else {
432 na.exports.streams[k] = nil
433 }
434 }
435 }
436 if a.exports.services != nil {
437 na.exports.services = make(map[string]*serviceExport)
438 for k, v := range a.exports.services {
439 if v != nil {
440 se := *v
441 na.exports.services[k] = &se
442 } else {
443 na.exports.services[k] = nil
444 }
445 }
446 }
447 na.mappings = a.mappings
448 na.hasMapped.Store(len(na.mappings) > 0)
449
450 // JetStream
451 na.jsLimits = a.jsLimits
452 // Server config account limits.
453 na.limits = a.limits
454 }
455
456 // nextEventID uses its own lock for better concurrency.
457 func (a *Account) nextEventID() string {
458 a.eventIdsMu.Lock()
459 id := a.eventIds.Next()
460 a.eventIdsMu.Unlock()
461 return id
462 }
463
464 // Returns a slice of clients stored in the account, or nil if none is present.
465 // Lock is held on entry.
466 func (a *Account) getClientsLocked() []*client {
467 if len(a.clients) == 0 {
468 return nil
469 }
470 clients := make([]*client, 0, len(a.clients))
471 for c := range a.clients {
472 clients = append(clients, c)
473 }
474 return clients
475 }
476
477 // Returns a slice of clients stored in the account, or nil if none is present.
478 func (a *Account) getClients() []*client {
479 a.mu.RLock()
480 clients := a.getClientsLocked()
481 a.mu.RUnlock()
482 return clients
483 }
484
485 // Returns a slice of external (non-internal) clients stored in the account, or nil if none is present.
486 // Lock is held on entry.
487 func (a *Account) getExternalClientsLocked() []*client {
488 if len(a.clients) == 0 {
489 return nil
490 }
491 var clients []*client
492 for c := range a.clients {
493 if !isInternalClient(c.kind) {
494 clients = append(clients, c)
495 }
496 }
497 return clients
498 }
499
500 // Called to track a remote server and connections and leafnodes it
501 // has for this account.
502 func (a *Account) updateRemoteServer(m *AccountNumConns) []*client {
503 a.mu.Lock()
504 if a.strack == nil {
505 a.strack = make(map[string]sconns)
506 }
507 // This does not depend on receiving all updates since each one is idempotent.
508 // FIXME(dlc) - We should cleanup when these both go to zero.
509 prev := a.strack[m.Server.ID]
510 a.strack[m.Server.ID] = sconns{conns: int32(m.Conns), leafs: int32(m.LeafNodes)}
511 a.nrclients += int32(m.Conns) - prev.conns
512 a.nrleafs += int32(m.LeafNodes) - prev.leafs
513
514 mtce := a.mconns != jwt.NoLimit && (len(a.clients)-int(a.sysclients)+int(a.nrclients) > int(a.mconns))
515 // If we are over here some have snuck in and we need to rebalance.
516 // All others will probably be doing the same thing but better to be
517 // conservative and bit harsh here. Clients will reconnect if we over compensate.
518 var clients []*client
519 if mtce {
520 clients = a.getExternalClientsLocked()
521
522 // Sort in reverse chronological.
523 slices.SortFunc(clients, func(i, j *client) int { return -i.start.Compare(j.start) })
524 over := (len(a.clients) - int(a.sysclients) + int(a.nrclients)) - int(a.mconns)
525 if over < len(clients) {
526 clients = clients[:over]
527 }
528 }
529 // Now check leafnodes.
530 mtlce := a.mleafs != jwt.NoLimit && (a.nleafs+a.nrleafs > a.mleafs)
531 if mtlce {
532 // Take ones from the end.
533 a.lmu.RLock()
534 leafs := a.lleafs
535 over := int(a.nleafs + a.nrleafs - a.mleafs)
536 if over < len(leafs) {
537 leafs = leafs[len(leafs)-over:]
538 }
539 clients = append(clients, leafs...)
540 a.lmu.RUnlock()
541 }
542 a.mu.Unlock()
543
544 // If we have exceeded our max clients this will be populated.
545 return clients
546 }
547
548 // Removes tracking for a remote server that has shutdown.
549 func (a *Account) removeRemoteServer(sid string) {
550 a.mu.Lock()
551 if a.strack != nil {
552 prev := a.strack[sid]
553 delete(a.strack, sid)
554 a.nrclients -= prev.conns
555 a.nrleafs -= prev.leafs
556 }
557 a.mu.Unlock()
558 }
559
560 // When querying for subject interest this is the number of
561 // expected responses. We need to actually check that the entry
562 // has active connections.
563 func (a *Account) expectedRemoteResponses() (expected int32) {
564 a.mu.RLock()
565 for _, sc := range a.strack {
566 if sc.conns > 0 || sc.leafs > 0 {
567 expected++
568 }
569 }
570 a.mu.RUnlock()
571 return
572 }
573
574 // Clears eventing and tracking for this account.
575 func (a *Account) clearEventing() {
576 a.mu.Lock()
577 a.nrclients = 0
578 // Now clear state
579 clearTimer(&a.etmr)
580 clearTimer(&a.ctmr)
581 a.clients = nil
582 a.strack = nil
583 a.mu.Unlock()
584 }
585
586 // GetName will return the accounts name.
587 func (a *Account) GetName() string {
588 if a == nil {
589 return "n/a"
590 }
591 a.mu.RLock()
592 name := a.Name
593 a.mu.RUnlock()
594 return name
595 }
596
597 // getNameTag will return the name tag or the account name if not set.
598 func (a *Account) getNameTag() string {
599 if a == nil {
600 return _EMPTY_
601 }
602 a.mu.RLock()
603 defer a.mu.RUnlock()
604 return a.getNameTagLocked()
605 }
606
607 // getNameTagLocked will return the name tag or the account name if not set.
608 // Lock should be held.
609 func (a *Account) getNameTagLocked() string {
610 if a == nil {
611 return _EMPTY_
612 }
613 nameTag := a.nameTag
614 if nameTag == _EMPTY_ {
615 nameTag = a.Name
616 }
617 return nameTag
618 }
619
620 // NumConnections returns active number of clients for this account for
621 // all known servers.
622 func (a *Account) NumConnections() int {
623 a.mu.RLock()
624 nc := len(a.clients) - int(a.sysclients) + int(a.nrclients)
625 a.mu.RUnlock()
626 return nc
627 }
628
629 // NumRemoteConnections returns the number of client or leaf connections that
630 // are not on this server.
631 func (a *Account) NumRemoteConnections() int {
632 a.mu.RLock()
633 nc := int(a.nrclients + a.nrleafs)
634 a.mu.RUnlock()
635 return nc
636 }
637
638 // NumLocalConnections returns active number of clients for this account
639 // on this server.
640 func (a *Account) NumLocalConnections() int {
641 a.mu.RLock()
642 nlc := a.numLocalConnections()
643 a.mu.RUnlock()
644 return nlc
645 }
646
647 // Do not account for the system accounts.
648 func (a *Account) numLocalConnections() int {
649 return len(a.clients) - int(a.sysclients) - int(a.nleafs)
650 }
651
652 // This is for extended local interest.
653 // Lock should not be held.
654 func (a *Account) numLocalAndLeafConnections() int {
655 a.mu.RLock()
656 nlc := len(a.clients) - int(a.sysclients)
657 a.mu.RUnlock()
658 return nlc
659 }
660
661 func (a *Account) numLocalLeafNodes() int {
662 return int(a.nleafs)
663 }
664
665 // MaxTotalConnectionsReached returns if we have reached our limit for number of connections.
666 func (a *Account) MaxTotalConnectionsReached() bool {
667 var mtce bool
668 a.mu.RLock()
669 if a.mconns != jwt.NoLimit {
670 mtce = len(a.clients)-int(a.sysclients)+int(a.nrclients) >= int(a.mconns)
671 }
672 a.mu.RUnlock()
673 return mtce
674 }
675
676 // MaxActiveConnections return the set limit for the account system
677 // wide for total number of active connections.
678 func (a *Account) MaxActiveConnections() int {
679 a.mu.RLock()
680 mconns := int(a.mconns)
681 a.mu.RUnlock()
682 return mconns
683 }
684
685 // MaxTotalLeafNodesReached returns if we have reached our limit for number of leafnodes.
686 func (a *Account) MaxTotalLeafNodesReached() bool {
687 a.mu.RLock()
688 mtc := a.maxTotalLeafNodesReached()
689 a.mu.RUnlock()
690 return mtc
691 }
692
693 func (a *Account) maxTotalLeafNodesReached() bool {
694 if a.mleafs != jwt.NoLimit {
695 return a.nleafs+a.nrleafs >= a.mleafs
696 }
697 return false
698 }
699
700 // NumLeafNodes returns the active number of local and remote
701 // leaf node connections.
702 func (a *Account) NumLeafNodes() int {
703 a.mu.RLock()
704 nln := int(a.nleafs + a.nrleafs)
705 a.mu.RUnlock()
706 return nln
707 }
708
709 // NumRemoteLeafNodes returns the active number of remote
710 // leaf node connections.
711 func (a *Account) NumRemoteLeafNodes() int {
712 a.mu.RLock()
713 nrn := int(a.nrleafs)
714 a.mu.RUnlock()
715 return nrn
716 }
717
718 // MaxActiveLeafNodes return the set limit for the account system
719 // wide for total number of leavenode connections.
720 // NOTE: these are tracked separately.
721 func (a *Account) MaxActiveLeafNodes() int {
722 a.mu.RLock()
723 mleafs := int(a.mleafs)
724 a.mu.RUnlock()
725 return mleafs
726 }
727
728 // RoutedSubs returns how many subjects we would send across a route when first
729 // connected or expressing interest. Local client subs.
730 func (a *Account) RoutedSubs() int {
731 a.mu.RLock()
732 defer a.mu.RUnlock()
733 return len(a.rm)
734 }
735
736 // TotalSubs returns total number of Subscriptions for this account.
737 func (a *Account) TotalSubs() int {
738 a.mu.RLock()
739 defer a.mu.RUnlock()
740 if a.sl == nil {
741 return 0
742 }
743 return int(a.sl.Count())
744 }
745
746 func (a *Account) shouldLogMaxSubErr() bool {
747 if a == nil {
748 return true
749 }
750 a.mu.RLock()
751 last := a.lastLimErr
752 a.mu.RUnlock()
753 if now := time.Now().UnixNano(); now-last >= maxSubLimitReportThreshold {
754 a.mu.Lock()
755 a.lastLimErr = now
756 a.mu.Unlock()
757 return true
758 }
759 return false
760 }
761
762 // MapDest is for mapping published subjects for clients.
763 type MapDest struct {
764 Subject string `json:"subject"`
765 Weight uint8 `json:"weight"`
766 Cluster string `json:"cluster,omitempty"`
767 }
768
769 func NewMapDest(subject string, weight uint8) *MapDest {
770 return &MapDest{subject, weight, _EMPTY_}
771 }
772
773 // destination is for internal representation for a weighted mapped destination.
774 type destination struct {
775 tr *subjectTransform
776 weight uint8
777 }
778
779 // mapping is an internal entry for mapping subjects.
780 type mapping struct {
781 src string
782 wc bool
783 dests []*destination
784 cdests map[string][]*destination
785 }
786
787 // AddMapping adds in a simple route mapping from src subject to dest subject
788 // for inbound client messages.
789 func (a *Account) AddMapping(src, dest string) error {
790 return a.AddWeightedMappings(src, NewMapDest(dest, 100))
791 }
792
793 // AddWeightedMappings will add in a weighted mappings for the destinations.
794 func (a *Account) AddWeightedMappings(src string, dests ...*MapDest) error {
795 a.mu.Lock()
796 defer a.mu.Unlock()
797
798 if !IsValidSubject(src) {
799 return ErrBadSubject
800 }
801
802 m := &mapping{src: src, wc: subjectHasWildcard(src), dests: make([]*destination, 0, len(dests)+1)}
803 seen := make(map[string]struct{})
804
805 var tw = make(map[string]uint8)
806 for _, d := range dests {
807 if _, ok := seen[d.Subject]; ok {
808 return fmt.Errorf("duplicate entry for %q", d.Subject)
809 }
810 seen[d.Subject] = struct{}{}
811 if d.Weight > 100 {
812 return fmt.Errorf("individual weights need to be <= 100")
813 }
814 tw[d.Cluster] += d.Weight
815 if tw[d.Cluster] > 100 {
816 return fmt.Errorf("total weight needs to be <= 100")
817 }
818 err := ValidateMapping(src, d.Subject)
819 if err != nil {
820 return err
821 }
822 tr, err := NewSubjectTransform(src, d.Subject)
823 if err != nil {
824 return err
825 }
826 if d.Cluster == _EMPTY_ {
827 m.dests = append(m.dests, &destination{tr, d.Weight})
828 } else {
829 // We have a cluster scoped filter.
830 if m.cdests == nil {
831 m.cdests = make(map[string][]*destination)
832 }
833 ad := m.cdests[d.Cluster]
834 ad = append(ad, &destination{tr, d.Weight})
835 m.cdests[d.Cluster] = ad
836 }
837 }
838
839 processDestinations := func(dests []*destination) ([]*destination, error) {
840 var ltw uint8
841 for _, d := range dests {
842 ltw += d.weight
843 }
844 // Auto add in original at weight difference if all entries weight does not total to 100.
845 // Iff the src was not already added in explicitly, meaning they want loss.
846 _, haveSrc := seen[src]
847 if ltw != 100 && !haveSrc {
848 dest := src
849 if m.wc {
850 // We need to make the appropriate markers for the wildcards etc.
851 dest = transformTokenize(dest)
852 }
853 tr, err := NewSubjectTransform(src, dest)
854 if err != nil {
855 return nil, err
856 }
857 aw := 100 - ltw
858 if len(dests) == 0 {
859 aw = 100
860 }
861 dests = append(dests, &destination{tr, aw})
862 }
863 slices.SortFunc(dests, func(i, j *destination) int { return cmp.Compare(i.weight, j.weight) })
864
865 var lw uint8
866 for _, d := range dests {
867 d.weight += lw
868 lw = d.weight
869 }
870 return dests, nil
871 }
872
873 var err error
874 if m.dests, err = processDestinations(m.dests); err != nil {
875 return err
876 }
877
878 // Option cluster scoped destinations
879 for cluster, dests := range m.cdests {
880 if dests, err = processDestinations(dests); err != nil {
881 return err
882 }
883 m.cdests[cluster] = dests
884 }
885
886 // Replace an old one if it exists.
887 for i, em := range a.mappings {
888 if em.src == src {
889 a.mappings[i] = m
890 return nil
891 }
892 }
893 // If we did not replace add to the end.
894 a.mappings = append(a.mappings, m)
895 a.hasMapped.Store(len(a.mappings) > 0)
896
897 // If we have connected leafnodes make sure to update.
898 if a.nleafs > 0 {
899 // Need to release because lock ordering is client -> account
900 a.mu.Unlock()
901 // Now grab the leaf list lock. We can hold client lock under this one.
902 a.lmu.RLock()
903 for _, lc := range a.lleafs {
904 lc.forceAddToSmap(src)
905 }
906 a.lmu.RUnlock()
907 a.mu.Lock()
908 }
909 return nil
910 }
911
912 // RemoveMapping will remove an existing mapping.
913 func (a *Account) RemoveMapping(src string) bool {
914 a.mu.Lock()
915 defer a.mu.Unlock()
916 for i, m := range a.mappings {
917 if m.src == src {
918 // Swap last one into this spot. Its ok to change order.
919 a.mappings[i] = a.mappings[len(a.mappings)-1]
920 a.mappings[len(a.mappings)-1] = nil // gc
921 a.mappings = a.mappings[:len(a.mappings)-1]
922 a.hasMapped.Store(len(a.mappings) > 0)
923 // If we have connected leafnodes make sure to update.
924 if a.nleafs > 0 {
925 // Need to release because lock ordering is client -> account
926 a.mu.Unlock()
927 // Now grab the leaf list lock. We can hold client lock under this one.
928 a.lmu.RLock()
929 for _, lc := range a.lleafs {
930 lc.forceRemoveFromSmap(src)
931 }
932 a.lmu.RUnlock()
933 a.mu.Lock()
934 }
935 return true
936 }
937 }
938 return false
939 }
940
941 // Indicates we have mapping entries.
942 func (a *Account) hasMappings() bool {
943 if a == nil {
944 return false
945 }
946 return a.hasMapped.Load()
947 }
948
949 // This performs the logic to map to a new dest subject based on mappings.
950 // Should only be called from processInboundClientMsg or service import processing.
951 func (a *Account) selectMappedSubject(dest string) (string, bool) {
952 if !a.hasMappings() {
953 return dest, false
954 }
955
956 a.mu.RLock()
957 // In case we have to tokenize for subset matching.
958 tsa := [32]string{}
959 tts := tsa[:0]
960
961 var m *mapping
962 for _, rm := range a.mappings {
963 if !rm.wc && rm.src == dest {
964 m = rm
965 break
966 } else {
967 // tokenize and reuse for subset matching.
968 if len(tts) == 0 {
969 start := 0
970 subject := dest
971 for i := 0; i < len(subject); i++ {
972 if subject[i] == btsep {
973 tts = append(tts, subject[start:i])
974 start = i + 1
975 }
976 }
977 tts = append(tts, subject[start:])
978 }
979 if isSubsetMatch(tts, rm.src) {
980 m = rm
981 break
982 }
983 }
984 }
985
986 if m == nil {
987 a.mu.RUnlock()
988 return dest, false
989 }
990
991 // The selected destination for the mapping.
992 var d *destination
993 var ndest string
994
995 dests := m.dests
996 if len(m.cdests) > 0 {
997 cn := a.srv.cachedClusterName()
998 dests = m.cdests[cn]
999 if dests == nil {
1000 // Fallback to main if we do not match the cluster.
1001 dests = m.dests
1002 }
1003 }
1004
1005 // Optimize for single entry case.
1006 if len(dests) == 1 && dests[0].weight == 100 {
1007 d = dests[0]
1008 } else {
1009 w := uint8(fastrand.Uint32n(100))
1010 for _, rm := range dests {
1011 if w < rm.weight {
1012 d = rm
1013 break
1014 }
1015 }
1016 }
1017
1018 if d != nil {
1019 if len(d.tr.dtokmftokindexesargs) == 0 {
1020 ndest = d.tr.dest
1021 } else {
1022 ndest = d.tr.TransformTokenizedSubject(tts)
1023 }
1024 }
1025
1026 a.mu.RUnlock()
1027 return ndest, true
1028 }
1029
1030 // SubscriptionInterest returns true if this account has a matching subscription
1031 // for the given `subject`.
1032 func (a *Account) SubscriptionInterest(subject string) bool {
1033 return a.Interest(subject) > 0
1034 }
1035
1036 // Interest returns the number of subscriptions for a given subject that match.
1037 func (a *Account) Interest(subject string) int {
1038 var nms int
1039 a.mu.RLock()
1040 if a.sl != nil {
1041 np, nq := a.sl.NumInterest(subject)
1042 nms = np + nq
1043 }
1044 a.mu.RUnlock()
1045 return nms
1046 }
1047
1048 // addClient keeps our accounting of local active clients or leafnodes updated.
1049 // Returns previous total.
1050 func (a *Account) addClient(c *client) int {
1051 a.mu.Lock()
1052 n := len(a.clients)
1053
1054 // Could come here earlier than the account is registered with the server.
1055 // Make sure we can still track clients.
1056 if a.clients == nil {
1057 a.clients = make(map[*client]struct{})
1058 }
1059 a.clients[c] = struct{}{}
1060
1061 // If we did not add it, we are done
1062 if n == len(a.clients) {
1063 a.mu.Unlock()
1064 return n
1065 }
1066 if c.kind != CLIENT && c.kind != LEAF {
1067 a.sysclients++
1068 } else if c.kind == LEAF {
1069 a.nleafs++
1070 }
1071 a.mu.Unlock()
1072
1073 // If we added a new leaf use the list lock and add it to the list.
1074 if c.kind == LEAF {
1075 a.lmu.Lock()
1076 a.lleafs = append(a.lleafs, c)
1077 a.lmu.Unlock()
1078 }
1079
1080 if c != nil && c.srv != nil {
1081 c.srv.accConnsUpdate(a)
1082 }
1083
1084 return n
1085 }
1086
1087 // For registering clusters for remote leafnodes.
1088 // We only register as the hub.
1089 func (a *Account) registerLeafNodeCluster(cluster string) {
1090 a.mu.Lock()
1091 defer a.mu.Unlock()
1092 if a.leafClusters == nil {
1093 a.leafClusters = make(map[string]uint64)
1094 }
1095 a.leafClusters[cluster]++
1096 }
1097
1098 // Check to see if we already have this cluster registered.
1099 func (a *Account) hasLeafNodeCluster(cluster string) bool {
1100 a.mu.RLock()
1101 defer a.mu.RUnlock()
1102 return a.leafClusters[cluster] > 0
1103 }
1104
1105 // Check to see if this cluster is isolated, meaning the only one.
1106 // Read Lock should be held.
1107 func (a *Account) isLeafNodeClusterIsolated(cluster string) bool {
1108 if cluster == _EMPTY_ {
1109 return false
1110 }
1111 if len(a.leafClusters) > 1 {
1112 return false
1113 }
1114 return a.leafClusters[cluster] == uint64(a.nleafs)
1115 }
1116
1117 // Helper function to remove leaf nodes. If number of leafnodes gets large
1118 // this may need to be optimized out of linear search but believe number
1119 // of active leafnodes per account scope to be small and therefore cache friendly.
1120 // Lock should not be held on general account lock.
1121 func (a *Account) removeLeafNode(c *client) {
1122 // Make sure we hold the list lock as well.
1123 a.lmu.Lock()
1124 defer a.lmu.Unlock()
1125
1126 ll := len(a.lleafs)
1127 for i, l := range a.lleafs {
1128 if l == c {
1129 a.lleafs[i] = a.lleafs[ll-1]
1130 if ll == 1 {
1131 a.lleafs = nil
1132 } else {
1133 a.lleafs = a.lleafs[:ll-1]
1134 }
1135 return
1136 }
1137 }
1138 }
1139
1140 // removeClient keeps our accounting of local active clients updated.
1141 func (a *Account) removeClient(c *client) int {
1142 a.mu.Lock()
1143 n := len(a.clients)
1144 delete(a.clients, c)
1145 // If we did not actually remove it, we are done.
1146 if n == len(a.clients) {
1147 a.mu.Unlock()
1148 return n
1149 }
1150 if c.kind != CLIENT && c.kind != LEAF {
1151 a.sysclients--
1152 } else if c.kind == LEAF {
1153 a.nleafs--
1154 // Need to do cluster accounting here.
1155 // Do cluster accounting if we are a hub.
1156 if c.isHubLeafNode() {
1157 cluster := c.remoteCluster()
1158 if count := a.leafClusters[cluster]; count > 1 {
1159 a.leafClusters[cluster]--
1160 } else if count == 1 {
1161 delete(a.leafClusters, cluster)
1162 }
1163 }
1164 }
1165 a.mu.Unlock()
1166
1167 if c.kind == LEAF {
1168 a.removeLeafNode(c)
1169 }
1170
1171 if c != nil && c.srv != nil {
1172 c.srv.accConnsUpdate(a)
1173 }
1174
1175 return n
1176 }
1177
1178 func setExportAuth(ea *exportAuth, subject string, accounts []*Account, accountPos uint) error {
1179 if accountPos > 0 {
1180 token := strings.Split(subject, tsep)
1181 if len(token) < int(accountPos) || token[accountPos-1] != "*" {
1182 return ErrInvalidSubject
1183 }
1184 }
1185 ea.accountPos = accountPos
1186 // empty means auth required but will be import token.
1187 if accounts == nil {
1188 return nil
1189 }
1190 if len(accounts) == 0 {
1191 ea.tokenReq = true
1192 return nil
1193 }
1194 if ea.approved == nil {
1195 ea.approved = make(map[string]*Account, len(accounts))
1196 }
1197 for _, acc := range accounts {
1198 ea.approved[acc.Name] = acc
1199 }
1200 return nil
1201 }
1202
1203 // AddServiceExport will configure the account with the defined export.
1204 func (a *Account) AddServiceExport(subject string, accounts []*Account) error {
1205 return a.addServiceExportWithResponseAndAccountPos(subject, Singleton, accounts, 0)
1206 }
1207
1208 // AddServiceExport will configure the account with the defined export.
1209 func (a *Account) addServiceExportWithAccountPos(subject string, accounts []*Account, accountPos uint) error {
1210 return a.addServiceExportWithResponseAndAccountPos(subject, Singleton, accounts, accountPos)
1211 }
1212
1213 // AddServiceExportWithResponse will configure the account with the defined export and response type.
1214 func (a *Account) AddServiceExportWithResponse(subject string, respType ServiceRespType, accounts []*Account) error {
1215 return a.addServiceExportWithResponseAndAccountPos(subject, respType, accounts, 0)
1216 }
1217
1218 // AddServiceExportWithresponse will configure the account with the defined export and response type.
1219 func (a *Account) addServiceExportWithResponseAndAccountPos(
1220 subject string, respType ServiceRespType, accounts []*Account, accountPos uint) error {
1221 if a == nil {
1222 return ErrMissingAccount
1223 }
1224
1225 a.mu.Lock()
1226 if a.exports.services == nil {
1227 a.exports.services = make(map[string]*serviceExport)
1228 }
1229
1230 se := a.exports.services[subject]
1231 // Always create a service export
1232 if se == nil {
1233 se = &serviceExport{}
1234 }
1235
1236 if respType != Singleton {
1237 se.respType = respType
1238 }
1239
1240 if accounts != nil || accountPos > 0 {
1241 if err := setExportAuth(&se.exportAuth, subject, accounts, accountPos); err != nil {
1242 a.mu.Unlock()
1243 return err
1244 }
1245 }
1246 lrt := a.lowestServiceExportResponseTime()
1247 se.acc = a
1248 se.respThresh = DEFAULT_SERVICE_EXPORT_RESPONSE_THRESHOLD
1249 a.exports.services[subject] = se
1250
1251 var clients []*client
1252 nlrt := a.lowestServiceExportResponseTime()
1253 if nlrt != lrt && len(a.clients) > 0 {
1254 clients = a.getClientsLocked()
1255 }
1256 // Need to release because lock ordering is client -> Account
1257 a.mu.Unlock()
1258 if len(clients) > 0 {
1259 updateAllClientsServiceExportResponseTime(clients, nlrt)
1260 }
1261 return nil
1262 }
1263
1264 // TrackServiceExport will enable latency tracking of the named service.
1265 // Results will be published in this account to the given results subject.
1266 func (a *Account) TrackServiceExport(service, results string) error {
1267 return a.TrackServiceExportWithSampling(service, results, DEFAULT_SERVICE_LATENCY_SAMPLING)
1268 }
1269
1270 // TrackServiceExportWithSampling will enable latency tracking of the named service for the given
1271 // sampling rate (1-100). Results will be published in this account to the given results subject.
1272 func (a *Account) TrackServiceExportWithSampling(service, results string, sampling int) error {
1273 if a == nil {
1274 return ErrMissingAccount
1275 }
1276
1277 if sampling != 0 { // 0 means triggered by header
1278 if sampling < 1 || sampling > 100 {
1279 return ErrBadSampling
1280 }
1281 }
1282 if !IsValidPublishSubject(results) {
1283 return ErrBadPublishSubject
1284 }
1285 // Don't loop back on outselves.
1286 if a.IsExportService(results) {
1287 return ErrBadPublishSubject
1288 }
1289
1290 if a.srv != nil && !a.srv.EventsEnabled() {
1291 return ErrNoSysAccount
1292 }
1293
1294 a.mu.Lock()
1295 if a.exports.services == nil {
1296 a.mu.Unlock()
1297 return ErrMissingService
1298 }
1299 ea, ok := a.exports.services[service]
1300 if !ok {
1301 a.mu.Unlock()
1302 return ErrMissingService
1303 }
1304 if ea == nil {
1305 ea = &serviceExport{}
1306 a.exports.services[service] = ea
1307 } else if ea.respType != Singleton {
1308 a.mu.Unlock()
1309 return ErrBadServiceType
1310 }
1311 ea.latency = &serviceLatency{
1312 sampling: int8(sampling),
1313 subject: results,
1314 }
1315 s := a.srv
1316 a.mu.Unlock()
1317
1318 if s == nil {
1319 return nil
1320 }
1321
1322 // Now track down the imports and add in latency as needed to enable.
1323 s.accounts.Range(func(k, v any) bool {
1324 acc := v.(*Account)
1325 acc.mu.Lock()
1326 for _, ims := range acc.imports.services {
1327 for _, im := range ims {
1328 if im != nil && im.acc.Name == a.Name && subjectIsSubsetMatch(im.to, service) {
1329 im.latency = ea.latency
1330 }
1331 }
1332 }
1333 acc.mu.Unlock()
1334 return true
1335 })
1336
1337 return nil
1338 }
1339
1340 // UnTrackServiceExport will disable latency tracking of the named service.
1341 func (a *Account) UnTrackServiceExport(service string) {
1342 if a == nil || (a.srv != nil && !a.srv.EventsEnabled()) {
1343 return
1344 }
1345
1346 a.mu.Lock()
1347 if a.exports.services == nil {
1348 a.mu.Unlock()
1349 return
1350 }
1351 ea, ok := a.exports.services[service]
1352 if !ok || ea == nil || ea.latency == nil {
1353 a.mu.Unlock()
1354 return
1355 }
1356 // We have latency here.
1357 ea.latency = nil
1358 s := a.srv
1359 a.mu.Unlock()
1360
1361 if s == nil {
1362 return
1363 }
1364
1365 // Now track down the imports and clean them up.
1366 s.accounts.Range(func(k, v any) bool {
1367 acc := v.(*Account)
1368 acc.mu.Lock()
1369 for _, ims := range acc.imports.services {
1370 for _, im := range ims {
1371 if im != nil && im.acc.Name == a.Name {
1372 if subjectIsSubsetMatch(im.to, service) {
1373 im.latency, im.m1 = nil, nil
1374 }
1375 }
1376 }
1377 }
1378 acc.mu.Unlock()
1379 return true
1380 })
1381 }
1382
1383 // IsExportService will indicate if this service exists. Will check wildcard scenarios.
1384 func (a *Account) IsExportService(service string) bool {
1385 a.mu.RLock()
1386 defer a.mu.RUnlock()
1387 _, ok := a.exports.services[service]
1388 if ok {
1389 return true
1390 }
1391 tokens := strings.Split(service, tsep)
1392 for subj := range a.exports.services {
1393 if isSubsetMatch(tokens, subj) {
1394 return true
1395 }
1396 }
1397 return false
1398 }
1399
1400 // IsExportServiceTracking will indicate if given publish subject is an export service with tracking enabled.
1401 func (a *Account) IsExportServiceTracking(service string) bool {
1402 a.mu.RLock()
1403 ea, ok := a.exports.services[service]
1404 if ok && ea == nil {
1405 a.mu.RUnlock()
1406 return false
1407 }
1408 if ok && ea != nil && ea.latency != nil {
1409 a.mu.RUnlock()
1410 return true
1411 }
1412 // FIXME(dlc) - Might want to cache this is in the hot path checking for latency tracking.
1413 tokens := strings.Split(service, tsep)
1414 for subj, ea := range a.exports.services {
1415 if isSubsetMatch(tokens, subj) && ea != nil && ea.latency != nil {
1416 a.mu.RUnlock()
1417 return true
1418 }
1419 }
1420 a.mu.RUnlock()
1421 return false
1422 }
1423
1424 // ServiceLatency is the JSON message sent out in response to latency tracking for
1425 // an accounts exported services. Additional client info is available in requestor
1426 // and responder. Note that for a requestor, the only information shared by default
1427 // is the RTT used to calculate the total latency. The requestor's account can
1428 // designate to share the additional information in the service import.
1429 type ServiceLatency struct {
1430 TypedEvent
1431 Status int `json:"status"`
1432 Error string `json:"description,omitempty"`
1433 Requestor *ClientInfo `json:"requestor,omitempty"`
1434 Responder *ClientInfo `json:"responder,omitempty"`
1435 RequestHeader http.Header `json:"header,omitempty"` // only contains header(s) triggering the measurement
1436 RequestStart time.Time `json:"start"`
1437 ServiceLatency time.Duration `json:"service"`
1438 SystemLatency time.Duration `json:"system"`
1439 TotalLatency time.Duration `json:"total"`
1440 }
1441
1442 // ServiceLatencyType is the NATS Event Type for ServiceLatency
1443 const ServiceLatencyType = "io.nats.server.metric.v1.service_latency"
1444
1445 // NATSTotalTime is a helper function that totals the NATS latencies.
1446 func (m1 *ServiceLatency) NATSTotalTime() time.Duration {
1447 return m1.Requestor.RTT + m1.Responder.RTT + m1.SystemLatency
1448 }
1449
1450 // Merge function to merge m1 and m2 (requestor and responder) measurements
1451 // when there are two samples. This happens when the requestor and responder
1452 // are on different servers.
1453 //
1454 // m2 ServiceLatency is correct, so use that.
1455 // m1 TotalLatency is correct, so use that.
1456 // Will use those to back into NATS latency.
1457 func (m1 *ServiceLatency) merge(m2 *ServiceLatency) {
1458 rtt := time.Duration(0)
1459 if m2.Responder != nil {
1460 rtt = m2.Responder.RTT
1461 }
1462 m1.SystemLatency = m1.ServiceLatency - (m2.ServiceLatency + rtt)
1463 m1.ServiceLatency = m2.ServiceLatency
1464 m1.Responder = m2.Responder
1465 sanitizeLatencyMetric(m1)
1466 }
1467
1468 // sanitizeLatencyMetric adjusts latency metric values that could go
1469 // negative in some edge conditions since we estimate client RTT
1470 // for both requestor and responder.
1471 // These numbers are never meant to be negative, it just could be
1472 // how we back into the values based on estimated RTT.
1473 func sanitizeLatencyMetric(sl *ServiceLatency) {
1474 if sl.ServiceLatency < 0 {
1475 sl.ServiceLatency = 0
1476 }
1477 if sl.SystemLatency < 0 {
1478 sl.SystemLatency = 0
1479 }
1480 }
1481
1482 // Used for transporting remote latency measurements.
1483 type remoteLatency struct {
1484 Account string `json:"account"`
1485 ReqId string `json:"req_id"`
1486 M2 ServiceLatency `json:"m2"`
1487 respThresh time.Duration
1488 }
1489
1490 // sendLatencyResult will send a latency result and clear the si of the requestor(rc).
1491 func (a *Account) sendLatencyResult(si *serviceImport, sl *ServiceLatency) {
1492 sl.Type = ServiceLatencyType
1493 sl.ID = a.nextEventID()
1494 sl.Time = time.Now().UTC()
1495 a.mu.Lock()
1496 lsubj := si.latency.subject
1497 si.rc = nil
1498 a.mu.Unlock()
1499
1500 a.srv.sendInternalAccountMsg(a, lsubj, sl)
1501 }
1502
1503 // Used to send a bad request metric when we do not have a reply subject
1504 func (a *Account) sendBadRequestTrackingLatency(si *serviceImport, requestor *client, header http.Header) {
1505 sl := &ServiceLatency{
1506 Status: 400,
1507 Error: "Bad Request",
1508 Requestor: requestor.getClientInfo(si.share),
1509 }
1510 sl.RequestHeader = header
1511 sl.RequestStart = time.Now().Add(-sl.Requestor.RTT).UTC()
1512 a.sendLatencyResult(si, sl)
1513 }
1514
1515 // Used to send a latency result when the requestor interest was lost before the
1516 // response could be delivered.
1517 func (a *Account) sendReplyInterestLostTrackLatency(si *serviceImport) {
1518 sl := &ServiceLatency{
1519 Status: 408,
1520 Error: "Request Timeout",
1521 }
1522 a.mu.RLock()
1523 rc, share, ts := si.rc, si.share, si.ts
1524 sl.RequestHeader = si.trackingHdr
1525 a.mu.RUnlock()
1526 if rc != nil {
1527 sl.Requestor = rc.getClientInfo(share)
1528 }
1529 var reqRTT time.Duration
1530 if sl.Requestor != nil {
1531 reqRTT = sl.Requestor.RTT
1532 }
1533 sl.RequestStart = time.Unix(0, ts-int64(reqRTT)).UTC()
1534 a.sendLatencyResult(si, sl)
1535 }
1536
1537 func (a *Account) sendBackendErrorTrackingLatency(si *serviceImport, reason rsiReason) {
1538 sl := &ServiceLatency{}
1539 a.mu.RLock()
1540 rc, share, ts := si.rc, si.share, si.ts
1541 sl.RequestHeader = si.trackingHdr
1542 a.mu.RUnlock()
1543 if rc != nil {
1544 sl.Requestor = rc.getClientInfo(share)
1545 }
1546 var reqRTT time.Duration
1547 if sl.Requestor != nil {
1548 reqRTT = sl.Requestor.RTT
1549 }
1550 sl.RequestStart = time.Unix(0, ts-int64(reqRTT)).UTC()
1551 if reason == rsiNoDelivery {
1552 sl.Status = 503
1553 sl.Error = "Service Unavailable"
1554 } else if reason == rsiTimeout {
1555 sl.Status = 504
1556 sl.Error = "Service Timeout"
1557 }
1558 a.sendLatencyResult(si, sl)
1559 }
1560
1561 // sendTrackingLatency will send out the appropriate tracking information for the
1562 // service request/response latency. This is called when the requestor's server has
1563 // received the response.
1564 // TODO(dlc) - holding locks for RTTs may be too much long term. Should revisit.
1565 func (a *Account) sendTrackingLatency(si *serviceImport, responder *client) bool {
1566 a.mu.RLock()
1567 rc, share, siTs := si.rc, si.share, si.ts
1568 a.mu.RUnlock()
1569 if rc == nil {
1570 return true
1571 }
1572
1573 ts := time.Now()
1574 serviceRTT := time.Duration(ts.UnixNano() - siTs)
1575 requestor := rc
1576
1577 sl := &ServiceLatency{
1578 Status: 200,
1579 Requestor: requestor.getClientInfo(share),
1580 Responder: responder.getClientInfo(true),
1581 }
1582 var respRTT, reqRTT time.Duration
1583 if sl.Responder != nil {
1584 respRTT = sl.Responder.RTT
1585 }
1586 if sl.Requestor != nil {
1587 reqRTT = sl.Requestor.RTT
1588 }
1589 sl.RequestStart = time.Unix(0, siTs-int64(reqRTT)).UTC()
1590 sl.ServiceLatency = serviceRTT - respRTT
1591 sl.TotalLatency = reqRTT + serviceRTT
1592 if respRTT > 0 {
1593 sl.SystemLatency = time.Since(ts)
1594 sl.TotalLatency += sl.SystemLatency
1595 }
1596 sl.RequestHeader = si.trackingHdr
1597 sanitizeLatencyMetric(sl)
1598
1599 sl.Type = ServiceLatencyType
1600 sl.ID = a.nextEventID()
1601 sl.Time = time.Now().UTC()
1602
1603 // If we are expecting a remote measurement, store our sl here.
1604 // We need to account for the race between this and us receiving the
1605 // remote measurement.
1606 // FIXME(dlc) - We need to clean these up but this should happen
1607 // already with the auto-expire logic.
1608 if responder != nil && responder.kind != CLIENT {
1609 si.acc.mu.Lock()
1610 if si.m1 != nil {
1611 m1, m2 := sl, si.m1
1612 m1.merge(m2)
1613 si.acc.mu.Unlock()
1614 a.srv.sendInternalAccountMsg(a, si.latency.subject, m1)
1615 a.mu.Lock()
1616 si.rc = nil
1617 a.mu.Unlock()
1618 return true
1619 }
1620 si.m1 = sl
1621 si.acc.mu.Unlock()
1622 return false
1623 } else {
1624 a.srv.sendInternalAccountMsg(a, si.latency.subject, sl)
1625 a.mu.Lock()
1626 si.rc = nil
1627 a.mu.Unlock()
1628 }
1629 return true
1630 }
1631
1632 // This will check to make sure our response lower threshold is set
1633 // properly in any clients doing rrTracking.
1634 func updateAllClientsServiceExportResponseTime(clients []*client, lrt time.Duration) {
1635 for _, c := range clients {
1636 c.mu.Lock()
1637 if c.rrTracking != nil && lrt != c.rrTracking.lrt {
1638 c.rrTracking.lrt = lrt
1639 if c.rrTracking.ptmr.Stop() {
1640 c.rrTracking.ptmr.Reset(lrt)
1641 }
1642 }
1643 c.mu.Unlock()
1644 }
1645 }
1646
1647 // Will select the lowest respThresh from all service exports.
1648 // Read lock should be held.
1649 func (a *Account) lowestServiceExportResponseTime() time.Duration {
1650 // Lowest we will allow is 5 minutes. Its an upper bound for this function.
1651 lrt := 5 * time.Minute
1652 for _, se := range a.exports.services {
1653 if se.respThresh < lrt {
1654 lrt = se.respThresh
1655 }
1656 }
1657 return lrt
1658 }
1659
1660 // AddServiceImportWithClaim will add in the service import via the jwt claim.
1661 func (a *Account) AddServiceImportWithClaim(destination *Account, from, to string, imClaim *jwt.Import) error {
1662 return a.addServiceImportWithClaim(destination, from, to, imClaim, false)
1663 }
1664
1665 // addServiceImportWithClaim will add in the service import via the jwt claim.
1666 // It will also skip the authorization check in cases where internal is true
1667 func (a *Account) addServiceImportWithClaim(destination *Account, from, to string, imClaim *jwt.Import, internal bool) error {
1668 if destination == nil {
1669 return ErrMissingAccount
1670 }
1671 // Empty means use from.
1672 if to == _EMPTY_ {
1673 to = from
1674 }
1675 if !IsValidSubject(from) || !IsValidSubject(to) {
1676 return ErrInvalidSubject
1677 }
1678
1679 // First check to see if the account has authorized us to route to the "to" subject.
1680 if !internal && !destination.checkServiceImportAuthorized(a, to, imClaim) {
1681 return ErrServiceImportAuthorization
1682 }
1683
1684 // Check if this introduces a cycle before proceeding.
1685 // From will be the mapped subject.
1686 // If the 'to' has a wildcard make sure we pre-transform the 'from' before we check for cycles, e.g. '$1'
1687 fromT := from
1688 if subjectHasWildcard(to) {
1689 fromT, _ = transformUntokenize(from)
1690 }
1691 if err := a.serviceImportFormsCycle(destination, fromT); err != nil {
1692 return err
1693 }
1694
1695 _, err := a.addServiceImport(destination, from, to, imClaim)
1696
1697 return err
1698 }
1699
1700 const MaxAccountCycleSearchDepth = 1024
1701
1702 func (a *Account) serviceImportFormsCycle(dest *Account, from string) error {
1703 return dest.checkServiceImportsForCycles(from, map[string]bool{a.Name: true})
1704 }
1705
1706 func (a *Account) checkServiceImportsForCycles(from string, visited map[string]bool) error {
1707 if len(visited) >= MaxAccountCycleSearchDepth {
1708 return ErrCycleSearchDepth
1709 }
1710 a.mu.RLock()
1711 for _, sis := range a.imports.services {
1712 for _, si := range sis {
1713 if SubjectsCollide(from, si.to) {
1714 a.mu.RUnlock()
1715 if visited[si.acc.Name] {
1716 return ErrImportFormsCycle
1717 }
1718 // Push ourselves and check si.acc
1719 visited[a.Name] = true
1720 // Make a copy to not overwrite the passed value.
1721 f := from
1722 if subjectIsSubsetMatch(si.from, f) {
1723 f = si.from
1724 }
1725 if err := si.acc.checkServiceImportsForCycles(f, visited); err != nil {
1726 return err
1727 }
1728 a.mu.RLock()
1729 }
1730 }
1731 }
1732 a.mu.RUnlock()
1733 return nil
1734 }
1735
1736 func (a *Account) streamImportFormsCycle(dest *Account, to string) error {
1737 return dest.checkStreamImportsForCycles(to, map[string]bool{a.Name: true})
1738 }
1739
1740 // Lock should be held.
1741 func (a *Account) hasServiceExportMatching(to string) bool {
1742 for subj := range a.exports.services {
1743 if subjectIsSubsetMatch(to, subj) {
1744 return true
1745 }
1746 }
1747 return false
1748 }
1749
1750 // Lock should be held.
1751 func (a *Account) hasStreamExportMatching(to string) bool {
1752 for subj := range a.exports.streams {
1753 if subjectIsSubsetMatch(to, subj) {
1754 return true
1755 }
1756 }
1757 return false
1758 }
1759
1760 func (a *Account) checkStreamImportsForCycles(to string, visited map[string]bool) error {
1761 if len(visited) >= MaxAccountCycleSearchDepth {
1762 return ErrCycleSearchDepth
1763 }
1764
1765 a.mu.RLock()
1766
1767 if !a.hasStreamExportMatching(to) {
1768 a.mu.RUnlock()
1769 return nil
1770 }
1771
1772 for _, si := range a.imports.streams {
1773 if SubjectsCollide(to, si.to) {
1774 a.mu.RUnlock()
1775 if visited[si.acc.Name] {
1776 return ErrImportFormsCycle
1777 }
1778 // Push ourselves and check si.acc
1779 visited[a.Name] = true
1780 // Make a copy to not overwrite the passed value.
1781 t := to
1782 if subjectIsSubsetMatch(si.to, t) {
1783 t = si.to
1784 }
1785 if err := si.acc.checkStreamImportsForCycles(t, visited); err != nil {
1786 return err
1787 }
1788 a.mu.RLock()
1789 }
1790 }
1791 a.mu.RUnlock()
1792 return nil
1793 }
1794
1795 // SetServiceImportSharing will allow sharing of information about requests with the export account.
1796 // Used for service latency tracking at the moment.
1797 func (a *Account) SetServiceImportSharing(destination *Account, to string, allow bool) error {
1798 return a.setServiceImportSharing(destination, to, true, allow)
1799 }
1800
1801 // setServiceImportSharing will allow sharing of information about requests with the export account.
1802 func (a *Account) setServiceImportSharing(destination *Account, to string, check, allow bool) error {
1803 a.mu.Lock()
1804 defer a.mu.Unlock()
1805 if check && a.isClaimAccount() {
1806 return fmt.Errorf("claim based accounts can not be updated directly")
1807 }
1808 // We can't use getServiceImportForAccountLocked() here since we are looking
1809 // for the service import with the si.to == to, which may not be the key
1810 // for the service import in the map.
1811 for _, sis := range a.imports.services {
1812 for _, si := range sis {
1813 if si.acc.Name == destination.Name && si.to == to {
1814 si.share = allow
1815 return nil
1816 }
1817 }
1818 }
1819 return fmt.Errorf("service import not found")
1820 }
1821
1822 // AddServiceImport will add a route to an account to send published messages / requests
1823 // to the destination account. From is the local subject to map, To is the
1824 // subject that will appear on the destination account. Destination will need
1825 // to have an import rule to allow access via addService.
1826 func (a *Account) AddServiceImport(destination *Account, from, to string) error {
1827 return a.AddServiceImportWithClaim(destination, from, to, nil)
1828 }
1829
1830 // NumPendingReverseResponses returns the number of response mappings we have for all outstanding
1831 // requests for service imports.
1832 func (a *Account) NumPendingReverseResponses() int {
1833 a.mu.RLock()
1834 defer a.mu.RUnlock()
1835 return len(a.imports.rrMap)
1836 }
1837
1838 // NumPendingAllResponses return the number of all responses outstanding for service exports.
1839 func (a *Account) NumPendingAllResponses() int {
1840 return a.NumPendingResponses(_EMPTY_)
1841 }
1842
1843 // NumPendingResponses returns the number of responses outstanding for service exports
1844 // on this account. An empty filter string returns all responses regardless of which export.
1845 // If you specify the filter we will only return ones that are for that export.
1846 // NOTE this is only for what this server is tracking.
1847 func (a *Account) NumPendingResponses(filter string) int {
1848 a.mu.RLock()
1849 defer a.mu.RUnlock()
1850 if filter == _EMPTY_ {
1851 return len(a.exports.responses)
1852 }
1853 se := a.getServiceExport(filter)
1854 if se == nil {
1855 return 0
1856 }
1857 var nre int
1858 for _, si := range a.exports.responses {
1859 if si.se == se {
1860 nre++
1861 }
1862 }
1863 return nre
1864 }
1865
1866 // NumServiceImports returns the number of service imports we have configured.
1867 func (a *Account) NumServiceImports() int {
1868 a.mu.RLock()
1869 defer a.mu.RUnlock()
1870 return len(a.imports.services)
1871 }
1872
1873 // Reason why we are removing this response serviceImport.
1874 type rsiReason int
1875
1876 const (
1877 rsiOk = rsiReason(iota)
1878 rsiNoDelivery
1879 rsiTimeout
1880 )
1881
1882 // removeRespServiceImport removes a response si mapping and the reverse entries for interest detection.
1883 func (a *Account) removeRespServiceImport(si *serviceImport, reason rsiReason) {
1884 if si == nil {
1885 return
1886 }
1887
1888 a.mu.Lock()
1889 c := a.ic
1890 delete(a.exports.responses, si.from)
1891 dest, to, tracking, rc, didDeliver := si.acc, si.to, si.tracking, si.rc, si.didDeliver
1892 a.mu.Unlock()
1893
1894 // If we have a sid make sure to unsub.
1895 if len(si.sid) > 0 && c != nil {
1896 c.processUnsub(si.sid)
1897 }
1898
1899 if tracking && rc != nil && !didDeliver {
1900 a.sendBackendErrorTrackingLatency(si, reason)
1901 }
1902
1903 dest.checkForReverseEntry(to, si, false)
1904 }
1905
1906 func (a *Account) getServiceImportForAccountLocked(dstAccName, subject string) *serviceImport {
1907 sis, ok := a.imports.services[subject]
1908 if !ok {
1909 return nil
1910 }
1911 if len(sis) == 1 && sis[0].acc.Name == dstAccName {
1912 return sis[0]
1913 }
1914 for _, si := range sis {
1915 if si.acc.Name == dstAccName {
1916 return si
1917 }
1918 }
1919 return nil
1920 }
1921
1922 // removeServiceImport will remove the route by subject.
1923 func (a *Account) removeServiceImport(dstAccName, subject string) {
1924 a.mu.Lock()
1925 sis, ok := a.imports.services[subject]
1926 if !ok {
1927 a.mu.Unlock()
1928 return
1929 }
1930 var si *serviceImport
1931 if len(sis) == 1 {
1932 si = sis[0]
1933 if si.acc.Name != dstAccName {
1934 si = nil
1935 } else {
1936 delete(a.imports.services, subject)
1937 }
1938 } else {
1939 for i, esi := range sis {
1940 if esi.acc.Name == dstAccName {
1941 si = esi
1942 last := len(sis) - 1
1943 if i != last {
1944 sis[i] = sis[last]
1945 }
1946 sis = sis[:last]
1947 a.imports.services[subject] = sis
1948 break
1949 }
1950 }
1951 }
1952 if si == nil {
1953 a.mu.Unlock()
1954 return
1955 }
1956 var sid []byte
1957 c := a.ic
1958 if c != nil && si.sid != nil {
1959 sid = si.sid
1960 }
1961 a.mu.Unlock()
1962
1963 if sid != nil {
1964 c.processUnsub(sid)
1965 }
1966 }
1967
1968 // This tracks responses to service requests mappings. This is used for cleanup.
1969 func (a *Account) addReverseRespMapEntry(acc *Account, reply, from string) {
1970 a.mu.Lock()
1971 a.imports.addRespEntry(reply, &serviceRespEntry{acc, from})
1972 a.mu.Unlock()
1973 }
1974
1975 // checkForReverseEntries is for when we are trying to match reverse entries to a wildcard.
1976 // This will be called from checkForReverseEntry when the reply arg is a wildcard subject.
1977 // This will usually be called in a go routine since we need to walk all the entries.
1978 func (a *Account) checkForReverseEntries(reply string, checkInterest, recursed bool) {
1979 if subjectIsLiteral(reply) {
1980 a._checkForReverseEntry(reply, nil, checkInterest, recursed)
1981 return
1982 }
1983
1984 a.mu.RLock()
1985 if len(a.imports.rrMap) == 0 {
1986 a.mu.RUnlock()
1987 return
1988 }
1989
1990 var _rs [64]string
1991 rs := _rs[:0]
1992 if n := len(a.imports.rrMap); n > cap(rs) {
1993 rs = make([]string, 0, n)
1994 }
1995
1996 for k := range a.imports.rrMap {
1997 rs = append(rs, k)
1998 }
1999 a.mu.RUnlock()
2000
2001 tsa := [32]string{}
2002 tts := tokenizeSubjectIntoSlice(tsa[:0], reply)
2003
2004 rsa := [32]string{}
2005 for _, r := range rs {
2006 rts := tokenizeSubjectIntoSlice(rsa[:0], r)
2007 // isSubsetMatchTokenized is heavy so make sure we do this without the lock.
2008 if isSubsetMatchTokenized(rts, tts) {
2009 a._checkForReverseEntry(r, nil, checkInterest, recursed)
2010 }
2011 }
2012 }
2013
2014 // This checks for any response map entries. If you specify an si we will only match and
2015 // clean up for that one, otherwise we remove them all.
2016 func (a *Account) checkForReverseEntry(reply string, si *serviceImport, checkInterest bool) {
2017 a._checkForReverseEntry(reply, si, checkInterest, false)
2018 }
2019
2020 // Callers should use checkForReverseEntry instead. This function exists to help prevent
2021 // infinite recursion.
2022 func (a *Account) _checkForReverseEntry(reply string, si *serviceImport, checkInterest, recursed bool) {
2023 a.mu.RLock()
2024 if len(a.imports.rrMap) == 0 {
2025 a.mu.RUnlock()
2026 return
2027 }
2028
2029 if subjectHasWildcard(reply) {
2030 if recursed {
2031 // If we have reached this condition then it is because the reverse entries also
2032 // contain wildcards (that shouldn't happen but a client *could* provide an inbox
2033 // prefix that is illegal because it ends in a wildcard character), at which point
2034 // we will end up with infinite recursion between this func and checkForReverseEntries.
2035 // To avoid a stack overflow panic, we'll give up instead.
2036 a.mu.RUnlock()
2037 return
2038 }
2039
2040 doInline := len(a.imports.rrMap) <= 64
2041 a.mu.RUnlock()
2042
2043 if doInline {
2044 a.checkForReverseEntries(reply, checkInterest, true)
2045 } else {
2046 go a.checkForReverseEntries(reply, checkInterest, true)
2047 }
2048 return
2049 }
2050
2051 if _, ok := a.imports.rrMap[reply]; !ok {
2052 a.mu.RUnlock()
2053 return
2054 }
2055
2056 // If we are here we have an entry we should check.
2057 // If requested we will first check if there is any
2058 // interest for this subject for the entire account.
2059 // If there is we can not delete any entries yet.
2060 // Note that if we are here reply has to be a literal subject.
2061 if checkInterest {
2062 // If interest still exists we can not clean these up yet.
2063 if a.sl.HasInterest(reply) {
2064 a.mu.RUnlock()
2065 return
2066 }
2067 }
2068 a.mu.RUnlock()
2069
2070 // Delete the appropriate entries here based on optional si.
2071 a.mu.Lock()
2072 // We need a new lookup here because we have released the lock.
2073 var sres []*serviceRespEntry
2074 if si == nil {
2075 sres = a.imports.rrMap[reply].list
2076 delete(a.imports.rrMap, reply)
2077 } else {
2078 // Constant time once indexed, instead of a linear scan across every
2079 // outstanding response that happens to share this reply subject.
2080 // This also keys the write back off reply rather than si.to. Every
2081 // caller reaches here with si.to equal to reply, so behavior is
2082 // unchanged, but the lookup and the write back can no longer drift
2083 // apart if that ever stops holding.
2084 a.imports.removeRespEntry(reply, si.from)
2085 }
2086 a.mu.Unlock()
2087
2088 // If we are here we no longer have interest and we have
2089 // response entries that we should clean up.
2090 if si == nil {
2091 // sres is now known to have been removed from a.imports.rrMap, so we
2092 // can safely (data race wise) iterate through.
2093 for _, sre := range sres {
2094 acc := sre.acc
2095 var trackingCleanup bool
2096 var rsi *serviceImport
2097 acc.mu.Lock()
2098 c := acc.ic
2099 if rsi = acc.exports.responses[sre.msub]; rsi != nil && !rsi.didDeliver {
2100 delete(acc.exports.responses, rsi.from)
2101 trackingCleanup = rsi.tracking && rsi.rc != nil
2102 }
2103 acc.mu.Unlock()
2104 // If we are doing explicit subs for all responses (e.g. bound to leafnode)
2105 // we will have a non-empty sid here.
2106 if rsi != nil && len(rsi.sid) > 0 && c != nil {
2107 c.processUnsub(rsi.sid)
2108 }
2109 if trackingCleanup {
2110 acc.sendReplyInterestLostTrackLatency(rsi)
2111 }
2112 }
2113 }
2114 }
2115
2116 // Checks to see if a potential service import subject is already overshadowed.
2117 func (a *Account) serviceImportShadowed(from string) bool {
2118 a.mu.RLock()
2119 defer a.mu.RUnlock()
2120 if a.imports.services[from] != nil {
2121 return true
2122 }
2123 // We did not find a direct match, so check individually.
2124 for subj := range a.imports.services {
2125 if subjectIsSubsetMatch(from, subj) {
2126 return true
2127 }
2128 }
2129 return false
2130 }
2131
2132 // Internal check to see if a service import exists.
2133 func (a *Account) serviceImportExists(dstAccName, from string) bool {
2134 a.mu.RLock()
2135 dup := a.getServiceImportForAccountLocked(dstAccName, from)
2136 a.mu.RUnlock()
2137 return dup != nil
2138 }
2139
2140 // Add a service import.
2141 // This does no checks and should only be called by the msg processing code.
2142 // Use AddServiceImport from above if responding to user input or config changes, etc.
2143 func (a *Account) addServiceImport(dest *Account, from, to string, claim *jwt.Import) (*serviceImport, error) {
2144 rt := Singleton
2145 var lat *serviceLatency
2146
2147 if dest == nil {
2148 return nil, ErrMissingAccount
2149 }
2150
2151 var atrc bool
2152 dest.mu.RLock()
2153 se := dest.getServiceExport(to)
2154 if se != nil {
2155 rt = se.respType
2156 lat = se.latency
2157 atrc = se.atrc
2158 }
2159 destAccName := dest.Name
2160 dest.mu.RUnlock()
2161
2162 a.mu.Lock()
2163 if a.imports.services == nil {
2164 a.imports.services = make(map[string][]*serviceImport)
2165 } else if dup := a.getServiceImportForAccountLocked(destAccName, from); dup != nil {
2166 a.mu.Unlock()
2167 return nil, fmt.Errorf("duplicate service import subject %q, previously used in import for account %q, subject %q",
2168 from, dup.acc.Name, dup.to)
2169 }
2170
2171 if to == _EMPTY_ {
2172 to = from
2173 }
2174 // Check to see if we have a wildcard
2175 var (
2176 usePub bool
2177 tr *subjectTransform
2178 err error
2179 )
2180
2181 if subjectHasWildcard(to) {
2182 // If to and from match, then we use the published subject.
2183 if to == from {
2184 usePub = true
2185 } else {
2186 to, _ = transformUntokenize(to)
2187 // Create a transform. Do so in reverse such that $ symbols only exist in to
2188 if tr, err = NewSubjectTransformStrict(to, transformTokenize(from)); err != nil {
2189 a.mu.Unlock()
2190 return nil, fmt.Errorf("failed to create mapping transform for service import subject from %q to %q: %v",
2191 from, to, err)
2192 } else {
2193 // un-tokenize and reverse transform so we get the transform needed
2194 from, _ = transformUntokenize(from)
2195 tr = tr.reverse()
2196 }
2197 }
2198 }
2199 var share bool
2200 if claim != nil {
2201 share = claim.Share
2202 }
2203 si := &serviceImport{dest, claim, se, nil, from, to, tr, 0, rt, lat, nil, nil, nil, usePub, false, false, share, false, false, atrc, nil}
2204 sis := a.imports.services[from]
2205 sis = append(sis, si)
2206 a.imports.services[from] = sis
2207 a.mu.Unlock()
2208
2209 if err := a.addServiceImportSub(si); err != nil {
2210 a.removeServiceImport(destAccName, si.from)
2211 return nil, err
2212 }
2213 return si, nil
2214 }
2215
2216 // Returns the internal client, will create one if not present.
2217 // Lock should be held.
2218 func (a *Account) internalClient() *client {
2219 if a.ic == nil && a.srv != nil {
2220 a.ic = a.srv.createInternalAccountClient()
2221 a.ic.acc = a
2222 }
2223 return a.ic
2224 }
2225
2226 // Internal account scoped subscriptions.
2227 func (a *Account) subscribeInternal(subject string, cb msgHandler) (*subscription, error) {
2228 return a.subscribeInternalEx(subject, cb, false)
2229 }
2230
2231 // Unsubscribe from an internal account subscription.
2232 func (a *Account) unsubscribeInternal(sub *subscription) {
2233 if ic := a.internalClient(); ic != nil {
2234 ic.processUnsub(sub.sid)
2235 }
2236 }
2237
2238 // Creates internal subscription for service import responses.
2239 func (a *Account) subscribeServiceImportResponse(subject string) (*subscription, error) {
2240 return a.subscribeInternalEx(subject, a.processServiceImportResponse, true)
2241 }
2242
2243 func (a *Account) subscribeInternalEx(subject string, cb msgHandler, ri bool) (*subscription, error) {
2244 a.mu.Lock()
2245 a.isid++
2246 c, sid := a.internalClient(), strconv.FormatUint(a.isid, 10)
2247 a.mu.Unlock()
2248
2249 // This will happen in parsing when the account has not been properly setup.
2250 if c == nil {
2251 return nil, fmt.Errorf("no internal account client")
2252 }
2253
2254 return c.processSubEx([]byte(subject), nil, []byte(sid), cb, false, false, ri)
2255 }
2256
2257 // This will add an account subscription that matches the "from" from a service import entry.
2258 func (a *Account) addServiceImportSub(si *serviceImport) error {
2259 a.mu.Lock()
2260 c := a.internalClient()
2261 // This will happen in parsing when the account has not been properly setup.
2262 if c == nil {
2263 a.mu.Unlock()
2264 return nil
2265 }
2266 if si.sid != nil {
2267 a.mu.Unlock()
2268 return fmt.Errorf("duplicate call to create subscription for service import")
2269 }
2270 a.isid++
2271 sid := strconv.FormatUint(a.isid, 10)
2272 si.sid = []byte(sid)
2273 subject := si.from
2274 a.mu.Unlock()
2275
2276 cb := func(sub *subscription, c *client, acc *Account, subject, reply string, msg []byte) {
2277 c.pa.delivered = c.processServiceImport(si, acc, msg)
2278 }
2279 sub, err := c.processSubEx([]byte(subject), nil, []byte(sid), cb, true, true, false)
2280 if err != nil {
2281 return err
2282 }
2283 // Leafnodes introduce a new way to introduce messages into the system. Therefore forward import subscription
2284 // This is similar to what initLeafNodeSmapAndSendSubs does
2285 // TODO we need to consider performing this update as we get client subscriptions.
2286 // This behavior would result in subscription propagation only where actually used.
2287 a.updateLeafNodes(sub, 1)
2288 return nil
2289 }
2290
2291 // Remove all the subscriptions associated with service imports.
2292 func (a *Account) removeAllServiceImportSubs() {
2293 a.mu.Lock()
2294 var sids [][]byte
2295 for _, sis := range a.imports.services {
2296 for _, si := range sis {
2297 if si.sid != nil {
2298 sids = append(sids, si.sid)
2299 si.sid = nil
2300 }
2301 }
2302 }
2303 c := a.ic
2304 a.ic = nil
2305 a.mu.Unlock()
2306
2307 if c == nil {
2308 return
2309 }
2310 for _, sid := range sids {
2311 c.processUnsub(sid)
2312 }
2313 c.closeConnection(InternalClient)
2314 }
2315
2316 // Add in subscriptions for all registered service imports.
2317 func (a *Account) addAllServiceImportSubs() {
2318 var sis [32]*serviceImport
2319 serviceImports := sis[:0]
2320 a.mu.RLock()
2321 for _, sis := range a.imports.services {
2322 serviceImports = append(serviceImports, sis...)
2323 }
2324 a.mu.RUnlock()
2325 for _, si := range serviceImports {
2326 a.addServiceImportSub(si)
2327 }
2328 }
2329
2330 var (
2331 // header where all information is encoded in one value.
2332 trcUber = textproto.CanonicalMIMEHeaderKey("Uber-Trace-Id")
2333 trcCtx = textproto.CanonicalMIMEHeaderKey("Traceparent")
2334 trcB3 = textproto.CanonicalMIMEHeaderKey("B3")
2335 // openzipkin header to check
2336 trcB3Sm = textproto.CanonicalMIMEHeaderKey("X-B3-Sampled")
2337 trcB3Id = textproto.CanonicalMIMEHeaderKey("X-B3-TraceId")
2338 // additional header needed to include when present
2339 trcB3PSId = textproto.CanonicalMIMEHeaderKey("X-B3-ParentSpanId")
2340 trcB3SId = textproto.CanonicalMIMEHeaderKey("X-B3-SpanId")
2341 trcCtxSt = textproto.CanonicalMIMEHeaderKey("Tracestate")
2342 trcUberCtxPrefix = textproto.CanonicalMIMEHeaderKey("Uberctx-")
2343 )
2344
2345 func newB3Header(h http.Header) http.Header {
2346 retHdr := http.Header{}
2347 if v, ok := h[trcB3Sm]; ok {
2348 retHdr[trcB3Sm] = v
2349 }
2350 if v, ok := h[trcB3Id]; ok {
2351 retHdr[trcB3Id] = v
2352 }
2353 if v, ok := h[trcB3PSId]; ok {
2354 retHdr[trcB3PSId] = v
2355 }
2356 if v, ok := h[trcB3SId]; ok {
2357 retHdr[trcB3SId] = v
2358 }
2359 return retHdr
2360 }
2361
2362 func newUberHeader(h http.Header, tId []string) http.Header {
2363 retHdr := http.Header{trcUber: tId}
2364 for k, v := range h {
2365 if strings.HasPrefix(k, trcUberCtxPrefix) {
2366 retHdr[k] = v
2367 }
2368 }
2369 return retHdr
2370 }
2371
2372 func newTraceCtxHeader(h http.Header, tId []string) http.Header {
2373 retHdr := http.Header{trcCtx: tId}
2374 if v, ok := h[trcCtxSt]; ok {
2375 retHdr[trcCtxSt] = v
2376 }
2377 return retHdr
2378 }
2379
2380 // Helper to determine when to sample. When header has a value, sampling is driven by header
2381 func shouldSample(l *serviceLatency, c *client) (bool, http.Header) {
2382 if l == nil {
2383 return false, nil
2384 }
2385 if l.sampling < 0 {
2386 return false, nil
2387 }
2388 if l.sampling >= 100 {
2389 return true, nil
2390 }
2391 if l.sampling > 0 && rand.Int31n(100) <= int32(l.sampling) {
2392 return true, nil
2393 }
2394 h := c.parseState.getHeader()
2395 if len(h) == 0 {
2396 return false, nil
2397 }
2398 if tId := h[trcUber]; len(tId) != 0 {
2399 // sample 479fefe9525eddb:5adb976bfc1f95c1:479fefe9525eddb:1
2400 tk := strings.Split(tId[0], ":")
2401 if len(tk) == 4 && len(tk[3]) > 0 && len(tk[3]) <= 2 {
2402 dst := [2]byte{}
2403 src := [2]byte{'0', tk[3][0]}
2404 if len(tk[3]) == 2 {
2405 src[1] = tk[3][1]
2406 }
2407 if _, err := hex.Decode(dst[:], src[:]); err == nil && dst[0]&1 == 1 {
2408 return true, newUberHeader(h, tId)
2409 }
2410 }
2411 return false, nil
2412 } else if sampled := h[trcB3Sm]; len(sampled) != 0 && sampled[0] == "1" {
2413 return true, newB3Header(h) // allowed
2414 } else if len(sampled) != 0 && sampled[0] == "0" {
2415 return false, nil // denied
2416 } else if _, ok := h[trcB3Id]; ok {
2417 // sample 80f198ee56343ba864fe8b2a57d3eff7
2418 // presence (with X-B3-Sampled not being 0) means sampling left to recipient
2419 return true, newB3Header(h)
2420 } else if b3 := h[trcB3]; len(b3) != 0 {
2421 // sample 80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1-1-05e3ac9a4f6e3b90
2422 // sample 0
2423 tk := strings.Split(b3[0], "-")
2424 if len(tk) > 2 && tk[2] == "0" {
2425 return false, nil // denied
2426 } else if len(tk) == 1 && tk[0] == "0" {
2427 return false, nil // denied
2428 }
2429 return true, http.Header{trcB3: b3} // sampling allowed or left to recipient of header
2430 } else if tId := h[trcCtx]; len(tId) != 0 {
2431 var sample bool
2432 // sample 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
2433 tk := strings.Split(tId[0], "-")
2434 if len(tk) == 4 && len([]byte(tk[3])) == 2 {
2435 if hexVal, err := strconv.ParseInt(tk[3], 16, 8); err == nil {
2436 sample = hexVal&0x1 == 0x1
2437 }
2438 }
2439 if sample {
2440 return true, newTraceCtxHeader(h, tId)
2441 } else {
2442 return false, nil
2443 }
2444 }
2445 return false, nil
2446 }
2447
2448 // Used to mimic client like replies.
2449 const (
2450 replyPrefix = "_R_."
2451 replyPrefixLen = len(replyPrefix)
2452 baseServerLen = 10
2453 replyLen = 6
2454 minReplyLen = 15
2455 digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
2456 base = 62
2457 )
2458
2459 // This is where all service export responses are handled.
2460 func (a *Account) processServiceImportResponse(sub *subscription, c *client, _ *Account, subject, reply string, msg []byte) {
2461 a.mu.RLock()
2462 if a.expired.Load() || len(a.exports.responses) == 0 {
2463 a.mu.RUnlock()
2464 return
2465 }
2466 si := a.exports.responses[subject]
2467
2468 if si == nil || si.invalid {
2469 a.mu.RUnlock()
2470 return
2471 }
2472 a.mu.RUnlock()
2473
2474 // Send for normal processing.
2475 c.processServiceImport(si, a, msg)
2476 }
2477
2478 // Will create the response prefix for fast generation of responses.
2479 // A wildcard subscription may be used handle interest graph propagation
2480 // for all service replies, unless we are bound to a leafnode.
2481 // Lock should be held.
2482 func (a *Account) createRespWildcard() {
2483 var b = [baseServerLen]byte{'_', 'R', '_', '.'}
2484 rn := fastrand.Uint64()
2485 for i, l := replyPrefixLen, rn; i < len(b); i++ {
2486 b[i] = digits[l%base]
2487 l /= base
2488 }
2489 a.siReply = append(b[:], '.')
2490 }
2491
2492 // Test whether this is a tracked reply.
2493 func isTrackedReply(reply []byte) bool {
2494 lreply := len(reply) - 1
2495 return lreply > 3 && reply[lreply-1] == '.' && reply[lreply] == 'T'
2496 }
2497
2498 // Generate a new service reply from the wildcard prefix.
2499 // FIXME(dlc) - probably do not have to use rand here. about 25ns per.
2500 func (a *Account) newServiceReply(tracking bool) []byte {
2501 a.mu.Lock()
2502 s := a.srv
2503 rn := fastrand.Uint64()
2504
2505 // Check if we need to create the reply here.
2506 var createdSiReply bool
2507 if a.siReply == nil {
2508 a.createRespWildcard()
2509 createdSiReply = true
2510 }
2511 replyPre := a.siReply
2512 a.mu.Unlock()
2513
2514 // If we created the siReply and we are not bound to a leafnode
2515 // we need to do the wildcard subscription.
2516 if createdSiReply {
2517 a.subscribeServiceImportResponse(string(append(replyPre, '>')))
2518 }
2519
2520 var b [replyLen]byte
2521 for i, l := 0, rn; i < len(b); i++ {
2522 b[i] = digits[l%base]
2523 l /= base
2524 }
2525 // Make sure to copy.
2526 reply := make([]byte, 0, len(replyPre)+len(b))
2527 reply = append(reply, replyPre...)
2528 reply = append(reply, b[:]...)
2529
2530 if tracking && s.sys != nil {
2531 // Add in our tracking identifier. This allows the metrics to get back to only
2532 // this server without needless SUBS/UNSUBS.
2533 reply = append(reply, '.')
2534 reply = append(reply, s.sys.shash...)
2535 reply = append(reply, '.', 'T')
2536 }
2537
2538 return reply
2539 }
2540
2541 // Checks if a serviceImport was created to map responses.
2542 func (si *serviceImport) isRespServiceImport() bool {
2543 return si != nil && si.response
2544 }
2545
2546 // Sets the response threshold timer for a service export.
2547 // Account lock should be held
2548 func (se *serviceExport) setResponseThresholdTimer() {
2549 if se.rtmr != nil {
2550 return // Already set
2551 }
2552 se.rtmr = time.AfterFunc(se.respThresh, se.checkExpiredResponses)
2553 }
2554
2555 // Account lock should be held
2556 func (se *serviceExport) clearResponseThresholdTimer() bool {
2557 if se.rtmr == nil {
2558 return true
2559 }
2560 stopped := se.rtmr.Stop()
2561 se.rtmr = nil
2562 return stopped
2563 }
2564
2565 // checkExpiredResponses will check for any pending responses that need to
2566 // be cleaned up.
2567 func (se *serviceExport) checkExpiredResponses() {
2568 acc := se.acc
2569 if acc == nil {
2570 se.clearResponseThresholdTimer()
2571 return
2572 }
2573
2574 var expired []*serviceImport
2575 mints := time.Now().UnixNano() - int64(se.respThresh)
2576
2577 // TODO(dlc) - Should we release lock while doing this? Or only do these in batches?
2578 // Should we break this up for responses only from this service export?
2579 // Responses live on acc directly for fast inbound processsing for the _R_ wildcard.
2580 // We could do another indirection at this level but just to get to the service export?
2581 var totalResponses int
2582 acc.mu.RLock()
2583 for _, si := range acc.exports.responses {
2584 if si.se == se {
2585 totalResponses++
2586 if si.ts <= mints {
2587 expired = append(expired, si)
2588 }
2589 }
2590 }
2591 acc.mu.RUnlock()
2592
2593 for _, si := range expired {
2594 acc.removeRespServiceImport(si, rsiTimeout)
2595 }
2596
2597 // Pull out expired to determine if we have any left for timer.
2598 totalResponses -= len(expired)
2599
2600 // Redo timer as needed.
2601 acc.mu.Lock()
2602 if totalResponses > 0 && se.rtmr != nil {
2603 se.rtmr.Stop()
2604 se.rtmr.Reset(se.respThresh)
2605 } else {
2606 se.clearResponseThresholdTimer()
2607 }
2608 acc.mu.Unlock()
2609 }
2610
2611 // ServiceExportResponseThreshold returns the current threshold.
2612 func (a *Account) ServiceExportResponseThreshold(export string) (time.Duration, error) {
2613 a.mu.Lock()
2614 defer a.mu.Unlock()
2615 se := a.getServiceExport(export)
2616 if se == nil {
2617 return 0, fmt.Errorf("no export defined for %q", export)
2618 }
2619 return se.respThresh, nil
2620 }
2621
2622 // SetServiceExportResponseThreshold sets the maximum time the system will a response to be delivered
2623 // from a service export responder.
2624 func (a *Account) SetServiceExportResponseThreshold(export string, maxTime time.Duration) error {
2625 a.mu.Lock()
2626 if a.isClaimAccount() {
2627 a.mu.Unlock()
2628 return fmt.Errorf("claim based accounts can not be updated directly")
2629 }
2630 lrt := a.lowestServiceExportResponseTime()
2631 se := a.getServiceExport(export)
2632 if se == nil {
2633 a.mu.Unlock()
2634 return fmt.Errorf("no export defined for %q", export)
2635 }
2636 se.respThresh = maxTime
2637
2638 var clients []*client
2639 nlrt := a.lowestServiceExportResponseTime()
2640 if nlrt != lrt && len(a.clients) > 0 {
2641 clients = a.getClientsLocked()
2642 }
2643 // Need to release because lock ordering is client -> Account
2644 a.mu.Unlock()
2645 if len(clients) > 0 {
2646 updateAllClientsServiceExportResponseTime(clients, nlrt)
2647 }
2648 return nil
2649 }
2650
2651 func (a *Account) SetServiceExportAllowTrace(export string, allowTrace bool) error {
2652 a.mu.Lock()
2653 se := a.getServiceExport(export)
2654 if se == nil {
2655 a.mu.Unlock()
2656 return fmt.Errorf("no export defined for %q", export)
2657 }
2658 se.atrc = allowTrace
2659 a.mu.Unlock()
2660 return nil
2661 }
2662
2663 // This is for internal service import responses.
2664 func (a *Account) addRespServiceImport(dest *Account, to string, osi *serviceImport, tracking bool, header http.Header, mt *msgTrace) *serviceImport {
2665 nrr := string(osi.acc.newServiceReply(tracking))
2666
2667 a.mu.Lock()
2668 rt := osi.rt
2669
2670 // dest is the requestor's account. a is the service responder with the export.
2671 // Marked as internal here, that is how we distinguish.
2672 si := &serviceImport{dest, nil, osi.se, nil, nrr, to, nil, 0, rt, nil, nil, nil, mt, false, true, false, osi.share, false, false, false, nil}
2673
2674 if a.exports.responses == nil {
2675 a.exports.responses = make(map[string]*serviceImport)
2676 }
2677 a.exports.responses[nrr] = si
2678
2679 // Always grab time and make sure response threshold timer is running.
2680 si.ts = time.Now().UnixNano()
2681 if osi.se != nil {
2682 osi.se.setResponseThresholdTimer()
2683 }
2684
2685 if rt == Singleton && tracking {
2686 si.latency = osi.latency
2687 si.tracking = true
2688 si.trackingHdr = header
2689 }
2690 a.mu.Unlock()
2691
2692 // We do add in the reverse map such that we can detect loss of interest and do proper
2693 // cleanup of this si as interest goes away.
2694 dest.addReverseRespMapEntry(a, to, nrr)
2695
2696 return si
2697 }
2698
2699 // AddStreamImportWithClaim will add in the stream import from a specific account with optional token.
2700 func (a *Account) AddStreamImportWithClaim(account *Account, from, prefix string, imClaim *jwt.Import) error {
2701 return a.addStreamImportWithClaim(account, from, prefix, false, imClaim)
2702 }
2703
2704 func (a *Account) addStreamImportWithClaim(account *Account, from, prefix string, allowTrace bool, imClaim *jwt.Import) error {
2705 if account == nil {
2706 return ErrMissingAccount
2707 }
2708
2709 // First check to see if the account has authorized export of the subject.
2710 if !account.checkStreamImportAuthorized(a, from, imClaim) {
2711 return ErrStreamImportAuthorization
2712 }
2713
2714 // Check prefix if it exists and make sure its a literal.
2715 // Append token separator if not already present.
2716 if prefix != _EMPTY_ {
2717 // Make sure there are no wildcards here, this prefix needs to be a literal
2718 // since it will be prepended to a publish subject.
2719 if !subjectIsLiteral(prefix) {
2720 return ErrStreamImportBadPrefix
2721 }
2722 if prefix[len(prefix)-1] != btsep {
2723 prefix = prefix + string(btsep)
2724 }
2725 }
2726
2727 return a.addMappedStreamImportWithClaim(account, from, prefix+from, allowTrace, imClaim)
2728 }
2729
2730 // AddMappedStreamImport helper for AddMappedStreamImportWithClaim
2731 func (a *Account) AddMappedStreamImport(account *Account, from, to string) error {
2732 return a.AddMappedStreamImportWithClaim(account, from, to, nil)
2733 }
2734
2735 // AddMappedStreamImportWithClaim will add in the stream import from a specific account with optional token.
2736 func (a *Account) AddMappedStreamImportWithClaim(account *Account, from, to string, imClaim *jwt.Import) error {
2737 return a.addMappedStreamImportWithClaim(account, from, to, false, imClaim)
2738 }
2739
2740 func (a *Account) addMappedStreamImportWithClaim(account *Account, from, to string, allowTrace bool, imClaim *jwt.Import) error {
2741 if account == nil {
2742 return ErrMissingAccount
2743 }
2744
2745 // First check to see if the account has authorized export of the subject.
2746 if !account.checkStreamImportAuthorized(a, from, imClaim) {
2747 return ErrStreamImportAuthorization
2748 }
2749
2750 if to == _EMPTY_ {
2751 to = from
2752 }
2753
2754 // Check if this forms a cycle.
2755 if err := a.streamImportFormsCycle(account, to); err != nil {
2756 return err
2757 }
2758
2759 if err := a.streamImportFormsCycle(account, from); err != nil {
2760 return err
2761 }
2762
2763 var (
2764 usePub bool
2765 tr *subjectTransform
2766 err error
2767 )
2768 if subjectHasWildcard(from) {
2769 if to == from {
2770 usePub = true
2771 } else {
2772 // Create a transform
2773 if tr, err = NewSubjectTransformStrict(from, transformTokenize(to)); err != nil {
2774 return fmt.Errorf("failed to create mapping transform for stream import subject from %q to %q: %v",
2775 from, to, err)
2776 }
2777 to, _ = transformUntokenize(to)
2778 }
2779 }
2780
2781 a.mu.Lock()
2782 if a.isStreamImportDuplicate(account, from) {
2783 a.mu.Unlock()
2784 return ErrStreamImportDuplicate
2785 }
2786 if imClaim != nil {
2787 allowTrace = imClaim.AllowTrace
2788 }
2789 a.imports.streams = append(a.imports.streams, &streamImport{account, from, to, tr, nil, imClaim, usePub, false, allowTrace})
2790 a.mu.Unlock()
2791 return nil
2792 }
2793
2794 // isStreamImportDuplicate checks for duplicate.
2795 // Lock should be held.
2796 func (a *Account) isStreamImportDuplicate(acc *Account, from string) bool {
2797 for _, si := range a.imports.streams {
2798 if si.acc == acc && si.from == from {
2799 return true
2800 }
2801 }
2802 return false
2803 }
2804
2805 // AddStreamImport will add in the stream import from a specific account.
2806 func (a *Account) AddStreamImport(account *Account, from, prefix string) error {
2807 return a.addStreamImportWithClaim(account, from, prefix, false, nil)
2808 }
2809
2810 // IsPublicExport is a placeholder to denote a public export.
2811 var IsPublicExport = []*Account(nil)
2812
2813 // AddStreamExport will add an export to the account. If accounts is nil
2814 // it will signify a public export, meaning anyone can import.
2815 func (a *Account) AddStreamExport(subject string, accounts []*Account) error {
2816 return a.addStreamExportWithAccountPos(subject, accounts, 0)
2817 }
2818
2819 // AddStreamExport will add an export to the account. If accounts is nil
2820 // it will signify a public export, meaning anyone can import.
2821 // if accountPos is > 0, all imports will be granted where the following holds:
2822 // strings.Split(subject, tsep)[accountPos] == account id will be granted.
2823 func (a *Account) addStreamExportWithAccountPos(subject string, accounts []*Account, accountPos uint) error {
2824 if a == nil {
2825 return ErrMissingAccount
2826 }
2827
2828 a.mu.Lock()
2829 defer a.mu.Unlock()
2830
2831 if a.exports.streams == nil {
2832 a.exports.streams = make(map[string]*streamExport)
2833 }
2834 ea := a.exports.streams[subject]
2835 if accounts != nil || accountPos > 0 {
2836 if ea == nil {
2837 ea = &streamExport{}
2838 }
2839 if err := setExportAuth(&ea.exportAuth, subject, accounts, accountPos); err != nil {
2840 return err
2841 }
2842 }
2843 a.exports.streams[subject] = ea
2844 return nil
2845 }
2846
2847 // Check if another account is authorized to import from us.
2848 func (a *Account) checkStreamImportAuthorized(account *Account, subject string, imClaim *jwt.Import) bool {
2849 // Find the subject in the exports list.
2850 a.mu.RLock()
2851 auth := a.checkStreamImportAuthorizedNoLock(account, subject, imClaim)
2852 a.mu.RUnlock()
2853 return auth
2854 }
2855
2856 func (a *Account) checkStreamImportAuthorizedNoLock(account *Account, subject string, imClaim *jwt.Import) bool {
2857 if a.exports.streams == nil || !IsValidSubject(subject) {
2858 return false
2859 }
2860 return a.checkStreamExportApproved(account, subject, imClaim)
2861 }
2862
2863 func (a *Account) checkAuth(ea *exportAuth, account *Account, imClaim *jwt.Import, tokens []string) bool {
2864 // if ea is nil or ea.approved is nil, that denotes a public export
2865 if ea == nil || (len(ea.approved) == 0 && !ea.tokenReq && ea.accountPos == 0) {
2866 return true
2867 }
2868 // Check if the export is protected and enforces presence of importing account identity
2869 if ea.accountPos > 0 {
2870 return ea.accountPos <= uint(len(tokens)) && tokens[ea.accountPos-1] == account.Name
2871 }
2872 // Check if token required
2873 if ea.tokenReq {
2874 return a.checkActivation(account, imClaim, ea, true)
2875 }
2876 if ea.approved == nil {
2877 return false
2878 }
2879 // If we have a matching account we are authorized
2880 _, ok := ea.approved[account.Name]
2881 return ok
2882 }
2883
2884 func (a *Account) checkStreamExportApproved(account *Account, subject string, imClaim *jwt.Import) bool {
2885 // Check direct match of subject first
2886 ea, ok := a.exports.streams[subject]
2887 if ok {
2888 // if ea is nil or eq.approved is nil, that denotes a public export
2889 if ea == nil {
2890 return true
2891 }
2892 return a.checkAuth(&ea.exportAuth, account, imClaim, nil)
2893 }
2894
2895 // ok if we are here we did not match directly so we need to test each one.
2896 // The import subject arg has to take precedence, meaning the export
2897 // has to be a true subset of the import claim. We already checked for
2898 // exact matches above.
2899 tokens := strings.Split(subject, tsep)
2900 for subj, ea := range a.exports.streams {
2901 if isSubsetMatch(tokens, subj) {
2902 if ea == nil {
2903 return true
2904 }
2905 return a.checkAuth(&ea.exportAuth, account, imClaim, tokens)
2906 }
2907 }
2908 return false
2909 }
2910
2911 func (a *Account) checkServiceExportApproved(account *Account, subject string, imClaim *jwt.Import) bool {
2912 // Check direct match of subject first
2913 se, ok := a.exports.services[subject]
2914 if ok {
2915 // if se is nil or eq.approved is nil, that denotes a public export
2916 if se == nil {
2917 return true
2918 }
2919 return a.checkAuth(&se.exportAuth, account, imClaim, nil)
2920 }
2921 // ok if we are here we did not match directly so we need to test each one.
2922 // The import subject arg has to take precedence, meaning the export
2923 // has to be a true subset of the import claim. We already checked for
2924 // exact matches above.
2925 tokens := strings.Split(subject, tsep)
2926 for subj, se := range a.exports.services {
2927 if isSubsetMatch(tokens, subj) {
2928 if se == nil {
2929 return true
2930 }
2931 return a.checkAuth(&se.exportAuth, account, imClaim, tokens)
2932 }
2933 }
2934 return false
2935 }
2936
2937 // Helper function to get a serviceExport.
2938 // Lock should be held on entry.
2939 func (a *Account) getServiceExport(subj string) *serviceExport {
2940 se, ok := a.exports.services[subj]
2941 // The export probably has a wildcard, so lookup that up.
2942 if !ok {
2943 se = a.getWildcardServiceExport(subj)
2944 }
2945 return se
2946 }
2947
2948 // This helper is used when trying to match a serviceExport record that is
2949 // represented by a wildcard.
2950 // Lock should be held on entry.
2951 func (a *Account) getWildcardServiceExport(from string) *serviceExport {
2952 tokens := strings.Split(from, tsep)
2953 for subj, se := range a.exports.services {
2954 if isSubsetMatch(tokens, subj) {
2955 return se
2956 }
2957 }
2958 return nil
2959 }
2960
2961 // These are import stream specific versions for when an activation expires.
2962 func (a *Account) streamActivationExpired(exportAcc *Account, subject string) {
2963 a.mu.RLock()
2964 if a.expired.Load() || a.imports.streams == nil {
2965 a.mu.RUnlock()
2966 return
2967 }
2968 var si *streamImport
2969 for _, im := range a.imports.streams {
2970 if im.acc == exportAcc && im.from == subject {
2971 si = im
2972 break
2973 }
2974 }
2975
2976 if si == nil || si.invalid {
2977 a.mu.RUnlock()
2978 return
2979 }
2980 a.mu.RUnlock()
2981
2982 if si.acc.checkActivation(a, si.claim, nil, false) {
2983 // The token has been updated most likely and we are good to go.
2984 return
2985 }
2986
2987 a.mu.Lock()
2988 si.invalid = true
2989 clients := a.getClientsLocked()
2990 awcsti := map[string]struct{}{a.Name: {}}
2991 a.mu.Unlock()
2992 for _, c := range clients {
2993 c.processSubsOnConfigReload(awcsti)
2994 }
2995 }
2996
2997 // These are import service specific versions for when an activation expires.
2998 func (a *Account) serviceActivationExpired(dstAcc *Account, subject string) {
2999 a.mu.RLock()
3000 if a.expired.Load() || a.imports.services == nil {
3001 a.mu.RUnlock()
3002 return
3003 }
3004 si := a.getServiceImportForAccountLocked(dstAcc.Name, subject)
3005 if si == nil || si.invalid {
3006 a.mu.RUnlock()
3007 return
3008 }
3009 a.mu.RUnlock()
3010
3011 if si.acc.checkActivation(a, si.claim, nil, false) {
3012 // The token has been updated most likely and we are good to go.
3013 return
3014 }
3015
3016 a.mu.Lock()
3017 si.invalid = true
3018 a.mu.Unlock()
3019 }
3020
3021 // Fires for expired activation tokens. We could track this with timers etc.
3022 // Instead we just re-analyze where we are and if we need to act.
3023 func (a *Account) activationExpired(exportAcc *Account, subject string, kind jwt.ExportType) {
3024 switch kind {
3025 case jwt.Stream:
3026 a.streamActivationExpired(exportAcc, subject)
3027 case jwt.Service:
3028 a.serviceActivationExpired(exportAcc, subject)
3029 }
3030 }
3031
3032 func isRevoked(revocations map[string]int64, subject string, issuedAt int64) bool {
3033 if len(revocations) == 0 {
3034 return false
3035 }
3036 if t, ok := revocations[subject]; !ok || t < issuedAt {
3037 if t, ok := revocations[jwt.All]; !ok || t < issuedAt {
3038 return false
3039 }
3040 }
3041 return true
3042 }
3043
3044 // checkActivation will check the activation token for validity.
3045 // ea may only be nil in cases where revocation may not be checked, say triggered by expiration timer.
3046 func (a *Account) checkActivation(importAcc *Account, claim *jwt.Import, ea *exportAuth, expTimer bool) bool {
3047 if claim == nil || claim.Token == _EMPTY_ {
3048 return false
3049 }
3050 // Create a quick clone so we can inline Token JWT.
3051 clone := *claim
3052
3053 vr := jwt.CreateValidationResults()
3054 clone.Validate(importAcc.Name, vr)
3055 if vr.IsBlocking(true) {
3056 return false
3057 }
3058 act, err := jwt.DecodeActivationClaims(clone.Token)
3059 if err != nil {
3060 return false
3061 }
3062 if !a.isIssuerClaimTrusted(act) {
3063 return false
3064 }
3065 vr = jwt.CreateValidationResults()
3066 act.Validate(vr)
3067 if vr.IsBlocking(true) {
3068 return false
3069 }
3070 if act.Expires != 0 {
3071 tn := time.Now().Unix()
3072 if act.Expires <= tn {
3073 return false
3074 }
3075 if expTimer {
3076 expiresAt := time.Duration(act.Expires - tn)
3077 time.AfterFunc(expiresAt*time.Second, func() {
3078 importAcc.activationExpired(a, string(act.ImportSubject), claim.Type)
3079 })
3080 }
3081 }
3082 if ea == nil {
3083 return true
3084 }
3085 // Check for token revocation..
3086 return !isRevoked(ea.actsRevoked, act.Subject, act.IssuedAt)
3087 }
3088
3089 // Returns true if the activation claim is trusted. That is the issuer matches
3090 // the account or is an entry in the signing keys.
3091 func (a *Account) isIssuerClaimTrusted(claims *jwt.ActivationClaims) bool {
3092 // if no issuer account, issuer is the account
3093 if claims.IssuerAccount == _EMPTY_ {
3094 return true
3095 }
3096 // If the IssuerAccount is not us, then this is considered an error.
3097 if a.Name != claims.IssuerAccount {
3098 if a.srv != nil {
3099 a.srv.Errorf("Invalid issuer account %q in activation claim (subject: %q - type: %q) for account %q",
3100 claims.IssuerAccount, claims.Activation.ImportSubject, claims.Activation.ImportType, a.Name)
3101 }
3102 return false
3103 }
3104 _, ok := a.hasIssuerNoLock(claims.Issuer)
3105 return ok
3106 }
3107
3108 // Returns true if `a` and `b` stream imports are the same. Note that the
3109 // check is done with the account's name, not the pointer. This is used
3110 // during config reload where we are comparing current and new config
3111 // in which pointers are different.
3112 // Acquires `a` read lock, but `b` is assumed to not be accessed
3113 // by anyone but the caller (`b` is not registered anywhere).
3114 func (a *Account) checkStreamImportsEqual(b *Account) bool {
3115 a.mu.RLock()
3116 defer a.mu.RUnlock()
3117
3118 if len(a.imports.streams) != len(b.imports.streams) {
3119 return false
3120 }
3121 // Load the b imports into a map index by what we are looking for.
3122 bm := make(map[string]*streamImport, len(b.imports.streams))
3123 for _, bim := range b.imports.streams {
3124 bm[bim.acc.Name+bim.from+bim.to] = bim
3125 }
3126 for _, aim := range a.imports.streams {
3127 if bim, ok := bm[aim.acc.Name+aim.from+aim.to]; !ok {
3128 return false
3129 } else if aim.atrc != bim.atrc {
3130 return false
3131 }
3132 }
3133 return true
3134 }
3135
3136 // Returns true if `a` and `b` stream exports are the same.
3137 // Acquires `a` read lock, but `b` is assumed to not be accessed
3138 // by anyone but the caller (`b` is not registered anywhere).
3139 func (a *Account) checkStreamExportsEqual(b *Account) bool {
3140 a.mu.RLock()
3141 defer a.mu.RUnlock()
3142 if len(a.exports.streams) != len(b.exports.streams) {
3143 return false
3144 }
3145 for subj, aea := range a.exports.streams {
3146 bea, ok := b.exports.streams[subj]
3147 if !ok {
3148 return false
3149 }
3150 if !isStreamExportEqual(aea, bea) {
3151 return false
3152 }
3153 }
3154 return true
3155 }
3156
3157 func isStreamExportEqual(a, b *streamExport) bool {
3158 if a == nil && b == nil {
3159 return true
3160 }
3161 if (a == nil && b != nil) || (a != nil && b == nil) {
3162 return false
3163 }
3164 return isExportAuthEqual(&a.exportAuth, &b.exportAuth)
3165 }
3166
3167 // Returns true if `a` and `b` service exports are the same.
3168 // Acquires `a` read lock, but `b` is assumed to not be accessed
3169 // by anyone but the caller (`b` is not registered anywhere).
3170 func (a *Account) checkServiceExportsEqual(b *Account) bool {
3171 a.mu.RLock()
3172 defer a.mu.RUnlock()
3173 if len(a.exports.services) != len(b.exports.services) {
3174 return false
3175 }
3176 for subj, aea := range a.exports.services {
3177 bea, ok := b.exports.services[subj]
3178 if !ok {
3179 return false
3180 }
3181 if !isServiceExportEqual(aea, bea) {
3182 return false
3183 }
3184 }
3185 return true
3186 }
3187
3188 func isServiceExportEqual(a, b *serviceExport) bool {
3189 if a == nil && b == nil {
3190 return true
3191 }
3192 if (a == nil && b != nil) || (a != nil && b == nil) {
3193 return false
3194 }
3195 if !isExportAuthEqual(&a.exportAuth, &b.exportAuth) {
3196 return false
3197 }
3198 if a.acc.Name != b.acc.Name {
3199 return false
3200 }
3201 if a.respType != b.respType {
3202 return false
3203 }
3204 if a.latency != nil || b.latency != nil {
3205 if (a.latency != nil && b.latency == nil) || (a.latency == nil && b.latency != nil) {
3206 return false
3207 }
3208 if a.latency.sampling != b.latency.sampling {
3209 return false
3210 }
3211 if a.latency.subject != b.latency.subject {
3212 return false
3213 }
3214 }
3215 if a.atrc != b.atrc {
3216 return false
3217 }
3218 return true
3219 }
3220
3221 // Returns true if `a` and `b` exportAuth structures are equal.
3222 // Both `a` and `b` are guaranteed to be non-nil.
3223 // Locking is handled by the caller.
3224 func isExportAuthEqual(a, b *exportAuth) bool {
3225 if a.tokenReq != b.tokenReq {
3226 return false
3227 }
3228 if a.accountPos != b.accountPos {
3229 return false
3230 }
3231 if len(a.approved) != len(b.approved) {
3232 return false
3233 }
3234 for ak, av := range a.approved {
3235 if bv, ok := b.approved[ak]; !ok || av.Name != bv.Name {
3236 return false
3237 }
3238 }
3239 if len(a.actsRevoked) != len(b.actsRevoked) {
3240 return false
3241 }
3242 for ak, av := range a.actsRevoked {
3243 if bv, ok := b.actsRevoked[ak]; !ok || av != bv {
3244 return false
3245 }
3246 }
3247 return true
3248 }
3249
3250 // Check if another account is authorized to route requests to this service.
3251 func (a *Account) checkServiceImportAuthorized(account *Account, subject string, imClaim *jwt.Import) bool {
3252 a.mu.RLock()
3253 authorized := a.checkServiceImportAuthorizedNoLock(account, subject, imClaim)
3254 a.mu.RUnlock()
3255 return authorized
3256 }
3257
3258 // Check if another account is authorized to route requests to this service.
3259 func (a *Account) checkServiceImportAuthorizedNoLock(account *Account, subject string, imClaim *jwt.Import) bool {
3260 // Find the subject in the services list.
3261 if a.exports.services == nil {
3262 return false
3263 }
3264 return a.checkServiceExportApproved(account, subject, imClaim)
3265 }
3266
3267 // IsExpired returns expiration status.
3268 func (a *Account) IsExpired() bool {
3269 return a.expired.Load()
3270 }
3271
3272 // Called when an account has expired.
3273 func (a *Account) expiredTimeout() {
3274 // Mark expired first.
3275 a.expired.Store(true)
3276
3277 // Collect the clients and expire them.
3278 cs := a.getClients()
3279 for _, c := range cs {
3280 if !isInternalClient(c.kind) {
3281 c.accountAuthExpired()
3282 }
3283 }
3284 }
3285
3286 // Sets the expiration timer for an account JWT that has it set.
3287 func (a *Account) setExpirationTimer(d time.Duration) {
3288 a.etmr = time.AfterFunc(d, a.expiredTimeout)
3289 }
3290
3291 // Lock should be held
3292 func (a *Account) clearExpirationTimer() bool {
3293 if a.etmr == nil {
3294 return true
3295 }
3296 stopped := a.etmr.Stop()
3297 a.etmr = nil
3298 return stopped
3299 }
3300
3301 // checkUserRevoked will check if a user has been revoked.
3302 func (a *Account) checkUserRevoked(nkey string, issuedAt int64) bool {
3303 a.mu.RLock()
3304 defer a.mu.RUnlock()
3305 return isRevoked(a.usersRevoked, nkey, issuedAt)
3306 }
3307
3308 // failBearer will return if bearer token are allowed (false) or disallowed (true)
3309 func (a *Account) failBearer() bool {
3310 a.mu.RLock()
3311 defer a.mu.RUnlock()
3312 return a.disallowBearer
3313 }
3314
3315 // Check expiration and set the proper state as needed.
3316 func (a *Account) checkExpiration(claims *jwt.ClaimsData) {
3317 a.mu.Lock()
3318 defer a.mu.Unlock()
3319
3320 a.clearExpirationTimer()
3321 if claims.Expires == 0 {
3322 a.expired.Store(false)
3323 return
3324 }
3325 tn := time.Now().Unix()
3326 if claims.Expires <= tn {
3327 a.expired.Store(true)
3328 return
3329 }
3330 expiresAt := time.Duration(claims.Expires - tn)
3331 a.setExpirationTimer(expiresAt * time.Second)
3332 a.expired.Store(false)
3333 }
3334
3335 // hasIssuer returns true if the issuer matches the account
3336 // If the issuer is a scoped signing key, the scope will be returned as well
3337 // issuer or it is a signing key for the account.
3338 func (a *Account) hasIssuer(issuer string) (jwt.Scope, bool) {
3339 a.mu.RLock()
3340 scope, ok := a.hasIssuerNoLock(issuer)
3341 a.mu.RUnlock()
3342 return scope, ok
3343 }
3344
3345 // hasIssuerNoLock is the unlocked version of hasIssuer
3346 func (a *Account) hasIssuerNoLock(issuer string) (jwt.Scope, bool) {
3347 scope, ok := a.signingKeys[issuer]
3348 return scope, ok
3349 }
3350
3351 // Returns the loop detection subject used for leafnodes
3352 func (a *Account) getLDSubject() string {
3353 a.mu.RLock()
3354 lds := a.lds
3355 a.mu.RUnlock()
3356 return lds
3357 }
3358
3359 // Placeholder for signaling token auth required.
3360 var tokenAuthReq = []*Account{}
3361
3362 func authAccounts(tokenReq bool) []*Account {
3363 if tokenReq {
3364 return tokenAuthReq
3365 }
3366 return nil
3367 }
3368
3369 // SetAccountResolver will assign the account resolver.
3370 func (s *Server) SetAccountResolver(ar AccountResolver) {
3371 s.mu.Lock()
3372 s.accResolver = ar
3373 s.mu.Unlock()
3374 }
3375
3376 // AccountResolver returns the registered account resolver.
3377 func (s *Server) AccountResolver() AccountResolver {
3378 s.mu.RLock()
3379 ar := s.accResolver
3380 s.mu.RUnlock()
3381 return ar
3382 }
3383
3384 // isClaimAccount returns if this account is backed by a JWT claim.
3385 // Lock should be held.
3386 func (a *Account) isClaimAccount() bool {
3387 return a.claimJWT != _EMPTY_
3388 }
3389
3390 // UpdateAccountClaims will update an existing account with new claims.
3391 // This will replace any exports or imports previously defined.
3392 // Lock MUST NOT be held upon entry.
3393 func (s *Server) UpdateAccountClaims(a *Account, ac *jwt.AccountClaims) {
3394 s.updateAccountClaimsWithRefresh(a, ac, true)
3395 }
3396
3397 func (a *Account) traceLabel() string {
3398 if a == nil {
3399 return _EMPTY_
3400 }
3401 if a.nameTag != _EMPTY_ {
3402 return fmt.Sprintf("%s/%s", a.Name, a.nameTag)
3403 }
3404 return a.Name
3405 }
3406
3407 // Check if an account has external auth set.
3408 // Operator/Account Resolver only.
3409 func (a *Account) hasExternalAuth() bool {
3410 if a == nil {
3411 return false
3412 }
3413 a.mu.RLock()
3414 defer a.mu.RUnlock()
3415 return a.extAuth != nil
3416 }
3417
3418 // Deterimine if this is an external auth user.
3419 func (a *Account) isExternalAuthUser(userID string) bool {
3420 if a == nil {
3421 return false
3422 }
3423 a.mu.RLock()
3424 defer a.mu.RUnlock()
3425 if a.extAuth != nil {
3426 for _, u := range a.extAuth.AuthUsers {
3427 if userID == u {
3428 return true
3429 }
3430 }
3431 }
3432 return false
3433 }
3434
3435 // Return the external authorization xkey if external authorization is enabled and the xkey is set.
3436 // Operator/Account Resolver only.
3437 func (a *Account) externalAuthXKey() string {
3438 if a == nil {
3439 return _EMPTY_
3440 }
3441 a.mu.RLock()
3442 defer a.mu.RUnlock()
3443 if a.extAuth != nil && a.extAuth.XKey != _EMPTY_ {
3444 return a.extAuth.XKey
3445 }
3446 return _EMPTY_
3447 }
3448
3449 // Check if an account switch for external authorization is allowed.
3450 func (a *Account) isAllowedAcount(acc string) bool {
3451 if a == nil {
3452 return false
3453 }
3454 a.mu.RLock()
3455 defer a.mu.RUnlock()
3456 if a.extAuth != nil {
3457 // if we have a single allowed account, and we have a wildcard
3458 // we accept it
3459 if len(a.extAuth.AllowedAccounts) == 1 &&
3460 a.extAuth.AllowedAccounts[0] == jwt.AnyAccount {
3461 return true
3462 }
3463 // otherwise must match exactly
3464 for _, a := range a.extAuth.AllowedAccounts {
3465 if a == acc {
3466 return true
3467 }
3468 }
3469 }
3470 return false
3471 }
3472
3473 // updateAccountClaimsWithRefresh will update an existing account with new claims.
3474 // If refreshImportingAccounts is true it will also update incomplete dependent accounts
3475 // This will replace any exports or imports previously defined.
3476 // Lock MUST NOT be held upon entry.
3477 func (s *Server) updateAccountClaimsWithRefresh(a *Account, ac *jwt.AccountClaims, refreshImportingAccounts bool) {
3478 if a == nil {
3479 return
3480 }
3481 s.Debugf("Updating account claims: %s/%s", a.Name, ac.Name)
3482 a.checkExpiration(ac.Claims())
3483
3484 a.mu.Lock()
3485 // Clone to update, only select certain fields.
3486 old := &Account{
3487 Name: a.Name,
3488 exports: a.exports,
3489 limits: a.limits,
3490 signingKeys: a.signingKeys,
3491 defaultPerms: a.defaultPerms.clone(),
3492 }
3493
3494 // overwrite claim meta data
3495 a.nameTag = ac.Name
3496 a.tags = ac.Tags
3497
3498 // Grab trace label under lock.
3499 tl := a.traceLabel()
3500
3501 var td string
3502 var tds int
3503 if ac.Trace != nil {
3504 // Update trace destination and sampling
3505 td, tds = string(ac.Trace.Destination), ac.Trace.Sampling
3506 if !IsValidPublishSubject(td) {
3507 td, tds = _EMPTY_, 0
3508 } else if tds <= 0 || tds > 100 {
3509 tds = 100
3510 }
3511 }
3512 a.traceDest, a.traceDestSampling = td, tds
3513
3514 // Check for external authorization.
3515 if ac.HasExternalAuthorization() {
3516 a.extAuth = &jwt.ExternalAuthorization{}
3517 a.extAuth.AuthUsers.Add(ac.Authorization.AuthUsers...)
3518 a.extAuth.AllowedAccounts.Add(ac.Authorization.AllowedAccounts...)
3519 a.extAuth.XKey = ac.Authorization.XKey
3520 } else {
3521 a.extAuth = nil
3522 }
3523
3524 // Reset exports and imports here.
3525
3526 // Exports is creating a whole new map.
3527 a.exports = exportMap{}
3528
3529 // Imports are checked unlocked in processInbound, so we can't change out the struct here. Need to process inline.
3530 if a.imports.streams != nil {
3531 old.imports.streams = a.imports.streams
3532 a.imports.streams = nil
3533 }
3534 if a.imports.services != nil {
3535 old.imports.services = make(map[string][]*serviceImport, len(a.imports.services))
3536 for k, v := range a.imports.services {
3537 sis := append([]*serviceImport(nil), v...)
3538 old.imports.services[k] = sis
3539 delete(a.imports.services, k)
3540 }
3541 }
3542
3543 alteredScope := map[string]struct{}{}
3544
3545 // update account signing keys
3546 a.signingKeys = nil
3547 _, strict := s.strictSigningKeyUsage[a.Issuer]
3548 if len(ac.SigningKeys) > 0 || !strict {
3549 a.signingKeys = make(map[string]jwt.Scope)
3550 }
3551 signersChanged := false
3552 for k, scope := range ac.SigningKeys {
3553 a.signingKeys[k] = scope
3554 }
3555 if !strict {
3556 a.signingKeys[a.Name] = nil
3557 }
3558 if len(a.signingKeys) != len(old.signingKeys) {
3559 signersChanged = true
3560 }
3561 for k, scope := range a.signingKeys {
3562 if oldScope, ok := old.signingKeys[k]; !ok {
3563 signersChanged = true
3564 } else if !reflect.DeepEqual(scope, oldScope) {
3565 signersChanged = true
3566 alteredScope[k] = struct{}{}
3567 }
3568 }
3569 // collect mappings that need to be removed
3570 removeList := []string{}
3571 for _, m := range a.mappings {
3572 if _, ok := ac.Mappings[jwt.Subject(m.src)]; !ok {
3573 removeList = append(removeList, m.src)
3574 }
3575 }
3576 a.mu.Unlock()
3577
3578 for sub, wm := range ac.Mappings {
3579 mappings := make([]*MapDest, len(wm))
3580 for i, m := range wm {
3581 mappings[i] = &MapDest{
3582 Subject: string(m.Subject),
3583 Weight: m.GetWeight(),
3584 Cluster: m.Cluster,
3585 }
3586 }
3587 // This will overwrite existing entries
3588 a.AddWeightedMappings(string(sub), mappings...)
3589 }
3590 // remove mappings
3591 for _, rmMapping := range removeList {
3592 a.RemoveMapping(rmMapping)
3593 }
3594
3595 // Re-register system exports/imports.
3596 if a == s.SystemAccount() {
3597 s.addSystemAccountExports(a)
3598 } else {
3599 s.registerSystemImports(a)
3600 }
3601
3602 jsEnabled := s.JetStreamEnabled()
3603
3604 streamTokenExpirationChanged := false
3605 serviceTokenExpirationChanged := false
3606
3607 for _, e := range ac.Exports {
3608 switch e.Type {
3609 case jwt.Stream:
3610 s.Debugf("Adding stream export %q for %s", e.Subject, tl)
3611 if err := a.addStreamExportWithAccountPos(
3612 string(e.Subject), authAccounts(e.TokenReq), e.AccountTokenPosition); err != nil {
3613 s.Debugf("Error adding stream export to account [%s]: %v", tl, err.Error())
3614 }
3615 case jwt.Service:
3616 s.Debugf("Adding service export %q for %s", e.Subject, tl)
3617 rt := Singleton
3618 switch e.ResponseType {
3619 case jwt.ResponseTypeStream:
3620 rt = Streamed
3621 case jwt.ResponseTypeChunked:
3622 rt = Chunked
3623 }
3624 if err := a.addServiceExportWithResponseAndAccountPos(
3625 string(e.Subject), rt, authAccounts(e.TokenReq), e.AccountTokenPosition); err != nil {
3626 s.Debugf("Error adding service export to account [%s]: %v", tl, err)
3627 continue
3628 }
3629 sub := string(e.Subject)
3630 if e.Latency != nil {
3631 if err := a.TrackServiceExportWithSampling(sub, string(e.Latency.Results), int(e.Latency.Sampling)); err != nil {
3632 hdrNote := _EMPTY_
3633 if e.Latency.Sampling == jwt.Headers {
3634 hdrNote = " (using headers)"
3635 }
3636 s.Debugf("Error adding latency tracking%s for service export to account [%s]: %v", hdrNote, tl, err)
3637 }
3638 }
3639 if e.ResponseThreshold != 0 {
3640 // Response threshold was set in options.
3641 if err := a.SetServiceExportResponseThreshold(sub, e.ResponseThreshold); err != nil {
3642 s.Debugf("Error adding service export response threshold for [%s]: %v", tl, err)
3643 }
3644 }
3645 if err := a.SetServiceExportAllowTrace(sub, e.AllowTrace); err != nil {
3646 s.Debugf("Error adding allow_trace for %q: %v", sub, err)
3647 }
3648 }
3649
3650 var revocationChanged *bool
3651 var ea *exportAuth
3652
3653 a.mu.Lock()
3654 switch e.Type {
3655 case jwt.Stream:
3656 revocationChanged = &streamTokenExpirationChanged
3657 if se, ok := a.exports.streams[string(e.Subject)]; ok && se != nil {
3658 ea = &se.exportAuth
3659 }
3660 case jwt.Service:
3661 revocationChanged = &serviceTokenExpirationChanged
3662 if se, ok := a.exports.services[string(e.Subject)]; ok && se != nil {
3663 ea = &se.exportAuth
3664 }
3665 }
3666 if ea != nil {
3667 oldRevocations := ea.actsRevoked
3668 if len(e.Revocations) == 0 {
3669 // remove all, no need to evaluate existing imports
3670 ea.actsRevoked = nil
3671 } else if len(oldRevocations) == 0 {
3672 // add all, existing imports need to be re evaluated
3673 ea.actsRevoked = e.Revocations
3674 *revocationChanged = true
3675 } else {
3676 ea.actsRevoked = e.Revocations
3677 // diff, existing imports need to be conditionally re evaluated, depending on:
3678 // if a key was added, or it's timestamp increased
3679 for k, t := range e.Revocations {
3680 if tOld, ok := oldRevocations[k]; !ok || tOld < t {
3681 *revocationChanged = true
3682 }
3683 }
3684 }
3685 }
3686 a.mu.Unlock()
3687 }
3688 var incompleteImports []*jwt.Import
3689 for _, i := range ac.Imports {
3690 acc, err := s.lookupAccount(i.Account)
3691 if acc == nil || err != nil {
3692 s.Errorf("Can't locate account [%s] for import of [%v] %s (err=%v)", i.Account, i.Subject, i.Type, err)
3693 incompleteImports = append(incompleteImports, i)
3694 continue
3695 }
3696 // Capture trace labels.
3697 acc.mu.RLock()
3698 atl := acc.traceLabel()
3699 acc.mu.RUnlock()
3700 // Grab from and to
3701 from, to := string(i.Subject), i.GetTo()
3702 switch i.Type {
3703 case jwt.Stream:
3704 if i.LocalSubject != _EMPTY_ {
3705 // set local subject implies to is empty
3706 to = string(i.LocalSubject)
3707 s.Debugf("Adding stream import %s:%q for %s:%q", atl, from, tl, to)
3708 err = a.AddMappedStreamImportWithClaim(acc, from, to, i)
3709 } else {
3710 s.Debugf("Adding stream import %s:%q for %s:%q", atl, from, tl, to)
3711 err = a.AddStreamImportWithClaim(acc, from, to, i)
3712 }
3713 if err != nil {
3714 s.Debugf("Error adding stream import to account [%s]: %v", tl, err.Error())
3715 incompleteImports = append(incompleteImports, i)
3716 }
3717 case jwt.Service:
3718 if i.LocalSubject != _EMPTY_ {
3719 from = string(i.LocalSubject)
3720 to = string(i.Subject)
3721 }
3722 s.Debugf("Adding service import %s:%q for %s:%q", atl, from, tl, to)
3723 if err := a.AddServiceImportWithClaim(acc, from, to, i); err != nil {
3724 s.Debugf("Error adding service import to account [%s]: %v", tl, err.Error())
3725 incompleteImports = append(incompleteImports, i)
3726 }
3727 }
3728 }
3729 // Now let's apply any needed changes from import/export changes.
3730 if !a.checkStreamImportsEqual(old) {
3731 awcsti := map[string]struct{}{a.Name: {}}
3732 for _, c := range a.getClients() {
3733 c.processSubsOnConfigReload(awcsti)
3734 }
3735 }
3736 // Now check if stream exports have changed.
3737 if !a.checkStreamExportsEqual(old) || signersChanged || streamTokenExpirationChanged {
3738 clients := map[*client]struct{}{}
3739 // We need to check all accounts that have an import claim from this account.
3740 awcsti := map[string]struct{}{}
3741
3742 // We must only allow one goroutine to go through here, otherwise we could deadlock
3743 // due to locking two accounts in succession.
3744 s.mu.Lock()
3745 s.accounts.Range(func(k, v any) bool {
3746 acc := v.(*Account)
3747 // Move to the next if this account is actually account "a".
3748 if acc.Name == a.Name {
3749 return true
3750 }
3751 acc.mu.Lock()
3752 for _, im := range acc.imports.streams {
3753 if im != nil && im.acc.Name == a.Name {
3754 // Check for if we are still authorized for an import.
3755 im.invalid = !a.checkStreamImportAuthorized(acc, im.from, im.claim)
3756 awcsti[acc.Name] = struct{}{}
3757 for c := range acc.clients {
3758 clients[c] = struct{}{}
3759 }
3760 }
3761 }
3762 acc.mu.Unlock()
3763 return true
3764 })
3765 s.mu.Unlock()
3766 // Now walk clients.
3767 for c := range clients {
3768 c.processSubsOnConfigReload(awcsti)
3769 }
3770 }
3771 // Now check if service exports have changed.
3772 if !a.checkServiceExportsEqual(old) || signersChanged || serviceTokenExpirationChanged {
3773 // We must only allow one goroutine to go through here, otherwise we could deadlock
3774 // due to locking two accounts in succession.
3775 s.mu.Lock()
3776 s.accounts.Range(func(k, v any) bool {
3777 acc := v.(*Account)
3778 // Move to the next if this account is actually account "a".
3779 if acc.Name == a.Name {
3780 return true
3781 }
3782 acc.mu.Lock()
3783 for _, sis := range acc.imports.services {
3784 for _, si := range sis {
3785 if si != nil && si.acc.Name == a.Name {
3786 // Check for if we are still authorized for an import.
3787 si.invalid = !a.checkServiceImportAuthorized(acc, si.to, si.claim)
3788 // Make sure we should still be tracking latency and if we
3789 // are allowed to trace.
3790 if !si.response {
3791 a.mu.RLock()
3792 if se := a.getServiceExport(si.to); se != nil {
3793 if si.latency != nil {
3794 si.latency = se.latency
3795 }
3796 // Update allow trace.
3797 si.atrc = se.atrc
3798 }
3799 a.mu.RUnlock()
3800 }
3801 }
3802 }
3803 }
3804 acc.mu.Unlock()
3805 return true
3806 })
3807 s.mu.Unlock()
3808 }
3809
3810 // Now make sure we shutdown the old service import subscriptions.
3811 var sids [][]byte
3812 a.mu.RLock()
3813 c := a.ic
3814 if c != nil {
3815 for _, sis := range old.imports.services {
3816 for _, si := range sis {
3817 if si.sid != nil {
3818 sids = append(sids, si.sid)
3819 }
3820 }
3821 }
3822 }
3823 a.mu.RUnlock()
3824 for _, sid := range sids {
3825 c.processUnsub(sid)
3826 }
3827
3828 // Now do limits if they are present.
3829 a.mu.Lock()
3830 a.msubs = clampInt64ToInt32(ac.Limits.Subs)
3831 a.mpay = clampInt64ToInt32(ac.Limits.Payload)
3832 a.mconns = clampInt64ToInt32(ac.Limits.Conn)
3833 a.mleafs = clampInt64ToInt32(ac.Limits.LeafNodeConn)
3834 a.disallowBearer = ac.Limits.DisallowBearer
3835 // Check for any revocations
3836 if len(ac.Revocations) > 0 {
3837 // We will always replace whatever we had with most current, so no
3838 // need to look at what we have.
3839 a.usersRevoked = make(map[string]int64, len(ac.Revocations))
3840 for pk, t := range ac.Revocations {
3841 a.usersRevoked[pk] = t
3842 }
3843 } else {
3844 a.usersRevoked = nil
3845 }
3846 a.defaultPerms = buildPermissionsFromJwt(&ac.DefaultPermissions)
3847 a.incomplete = len(incompleteImports) != 0
3848 for _, i := range incompleteImports {
3849 s.incompleteAccExporterMap.Store(i.Account, struct{}{})
3850 }
3851 if a.srv == nil {
3852 a.srv = s
3853 }
3854
3855 if ac.Limits.IsJSEnabled() {
3856 toUnlimited := func(value int64) int64 {
3857 if value > 0 {
3858 return value
3859 }
3860 return -1
3861 }
3862 if ac.Limits.JetStreamLimits.DiskStorage != 0 || ac.Limits.JetStreamLimits.MemoryStorage != 0 {
3863 // JetStreamAccountLimits and jwt.JetStreamLimits use same value for unlimited
3864 a.jsLimits = map[string]JetStreamAccountLimits{
3865 _EMPTY_: {
3866 MaxMemory: ac.Limits.JetStreamLimits.MemoryStorage,
3867 MaxStore: ac.Limits.JetStreamLimits.DiskStorage,
3868 MaxStreams: int(ac.Limits.JetStreamLimits.Streams),
3869 MaxConsumers: int(ac.Limits.JetStreamLimits.Consumer),
3870 MemoryMaxStreamBytes: toUnlimited(ac.Limits.JetStreamLimits.MemoryMaxStreamBytes),
3871 StoreMaxStreamBytes: toUnlimited(ac.Limits.JetStreamLimits.DiskMaxStreamBytes),
3872 MaxBytesRequired: ac.Limits.JetStreamLimits.MaxBytesRequired,
3873 MaxAckPending: int(toUnlimited(ac.Limits.JetStreamLimits.MaxAckPending)),
3874 },
3875 }
3876 } else {
3877 a.jsLimits = map[string]JetStreamAccountLimits{}
3878 for t, l := range ac.Limits.JetStreamTieredLimits {
3879 a.jsLimits[t] = JetStreamAccountLimits{
3880 MaxMemory: l.MemoryStorage,
3881 MaxStore: l.DiskStorage,
3882 MaxStreams: int(l.Streams),
3883 MaxConsumers: int(l.Consumer),
3884 MemoryMaxStreamBytes: toUnlimited(l.MemoryMaxStreamBytes),
3885 StoreMaxStreamBytes: toUnlimited(l.DiskMaxStreamBytes),
3886 MaxBytesRequired: l.MaxBytesRequired,
3887 MaxAckPending: int(toUnlimited(l.MaxAckPending)),
3888 }
3889 }
3890 }
3891 } else if a.jsLimits != nil {
3892 // covers failed update followed by disable
3893 a.jsLimits = nil
3894 }
3895
3896 defaultPerms := a.defaultPerms
3897 defaultPermsChanged := !reflect.DeepEqual(old.defaultPerms, defaultPerms)
3898 a.updated = time.Now()
3899 clients := a.getClientsLocked()
3900 ajs := a.js
3901 hasJsLimits := a.jsLimits != nil
3902 a.mu.Unlock()
3903
3904 // Sort in chronological order so that most recent connections over the limit are pruned.
3905 if a.MaxTotalConnectionsReached() {
3906 slices.SortFunc(clients, func(i, j *client) int { return i.start.Compare(j.start) })
3907 }
3908
3909 // If JetStream is enabled for this server we will call into configJetStream for the account
3910 // regardless of enabled or disabled. It handles both cases.
3911 if jsEnabled {
3912 if err := s.configJetStream(a, nil); err != nil {
3913 s.Errorf("Error configuring jetstream for account [%s]: %v", tl, err.Error())
3914 a.mu.Lock()
3915 // Absent reload of js server cfg, this is going to be broken until js is disabled
3916 a.incomplete = true
3917 a.mu.Unlock()
3918 } else {
3919 a.mu.Lock()
3920 // Refresh reference, we've just enabled JetStream, so it would have been nil before.
3921 ajs = a.js
3922 a.mu.Unlock()
3923 }
3924 } else if hasJsLimits {
3925 // We do not have JS enabled for this server, but the account has it enabled so setup
3926 // our imports properly. This allows this server to proxy JS traffic correctly.
3927 s.checkJetStreamExports()
3928 a.enableAllJetStreamServiceImportsAndMappings()
3929 }
3930
3931 if ajs != nil {
3932 // Check whether the account NRG status changed. If it has then we need to notify the
3933 // Raft groups running on the system so that they can move their subs if needed.
3934 a.mu.Lock()
3935 previous := a.nrgAccount
3936 switch ac.ClusterTraffic {
3937 case "system", _EMPTY_:
3938 a.nrgAccount = _EMPTY_
3939 case "owner":
3940 a.nrgAccount = a.Name
3941 default:
3942 s.Errorf("Account claim for %q has invalid value %q for cluster traffic account", a.Name, ac.ClusterTraffic)
3943 }
3944 changed := a.nrgAccount != previous
3945 a.mu.Unlock()
3946 if changed {
3947 s.updateNRGAccountStatus()
3948 }
3949 }
3950
3951 // client list is in chronological order (older cids at the beginning of the list).
3952 count := 0
3953 for _, c := range clients {
3954 a.mu.RLock()
3955 exceeded := a.mconns != jwt.NoLimit && count >= int(a.mconns)
3956 a.mu.RUnlock()
3957 // Only kick non-internal clients.
3958 if !isInternalClient(c.kind) {
3959 if exceeded {
3960 c.maxAccountConnExceeded()
3961 continue
3962 }
3963 count++
3964 }
3965 c.mu.Lock()
3966 c.applyAccountLimits()
3967 // if we have an nkey user we are a callout user - save
3968 // the issuedAt, and nkey user id to honor revocations
3969 var nkeyUserID string
3970 var issuedAt int64
3971 if c.user != nil {
3972 issuedAt = c.user.Issued
3973 nkeyUserID = c.user.Nkey
3974 }
3975 theJWT := c.opts.JWT
3976 c.mu.Unlock()
3977 if defaultPermsChanged && c.updateDefaultPermissions(defaultPerms) && defaultPerms != nil {
3978 c.processSubsOnConfigReload(nil)
3979 }
3980 // Check for being revoked here. We use ac one to avoid the account lock.
3981 if (ac.Revocations != nil || ac.Limits.DisallowBearer) && theJWT != _EMPTY_ {
3982 if juc, err := jwt.DecodeUserClaims(theJWT); err != nil {
3983 c.Debugf("User JWT not valid: %v", err)
3984 c.authViolation()
3985 continue
3986 } else if juc.BearerToken && ac.Limits.DisallowBearer {
3987 c.Debugf("Bearer User JWT not allowed")
3988 c.authViolation()
3989 continue
3990 } else if ok := ac.IsClaimRevoked(juc); ok {
3991 c.sendErrAndDebug("User Authentication Revoked")
3992 c.closeConnection(Revocation)
3993 continue
3994 }
3995 }
3996
3997 // if we extracted nkeyUserID and issuedAt we are a callout type
3998 // calloutIAT should only be set if we are in callout scenario as
3999 // the user JWT is _NOT_ associated with the client for callouts,
4000 // so we rely on the calloutIAT to know when the JWT was issued
4001 // revocations simply state that JWT issued before or by that date
4002 // are not valid
4003 if ac.Revocations != nil && nkeyUserID != _EMPTY_ && issuedAt > 0 {
4004 seconds, ok := ac.Revocations[jwt.All]
4005 if ok && seconds >= issuedAt {
4006 c.sendErrAndDebug("User Authentication Revoked")
4007 c.closeConnection(Revocation)
4008 continue
4009 }
4010 seconds, ok = ac.Revocations[nkeyUserID]
4011 if ok && seconds >= issuedAt {
4012 c.sendErrAndDebug("User Authentication Revoked")
4013 c.closeConnection(Revocation)
4014 continue
4015 }
4016 }
4017 }
4018
4019 // Check if the signing keys changed, might have to evict
4020 if signersChanged {
4021 for _, c := range clients {
4022 c.mu.Lock()
4023 if c.user == nil {
4024 c.mu.Unlock()
4025 continue
4026 }
4027 sk := c.user.SigningKey
4028 c.mu.Unlock()
4029 if sk == _EMPTY_ {
4030 continue
4031 }
4032 if _, ok := alteredScope[sk]; ok {
4033 c.closeConnection(AuthenticationViolation)
4034 } else if _, ok := a.hasIssuer(sk); !ok {
4035 c.closeConnection(AuthenticationViolation)
4036 }
4037 }
4038 }
4039
4040 if _, ok := s.incompleteAccExporterMap.Load(old.Name); ok && refreshImportingAccounts {
4041 s.incompleteAccExporterMap.Delete(old.Name)
4042 s.accounts.Range(func(key, value any) bool {
4043 acc := value.(*Account)
4044 acc.mu.RLock()
4045 incomplete := acc.incomplete
4046 name := acc.Name
4047 label := acc.traceLabel()
4048 // Must use jwt in account or risk failing on fetch
4049 // This jwt may not be the same that caused exportingAcc to be in incompleteAccExporterMap
4050 claimJWT := acc.claimJWT
4051 acc.mu.RUnlock()
4052 if incomplete && name != old.Name {
4053 if accClaims, _, err := s.verifyAccountClaims(claimJWT); err == nil {
4054 // Since claimJWT has not changed, acc can become complete
4055 // but it won't alter incomplete for it's dependents accounts.
4056 s.updateAccountClaimsWithRefresh(acc, accClaims, false)
4057 // old.Name was deleted before ranging over accounts
4058 // If it exists again, UpdateAccountClaims set it for failed imports of acc.
4059 // So there was one import of acc that imported this account and failed again.
4060 // Since this account just got updated, the import itself may be in error. So trace that.
4061 if _, ok := s.incompleteAccExporterMap.Load(old.Name); ok {
4062 s.incompleteAccExporterMap.Delete(old.Name)
4063 s.Errorf("Account %s has issues importing account %s", label, old.Name)
4064 }
4065 }
4066 }
4067 return true
4068 })
4069 }
4070 }
4071
4072 // Helper to build an internal account structure from a jwt.AccountClaims.
4073 // Lock MUST NOT be held upon entry.
4074 func (s *Server) buildInternalAccount(ac *jwt.AccountClaims) *Account {
4075 acc := NewAccount(ac.Subject)
4076 acc.Issuer = ac.Issuer
4077 // Set this here since we are placing in s.tmpAccounts below and may be
4078 // referenced by an route RS+, etc.
4079 s.setAccountSublist(acc)
4080
4081 // We don't want to register an account that is in the process of
4082 // being built, however, to solve circular import dependencies, we
4083 // need to store it here.
4084 if v, loaded := s.tmpAccounts.LoadOrStore(ac.Subject, acc); loaded {
4085 return v.(*Account)
4086 }
4087
4088 // Update based on claims.
4089 s.UpdateAccountClaims(acc, ac)
4090
4091 return acc
4092 }
4093
4094 // Helper to build Permissions from jwt.Permissions
4095 // or return nil if none were specified
4096 func buildPermissionsFromJwt(uc *jwt.Permissions) *Permissions {
4097 if uc == nil {
4098 return nil
4099 }
4100 var p *Permissions
4101 if len(uc.Pub.Allow) > 0 || len(uc.Pub.Deny) > 0 {
4102 p = &Permissions{}
4103 p.Publish = &SubjectPermission{}
4104 p.Publish.Allow = uc.Pub.Allow
4105 p.Publish.Deny = uc.Pub.Deny
4106 }
4107 if len(uc.Sub.Allow) > 0 || len(uc.Sub.Deny) > 0 {
4108 if p == nil {
4109 p = &Permissions{}
4110 }
4111 p.Subscribe = &SubjectPermission{}
4112 p.Subscribe.Allow = uc.Sub.Allow
4113 p.Subscribe.Deny = uc.Sub.Deny
4114 }
4115 if uc.Resp != nil {
4116 if p == nil {
4117 p = &Permissions{}
4118 }
4119 p.Response = &ResponsePermission{
4120 MaxMsgs: uc.Resp.MaxMsgs,
4121 Expires: uc.Resp.Expires,
4122 }
4123 validateResponsePermissions(p)
4124 }
4125 return p
4126 }
4127
4128 // Helper to build internal NKeyUser.
4129 func buildInternalNkeyUser(uc *jwt.UserClaims, acts map[string]struct{}, acc *Account) *NkeyUser {
4130 nu := &NkeyUser{Nkey: uc.Subject, Account: acc, AllowedConnectionTypes: acts, Issued: uc.IssuedAt}
4131 if uc.IssuerAccount != _EMPTY_ {
4132 nu.SigningKey = uc.Issuer
4133 }
4134
4135 // Now check for permissions.
4136 var p = buildPermissionsFromJwt(&uc.Permissions)
4137 if p == nil {
4138 nu.defaultPerms = true
4139 acc.mu.RLock()
4140 if acc.defaultPerms != nil {
4141 p = acc.defaultPerms.clone()
4142 }
4143 acc.mu.RUnlock()
4144 }
4145 nu.Permissions = p
4146 return nu
4147 }
4148
4149 func fetchAccount(res AccountResolver, name string) (string, error) {
4150 if !nkeys.IsValidPublicAccountKey(name) {
4151 return _EMPTY_, fmt.Errorf("will only fetch valid account keys")
4152 }
4153 return res.Fetch(copyString(name))
4154 }
4155
4156 // AccountResolver interface. This is to fetch Account JWTs by public nkeys
4157 type AccountResolver interface {
4158 Fetch(name string) (string, error)
4159 Store(name, jwt string) error
4160 IsReadOnly() bool
4161 Start(server *Server) error
4162 IsTrackingUpdate() bool
4163 Reload() error
4164 Close()
4165 }
4166
4167 // Default implementations of IsReadOnly/Start so only need to be written when changed
4168 type resolverDefaultsOpsImpl struct{}
4169
4170 func (*resolverDefaultsOpsImpl) IsReadOnly() bool {
4171 return true
4172 }
4173
4174 func (*resolverDefaultsOpsImpl) IsTrackingUpdate() bool {
4175 return false
4176 }
4177
4178 func (*resolverDefaultsOpsImpl) Start(*Server) error {
4179 return nil
4180 }
4181
4182 func (*resolverDefaultsOpsImpl) Reload() error {
4183 return nil
4184 }
4185
4186 func (*resolverDefaultsOpsImpl) Close() {
4187 }
4188
4189 func (*resolverDefaultsOpsImpl) Store(_, _ string) error {
4190 return fmt.Errorf("store operation not supported for URL Resolver")
4191 }
4192
4193 // MemAccResolver is a memory only resolver.
4194 // Mostly for testing.
4195 type MemAccResolver struct {
4196 sm sync.Map
4197 resolverDefaultsOpsImpl
4198 }
4199
4200 // Fetch will fetch the account jwt claims from the internal sync.Map.
4201 func (m *MemAccResolver) Fetch(name string) (string, error) {
4202 if j, ok := m.sm.Load(name); ok {
4203 return j.(string), nil
4204 }
4205 return _EMPTY_, ErrMissingAccount
4206 }
4207
4208 // Store will store the account jwt claims in the internal sync.Map.
4209 func (m *MemAccResolver) Store(name, jwt string) error {
4210 m.sm.Store(name, jwt)
4211 return nil
4212 }
4213
4214 func (m *MemAccResolver) IsReadOnly() bool {
4215 return false
4216 }
4217
4218 // URLAccResolver implements an http fetcher.
4219 type URLAccResolver struct {
4220 url string
4221 c *http.Client
4222 resolverDefaultsOpsImpl
4223 }
4224
4225 // NewURLAccResolver returns a new resolver for the given base URL.
4226 func NewURLAccResolver(url string) (*URLAccResolver, error) {
4227 if !strings.HasSuffix(url, "/") {
4228 url += "/"
4229 }
4230 // FIXME(dlc) - Make timeout and others configurable.
4231 // We create our own transport to amortize TLS.
4232 tr := &http.Transport{
4233 MaxIdleConns: 10,
4234 IdleConnTimeout: 30 * time.Second,
4235 }
4236 ur := &URLAccResolver{
4237 url: url,
4238 c: &http.Client{Timeout: DEFAULT_ACCOUNT_FETCH_TIMEOUT, Transport: tr},
4239 }
4240 return ur, nil
4241 }
4242
4243 // Fetch will fetch the account jwt claims from the base url, appending the
4244 // account name onto the end.
4245 func (ur *URLAccResolver) Fetch(name string) (string, error) {
4246 url := ur.url + name
4247 resp, err := ur.c.Get(url)
4248 if err != nil {
4249 return _EMPTY_, fmt.Errorf("could not fetch <%q>: %v", redactURLString(url), err)
4250 } else if resp == nil {
4251 return _EMPTY_, fmt.Errorf("could not fetch <%q>: no response", redactURLString(url))
4252 }
4253 defer resp.Body.Close()
4254 if resp.StatusCode != http.StatusOK {
4255 return _EMPTY_, fmt.Errorf("could not fetch <%q>: %v", redactURLString(url), resp.Status)
4256 }
4257 body, err := io.ReadAll(resp.Body)
4258 if err != nil {
4259 return _EMPTY_, err
4260 }
4261 return string(body), nil
4262 }
4263
4264 // Resolver based on nats for synchronization and backing directory for storage.
4265 type DirAccResolver struct {
4266 *DirJWTStore
4267 *Server
4268 syncInterval time.Duration
4269 fetchTimeout time.Duration
4270 }
4271
4272 func (dr *DirAccResolver) IsTrackingUpdate() bool {
4273 return true
4274 }
4275
4276 func (dr *DirAccResolver) Reload() error {
4277 return dr.DirJWTStore.Reload()
4278 }
4279
4280 // ServerAPIClaimUpdateResponse is the response to $SYS.REQ.ACCOUNT.<id>.CLAIMS.UPDATE and $SYS.REQ.CLAIMS.UPDATE
4281 type ServerAPIClaimUpdateResponse struct {
4282 Server *ServerInfo `json:"server"`
4283 Data *ClaimUpdateStatus `json:"data,omitempty"`
4284 Error *ClaimUpdateError `json:"error,omitempty"`
4285 }
4286
4287 type ClaimUpdateError struct {
4288 Account string `json:"account,omitempty"`
4289 Code int `json:"code"`
4290 Description string `json:"description,omitempty"`
4291 }
4292
4293 type ClaimUpdateStatus struct {
4294 Account string `json:"account,omitempty"`
4295 Code int `json:"code,omitempty"`
4296 Message string `json:"message,omitempty"`
4297 }
4298
4299 func respondToUpdate(s *Server, respSubj string, acc string, message string, err error) {
4300 if err == nil {
4301 if acc == _EMPTY_ {
4302 s.Debugf("%s", message)
4303 } else {
4304 s.Debugf("%s - %s", message, acc)
4305 }
4306 } else {
4307 if acc == _EMPTY_ {
4308 s.Errorf("%s - %s", message, err)
4309 } else {
4310 s.Errorf("%s - %s - %s", message, acc, err)
4311 }
4312 }
4313 if respSubj == _EMPTY_ {
4314 return
4315 }
4316
4317 response := ServerAPIClaimUpdateResponse{
4318 Server: &ServerInfo{},
4319 }
4320
4321 if err == nil {
4322 response.Data = &ClaimUpdateStatus{
4323 Account: acc,
4324 Code: http.StatusOK,
4325 Message: message,
4326 }
4327 } else {
4328 response.Error = &ClaimUpdateError{
4329 Account: acc,
4330 Code: http.StatusInternalServerError,
4331 Description: fmt.Sprintf("%s - %v", message, err),
4332 }
4333 }
4334
4335 s.sendInternalMsgLocked(respSubj, _EMPTY_, response.Server, response)
4336 }
4337
4338 func handleListRequest(store *DirJWTStore, s *Server, reply string) {
4339 if reply == _EMPTY_ {
4340 return
4341 }
4342 accIds := make([]string, 0, 1024)
4343 if err := store.PackWalk(1, func(partialPackMsg string) {
4344 if tk := strings.Split(partialPackMsg, "|"); len(tk) == 2 {
4345 accIds = append(accIds, tk[0])
4346 }
4347 }); err != nil {
4348 // let them timeout
4349 s.Errorf("list request error: %v", err)
4350 } else {
4351 s.Debugf("list request responded with %d account ids", len(accIds))
4352 server := &ServerInfo{}
4353 response := map[string]any{"server": server, "data": accIds}
4354 s.sendInternalMsgLocked(reply, _EMPTY_, server, response)
4355 }
4356 }
4357
4358 func handleDeleteRequest(store *DirJWTStore, s *Server, msg []byte, reply string) {
4359 var accIds []any
4360 var subj, sysAccName string
4361 if sysAcc := s.SystemAccount(); sysAcc != nil {
4362 sysAccName = sysAcc.GetName()
4363 }
4364 // Only operator and operator signing key are allowed to delete
4365 gk, err := jwt.DecodeGeneric(string(msg))
4366 if err == nil {
4367 subj = gk.Subject
4368 if store.deleteType == NoDelete {
4369 err = fmt.Errorf("delete must be enabled in server config")
4370 } else if subj != gk.Issuer {
4371 err = fmt.Errorf("not self signed")
4372 } else if _, ok := store.operator[gk.Issuer]; !ok {
4373 err = fmt.Errorf("not trusted")
4374 } else if list, ok := gk.Data["accounts"]; !ok {
4375 err = fmt.Errorf("malformed request")
4376 } else if accIds, ok = list.([]any); !ok {
4377 err = fmt.Errorf("malformed request")
4378 } else {
4379 for _, entry := range accIds {
4380 if acc, ok := entry.(string); !ok ||
4381 acc == _EMPTY_ || !nkeys.IsValidPublicAccountKey(acc) {
4382 err = fmt.Errorf("malformed request")
4383 break
4384 } else if acc == sysAccName {
4385 err = fmt.Errorf("not allowed to delete system account")
4386 break
4387 }
4388 }
4389 }
4390 }
4391 if err != nil {
4392 respondToUpdate(s, reply, _EMPTY_, fmt.Sprintf("delete accounts request by %s failed", subj), err)
4393 return
4394 }
4395 errs := []string{}
4396 passCnt := 0
4397 for _, acc := range accIds {
4398 if err := store.delete(acc.(string)); err != nil {
4399 errs = append(errs, err.Error())
4400 } else {
4401 passCnt++
4402 }
4403 }
4404 if len(errs) == 0 {
4405 respondToUpdate(s, reply, _EMPTY_, fmt.Sprintf("deleted %d accounts", passCnt), nil)
4406 } else {
4407 respondToUpdate(s, reply, _EMPTY_, fmt.Sprintf("deleted %d accounts, failed for %d", passCnt, len(errs)),
4408 errors.New(strings.Join(errs, "\n")))
4409 }
4410 }
4411
4412 func getOperatorKeys(s *Server) (string, map[string]struct{}, bool, error) {
4413 var op string
4414 var strict bool
4415 keys := make(map[string]struct{})
4416 if opts := s.getOpts(); opts != nil && len(opts.TrustedOperators) > 0 {
4417 op = opts.TrustedOperators[0].Subject
4418 strict = opts.TrustedOperators[0].StrictSigningKeyUsage
4419 if !strict {
4420 keys[opts.TrustedOperators[0].Subject] = struct{}{}
4421 }
4422 for _, key := range opts.TrustedOperators[0].SigningKeys {
4423 keys[key] = struct{}{}
4424 }
4425 }
4426 if len(keys) == 0 {
4427 return _EMPTY_, nil, false, fmt.Errorf("no operator key found")
4428 }
4429 return op, keys, strict, nil
4430 }
4431
4432 func claimValidate(claim *jwt.AccountClaims) error {
4433 vr := &jwt.ValidationResults{}
4434 claim.Validate(vr)
4435 if vr.IsBlocking(false) {
4436 return fmt.Errorf("validation errors: %v", vr.Errors())
4437 }
4438 return nil
4439 }
4440
4441 func removeCb(s *Server, pubKey string) {
4442 v, ok := s.accounts.Load(pubKey)
4443 if !ok {
4444 return
4445 }
4446 a := v.(*Account)
4447 s.Debugf("Disable account %s due to remove", pubKey)
4448 a.mu.Lock()
4449 // lock out new clients
4450 a.msubs = 0
4451 a.mpay = 0
4452 a.mconns = 0
4453 a.mleafs = 0
4454 a.updated = time.Now()
4455 jsa := a.js
4456 a.mu.Unlock()
4457 // set the account to be expired and disconnect clients
4458 a.expiredTimeout()
4459 // For JS, we need also to disable it.
4460 if js := s.getJetStream(); js != nil && jsa != nil {
4461 js.disableJetStream(jsa)
4462 // Remove JetStream state in memory, this will be reset
4463 // on the changed callback from the account in case it is
4464 // enabled again.
4465 a.mu.Lock()
4466 a.js = nil
4467 a.mu.Unlock()
4468 }
4469 // We also need to remove all ServerImport subscriptions
4470 a.removeAllServiceImportSubs()
4471 a.mu.Lock()
4472 a.clearExpirationTimer()
4473 a.mu.Unlock()
4474 }
4475
4476 func (dr *DirAccResolver) Start(s *Server) error {
4477 op, opKeys, strict, err := getOperatorKeys(s)
4478 if err != nil {
4479 return err
4480 }
4481 dr.Lock()
4482 defer dr.Unlock()
4483 dr.Server = s
4484 dr.operator = opKeys
4485 dr.DirJWTStore.changed = func(pubKey string) {
4486 if v, ok := s.accounts.Load(pubKey); ok {
4487 if theJwt, err := dr.LoadAcc(pubKey); err != nil {
4488 s.Errorf("DirResolver - Update got error on load: %v", err)
4489 } else {
4490 acc := v.(*Account)
4491 if err = s.updateAccountWithClaimJWT(acc, theJwt); err != nil {
4492 s.Errorf("DirResolver - Update for account %q resulted in error %v", pubKey, err)
4493 } else {
4494 if _, jsa, err := acc.checkForJetStream(); err != nil {
4495 if !IsNatsErr(err, JSNotEnabledForAccountErr) {
4496 s.Warnf("DirResolver - Error checking for JetStream support for account %q: %v", pubKey, err)
4497 }
4498 } else if jsa == nil {
4499 if err = s.configJetStream(acc, nil); err != nil {
4500 s.Errorf("DirResolver - Error configuring JetStream for account %q: %v", pubKey, err)
4501 }
4502 }
4503 }
4504 }
4505 }
4506 }
4507 dr.DirJWTStore.deleted = func(pubKey string) {
4508 removeCb(s, pubKey)
4509 }
4510 packRespIb := s.newRespInbox()
4511 for _, reqSub := range []string{accUpdateEventSubjOld, accUpdateEventSubjNew} {
4512 // subscribe to account jwt update requests
4513 if _, err := s.sysSubscribe(fmt.Sprintf(reqSub, "*"), func(_ *subscription, _ *client, _ *Account, subj, resp string, msg []byte) {
4514 var pubKey string
4515 tk := strings.Split(subj, tsep)
4516 if len(tk) == accUpdateTokensNew {
4517 pubKey = tk[accReqAccIndex]
4518 } else if len(tk) == accUpdateTokensOld {
4519 pubKey = tk[accUpdateAccIdxOld]
4520 } else {
4521 s.Debugf("DirResolver - jwt update skipped due to bad subject %q", subj)
4522 return
4523 }
4524 if claim, err := jwt.DecodeAccountClaims(string(msg)); err != nil {
4525 respondToUpdate(s, resp, "n/a", "jwt update resulted in error", err)
4526 } else if err := claimValidate(claim); err != nil {
4527 respondToUpdate(s, resp, claim.Subject, "jwt validation failed", err)
4528 } else if claim.Subject != pubKey {
4529 err := errors.New("subject does not match jwt content")
4530 respondToUpdate(s, resp, pubKey, "jwt update resulted in error", err)
4531 } else if claim.Issuer == op && strict {
4532 err := errors.New("operator requires issuer to be a signing key")
4533 respondToUpdate(s, resp, pubKey, "jwt update resulted in error", err)
4534 } else if err := dr.save(pubKey, string(msg)); err != nil {
4535 respondToUpdate(s, resp, pubKey, "jwt update resulted in error", err)
4536 } else {
4537 respondToUpdate(s, resp, pubKey, "jwt updated", nil)
4538 }
4539 }); err != nil {
4540 return fmt.Errorf("error setting up update handling: %v", err)
4541 }
4542 }
4543 if _, err := s.sysSubscribe(accClaimsReqSubj, func(_ *subscription, c *client, _ *Account, _, resp string, msg []byte) {
4544 // As this is a raw message, we need to extract payload and only decode claims from it,
4545 // in case request is sent with headers.
4546 _, msg = c.msgParts(msg)
4547 if claim, err := jwt.DecodeAccountClaims(string(msg)); err != nil {
4548 respondToUpdate(s, resp, "n/a", "jwt update resulted in error", err)
4549 } else if claim.Issuer == op && strict {
4550 err := errors.New("operator requires issuer to be a signing key")
4551 respondToUpdate(s, resp, claim.Subject, "jwt update resulted in error", err)
4552 } else if err := claimValidate(claim); err != nil {
4553 respondToUpdate(s, resp, claim.Subject, "jwt validation failed", err)
4554 } else if err := dr.save(claim.Subject, string(msg)); err != nil {
4555 respondToUpdate(s, resp, claim.Subject, "jwt update resulted in error", err)
4556 } else {
4557 respondToUpdate(s, resp, claim.Subject, "jwt updated", nil)
4558 }
4559 }); err != nil {
4560 return fmt.Errorf("error setting up update handling: %v", err)
4561 }
4562 // respond to lookups with our version
4563 if _, err := s.sysSubscribe(fmt.Sprintf(accLookupReqSubj, "*"), func(_ *subscription, _ *client, _ *Account, subj, reply string, msg []byte) {
4564 if reply == _EMPTY_ {
4565 return
4566 }
4567 tk := strings.Split(subj, tsep)
4568 if len(tk) != accLookupReqTokens {
4569 return
4570 }
4571 accName := tk[accReqAccIndex]
4572 if theJWT, err := dr.DirJWTStore.LoadAcc(accName); err != nil {
4573 if errors.Is(err, fs.ErrNotExist) {
4574 s.Debugf("DirResolver - Could not find account %q", accName)
4575 // Reply with empty response to signal absence of JWT to others.
4576 s.sendInternalMsgLocked(reply, _EMPTY_, nil, nil)
4577 } else {
4578 s.Errorf("DirResolver - Error looking up account %q: %v", accName, err)
4579 }
4580 } else {
4581 s.sendInternalMsgLocked(reply, _EMPTY_, nil, []byte(theJWT))
4582 }
4583 }); err != nil {
4584 return fmt.Errorf("error setting up lookup request handling: %v", err)
4585 }
4586 // respond to pack requests with one or more pack messages
4587 // an empty message signifies the end of the response responder.
4588 if _, err := s.sysSubscribeQ(accPackReqSubj, "responder", func(_ *subscription, _ *client, _ *Account, _, reply string, theirHash []byte) {
4589 if reply == _EMPTY_ {
4590 return
4591 }
4592 ourHash := dr.DirJWTStore.Hash()
4593 if bytes.Equal(theirHash, ourHash[:]) {
4594 s.sendInternalMsgLocked(reply, _EMPTY_, nil, []byte{})
4595 s.Debugf("DirResolver - Pack request matches hash %x", ourHash[:])
4596 } else if err := dr.DirJWTStore.PackWalk(1, func(partialPackMsg string) {
4597 s.sendInternalMsgLocked(reply, _EMPTY_, nil, []byte(partialPackMsg))
4598 }); err != nil {
4599 // let them timeout
4600 s.Errorf("DirResolver - Pack request error: %v", err)
4601 } else {
4602 s.Debugf("DirResolver - Pack request hash %x - finished responding with hash %x", theirHash, ourHash)
4603 s.sendInternalMsgLocked(reply, _EMPTY_, nil, []byte{})
4604 }
4605 }); err != nil {
4606 return fmt.Errorf("error setting up pack request handling: %v", err)
4607 }
4608 // respond to list requests with one message containing all account ids
4609 if _, err := s.sysSubscribe(accListReqSubj, func(_ *subscription, _ *client, _ *Account, _, reply string, _ []byte) {
4610 handleListRequest(dr.DirJWTStore, s, reply)
4611 }); err != nil {
4612 return fmt.Errorf("error setting up list request handling: %v", err)
4613 }
4614 if _, err := s.sysSubscribe(accDeleteReqSubj, func(_ *subscription, c *client, _ *Account, _, reply string, msg []byte) {
4615 // As this is a raw message, we need to extract payload and only decode claims from it,
4616 // in case request is sent with headers.
4617 _, msg = c.msgParts(msg)
4618 handleDeleteRequest(dr.DirJWTStore, s, msg, reply)
4619 }); err != nil {
4620 return fmt.Errorf("error setting up delete request handling: %v", err)
4621 }
4622 // embed pack responses into store
4623 if _, err := s.sysSubscribe(packRespIb, func(_ *subscription, _ *client, _ *Account, _, _ string, msg []byte) {
4624 hash := dr.DirJWTStore.Hash()
4625 if len(msg) == 0 { // end of response stream
4626 s.Debugf("DirResolver - Merging finished and resulting in: %x", dr.DirJWTStore.Hash())
4627 return
4628 } else if err := dr.DirJWTStore.Merge(string(msg)); err != nil {
4629 s.Errorf("DirResolver - Merging resulted in error: %v", err)
4630 } else {
4631 s.Debugf("DirResolver - Merging succeeded and changed %x to %x", hash, dr.DirJWTStore.Hash())
4632 }
4633 }); err != nil {
4634 return fmt.Errorf("error setting up pack response handling: %v", err)
4635 }
4636 // periodically send out pack message
4637 quit := s.quitCh
4638 s.startGoRoutine(func() {
4639 defer s.grWG.Done()
4640 ticker := time.NewTicker(dr.syncInterval)
4641 for {
4642 select {
4643 case <-quit:
4644 ticker.Stop()
4645 return
4646 case <-ticker.C:
4647 }
4648 ourHash := dr.DirJWTStore.Hash()
4649 s.Debugf("DirResolver - Checking store state: %x", ourHash)
4650 s.sendInternalMsgLocked(accPackReqSubj, packRespIb, nil, ourHash[:])
4651 }
4652 })
4653 s.Noticef("Managing all jwt in exclusive directory %s", dr.directory)
4654 return nil
4655 }
4656
4657 func (dr *DirAccResolver) Fetch(name string) (string, error) {
4658 if theJWT, err := dr.LoadAcc(name); theJWT != _EMPTY_ {
4659 return theJWT, nil
4660 } else {
4661 dr.Lock()
4662 srv := dr.Server
4663 to := dr.fetchTimeout
4664 dr.Unlock()
4665 if srv == nil {
4666 return _EMPTY_, err
4667 }
4668 return srv.fetch(dr, name, to) // lookup from other server
4669 }
4670 }
4671
4672 func (dr *DirAccResolver) Store(name, jwt string) error {
4673 return dr.saveIfNewer(name, jwt)
4674 }
4675
4676 type DirResOption func(s *DirAccResolver) error
4677
4678 // limits the amount of time spent waiting for an account fetch to complete
4679 func FetchTimeout(to time.Duration) DirResOption {
4680 return func(r *DirAccResolver) error {
4681 if to <= time.Duration(0) {
4682 return fmt.Errorf("Fetch timeout %v is too smal", to)
4683 }
4684 r.fetchTimeout = to
4685 return nil
4686 }
4687 }
4688
4689 func (dr *DirAccResolver) apply(opts ...DirResOption) error {
4690 for _, o := range opts {
4691 if err := o(dr); err != nil {
4692 return err
4693 }
4694 }
4695 return nil
4696 }
4697
4698 func NewDirAccResolver(path string, limit int64, syncInterval time.Duration, delete deleteType, opts ...DirResOption) (*DirAccResolver, error) {
4699 if limit == 0 {
4700 limit = math.MaxInt64
4701 }
4702 if syncInterval <= 0 {
4703 syncInterval = time.Minute
4704 }
4705 store, err := NewExpiringDirJWTStore(path, false, true, delete, 0, limit, false, 0, nil)
4706 if err != nil {
4707 return nil, err
4708 }
4709
4710 res := &DirAccResolver{store, nil, syncInterval, DEFAULT_ACCOUNT_FETCH_TIMEOUT}
4711 if err := res.apply(opts...); err != nil {
4712 return nil, err
4713 }
4714 return res, nil
4715 }
4716
4717 // Caching resolver using nats for lookups and making use of a directory for storage
4718 type CacheDirAccResolver struct {
4719 DirAccResolver
4720 ttl time.Duration
4721 }
4722
4723 func (s *Server) fetch(res AccountResolver, name string, timeout time.Duration) (string, error) {
4724 if s == nil {
4725 return _EMPTY_, ErrNoAccountResolver
4726 }
4727 respC := make(chan []byte, 1)
4728 accountLookupRequest := fmt.Sprintf(accLookupReqSubj, name)
4729 s.mu.Lock()
4730 if s.sys == nil || s.sys.replies == nil {
4731 s.mu.Unlock()
4732 return _EMPTY_, fmt.Errorf("eventing shut down")
4733 }
4734 // Resolver will wait for detected active servers to reply
4735 // before serving an error in case there weren't any found.
4736 expectedServers := len(s.sys.servers)
4737 replySubj := s.newRespInbox()
4738 replies := s.sys.replies
4739
4740 // Store our handler.
4741 replies[replySubj] = func(sub *subscription, _ *client, _ *Account, subject, _ string, msg []byte) {
4742 var clone []byte
4743 isEmpty := len(msg) == 0
4744 if !isEmpty {
4745 clone = make([]byte, len(msg))
4746 copy(clone, msg)
4747 }
4748 s.mu.Lock()
4749 defer s.mu.Unlock()
4750 expectedServers--
4751 // Skip empty responses until getting all the available servers.
4752 if isEmpty && expectedServers > 0 {
4753 return
4754 }
4755 // Use the first valid response if there is still interest or
4756 // one of the empty responses to signal that it was not found.
4757 if _, ok := replies[replySubj]; ok {
4758 select {
4759 case respC <- clone:
4760 default:
4761 }
4762 }
4763 }
4764 s.sendInternalMsg(accountLookupRequest, replySubj, nil, []byte{})
4765 quit := s.quitCh
4766 s.mu.Unlock()
4767 var err error
4768 var theJWT string
4769 select {
4770 case <-quit:
4771 err = errors.New("fetching jwt failed due to shutdown")
4772 case <-time.After(timeout):
4773 err = errors.New("fetching jwt timed out")
4774 case m := <-respC:
4775 if len(m) == 0 {
4776 err = errors.New("account jwt not found")
4777 } else if err = res.Store(name, string(m)); err == nil {
4778 theJWT = string(m)
4779 }
4780 }
4781 s.mu.Lock()
4782 delete(replies, replySubj)
4783 s.mu.Unlock()
4784 close(respC)
4785 return theJWT, err
4786 }
4787
4788 func NewCacheDirAccResolver(path string, limit int64, ttl time.Duration, opts ...DirResOption) (*CacheDirAccResolver, error) {
4789 if limit <= 0 {
4790 limit = 1_000
4791 }
4792 store, err := NewExpiringDirJWTStore(path, false, true, HardDelete, 0, limit, true, ttl, nil)
4793 if err != nil {
4794 return nil, err
4795 }
4796 res := &CacheDirAccResolver{DirAccResolver{store, nil, 0, DEFAULT_ACCOUNT_FETCH_TIMEOUT}, ttl}
4797 if err := res.apply(opts...); err != nil {
4798 return nil, err
4799 }
4800 return res, nil
4801 }
4802
4803 func (dr *CacheDirAccResolver) Start(s *Server) error {
4804 op, opKeys, strict, err := getOperatorKeys(s)
4805 if err != nil {
4806 return err
4807 }
4808 dr.Lock()
4809 defer dr.Unlock()
4810 dr.Server = s
4811 dr.operator = opKeys
4812 dr.DirJWTStore.changed = func(pubKey string) {
4813 if v, ok := s.accounts.Load(pubKey); !ok {
4814 } else if theJwt, err := dr.LoadAcc(pubKey); err != nil {
4815 s.Errorf("DirResolver - Update got error on load: %v", err)
4816 } else if err := s.updateAccountWithClaimJWT(v.(*Account), theJwt); err != nil {
4817 s.Errorf("DirResolver - Update resulted in error %v", err)
4818 }
4819 }
4820 dr.DirJWTStore.deleted = func(pubKey string) {
4821 removeCb(s, pubKey)
4822 }
4823 for _, reqSub := range []string{accUpdateEventSubjOld, accUpdateEventSubjNew} {
4824 // subscribe to account jwt update requests
4825 if _, err := s.sysSubscribe(fmt.Sprintf(reqSub, "*"), func(_ *subscription, _ *client, _ *Account, subj, resp string, msg []byte) {
4826 var pubKey string
4827 tk := strings.Split(subj, tsep)
4828 if len(tk) == accUpdateTokensNew {
4829 pubKey = tk[accReqAccIndex]
4830 } else if len(tk) == accUpdateTokensOld {
4831 pubKey = tk[accUpdateAccIdxOld]
4832 } else {
4833 s.Debugf("DirResolver - jwt update cache skipped due to bad subject %q", subj)
4834 return
4835 }
4836 if claim, err := jwt.DecodeAccountClaims(string(msg)); err != nil {
4837 respondToUpdate(s, resp, pubKey, "jwt update cache resulted in error", err)
4838 } else if claim.Subject != pubKey {
4839 err := errors.New("subject does not match jwt content")
4840 respondToUpdate(s, resp, pubKey, "jwt update cache resulted in error", err)
4841 } else if claim.Issuer == op && strict {
4842 err := errors.New("operator requires issuer to be a signing key")
4843 respondToUpdate(s, resp, pubKey, "jwt update cache resulted in error", err)
4844 } else if _, ok := s.accounts.Load(pubKey); !ok {
4845 respondToUpdate(s, resp, pubKey, "jwt update cache skipped", nil)
4846 } else if err := claimValidate(claim); err != nil {
4847 respondToUpdate(s, resp, claim.Subject, "jwt update cache validation failed", err)
4848 } else if err := dr.save(pubKey, string(msg)); err != nil {
4849 respondToUpdate(s, resp, pubKey, "jwt update cache resulted in error", err)
4850 } else {
4851 respondToUpdate(s, resp, pubKey, "jwt updated cache", nil)
4852 }
4853 }); err != nil {
4854 return fmt.Errorf("error setting up update handling: %v", err)
4855 }
4856 }
4857 if _, err := s.sysSubscribe(accClaimsReqSubj, func(_ *subscription, c *client, _ *Account, _, resp string, msg []byte) {
4858 // As this is a raw message, we need to extract payload and only decode claims from it,
4859 // in case request is sent with headers.
4860 _, msg = c.msgParts(msg)
4861 if claim, err := jwt.DecodeAccountClaims(string(msg)); err != nil {
4862 respondToUpdate(s, resp, "n/a", "jwt update cache resulted in error", err)
4863 } else if claim.Issuer == op && strict {
4864 err := errors.New("operator requires issuer to be a signing key")
4865 respondToUpdate(s, resp, claim.Subject, "jwt update cache resulted in error", err)
4866 } else if _, ok := s.accounts.Load(claim.Subject); !ok {
4867 respondToUpdate(s, resp, claim.Subject, "jwt update cache skipped", nil)
4868 } else if err := claimValidate(claim); err != nil {
4869 respondToUpdate(s, resp, claim.Subject, "jwt update cache validation failed", err)
4870 } else if err := dr.save(claim.Subject, string(msg)); err != nil {
4871 respondToUpdate(s, resp, claim.Subject, "jwt update cache resulted in error", err)
4872 } else {
4873 respondToUpdate(s, resp, claim.Subject, "jwt updated cache", nil)
4874 }
4875 }); err != nil {
4876 return fmt.Errorf("error setting up update handling: %v", err)
4877 }
4878 // respond to list requests with one message containing all account ids
4879 if _, err := s.sysSubscribe(accListReqSubj, func(_ *subscription, _ *client, _ *Account, _, reply string, _ []byte) {
4880 handleListRequest(dr.DirJWTStore, s, reply)
4881 }); err != nil {
4882 return fmt.Errorf("error setting up list request handling: %v", err)
4883 }
4884 if _, err := s.sysSubscribe(accDeleteReqSubj, func(_ *subscription, c *client, _ *Account, _, reply string, msg []byte) {
4885 // As this is a raw message, we need to extract payload and only decode claims from it,
4886 // in case request is sent with headers.
4887 _, msg = c.msgParts(msg)
4888 handleDeleteRequest(dr.DirJWTStore, s, msg, reply)
4889 }); err != nil {
4890 return fmt.Errorf("error setting up list request handling: %v", err)
4891 }
4892 s.Noticef("Managing some jwt in exclusive directory %s", dr.directory)
4893 return nil
4894 }
4895
4896 func (dr *CacheDirAccResolver) Reload() error {
4897 return dr.DirAccResolver.Reload()
4898 }