1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
|
/*
* Copyright 2018-2019 The NATS Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jwt
import (
"encoding/json"
"fmt"
"net"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
const MaxInfoLength = 8 * 1024
type Info struct {
Description string `json:"description,omitempty"`
InfoURL string `json:"info_url,omitempty"`
}
func (s Info) Validate(vr *ValidationResults) {
if len(s.Description) > MaxInfoLength {
vr.AddError("Description is too long")
}
if s.InfoURL != "" {
if len(s.InfoURL) > MaxInfoLength {
vr.AddError("Info URL is too long")
}
u, err := url.Parse(s.InfoURL)
if err == nil && (u.Hostname() == "" || u.Scheme == "") {
err = fmt.Errorf("no hostname or scheme")
}
if err != nil {
vr.AddError("error parsing info url: %v", err)
}
}
}
// ExportType defines the type of import/export.
type ExportType int
const (
// Unknown is used if we don't know the type
Unknown ExportType = iota
// Stream defines the type field value for a stream "stream"
Stream
// Service defines the type field value for a service "service"
Service
)
func (t ExportType) String() string {
switch t {
case Stream:
return "stream"
case Service:
return "service"
}
return "unknown"
}
// MarshalJSON marshals the enum as a quoted json string
func (t *ExportType) MarshalJSON() ([]byte, error) {
switch *t {
case Stream:
return []byte("\"stream\""), nil
case Service:
return []byte("\"service\""), nil
}
return nil, fmt.Errorf("unknown export type")
}
// UnmarshalJSON unmashals a quoted json string to the enum value
func (t *ExportType) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return err
}
switch j {
case "stream":
*t = Stream
return nil
case "service":
*t = Service
return nil
}
return fmt.Errorf("unknown export type %q", j)
}
type RenamingSubject Subject
func (s RenamingSubject) Validate(from Subject, vr *ValidationResults) {
v := Subject(s)
v.Validate(vr)
if from == "" {
vr.AddError("subject cannot be empty")
}
if strings.Contains(string(s), " ") {
vr.AddError("subject %q cannot have spaces", v)
}
matchesSuffix := func(s Subject) bool {
return s == ">" || strings.HasSuffix(string(s), ".>")
}
if matchesSuffix(v) != matchesSuffix(from) {
vr.AddError("both, renaming subject and subject, need to end or not end in >")
}
fromCnt := from.countTokenWildcards()
refCnt := 0
for _, tk := range strings.Split(string(v), ".") {
if tk == "*" {
refCnt++
}
if len(tk) < 2 {
continue
}
if tk[0] == '$' {
if idx, err := strconv.Atoi(tk[1:]); err == nil {
if idx > fromCnt {
vr.AddError("Reference $%d in %q reference * in %q that do not exist", idx, s, from)
} else {
refCnt++
}
}
}
}
if refCnt != fromCnt {
vr.AddError("subject does not contain enough * or reference wildcards $[0-9]")
}
}
// Replaces reference tokens with *
func (s RenamingSubject) ToSubject() Subject {
if !strings.Contains(string(s), "$") {
return Subject(s)
}
bldr := strings.Builder{}
tokens := strings.Split(string(s), ".")
for i, tk := range tokens {
convert := false
if len(tk) > 1 && tk[0] == '$' {
if _, err := strconv.Atoi(tk[1:]); err == nil {
convert = true
}
}
if convert {
bldr.WriteString("*")
} else {
bldr.WriteString(tk)
}
if i != len(tokens)-1 {
bldr.WriteString(".")
}
}
return Subject(bldr.String())
}
// Subject is a string that represents a NATS subject
type Subject string
// Validate checks that a subject string is valid, ie not empty and without spaces
func (s Subject) Validate(vr *ValidationResults) {
v := string(s)
if v == "" {
vr.AddError("subject cannot be empty")
// No other checks after that make sense
return
}
if strings.Contains(v, " ") {
vr.AddError("subject %q cannot have spaces", v)
}
if v[0] == '.' || v[len(v)-1] == '.' {
vr.AddError("subject %q cannot start or end with a `.`", v)
}
if strings.Contains(v, "..") {
vr.AddError("subject %q cannot contain consecutive `.`", v)
}
}
func (s Subject) countTokenWildcards() int {
v := string(s)
if v == "*" {
return 1
}
cnt := 0
for _, t := range strings.Split(v, ".") {
if t == "*" {
cnt++
}
}
return cnt
}
// HasWildCards is used to check if a subject contains a > or *
func (s Subject) HasWildCards() bool {
v := string(s)
return strings.HasSuffix(v, ".>") ||
strings.Contains(v, ".*.") ||
strings.HasSuffix(v, ".*") ||
strings.HasPrefix(v, "*.") ||
v == "*" ||
v == ">"
}
// IsContainedIn does a simple test to see if the subject is contained in another subject
func (s Subject) IsContainedIn(other Subject) bool {
otherArray := strings.Split(string(other), ".")
myArray := strings.Split(string(s), ".")
if len(myArray) > len(otherArray) && otherArray[len(otherArray)-1] != ">" {
return false
}
if len(myArray) < len(otherArray) {
return false
}
for ind, tok := range otherArray {
myTok := myArray[ind]
if ind == len(otherArray)-1 && tok == ">" {
return true
}
if tok != myTok && tok != "*" {
return false
}
}
return true
}
// TimeRange is used to represent a start and end time
type TimeRange struct {
Start string `json:"start,omitempty"`
End string `json:"end,omitempty"`
}
// Validate checks the values in a time range struct
func (tr *TimeRange) Validate(vr *ValidationResults) {
format := "15:04:05"
if tr.Start == "" {
vr.AddError("time ranges start must contain a start")
} else {
_, err := time.Parse(format, tr.Start)
if err != nil {
vr.AddError("start in time range is invalid %q", tr.Start)
}
}
if tr.End == "" {
vr.AddError("time ranges end must contain an end")
} else {
_, err := time.Parse(format, tr.End)
if err != nil {
vr.AddError("end in time range is invalid %q", tr.End)
}
}
}
// Src is a comma separated list of CIDR specifications
type UserLimits struct {
Src CIDRList `json:"src,omitempty"`
Times []TimeRange `json:"times,omitempty"`
Locale string `json:"times_location,omitempty"`
}
func (u *UserLimits) Empty() bool {
return reflect.DeepEqual(*u, UserLimits{})
}
func (u *UserLimits) IsUnlimited() bool {
return len(u.Src) == 0 && len(u.Times) == 0
}
// Limits are used to control acccess for users and importing accounts
type Limits struct {
UserLimits
NatsLimits
}
func (l *Limits) IsUnlimited() bool {
return l.UserLimits.IsUnlimited() && l.NatsLimits.IsUnlimited()
}
// Validate checks the values in a limit struct
func (l *Limits) Validate(vr *ValidationResults) {
if len(l.Src) != 0 {
for _, cidr := range l.Src {
_, ipNet, err := net.ParseCIDR(cidr)
if err != nil || ipNet == nil {
vr.AddError("invalid cidr %q in user src limits", cidr)
}
}
}
if len(l.Times) > 0 {
for _, t := range l.Times {
t.Validate(vr)
}
}
if l.Locale != "" {
if _, err := time.LoadLocation(l.Locale); err != nil {
vr.AddError("could not parse iana time zone by name: %v", err)
}
}
}
// Permission defines allow/deny subjects
type Permission struct {
Allow StringList `json:"allow,omitempty"`
Deny StringList `json:"deny,omitempty"`
}
func (p *Permission) Empty() bool {
return len(p.Allow) == 0 && len(p.Deny) == 0
}
func checkPermission(vr *ValidationResults, subj string, permitQueue bool) {
tk := strings.Split(subj, " ")
switch len(tk) {
case 1:
Subject(tk[0]).Validate(vr)
case 2:
Subject(tk[0]).Validate(vr)
Subject(tk[1]).Validate(vr)
if !permitQueue {
vr.AddError(`Permission Subject "%s" is not allowed to contain queue`, subj)
}
default:
vr.AddError(`Permission Subject "%s" contains too many spaces`, subj)
}
}
// Validate the allow, deny elements of a permission
func (p *Permission) Validate(vr *ValidationResults, permitQueue bool) {
for _, subj := range p.Allow {
checkPermission(vr, subj, permitQueue)
}
for _, subj := range p.Deny {
checkPermission(vr, subj, permitQueue)
}
}
// ResponsePermission can be used to allow responses to any reply subject
// that is received on a valid subscription.
type ResponsePermission struct {
MaxMsgs int `json:"max"`
Expires time.Duration `json:"ttl"`
}
// Validate the response permission.
func (p *ResponsePermission) Validate(_ *ValidationResults) {
// Any values can be valid for now.
}
// Permissions are used to restrict subject access, either on a user or for everyone on a server by default
type Permissions struct {
Pub Permission `json:"pub,omitempty"`
Sub Permission `json:"sub,omitempty"`
Resp *ResponsePermission `json:"resp,omitempty"`
}
// Validate the pub and sub fields in the permissions list
func (p *Permissions) Validate(vr *ValidationResults) {
if p.Resp != nil {
p.Resp.Validate(vr)
}
p.Sub.Validate(vr, true)
p.Pub.Validate(vr, false)
}
// StringList is a wrapper for an array of strings
type StringList []string
// Contains returns true if the list contains the string
func (u *StringList) Contains(p string) bool {
for _, t := range *u {
if t == p {
return true
}
}
return false
}
// Add appends 1 or more strings to a list
func (u *StringList) Add(p ...string) {
for _, v := range p {
if !u.Contains(v) && v != "" {
*u = append(*u, v)
}
}
}
// Remove removes 1 or more strings from a list
func (u *StringList) Remove(p ...string) {
for _, v := range p {
for i, t := range *u {
if t == v {
a := *u
*u = append(a[:i], a[i+1:]...)
break
}
}
}
}
// TagList is a unique array of lower case strings
// All tag list methods lower case the strings in the arguments
type TagList []string
// Contains returns true if the list contains the tags
func (u *TagList) Contains(p string) bool {
p = strings.ToLower(strings.TrimSpace(p))
for _, t := range *u {
if t == p {
return true
}
}
return false
}
// Add appends 1 or more tags to a list
func (u *TagList) Add(p ...string) {
for _, v := range p {
v = strings.ToLower(strings.TrimSpace(v))
if !u.Contains(v) && v != "" {
*u = append(*u, v)
}
}
}
// Remove removes 1 or more tags from a list
func (u *TagList) Remove(p ...string) {
for _, v := range p {
v = strings.ToLower(strings.TrimSpace(v))
for i, t := range *u {
if t == v {
a := *u
*u = append(a[:i], a[i+1:]...)
break
}
}
}
}
type CIDRList TagList
func (c *CIDRList) Contains(p string) bool {
return (*TagList)(c).Contains(p)
}
func (c *CIDRList) Add(p ...string) {
(*TagList)(c).Add(p...)
}
func (c *CIDRList) Remove(p ...string) {
(*TagList)(c).Remove(p...)
}
func (c *CIDRList) Set(values string) {
*c = CIDRList{}
c.Add(strings.Split(strings.ToLower(values), ",")...)
}
func (c *CIDRList) UnmarshalJSON(body []byte) (err error) {
// parse either as array of strings or comma separate list
var request []string
var list string
if err := json.Unmarshal(body, &request); err == nil {
*c = request
return nil
} else if err := json.Unmarshal(body, &list); err == nil {
c.Set(list)
return nil
} else {
return err
}
}
|