github.com/nats-io/jwt/v2@v2.5.6/user_claims.go (about)

     1  /*
     2   * Copyright 2018-2019 The NATS Authors
     3   * Licensed under the Apache License, Version 2.0 (the "License");
     4   * you may not use this file except in compliance with the License.
     5   * You may obtain a copy of the License at
     6   *
     7   * http://www.apache.org/licenses/LICENSE-2.0
     8   *
     9   * Unless required by applicable law or agreed to in writing, software
    10   * distributed under the License is distributed on an "AS IS" BASIS,
    11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12   * See the License for the specific language governing permissions and
    13   * limitations under the License.
    14   */
    15  
    16  package jwt
    17  
    18  import (
    19  	"errors"
    20  	"reflect"
    21  
    22  	"github.com/nats-io/nkeys"
    23  )
    24  
    25  const (
    26  	ConnectionTypeStandard   = "STANDARD"
    27  	ConnectionTypeWebsocket  = "WEBSOCKET"
    28  	ConnectionTypeLeafnode   = "LEAFNODE"
    29  	ConnectionTypeLeafnodeWS = "LEAFNODE_WS"
    30  	ConnectionTypeMqtt       = "MQTT"
    31  	ConnectionTypeMqttWS     = "MQTT_WS"
    32  )
    33  
    34  type UserPermissionLimits struct {
    35  	Permissions
    36  	Limits
    37  	BearerToken            bool       `json:"bearer_token,omitempty"`
    38  	AllowedConnectionTypes StringList `json:"allowed_connection_types,omitempty"`
    39  }
    40  
    41  // User defines the user specific data in a user JWT
    42  type User struct {
    43  	UserPermissionLimits
    44  	// IssuerAccount stores the public key for the account the issuer represents.
    45  	// When set, the claim was issued by a signing key.
    46  	IssuerAccount string `json:"issuer_account,omitempty"`
    47  	GenericFields
    48  }
    49  
    50  // Validate checks the permissions and limits in a User jwt
    51  func (u *User) Validate(vr *ValidationResults) {
    52  	u.Permissions.Validate(vr)
    53  	u.Limits.Validate(vr)
    54  	// When BearerToken is true server will ignore any nonce-signing verification
    55  }
    56  
    57  // UserClaims defines a user JWT
    58  type UserClaims struct {
    59  	ClaimsData
    60  	User `json:"nats,omitempty"`
    61  }
    62  
    63  // NewUserClaims creates a user JWT with the specific subject/public key
    64  func NewUserClaims(subject string) *UserClaims {
    65  	if subject == "" {
    66  		return nil
    67  	}
    68  	c := &UserClaims{}
    69  	c.Subject = subject
    70  	c.Limits = Limits{
    71  		UserLimits{CIDRList{}, nil, ""},
    72  		NatsLimits{NoLimit, NoLimit, NoLimit},
    73  	}
    74  	return c
    75  }
    76  
    77  func (u *UserClaims) SetScoped(t bool) {
    78  	if t {
    79  		u.UserPermissionLimits = UserPermissionLimits{}
    80  	} else {
    81  		u.Limits = Limits{
    82  			UserLimits{CIDRList{}, nil, ""},
    83  			NatsLimits{NoLimit, NoLimit, NoLimit},
    84  		}
    85  	}
    86  }
    87  
    88  func (u *UserClaims) HasEmptyPermissions() bool {
    89  	return reflect.DeepEqual(u.UserPermissionLimits, UserPermissionLimits{})
    90  }
    91  
    92  // Encode tries to turn the user claims into a JWT string
    93  func (u *UserClaims) Encode(pair nkeys.KeyPair) (string, error) {
    94  	if !nkeys.IsValidPublicUserKey(u.Subject) {
    95  		return "", errors.New("expected subject to be user public key")
    96  	}
    97  	u.Type = UserClaim
    98  	return u.ClaimsData.encode(pair, u)
    99  }
   100  
   101  // DecodeUserClaims tries to parse a user claims from a JWT string
   102  func DecodeUserClaims(token string) (*UserClaims, error) {
   103  	claims, err := Decode(token)
   104  	if err != nil {
   105  		return nil, err
   106  	}
   107  	ac, ok := claims.(*UserClaims)
   108  	if !ok {
   109  		return nil, errors.New("not user claim")
   110  	}
   111  	return ac, nil
   112  }
   113  
   114  func (u *UserClaims) ClaimType() ClaimType {
   115  	return u.Type
   116  }
   117  
   118  // Validate checks the generic and specific parts of the user jwt
   119  func (u *UserClaims) Validate(vr *ValidationResults) {
   120  	u.ClaimsData.Validate(vr)
   121  	u.User.Validate(vr)
   122  	if u.IssuerAccount != "" && !nkeys.IsValidPublicAccountKey(u.IssuerAccount) {
   123  		vr.AddError("account_id is not an account public key")
   124  	}
   125  }
   126  
   127  // ExpectedPrefixes defines the types that can encode a user JWT, account
   128  func (u *UserClaims) ExpectedPrefixes() []nkeys.PrefixByte {
   129  	return []nkeys.PrefixByte{nkeys.PrefixByteAccount}
   130  }
   131  
   132  // Claims returns the generic data from a user jwt
   133  func (u *UserClaims) Claims() *ClaimsData {
   134  	return &u.ClaimsData
   135  }
   136  
   137  // Payload returns the user specific data from a user JWT
   138  func (u *UserClaims) Payload() interface{} {
   139  	return &u.User
   140  }
   141  
   142  func (u *UserClaims) String() string {
   143  	return u.ClaimsData.String(u)
   144  }
   145  
   146  func (u *UserClaims) updateVersion() {
   147  	u.GenericFields.Version = libVersion
   148  }
   149  
   150  // IsBearerToken returns true if nonce-signing requirements should be skipped
   151  func (u *UserClaims) IsBearerToken() bool {
   152  	return u.BearerToken
   153  }
   154  
   155  func (u *UserClaims) GetTags() TagList {
   156  	return u.User.Tags
   157  }