Debian Codegraph @

server/jwt.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 "errors"
18 "fmt"
19 "net"
20 "os"
21 "strings"
22 "time"
23
24 "github.com/nats-io/jwt/v2"
25 "github.com/nats-io/nkeys"
26 )
27
28 // All JWTs once encoded start with this
29 const jwtPrefix = "eyJ"
30
31 // ReadOperatorJWT will read a jwt file for an operator claim. This can be a decorated file.
32 func ReadOperatorJWT(jwtfile string) (*jwt.OperatorClaims, error) {
33 _, claim, err := readOperatorJWT(jwtfile)
34 return claim, err
35 }
36
37 func readOperatorJWT(jwtfile string) (string, *jwt.OperatorClaims, error) {
38 contents, err := os.ReadFile(jwtfile)
39 if err != nil {
40 // Check to see if the JWT has been inlined.
41 if !strings.HasPrefix(jwtfile, jwtPrefix) {
42 return "", nil, err
43 }
44 // We may have an inline jwt here.
45 contents = []byte(jwtfile)
46 }
47 defer wipeSlice(contents)
48
49 theJWT, err := jwt.ParseDecoratedJWT(contents)
50 if err != nil {
51 return "", nil, err
52 }
53 opc, err := jwt.DecodeOperatorClaims(theJWT)
54 if err != nil {
55 return "", nil, err
56 }
57 return theJWT, opc, nil
58 }
59
60 // Just wipe slice with 'x', for clearing contents of nkey seed file.
61 func wipeSlice(buf []byte) {
62 for i := range buf {
63 buf[i] = 'x'
64 }
65 }
66
67 // validateTrustedOperators will check that we do not have conflicts with
68 // assigned trusted keys and trusted operators. If operators are defined we
69 // will expand the trusted keys in options.
70 func validateTrustedOperators(o *Options) error {
71 if len(o.TrustedOperators) == 0 {
72 // if we have no operator, default sentinel shouldn't be set
73 if o.DefaultSentinel != _EMPTY_ {
74 return fmt.Errorf("default sentinel requires operators and accounts")
75 }
76 return nil
77 }
78 if o.DefaultSentinel != _EMPTY_ {
79 juc, err := jwt.DecodeUserClaims(o.DefaultSentinel)
80 if err != nil {
81 return fmt.Errorf("default sentinel JWT not valid")
82 }
83
84 if !juc.BearerToken && juc.IssuerAccount != "" && juc.HasEmptyPermissions() {
85 // we cannot resolve the account yet - but this looks like a scoped user
86 // it will be rejected at runtime if not valid
87 } else if !juc.BearerToken {
88 return fmt.Errorf("default sentinel must be a bearer token")
89 }
90 }
91 if o.AccountResolver == nil {
92 return fmt.Errorf("operators require an account resolver to be configured")
93 }
94 if len(o.Accounts) > 0 {
95 return fmt.Errorf("operators do not allow Accounts to be configured directly")
96 }
97 if len(o.Users) > 0 || len(o.Nkeys) > 0 {
98 return fmt.Errorf("operators do not allow users to be configured directly")
99 }
100 if len(o.TrustedOperators) > 0 && len(o.TrustedKeys) > 0 {
101 return fmt.Errorf("conflicting options for 'TrustedKeys' and 'TrustedOperators'")
102 }
103 if o.SystemAccount != _EMPTY_ {
104 foundSys := false
105 foundNonEmpty := false
106 for _, op := range o.TrustedOperators {
107 if op.SystemAccount != _EMPTY_ {
108 foundNonEmpty = true
109 }
110 if op.SystemAccount == o.SystemAccount {
111 foundSys = true
112 break
113 }
114 }
115 if foundNonEmpty && !foundSys {
116 return fmt.Errorf("system_account in config and operator JWT must be identical")
117 }
118 } else if o.TrustedOperators[0].SystemAccount == _EMPTY_ {
119 // In case the system account is neither defined in config nor in the first operator.
120 // If it would be needed due to the nats account resolver, raise an error.
121 switch o.AccountResolver.(type) {
122 case *DirAccResolver, *CacheDirAccResolver:
123 return fmt.Errorf("using nats based account resolver - the system account needs to be specified in configuration or the operator jwt")
124 }
125 }
126
127 srvMajor, srvMinor, srvUpdate, _ := versionComponents(VERSION)
128 for _, opc := range o.TrustedOperators {
129 if major, minor, update, err := jwt.ParseServerVersion(opc.AssertServerVersion); err != nil {
130 return fmt.Errorf("operator %s expects version %s got error instead: %s",
131 opc.Subject, opc.AssertServerVersion, err)
132 } else if major > srvMajor {
133 return fmt.Errorf("operator %s expected major version %d > server major version %d",
134 opc.Subject, major, srvMajor)
135 } else if srvMajor > major {
136 } else if minor > srvMinor {
137 return fmt.Errorf("operator %s expected minor version %d > server minor version %d",
138 opc.Subject, minor, srvMinor)
139 } else if srvMinor > minor {
140 } else if update > srvUpdate {
141 return fmt.Errorf("operator %s expected update version %d > server update version %d",
142 opc.Subject, update, srvUpdate)
143 }
144 }
145 // If we have operators, fill in the trusted keys.
146 // FIXME(dlc) - We had TrustedKeys before TrustedOperators. The jwt.OperatorClaims
147 // has a DidSign(). Use that longer term. For now we can expand in place.
148 for _, opc := range o.TrustedOperators {
149 if o.TrustedKeys == nil {
150 o.TrustedKeys = make([]string, 0, 4)
151 }
152 if !opc.StrictSigningKeyUsage {
153 o.TrustedKeys = append(o.TrustedKeys, opc.Subject)
154 }
155 o.TrustedKeys = append(o.TrustedKeys, opc.SigningKeys...)
156 }
157 for _, key := range o.TrustedKeys {
158 if !nkeys.IsValidPublicOperatorKey(key) {
159 return fmt.Errorf("trusted Keys %q are required to be a valid public operator nkey", key)
160 }
161 }
162 if len(o.resolverPinnedAccounts) > 0 {
163 for key := range o.resolverPinnedAccounts {
164 if !nkeys.IsValidPublicAccountKey(key) {
165 return fmt.Errorf("pinned account key %q is not a valid public account nkey", key)
166 }
167 }
168 // ensure the system account (belonging to the operator can always connect)
169 if o.SystemAccount != _EMPTY_ {
170 o.resolverPinnedAccounts[o.SystemAccount] = struct{}{}
171 }
172 }
173
174 // If we have an auth callout defined make sure we are not in operator mode.
175 if o.AuthCallout != nil {
176 return errors.New("operators do not allow authorization callouts to be configured directly")
177 }
178
179 return nil
180 }
181
182 func validateSrc(claims *jwt.UserClaims, host string) bool {
183 if claims == nil {
184 return false
185 } else if len(claims.Src) == 0 {
186 return true
187 } else if host == "" {
188 return false
189 }
190 ip := net.ParseIP(host)
191 if ip == nil {
192 return false
193 }
194 for _, cidr := range claims.Src {
195 if _, net, err := net.ParseCIDR(cidr); err != nil {
196 return false // should not happen as this jwt is invalid
197 } else if net.Contains(ip) {
198 return true
199 }
200 }
201 return false
202 }
203
204 func validateTimes(claims *jwt.UserClaims) (bool, time.Duration) {
205 return validateTimesAt(claims, time.Now())
206 }
207
208 func validateTimesAt(claims *jwt.UserClaims, now time.Time) (bool, time.Duration) {
209 if claims == nil {
210 return false, time.Duration(0)
211 } else if len(claims.Times) == 0 {
212 return true, time.Duration(0)
213 }
214 loc := time.Local
215 if claims.Locale != "" {
216 var err error
217 if loc, err = time.LoadLocation(claims.Locale); err != nil {
218 return false, time.Duration(0) // parsing not expected to fail at this point
219 }
220 now = now.In(loc)
221 }
222
223 var ok bool
224 var validFor time.Duration
225
226 for _, timeRange := range claims.Times {
227 start, err := time.ParseInLocation("15:04:05", timeRange.Start, loc)
228 if err != nil {
229 return false, time.Duration(0) // parsing not expected to fail at this point
230 }
231 end, err := time.ParseInLocation("15:04:05", timeRange.End, loc)
232 if err != nil {
233 return false, time.Duration(0) // parsing not expected to fail at this point
234 }
235
236 y, m, d := now.Date()
237 start = time.Date(y, m, d, start.Hour(), start.Minute(), start.Second(), 0, loc)
238 end = time.Date(y, m, d, end.Hour(), end.Minute(), end.Second(), 0, loc)
239
240 inRange, expires := validateTimeRangeAt(start, end, now)
241 if inRange && (!ok || expires > validFor) {
242 ok = true
243 validFor = expires
244 }
245 }
246 return ok, validFor
247 }
248
249 // Returns true if now is within `start` and `end`, and
250 // how much time is left until `end`.
251 // False if `now` is not within range.
252 func validateTimeRangeAt(start, end, now time.Time) (bool, time.Duration) {
253 // Now falls within range.
254 // For example 11:00-22:00 at 13:00
255 if start.Before(now) && end.After(now) {
256 return true, end.Sub(now)
257 }
258
259 // Range crosses midnight.
260 if start.After(end) {
261 // Now is after midnight.
262 // For example 22:00-06:00 at 05:00.
263 if end.After(now) {
264 return true, end.Sub(now)
265 }
266
267 // Now is before midnight.
268 // For example 22:00-06:00 at 23:30.
269 end = end.AddDate(0, 0, 1)
270 if start.Before(now) && end.After(now) {
271 return true, end.Sub(now)
272 }
273 }
274 return false, time.Duration(0)
275 }