Update/delete vendor files

Refreshed / updated vendor dependencies

Tested with "make".

Signed-off-by: Alex Ellis (OpenFaaS Ltd) <alexellis2@gmail.com>
This commit is contained in:
Alex Ellis (OpenFaaS Ltd)
2019-10-06 22:30:47 +01:00
committed by Alex Ellis
parent f62bcb0736
commit d6cf72bb39
247 changed files with 51179 additions and 11409 deletions

View File

@ -1,26 +1,22 @@
language: go
sudo: false
go:
- 1.8.x
- 1.9.x
- 1.10.x
- 1.11.x
- 1.12.x
install:
- go get -t ./...
- go get github.com/nats-io/nats-streaming-server
- go get github.com/mattn/goveralls
- go get github.com/wadey/gocovmerge
- go get -u honnef.co/go/tools/cmd/megacheck
- go get -u honnef.co/go/tools/cmd/staticcheck
- go get -u github.com/client9/misspell/cmd/misspell
before_script:
- $(exit $(go fmt ./... | wc -l))
- go vet ./...
- misspell -error -locale US .
- megacheck ./...
- staticcheck ./...
script:
- go test -i -race ./...
- go test -v -race ./...
after_success:
- if [[ "$TRAVIS_GO_VERSION" == 1.9.* ]]; then ./scripts/cov.sh TRAVIS; fi
env:
global:
secure: OoCemKSHHH/SkkamHLWd0qh9qgQDx4/3fGuykYuzW/gjUhLlL0ThyUXOr3HOandoh3wTU8Ntj184WU6Sjh1oXzdDAYcI/ryNQXSmJ/DyGC6ffoj4Je/Rwj3sbwpaFTl1imawL8Lv6+5Dkb2JSbbbqapjbO3BhrrNfqLuQulqrLJKVaOyS5nOByiGFYsgjf/ac7Qrr9AnHhlkWRXoR+q8GlGG7qcKtLlmG5OqxifqfgQ+pcVtyeleT6zGPI0LUyr9gWHRZtMK9nYfxXuQK2d7V+SW4NBW1jdDKBHZbeJRxZ8N8rU8Nk3ka54YHXC2PeD8EloiAr5HkALuHbIdzyy40Y3rJyHfxyY6EYBcZEy+ZCRoqkVJ4NN4R46YE588BpYhT48YHK+lptM7YxrPtf08X+Cugc206X0hk/YFqqsaaNIwMfiTPbapuHxa8S4kgT2vDn3OTI53ZTrDiLVY3ZDp+EdUO1hiYFR6cpu5el/EQN5G0iW6sI69gOv26UmGI369D3fezbYPFPHHDao8xq7s8HdYUZleDNL0oCWK1MgL2g/Irbt5Kr6JjT/tpQOiiagqeR5dlV9mAiOZFr88gg7aqwOuSqmlULWVB4qYncQ6IBoednIHtrLW6H+2RfrZU01cI6tGSrXD+VoFnQ7aZwLxLc71VyN5khYPk0gGvyQhZxk=
- if [[ "$TRAVIS_GO_VERSION" =~ 1.12 ]]; then ./scripts/cov.sh TRAVIS; fi

View File

@ -0,0 +1,3 @@
# NATS Streaming Governance
NATS Streaming is part of the NATS project and is subject to the [NATS Governance](https://github.com/nats-io/nats-general/blob/master/GOVERNANCE.md).

View File

@ -0,0 +1,13 @@
# Maintainers
Maintainership is on a per project basis.
### Core-maintainers
- Derek Collison <derek@nats.io> [@derekcollison](https://github.com/derekcollison)
- Ivan Kozlovic <ivan@nats.io> [@kozlovic](https://github.com/kozlovic)
### Maintainers
- Alberto Ricart <alberto@nats.io> [@aricart](https://github.com/aricart)
- Colin Sullivan <colin@nats.io> [@ColinSullivan1](https://github.com/ColinSullivan1)
- Waldemar Quevedo <wally@nats.io> [@wallyqs](https://github.com/wallyqs)
- R.I. Pienaar <rip@devco.net> [@ripienaar](https://github.com/ripienaar)

View File

@ -1,9 +0,0 @@
reviewers:
- aricart
- ColinSullivan1
- derekcollison
- kozlovic
- wallyqs
approvers:
- derekcollison
- kozlovic

View File

@ -5,6 +5,7 @@ NATS Streaming is an extremely performant, lightweight reliable streaming platfo
[![License Apache 2](https://img.shields.io/badge/License-Apache2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
[![Build Status](https://travis-ci.org/nats-io/go-nats-streaming.svg?branch=master)](http://travis-ci.org/nats-io/go-nats-streaming)
[![Coverage Status](https://coveralls.io/repos/nats-io/go-nats-streaming/badge.svg?branch=master)](https://coveralls.io/r/nats-io/go-nats-streaming?branch=master)
[![GoDoc](https://godoc.org/github.com/nats-io/go-nats-streaming?status.svg)](http://godoc.org/github.com/nats-io/go-nats-streaming)
NATS Streaming provides the following high-level feature set:
- Log based persistence
@ -27,6 +28,7 @@ go get github.com/nats-io/go-nats-streaming
## Basic Usage
```go
import stan "github.com/nats-io/go-nats-streaming"
sc, _ := stan.Connect(clusterID, clientID)
@ -239,6 +241,27 @@ NATS Streaming subscriptions **do not** support wildcards.
## Advanced Usage
### Connection configuration such as TLS, etc..
If you want more advanced configuration of the underlying NATS Connection, you will need
to create a NATS connection and pass that connection to the `stan.Connect()` call with
the `stan.NatsConn()` option.
```go
// Create a NATS connection that you can configure the way you want
nc, err = nats.Connect("tls://localhost:4443", nats.ClientCert("mycerts/client-cert.pem", "mycerts/client-key.pem"))
if (err != nil)
...
// Then pass it to the stan.Connect() call.
sc, err = stan.Connect("test-cluster", "me", stan.NatsConn(nc))
if (err != nil)
...
// Note that you will be responsible for closing the NATS Connection after the streaming
// connection has been closed.
```
### Connection Status
The fact that the NATS Streaming server and clients are not directly connected poses a challenge when it comes to know if a client is still valid.
@ -306,7 +329,6 @@ Advanced users may wish to process these publish acknowledgements manually to ac
}
}
// can also use PublishAsyncWithReply(subj, replysubj, payload, ah)
nuid, err := sc.PublishAsync("foo", []byte("Hello World"), ackHandler) // returns immediately
if err != nil {
log.Printf("Error publishing msg %s: %v\n", nuid, err.Error())
@ -377,4 +399,4 @@ sc.Subscribe("foo", func(m *stan.Msg) {
## License
Unless otherwise noted, the NATS source files are distributed
under the Apache Version 2.0 license found in the LICENSE file.
under the Apache Version 2.0 license found in the LICENSE file.

View File

@ -1,4 +1,4 @@
// Copyright 2016-2018 The NATS Authors
// Copyright 2016-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
@ -17,7 +17,6 @@ package stan
import (
"errors"
"fmt"
"runtime"
"sync"
"time"
@ -27,7 +26,7 @@ import (
)
// Version is the NATS Streaming Go Client version
const Version = "0.4.0"
const Version = "0.4.4"
const (
// DefaultNatsURL is the default URL the client connects to
@ -50,17 +49,39 @@ const (
// Conn represents a connection to the NATS Streaming subsystem. It can Publish and
// Subscribe to messages within the NATS Streaming cluster.
type Conn interface {
// Publish
// Publish will publish to the cluster and wait for an ACK.
Publish(subject string, data []byte) error
// PublishAsync will publish to the cluster and asynchronously process
// the ACK or error state. It will return the GUID for the message being sent.
PublishAsync(subject string, data []byte, ah AckHandler) (string, error)
// Subscribe
// Subscribe will perform a subscription with the given options to the cluster.
//
// If no option is specified, DefaultSubscriptionOptions are used. The default start
// position is to receive new messages only (messages published after the subscription is
// registered in the cluster).
Subscribe(subject string, cb MsgHandler, opts ...SubscriptionOption) (Subscription, error)
// QueueSubscribe
// QueueSubscribe will perform a queue subscription with the given options to the cluster.
//
// If no option is specified, DefaultSubscriptionOptions are used. The default start
// position is to receive new messages only (messages published after the subscription is
// registered in the cluster).
QueueSubscribe(subject, qgroup string, cb MsgHandler, opts ...SubscriptionOption) (Subscription, error)
// Close
// Close a connection to the cluster.
//
// If there are active subscriptions at the time of the close, they are implicitly closed
// (not unsubscribed) by the cluster. This means that durable subscriptions are maintained.
//
// The wait on asynchronous publish calls are canceled and ErrConnectionClosed will be
// reported to the registered AckHandler. It is possible that the cluster received and
// persisted these messages.
//
// If a NATS connection is provided as an option to the Connect() call, the NATS
// connection is NOT closed when this call is invoked. This connection needs to be
// managed by the application.
Close() error
// NatsConn returns the underlying NATS conn. Use this with care. For
@ -106,15 +127,46 @@ type ConnectionLostHandler func(Conn, error)
// Options can be used to a create a customized connection.
type Options struct {
NatsURL string
NatsConn *nats.Conn
ConnectTimeout time.Duration
AckTimeout time.Duration
DiscoverPrefix string
// NatsURL is an URL (or comma separated list of URLs) to a node or nodes
// in the cluster.
NatsURL string
// NatsConn is a user provided low-level NATS connection that the streaming
// connection will use to communicate with the cluster. When set, closing
// the NATS streaming connection does NOT close this NATS connection.
// It is the responsibility of the application to manage the lifetime of
// the supplied NATS connection.
NatsConn *nats.Conn
// ConnectTimeout is the timeout for the initial Connect(). This value is also
// used for some of the internal request/replies with the cluster.
ConnectTimeout time.Duration
// AckTimeout is how long to wait when a message is published for an ACK from
// the cluster. If the library does not receive an ACK after this timeout,
// the Publish() call (or the AckHandler) will return ErrTimeout.
AckTimeout time.Duration
// DiscoverPrefix is the prefix connect requests are sent to for this cluster.
// The default is "_STAN.discover".
DiscoverPrefix string
// MaxPubAcksInflight specifies how many messages can be published without
// getting ACKs back from the cluster before the Publish() or PublishAsync()
// calls block.
MaxPubAcksInflight int
PingIterval int // In seconds
PingMaxOut int
ConnectionLostCB ConnectionLostHandler
// PingInterval is the interval at which client sends PINGs to the server
// to detect the loss of a connection.
PingIterval int
// PingMaxOut specifies the maximum number of PINGs without a corresponding
// PONG before declaring the connection permanently lost.
PingMaxOut int
// ConnectionLostCB specifies the handler to be invoked when the connection
// is permanently lost.
ConnectionLostCB ConnectionLostHandler
}
// DefaultOptions are the NATS Streaming client's default options
@ -132,6 +184,8 @@ var DefaultOptions = Options{
type Option func(*Options) error
// NatsURL is an Option to set the URL the client should connect to.
// The url can contain username/password semantics. e.g. nats://derek:pass@localhost:4222
// Comma separated arrays are also supported, e.g. urlA, urlB.
func NatsURL(u string) Option {
return func(o *Options) error {
o.NatsURL = u
@ -166,7 +220,8 @@ func MaxPubAcksInflight(max int) Option {
}
// NatsConn is an Option to set the underlying NATS connection to be used
// by a NATS Streaming Conn object.
// by a streaming connection object. When such option is set, closing the
// streaming connection does not close the provided NATS connection.
func NatsConn(nc *nats.Conn) Option {
return func(o *Options) error {
o.NatsConn = nc
@ -188,7 +243,7 @@ func Pings(interval, maxOut int) Option {
// do not check values.
if !testAllowMillisecInPings {
if interval < 1 || maxOut <= 2 {
return fmt.Errorf("Invalid ping values: interval=%v (min>0) maxOut=%v (min=2)", interval, maxOut)
return fmt.Errorf("invalid ping values: interval=%v (min>0) maxOut=%v (min=2)", interval, maxOut)
}
}
o.PingIterval = interval
@ -285,16 +340,15 @@ func Connect(stanClusterID, clientID string, options ...Option) (Conn, error) {
hbInbox := nats.NewInbox()
var err error
if c.hbSubscription, err = c.nc.Subscribe(hbInbox, c.processHeartBeat); err != nil {
c.Close()
c.failConnect(err)
return nil, err
}
// Prepare a subscription on ping responses, even if we are not
// going to need it, so that if that fails, it fails before initiating
// a connection.
pingSub, err := c.nc.Subscribe(nats.NewInbox(), c.processPingResponse)
if err != nil {
c.Close()
if c.pingSub, err = c.nc.Subscribe(nats.NewInbox(), c.processPingResponse); err != nil {
c.failConnect(err)
return nil, err
}
@ -311,7 +365,7 @@ func Connect(stanClusterID, clientID string, options ...Option) (Conn, error) {
b, _ := req.Marshal()
reply, err := c.nc.Request(discoverSubject, b, c.opts.ConnectTimeout)
if err != nil {
c.Close()
c.failConnect(err)
if err == nats.ErrTimeout {
return nil, ErrConnectReqTimeout
}
@ -321,14 +375,17 @@ func Connect(stanClusterID, clientID string, options ...Option) (Conn, error) {
cr := &pb.ConnectResponse{}
err = cr.Unmarshal(reply.Data)
if err != nil {
c.Close()
c.failConnect(err)
return nil, err
}
if cr.Error != "" {
c.Close()
c.failConnect(err)
return nil, errors.New(cr.Error)
}
// Past this point, we need to call Close() on error because the server
// has accepted our connection.
// Capture cluster configuration endpoints to publish and subscribe/unsubscribe.
c.pubPrefix = cr.PubPrefix
c.subRequests = cr.SubRequests
@ -354,7 +411,7 @@ func Connect(stanClusterID, clientID string, options ...Option) (Conn, error) {
c.connLostCB = c.opts.ConnectionLostCB
unsubPingSub := true
// Do this with servers which are at least at protcolOne.
// Do this with servers which are at least at protocolOne.
if cr.Protocol >= protocolOne {
// Note that in the future server may override client ping
// interval value sent in ConnectRequest, so use the
@ -367,7 +424,7 @@ func Connect(stanClusterID, clientID string, options ...Option) (Conn, error) {
// These will be immutable.
c.pingRequests = cr.PingRequests
c.pingInbox = pingSub.Subject
c.pingInbox = c.pingSub.Subject
// In test, it is possible that we get a negative value
// to represent milliseconds.
if testAllowMillisecInPings && cr.PingInterval < 0 {
@ -378,7 +435,6 @@ func Connect(stanClusterID, clientID string, options ...Option) (Conn, error) {
}
c.pingMaxOut = int(cr.PingMaxOut)
c.pingBytes, _ = (&pb.Ping{ConnID: c.connID}).Marshal()
c.pingSub = pingSub
// Set the timer now that we are set. Use lock to create
// synchronization point.
c.pingMu.Lock()
@ -387,15 +443,23 @@ func Connect(stanClusterID, clientID string, options ...Option) (Conn, error) {
}
}
if unsubPingSub {
pingSub.Unsubscribe()
c.pingSub.Unsubscribe()
c.pingSub = nil
}
// Attach a finalizer
runtime.SetFinalizer(&c, func(sc *conn) { sc.Close() })
return &c, nil
}
// Invoked on a failed connect.
// Perform appropriate cleanup operations but do not attempt to send
// a close request.
func (sc *conn) failConnect(err error) {
sc.cleanupOnClose(err)
if sc.nc != nil && sc.ncOwned {
sc.nc.Close()
}
}
// Sends a PING (containing the connection's ID) to the server at intervals
// specified by PingInterval option when connection is created.
// Everytime a PING is sent, the number of outstanding PINGs is increased.
@ -460,7 +524,7 @@ func (sc *conn) closeDueToPing(err error) {
}
// Stop timer, unsubscribe, fail the pubs, etc..
sc.cleanupOnClose(err)
// No need to send Close prototol, so simply close the underlying
// No need to send Close protocol, so simply close the underlying
// NATS connection (if we own it, and if not already closed)
if sc.ncOwned && !sc.nc.IsClosed() {
sc.nc.Close()
@ -488,15 +552,21 @@ func (sc *conn) cleanupOnClose(err error) {
}
sc.pingMu.Unlock()
// Unsubscribe only if the NATS connection is not already closed...
if !sc.nc.IsClosed() {
if sc.ackSubscription != nil {
sc.ackSubscription.Unsubscribe()
// Unsubscribe only if the NATS connection is not already closed
// and we don't own it (otherwise connection is going to be closed
// so no need for explicit unsubscribe).
if !sc.ncOwned && !sc.nc.IsClosed() {
if sc.hbSubscription != nil {
sc.hbSubscription.Unsubscribe()
}
if sc.pingSub != nil {
sc.pingSub.Unsubscribe()
}
if sc.ackSubscription != nil {
sc.ackSubscription.Unsubscribe()
}
}
// Fail all pending pubs
for guid, pubAck := range sc.pubAckMap {
if pubAck.t != nil {
@ -586,7 +656,7 @@ func (sc *conn) processAck(m *nats.Msg) {
pa := &pb.PubAck{}
err := pa.Unmarshal(m.Data)
if err != nil {
panic(fmt.Errorf("Error during ack unmarshal: %v", err))
panic(fmt.Errorf("error during ack unmarshal: %v", err))
}
// Remove
@ -722,13 +792,16 @@ func (sc *conn) processMsg(raw *nats.Msg) {
msg := &Msg{}
err := msg.Unmarshal(raw.Data)
if err != nil {
panic(fmt.Errorf("Error processing unmarshal for msg: %v", err))
panic(fmt.Errorf("error processing unmarshal for msg: %v", err))
}
var sub *subscription
// Lookup the subscription
sc.RLock()
nc := sc.nc
isClosed := nc == nil
sub := sc.subMap[raw.Subject]
if !isClosed {
sub = sc.subMap[raw.Subject]
}
sc.RUnlock()
// Check if sub is no longer valid or connection has been closed.

View File

@ -39,16 +39,8 @@ type Msg struct {
// Subscriptions and Options
// Subscription represents a subscription within the NATS Streaming cluster. Subscriptions
// will be rate matched and follow at-least delivery semantics.
// will be rate matched and follow at-least once delivery semantics.
type Subscription interface {
ClearMaxPending() error
Delivered() (int64, error)
Dropped() (int, error)
IsValid() bool
MaxPending() (int, int, error)
Pending() (int, int, error)
PendingLimits() (int, int, error)
SetPendingLimits(msgLimit, bytesLimit int) error
// Unsubscribe removes interest in the subscription.
// For durables, it means that the durable interest is also removed from
// the server. Restarting a durable with the same name will not resume
@ -60,6 +52,42 @@ type Subscription interface {
// for which this feature is not available, Close() will return a ErrNoServerSupport
// error.
Close() error
// These functions have been added for expert-users that need to get details
// about the low level NATS Subscription used internally to receive messages
// for this streaming subscription. They are documented in the Go client
// library: https://godoc.org/github.com/nats-io/go-nats#Subscription.ClearMaxPending
// ClearMaxPending resets the maximums seen so far.
ClearMaxPending() error
// Delivered returns the number of delivered messages for the internal low-level NATS subscription.
Delivered() (int64, error)
// Dropped returns the number of known dropped messages for the internal low-level NATS subscription.
// This will correspond to messages dropped by violations of PendingLimits. If the server declares
// the connection a SlowConsumer, this number may not be valid.
Dropped() (int, error)
// IsValid returns a boolean indicating whether the internal low-level NATS subscription is still active.
// This will return false if the subscription has already been closed.
IsValid() bool
// MaxPending returns the maximum number of queued messages and queued bytes seen so far for the internal
// low-level NATS subscription.
MaxPending() (int, int, error)
// Pending returns the number of queued messages and queued bytes in the client for the internal
// low-level NATS subscription.
Pending() (int, int, error)
// PendingLimits returns the current limits for the internal low-level NATS subscription. If no error is
// returned, a negative value indicates that the given metric is not limited.
PendingLimits() (int, int, error)
// SetPendingLimits sets the limits for pending msgs and bytes for the internal low-level NATS Subscription.
// Zero is not allowed. Any negative value means that the given metric is not limited.
SetPendingLimits(msgLimit, bytesLimit int) error
}
// A subscription represents a subscription to a stan cluster.
@ -183,7 +211,7 @@ func SetManualAckMode() SubscriptionOption {
}
}
// DurableName sets the DurableName for the subcriber.
// DurableName sets the DurableName for the subscriber.
func DurableName(name string) SubscriptionOption {
return func(o *SubscriptionOptions) error {
o.DurableName = name
@ -253,7 +281,7 @@ func (sc *conn) subscribe(subject, qgroup string, cb MsgHandler, options ...Subs
}
b, _ := sr.Marshal()
reply, err := sc.nc.Request(sc.subRequests, b, sc.opts.ConnectTimeout)
reply, err := nc.Request(sc.subRequests, b, sc.opts.ConnectTimeout)
if err != nil {
sub.inboxSub.Unsubscribe()
if err == nats.ErrTimeout {

View File

@ -1,21 +1,21 @@
language: go
sudo: false
go:
- 1.11.x
- 1.10.x
- 1.9.x
- 1.8.x
go_import_path: github.com/nats-io/go-nats
install:
- go get -t ./...
- go get github.com/nats-io/gnatsd
- go get github.com/mattn/goveralls
- go get github.com/wadey/gocovmerge
- go get -u honnef.co/go/tools/cmd/megacheck
- go get -u honnef.co/go/tools/cmd/staticcheck
- go get -u github.com/client9/misspell/cmd/misspell
before_script:
- $(exit $(go fmt ./... | wc -l))
- go vet ./...
- misspell -error -locale US .
- megacheck -ignore "$(cat staticcheck.ignore)" ./...
- staticcheck -ignore "$(cat staticcheck.ignore)" ./...
script:
- go test -i -race ./...
- if [[ "$TRAVIS_GO_VERSION" == 1.9.* ]]; then ./scripts/cov.sh TRAVIS; else go test -v -race ./...; fi
- go test -i -race ./...
- if [[ "$TRAVIS_GO_VERSION" =~ 1.11 ]]; then ./scripts/cov.sh TRAVIS; else go test -race ./...; fi

View File

@ -0,0 +1,3 @@
# NATS Go Client Governance
NATS Go Client (go-nats) is part of the NATS project and is subject to the [NATS Governance](https://github.com/nats-io/nats-general/blob/master/GOVERNANCE.md).

View File

@ -0,0 +1,10 @@
# Maintainers
Maintainership is on a per project basis.
### Core-maintainers
- Derek Collison <derek@nats.io> [@derekcollison](https://github.com/derekcollison)
- Ivan Kozlovic <ivan@nats.io> [@kozlovic](https://github.com/kozlovic)
### Maintainers
- Waldemar Quevedo <wally@nats.io> [@wallyqs](https://github.com/wallyqs)

View File

@ -1,7 +0,0 @@
reviewers:
- derekcollison
- kozlovic
- wallyqs
approvers:
- derekcollison
- kozlovic

View File

@ -2,6 +2,7 @@
A [Go](http://golang.org) client for the [NATS messaging system](https://nats.io).
[![License Apache 2](https://img.shields.io/badge/License-Apache2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fnats-io%2Fgo-nats.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fnats-io%2Fgo-nats?ref=badge_shield)
[![Go Report Card](https://goreportcard.com/badge/github.com/nats-io/go-nats)](https://goreportcard.com/report/github.com/nats-io/go-nats) [![Build Status](https://travis-ci.org/nats-io/go-nats.svg?branch=master)](http://travis-ci.org/nats-io/go-nats) [![GoDoc](https://godoc.org/github.com/nats-io/go-nats?status.svg)](http://godoc.org/github.com/nats-io/go-nats) [![Coverage Status](https://coveralls.io/repos/nats-io/go-nats/badge.svg?branch=master)](https://coveralls.io/r/nats-io/go-nats?branch=master)
## Installation
@ -17,7 +18,9 @@ go get github.com/nats-io/gnatsd
## Basic Usage
```go
import nats "github.com/nats-io/go-nats"
// Connect to a server
nc, _ := nats.Connect(nats.DefaultURL)
// Simple Publisher
@ -40,6 +43,9 @@ msg := <- ch
// Unsubscribe
sub.Unsubscribe()
// Drain
sub.Drain()
// Requests
msg, err := nc.Request("help", []byte("help me"), 10*time.Millisecond)
@ -48,9 +54,12 @@ nc.Subscribe("help", func(m *Msg) {
nc.Publish(m.Reply, []byte("I can help!"))
})
// Drain connection (Preferred for responders)
// Close() not needed if this is called.
nc.Drain()
// Close connection
nc, _ := nats.Connect("nats://localhost:4222")
nc.Close();
nc.Close()
```
## Encoded Connections
@ -107,6 +116,48 @@ c.Subscribe("help", func(subj, reply string, msg string) {
c.Close();
```
## New Authentication (Nkeys and User Credentials)
This requires server with version >= 2.0.0
NATS servers have a new security and authentication mechanism to authenticate with user credentials and Nkeys.
The simplest form is to use the helper method UserCredentials(credsFilepath).
```go
nc, err := nats.Connect(url, UserCredentials("user.creds"))
```
The helper methos creates two callback handlers to present the user JWT and sign the nonce challenge from the server.
The core client library never has direct access to your private key and simply performs the callback for signing the server challenge.
The helper will load and wipe and erase memory it uses for each connect or reconnect.
The helper also can take two entries, one for the JWT and one for the NKey seed file.
```go
nc, err := nats.Connect(url, UserCredentials("user.jwt", "user.nk"))
```
You can also set the callback handlers directly and manage challenge signing directly.
```go
nc, err := nats.Connect(url, UserJWT(jwtCB, sigCB))
```
Bare Nkeys are also supported. The nkey seed should be in a read only file, e.g. seed.txt
```bash
> cat seed.txt
# This is my seed nkey!
SUAGMJH5XLGZKQQWAWKRZJIGMOU4HPFUYLXJMXOO5NLFEO2OOQJ5LPRDPM
```
This is a helper function which will load and decode and do the proper signing for the server nonce.
It will clear memory in between invocations.
You can choose to use the low level option and provide the public key and a signature callback on your own.
```go
opt, err := nats.NkeyOptionFromSeed("seed.txt")
nc, err := nats.Connect(serverUrl, opt)
// Direct
nc, err := nats.Connect(serverUrl, Nkey(pubNkey, sigCB))
```
## TLS
```go
@ -263,7 +314,7 @@ nc, err = nats.Connect(servers,
nats.DisconnectHandler(func(nc *nats.Conn) {
fmt.Printf("Got disconnected!\n")
}),
nats.ReconnectHandler(func(_ *nats.Conn) {
nats.ReconnectHandler(func(nc *nats.Conn) {
fmt.Printf("Got reconnected to %v!\n", nc.ConnectedUrl())
}),
nats.ClosedHandler(func(nc *nats.Conn) {
@ -329,3 +380,5 @@ err := c.RequestWithContext(ctx, "foo", req, resp)
Unless otherwise noted, the NATS source files are distributed
under the Apache Version 2.0 license found in the LICENSE file.
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fnats-io%2Fgo-nats.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fnats-io%2Fgo-nats?ref=badge_large)

View File

@ -18,7 +18,6 @@ package nats
import (
"context"
"fmt"
"reflect"
)
@ -31,6 +30,11 @@ func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte
if nc == nil {
return nil, ErrInvalidConnection
}
// Check whether the context is done already before making
// the request.
if ctx.Err() != nil {
return nil, ctx.Err()
}
nc.mu.Lock()
// If user wants the old style.
@ -41,9 +45,7 @@ func (nc *Conn) RequestWithContext(ctx context.Context, subj string, data []byte
// Do setup for the new style.
if nc.respMap == nil {
// _INBOX wildcard
nc.respSub = fmt.Sprintf("%s.*", NewInbox())
nc.respMap = make(map[string]chan *Msg)
nc.initNewResp()
}
// Create literal Inbox and map to a chan msg.
mch := make(chan *Msg, RequestChanLen)
@ -116,6 +118,9 @@ func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error) {
if s == nil {
return nil, ErrBadSubscription
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
s.mu.Lock()
err := s.validateNextMsgState()
@ -131,13 +136,26 @@ func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error) {
var ok bool
var msg *Msg
// If something is available right away, let's optimize that case.
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
err := s.processNextMsgDelivered(msg)
if err != nil {
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
} else {
return msg, nil
}
default:
}
select {
case msg, ok = <-mch:
if !ok {
return nil, ErrConnectionClosed
}
if err := s.processNextMsgDelivered(msg); err != nil {
return nil, err
}
case <-ctx.Done():
@ -147,6 +165,52 @@ func (s *Subscription) NextMsgWithContext(ctx context.Context) (*Msg, error) {
return msg, nil
}
// FlushWithContext will allow a context to control the duration
// of a Flush() call. This context should be non-nil and should
// have a deadline set. We will return an error if none is present.
func (nc *Conn) FlushWithContext(ctx context.Context) error {
if nc == nil {
return ErrInvalidConnection
}
if ctx == nil {
return ErrInvalidContext
}
_, ok := ctx.Deadline()
if !ok {
return ErrNoDeadlineContext
}
nc.mu.Lock()
if nc.isClosed() {
nc.mu.Unlock()
return ErrConnectionClosed
}
// Create a buffered channel to prevent chan send to block
// in processPong()
ch := make(chan struct{}, 1)
nc.sendPing(ch)
nc.mu.Unlock()
var err error
select {
case _, ok := <-ch:
if !ok {
err = ErrConnectionClosed
} else {
close(ch)
}
case <-ctx.Done():
err = ctx.Err()
}
if err != nil {
nc.removeFlushEntry(ch)
}
return err
}
// RequestWithContext will create an Inbox and perform a Request
// using the provided cancellation context with the Inbox reply
// for the data v. A response will be decoded into the vPtrResponse.

View File

@ -21,7 +21,7 @@ import (
"time"
// Default Encoders
. "github.com/nats-io/go-nats/encoders/builtin"
"github.com/nats-io/go-nats/encoders/builtin"
)
// Encoder interface is for all register encoders
@ -43,9 +43,9 @@ const (
func init() {
encMap = make(map[string]Encoder)
// Register json, gob and default encoder
RegisterEncoder(JSON_ENCODER, &JsonEncoder{})
RegisterEncoder(GOB_ENCODER, &GobEncoder{})
RegisterEncoder(DEFAULT_ENCODER, &DefaultEncoder{})
RegisterEncoder(JSON_ENCODER, &builtin.JsonEncoder{})
RegisterEncoder(GOB_ENCODER, &builtin.GobEncoder{})
RegisterEncoder(DEFAULT_ENCODER, &builtin.DefaultEncoder{})
}
// EncodedConn are the preferred way to interface with NATS. They wrap a bare connection to
@ -67,7 +67,7 @@ func NewEncodedConn(c *Conn, encType string) (*EncodedConn, error) {
}
ec := &EncodedConn{Conn: c, Enc: EncoderForType(encType)}
if ec.Enc == nil {
return nil, fmt.Errorf("No encoder registered for '%s'", encType)
return nil, fmt.Errorf("no encoder registered for '%s'", encType)
}
return ec, nil
}
@ -207,9 +207,9 @@ func (c *EncodedConn) subscribe(subject, queue string, cb Handler) (*Subscriptio
}
if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil {
if c.Conn.Opts.AsyncErrorCB != nil {
c.Conn.ach <- func() {
c.Conn.ach.push(func() {
c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, errors.New("nats: Got an error trying to unmarshal: "+err.Error()))
}
})
}
return
}
@ -254,6 +254,15 @@ func (c *EncodedConn) Close() {
c.Conn.Close()
}
// Drain will put a connection into a drain state. All subscriptions will
// immediately be put into a drain state. Upon completion, the publishers
// will be drained and can not publish any additional messages. Upon draining
// of the publishers, the connection will be closed. Use the ClosedCB()
// option to know when the connection has moved from draining to closed.
func (c *EncodedConn) Drain() error {
return c.Conn.Drain()
}
// LastError reports the last error encountered via the Connection.
func (c *EncodedConn) LastError() error {
return c.Conn.err

File diff suppressed because it is too large Load Diff

View File

@ -52,7 +52,7 @@ func chPublish(c *EncodedConn, chVal reflect.Value, subject string) {
if c.Conn.isClosed() {
go c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e)
} else {
c.Conn.ach <- func() { c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e) }
c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e) })
}
}
return
@ -88,7 +88,7 @@ func (c *EncodedConn) bindRecvChan(subject, queue string, channel interface{}) (
if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil {
c.Conn.err = errors.New("nats: Got an error trying to unmarshal: " + err.Error())
if c.Conn.Opts.AsyncErrorCB != nil {
c.Conn.ach <- func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, c.Conn.err) }
c.Conn.ach.push(func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, c.Conn.err) })
}
return
}

15
gateway/vendor/github.com/nats-io/nkeys/.gitignore generated vendored Normal file
View File

@ -0,0 +1,15 @@
# Binaries for programs and plugins
*.exe
*.dll
*.so
*.dylib
build/
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736
.glide/

View File

@ -0,0 +1,38 @@
project_name: nkeys
release:
github:
owner: nats-io
name: nkeys
name_template: '{{.Tag}}'
draft: true
builds:
- main: ./nk/main.go
ldflags: "-X main.Version={{.Tag}}_{{.Commit}}"
binary: nk
goos:
- linux
- darwin
goarch:
- amd64
dist: build
archive:
wrap_in_directory: true
name_template: '{{ .ProjectName }}-v{{ .Version }}-{{ .Os }}-{{ .Arch }}{{ if .Arm
}}v{{ .Arm }}{{ end }}'
format: zip
checksum:
name_template: '{{ .ProjectName }}-v{{ .Version }}-checksums.txt'
snapshot:
name_template: 'dev'
nfpm:
formats:
- deb
bindir: /usr/local/bin
description: NKeys utility cli program
vendor: nats-io

31
gateway/vendor/github.com/nats-io/nkeys/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,31 @@
language: go
sudo: false
go:
- 1.12.x
- 1.11.x
install:
- go get -t ./...
- go get github.com/mattn/goveralls
- go get -u honnef.co/go/tools/cmd/staticcheck
- go get -u github.com/client9/misspell/cmd/misspell
before_script:
- $(exit $(go fmt ./... | wc -l))
- go vet ./...
- misspell -error -locale US .
- staticcheck ./...
script:
- go test -v
- go test -v --race
- go test -v -covermode=count -coverprofile=coverage.out
- $HOME/gopath/bin/goveralls -coverprofile coverage.out -service travis-ci
#deploy:
#- provider: script
# skip_cleanup: true
# script: curl -sL http://git.io/goreleaser | bash
# on:
# tags: true
# condition: $TRAVIS_OS_NAME = linux

View File

@ -0,0 +1,3 @@
# NATS NKEYS Governance
NATS NKEYS is part of the NATS project and is subject to the [NATS Governance](https://github.com/nats-io/nats-general/blob/master/GOVERNANCE.md).

201
gateway/vendor/github.com/nats-io/nkeys/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@ -0,0 +1,6 @@
# Maintainers
Maintainership is on a per project basis.
### Core-maintainers
- Derek Collison <derek@nats.io> [@derekcollison](https://github.com/derekcollison)

72
gateway/vendor/github.com/nats-io/nkeys/README.md generated vendored Normal file
View File

@ -0,0 +1,72 @@
# NKEYS
[![License Apache 2](https://img.shields.io/badge/License-Apache2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
[![ReportCard](http://goreportcard.com/badge/nats-io/nkeys)](http://goreportcard.com/report/nats-io/nkeys)
[![Build Status](https://travis-ci.org/nats-io/nkeys.svg?branch=master)](http://travis-ci.org/nats-io/nkeys)
[![GoDoc](http://godoc.org/github.com/nats-io/nkeys?status.svg)](http://godoc.org/github.com/nats-io/nkeys)
[![Coverage Status](https://coveralls.io/repos/github/nats-io/nkeys/badge.svg?branch=master&service=github)](https://coveralls.io/github/nats-io/nkeys?branch=master)
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fnats-io%2Fnkeys.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fnats-io%2Fnkeys?ref=badge_shield)
A public-key signature system based on [Ed25519](https://ed25519.cr.yp.to/) for the NATS ecosystem.
## About
The NATS ecosystem will be moving to [Ed25519](https://ed25519.cr.yp.to/) keys for identity, authentication and authorization for entities such as Accounts, Users, Servers and Clusters.
Ed25519 is fast and resistant to side channel attacks. Generation of a seed key is all that is needed to be stored and kept safe, as the seed can generate both the public and private keys.
The NATS system will utilize Ed25519 keys, meaning that NATS systems will never store or even have access to any private keys. Authentication will utilize a random challenge response mechanism.
Dealing with 32 byte and 64 byte raw keys can be challenging. NKEYS is designed to formulate keys in a much friendlier fashion and references work done in cryptocurrencies, specifically [Stellar](https://www.stellar.org/). Bitcoin and others used a form of Base58 (or Base58Check) to endode raw keys. Stellar utilized a more traditonal Base32 with a CRC16 and a version or prefix byte. NKEYS utilizes a similar format where the prefix will be 1 byte for public and private keys and will be 2 bytes for seeds. The base32 encoding of these prefixes will yield friendly human readbable prefixes, e.g. '**N**' = server, '**C**' = cluster, '**O**' = operator, '**A**' = account, and '**U**' = user. '**P**' is used for private keys. For seeds, the first encoded prefix is '**S**', and the second character will be the type for the public key, e.g. "**SU**" is a seed for a user key pair, "**SA**" is a seed for an account key pair.
## Installation
Use the `go` command:
$ go get github.com/nats-io/nkeys
## nk - Command Line Utility
Located under the nk [directory](https://github.com/nats-io/nkeys/tree/master/nk).
## Basic API Usage
```go
// Create a new User KeyPair
user, _ := nkeys.CreateUser()
// Sign some data with a full key pair user.
data := []byte("Hello World")
sig, _ := user.Sign(data)
// Verify the signature.
err = user.Verify(data, sig)
// Access the seed, the only thing that needs to be stored and kept safe.
// seed = "SUAKYRHVIOREXV7EUZTBHUHL7NUMHPMAS7QMDU3GTIUWEI5LDNOXD43IZY"
seed, _ := user.Seed()
// Access the public key which can be shared.
// publicKey = "UD466L6EBCM3YY5HEGHJANNTN4LSKTSUXTH7RILHCKEQMQHTBNLHJJXT"
publicKey, _ := user.PublicKey()
// Create a full User who can sign and verify from a private seed.
user, _ = nkeys.FromSeed(seed)
// Create a User who can only verify signatures via a public key.
user, _ = nkeys.FromPublicKey(publicKey)
// Create a User KeyPair with our own random data.
var rawSeed [32]byte
_, err := io.ReadFull(rand.Reader, rawSeed[:]) // Or some other random source.
user2, _ := nkeys.FromRawSeed(PrefixByteUser, rawSeed)
```
## License
Unless otherwise noted, the NATS source files are distributed
under the Apache Version 2.0 license found in the LICENSE file.
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fnats-io%2Fnkeys.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fnats-io%2Fnkeys?ref=badge_large)

5
gateway/vendor/github.com/nats-io/nkeys/TODO.md generated vendored Normal file
View File

@ -0,0 +1,5 @@
# General
- [ ] Child key derivation
- [ ] Hardware support, e.g. YubiHSM

75
gateway/vendor/github.com/nats-io/nkeys/crc16.go generated vendored Normal file
View File

@ -0,0 +1,75 @@
// Copyright 2018 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 nkeys
import (
"errors"
)
// An implementation of crc16 according to CCITT standards for XMODEM.
// ErrInvalidChecksum indicates a failed verification.
var ErrInvalidChecksum = errors.New("nkeys: invalid checksum")
var crc16tab = [256]uint16{
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
}
// crc16 returns the 2-byte crc for the data provided.
func crc16(data []byte) uint16 {
var crc uint16
for _, b := range data {
crc = ((crc << 8) & 0xffff) ^ crc16tab[((crc>>8)^uint16(b))&0x00FF]
}
return crc
}
// validate will check the calculated crc16 checksum for data against the expected.
func validate(data []byte, expected uint16) error {
if crc16(data) != expected {
return ErrInvalidChecksum
}
return nil
}

3
gateway/vendor/github.com/nats-io/nkeys/go.mod generated vendored Normal file
View File

@ -0,0 +1,3 @@
module github.com/nats-io/nkeys
require golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4

7
gateway/vendor/github.com/nats-io/nkeys/go.sum generated vendored Normal file
View File

@ -0,0 +1,7 @@
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 h1:HuIa8hRrWRSrqYzx1qI49NNxhdi2PrY7gxVSq1JjLDc=
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=

117
gateway/vendor/github.com/nats-io/nkeys/keypair.go generated vendored Normal file
View File

@ -0,0 +1,117 @@
// Copyright 2018 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 nkeys
import (
"bytes"
"crypto/rand"
"io"
"golang.org/x/crypto/ed25519"
)
// kp is the internal struct for a kepypair using seed.
type kp struct {
seed []byte
}
// CreatePair will create a KeyPair based on the rand entropy and a type/prefix byte. rand can be nil.
func CreatePair(prefix PrefixByte) (KeyPair, error) {
var rawSeed [32]byte
_, err := io.ReadFull(rand.Reader, rawSeed[:])
if err != nil {
return nil, err
}
seed, err := EncodeSeed(prefix, rawSeed[:])
if err != nil {
return nil, err
}
return &kp{seed}, nil
}
// rawSeed will return the raw, decoded 64 byte seed.
func (pair *kp) rawSeed() ([]byte, error) {
_, raw, err := DecodeSeed(pair.seed)
return raw, err
}
// keys will return a 32 byte public key and a 64 byte private key utilizing the seed.
func (pair *kp) keys() (ed25519.PublicKey, ed25519.PrivateKey, error) {
raw, err := pair.rawSeed()
if err != nil {
return nil, nil, err
}
return ed25519.GenerateKey(bytes.NewReader(raw))
}
// Wipe will randomize the contents of the seed key
func (pair *kp) Wipe() {
io.ReadFull(rand.Reader, pair.seed)
pair.seed = nil
}
// Seed will return the encoded seed.
func (pair *kp) Seed() ([]byte, error) {
return pair.seed, nil
}
// PublicKey will return the encoded public key associated with the KeyPair.
// All KeyPairs have a public key.
func (pair *kp) PublicKey() (string, error) {
public, raw, err := DecodeSeed(pair.seed)
if err != nil {
return "", err
}
pub, _, err := ed25519.GenerateKey(bytes.NewReader(raw))
if err != nil {
return "", err
}
pk, err := Encode(public, pub)
if err != nil {
return "", err
}
return string(pk), nil
}
// PrivateKey will return the encoded private key for KeyPair.
func (pair *kp) PrivateKey() ([]byte, error) {
_, priv, err := pair.keys()
if err != nil {
return nil, err
}
return Encode(PrefixBytePrivate, priv)
}
// Sign will sign the input with KeyPair's private key.
func (pair *kp) Sign(input []byte) ([]byte, error) {
_, priv, err := pair.keys()
if err != nil {
return nil, err
}
return ed25519.Sign(priv, input), nil
}
// Verify will verify the input against a signature utilizing the public key.
func (pair *kp) Verify(input []byte, sig []byte) error {
pub, _, err := pair.keys()
if err != nil {
return err
}
if !ed25519.Verify(pub, input, sig) {
return ErrInvalidSignature
}
return nil
}

103
gateway/vendor/github.com/nats-io/nkeys/main.go generated vendored Normal file
View File

@ -0,0 +1,103 @@
// 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 nkeys is an Ed25519 based public-key signature system that simplifies keys and seeds
// and performs signing and verification.
package nkeys
import (
"errors"
)
// Version
const Version = "0.1.0"
// Errors
var (
ErrInvalidPrefixByte = errors.New("nkeys: invalid prefix byte")
ErrInvalidKey = errors.New("nkeys: invalid key")
ErrInvalidPublicKey = errors.New("nkeys: invalid public key")
ErrInvalidSeedLen = errors.New("nkeys: invalid seed length")
ErrInvalidSeed = errors.New("nkeys: invalid seed")
ErrInvalidEncoding = errors.New("nkeys: invalid encoded key")
ErrInvalidSignature = errors.New("nkeys: signature verification failed")
ErrCannotSign = errors.New("nkeys: can not sign, no private key available")
ErrPublicKeyOnly = errors.New("nkeys: no seed or private key available")
)
// KeyPair provides the central interface to nkeys.
type KeyPair interface {
Seed() ([]byte, error)
PublicKey() (string, error)
PrivateKey() ([]byte, error)
Sign(input []byte) ([]byte, error)
Verify(input []byte, sig []byte) error
Wipe()
}
// CreateUser will create a User typed KeyPair.
func CreateUser() (KeyPair, error) {
return CreatePair(PrefixByteUser)
}
// CreateAccount will create an Account typed KeyPair.
func CreateAccount() (KeyPair, error) {
return CreatePair(PrefixByteAccount)
}
// CreateServer will create a Server typed KeyPair.
func CreateServer() (KeyPair, error) {
return CreatePair(PrefixByteServer)
}
// CreateCluster will create a Cluster typed KeyPair.
func CreateCluster() (KeyPair, error) {
return CreatePair(PrefixByteCluster)
}
// CreateOperator will create an Operator typed KeyPair.
func CreateOperator() (KeyPair, error) {
return CreatePair(PrefixByteOperator)
}
// FromPublicKey will create a KeyPair capable of verifying signatures.
func FromPublicKey(public string) (KeyPair, error) {
raw, err := decode([]byte(public))
if err != nil {
return nil, err
}
pre := PrefixByte(raw[0])
if err := checkValidPublicPrefixByte(pre); err != nil {
return nil, ErrInvalidPublicKey
}
return &pub{pre, raw[1:]}, nil
}
// FromSeed will create a KeyPair capable of signing and verifying signatures.
func FromSeed(seed []byte) (KeyPair, error) {
_, _, err := DecodeSeed(seed)
if err != nil {
return nil, err
}
copy := append([]byte{}, seed...)
return &kp{copy}, nil
}
// Create a KeyPair from the raw 32 byte seed for a given type.
func FromRawSeed(prefix PrefixByte, rawSeed []byte) (KeyPair, error) {
seed, err := EncodeSeed(prefix, rawSeed)
if err != nil {
return nil, err
}
return &kp{seed}, nil
}

66
gateway/vendor/github.com/nats-io/nkeys/public.go generated vendored Normal file
View File

@ -0,0 +1,66 @@
// Copyright 2018 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 nkeys
import (
"crypto/rand"
"io"
"golang.org/x/crypto/ed25519"
)
// A KeyPair from a public key capable of verifying only.
type pub struct {
pre PrefixByte
pub ed25519.PublicKey
}
// PublicKey will return the encoded public key associated with the KeyPair.
// All KeyPairs have a public key.
func (p *pub) PublicKey() (string, error) {
pk, err := Encode(p.pre, p.pub)
if err != nil {
return "", err
}
return string(pk), nil
}
// Seed will return an error since this is not available for public key only KeyPairs.
func (p *pub) Seed() ([]byte, error) {
return nil, ErrPublicKeyOnly
}
// PrivateKey will return an error since this is not available for public key only KeyPairs.
func (p *pub) PrivateKey() ([]byte, error) {
return nil, ErrPublicKeyOnly
}
// Sign will return an error since this is not available for public key only KeyPairs.
func (p *pub) Sign(input []byte) ([]byte, error) {
return nil, ErrCannotSign
}
// Verify will verify the input against a signature utilizing the public key.
func (p *pub) Verify(input []byte, sig []byte) error {
if !ed25519.Verify(p.pub, input, sig) {
return ErrInvalidSignature
}
return nil
}
// Wipe will randomize the public key and erase the pre byte.
func (p *pub) Wipe() {
p.pre = '0'
io.ReadFull(rand.Reader, p.pub)
}

290
gateway/vendor/github.com/nats-io/nkeys/strkey.go generated vendored Normal file
View File

@ -0,0 +1,290 @@
// Copyright 2018 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 nkeys
import (
"bytes"
"encoding/base32"
"encoding/binary"
"golang.org/x/crypto/ed25519"
)
// PrefixByte is a lead byte representing the type.
type PrefixByte byte
const (
// PrefixByteSeed is the version byte used for encoded NATS Seeds
PrefixByteSeed PrefixByte = 18 << 3 // Base32-encodes to 'S...'
// PrefixBytePrivate is the version byte used for encoded NATS Private keys
PrefixBytePrivate PrefixByte = 15 << 3 // Base32-encodes to 'P...'
// PrefixByteServer is the version byte used for encoded NATS Servers
PrefixByteServer PrefixByte = 13 << 3 // Base32-encodes to 'N...'
// PrefixByteCluster is the version byte used for encoded NATS Clusters
PrefixByteCluster PrefixByte = 2 << 3 // Base32-encodes to 'C...'
// PrefixByteOperator is the version byte used for encoded NATS Operators
PrefixByteOperator PrefixByte = 14 << 3 // Base32-encodes to 'O...'
// PrefixByteAccount is the version byte used for encoded NATS Accounts
PrefixByteAccount PrefixByte = 0 // Base32-encodes to 'A...'
// PrefixByteUser is the version byte used for encoded NATS Users
PrefixByteUser PrefixByte = 20 << 3 // Base32-encodes to 'U...'
// PrefixByteUnknown is for unknown prefixes.
PrefixByteUknown PrefixByte = 23 << 3 // Base32-encodes to 'X...'
)
// Set our encoding to not include padding '=='
var b32Enc = base32.StdEncoding.WithPadding(base32.NoPadding)
// Encode will encode a raw key or seed with the prefix and crc16 and then base32 encoded.
func Encode(prefix PrefixByte, src []byte) ([]byte, error) {
if err := checkValidPrefixByte(prefix); err != nil {
return nil, err
}
var raw bytes.Buffer
// write prefix byte
if err := raw.WriteByte(byte(prefix)); err != nil {
return nil, err
}
// write payload
if _, err := raw.Write(src); err != nil {
return nil, err
}
// Calculate and write crc16 checksum
err := binary.Write(&raw, binary.LittleEndian, crc16(raw.Bytes()))
if err != nil {
return nil, err
}
data := raw.Bytes()
buf := make([]byte, b32Enc.EncodedLen(len(data)))
b32Enc.Encode(buf, data)
return buf[:], nil
}
// EncodeSeed will encode a raw key with the prefix and then seed prefix and crc16 and then base32 encoded.
func EncodeSeed(public PrefixByte, src []byte) ([]byte, error) {
if err := checkValidPublicPrefixByte(public); err != nil {
return nil, err
}
if len(src) != ed25519.SeedSize {
return nil, ErrInvalidSeedLen
}
// In order to make this human printable for both bytes, we need to do a little
// bit manipulation to setup for base32 encoding which takes 5 bits at a time.
b1 := byte(PrefixByteSeed) | (byte(public) >> 5)
b2 := (byte(public) & 31) << 3 // 31 = 00011111
var raw bytes.Buffer
raw.WriteByte(b1)
raw.WriteByte(b2)
// write payload
if _, err := raw.Write(src); err != nil {
return nil, err
}
// Calculate and write crc16 checksum
err := binary.Write(&raw, binary.LittleEndian, crc16(raw.Bytes()))
if err != nil {
return nil, err
}
data := raw.Bytes()
buf := make([]byte, b32Enc.EncodedLen(len(data)))
b32Enc.Encode(buf, data)
return buf, nil
}
// IsValidEncoding will tell you if the encoding is a valid key.
func IsValidEncoding(src []byte) bool {
_, err := decode(src)
return err == nil
}
// decode will decode the base32 and check crc16 and the prefix for validity.
func decode(src []byte) ([]byte, error) {
raw := make([]byte, b32Enc.DecodedLen(len(src)))
n, err := b32Enc.Decode(raw, src)
if err != nil {
return nil, err
}
raw = raw[:n]
if len(raw) < 4 {
return nil, ErrInvalidEncoding
}
var crc uint16
checksum := bytes.NewReader(raw[len(raw)-2:])
if err := binary.Read(checksum, binary.LittleEndian, &crc); err != nil {
return nil, err
}
// ensure checksum is valid
if err := validate(raw[0:len(raw)-2], crc); err != nil {
return nil, err
}
return raw[:len(raw)-2], nil
}
// Decode will decode the base32 string and check crc16 and enforce the prefix is what is expected.
func Decode(expectedPrefix PrefixByte, src []byte) ([]byte, error) {
if err := checkValidPrefixByte(expectedPrefix); err != nil {
return nil, err
}
raw, err := decode(src)
if err != nil {
return nil, err
}
if prefix := PrefixByte(raw[0]); prefix != expectedPrefix {
return nil, ErrInvalidPrefixByte
}
return raw[1:], nil
}
// DecodeSeed will decode the base32 string and check crc16 and enforce the prefix is a seed
// and the subsequent type is a valid type.
func DecodeSeed(src []byte) (PrefixByte, []byte, error) {
raw, err := decode(src)
if err != nil {
return PrefixByteSeed, nil, err
}
// Need to do the reverse here to get back to internal representation.
b1 := raw[0] & 248 // 248 = 11111000
b2 := (raw[0]&7)<<5 | ((raw[1] & 248) >> 3) // 7 = 00000111
if PrefixByte(b1) != PrefixByteSeed {
return PrefixByteSeed, nil, ErrInvalidSeed
}
if checkValidPublicPrefixByte(PrefixByte(b2)) != nil {
return PrefixByteSeed, nil, ErrInvalidSeed
}
return PrefixByte(b2), raw[2:], nil
}
func Prefix(src string) PrefixByte {
b, err := decode([]byte(src))
if err != nil {
return PrefixByteUknown
}
prefix := PrefixByte(b[0])
err = checkValidPrefixByte(prefix)
if err == nil {
return prefix
}
// Might be a seed.
b1 := b[0] & 248
if PrefixByte(b1) == PrefixByteSeed {
return PrefixByteSeed
}
return PrefixByteUknown
}
// IsValidPublicKey will decode and verify that the string is a valid encoded public key.
func IsValidPublicKey(src string) bool {
b, err := decode([]byte(src))
if err != nil {
return false
}
if prefix := PrefixByte(b[0]); checkValidPublicPrefixByte(prefix) != nil {
return false
}
return true
}
// IsValidPublicUserKey will decode and verify the string is a valid encoded Public User Key.
func IsValidPublicUserKey(src string) bool {
_, err := Decode(PrefixByteUser, []byte(src))
return err == nil
}
// IsValidPublicAccountKey will decode and verify the string is a valid encoded Public Account Key.
func IsValidPublicAccountKey(src string) bool {
_, err := Decode(PrefixByteAccount, []byte(src))
return err == nil
}
// IsValidPublicServerKey will decode and verify the string is a valid encoded Public Server Key.
func IsValidPublicServerKey(src string) bool {
_, err := Decode(PrefixByteServer, []byte(src))
return err == nil
}
// IsValidPublicClusterKey will decode and verify the string is a valid encoded Public Cluster Key.
func IsValidPublicClusterKey(src string) bool {
_, err := Decode(PrefixByteCluster, []byte(src))
return err == nil
}
// IsValidPublicOperatorKey will decode and verify the string is a valid encoded Public Operator Key.
func IsValidPublicOperatorKey(src string) bool {
_, err := Decode(PrefixByteOperator, []byte(src))
return err == nil
}
// checkValidPrefixByte returns an error if the provided value
// is not one of the defined valid prefix byte constants.
func checkValidPrefixByte(prefix PrefixByte) error {
switch prefix {
case PrefixByteOperator, PrefixByteServer, PrefixByteCluster,
PrefixByteAccount, PrefixByteUser, PrefixByteSeed, PrefixBytePrivate:
return nil
}
return ErrInvalidPrefixByte
}
// checkValidPublicPrefixByte returns an error if the provided value
// is not one of the public defined valid prefix byte constants.
func checkValidPublicPrefixByte(prefix PrefixByte) error {
switch prefix {
case PrefixByteServer, PrefixByteCluster, PrefixByteOperator, PrefixByteAccount, PrefixByteUser:
return nil
}
return ErrInvalidPrefixByte
}
func (p PrefixByte) String() string {
switch p {
case PrefixByteOperator:
return "operator"
case PrefixByteServer:
return "server"
case PrefixByteCluster:
return "cluster"
case PrefixByteAccount:
return "account"
case PrefixByteUser:
return "user"
case PrefixByteSeed:
return "seed"
case PrefixBytePrivate:
return "private"
}
return "unknown"
}

View File

@ -1,7 +1,8 @@
language: go
sudo: false
go:
- 1.5
- 1.9.x
- 1.10.x
install:
- go get -t ./...

3
gateway/vendor/github.com/nats-io/nuid/GOVERNANCE.md generated vendored Normal file
View File

@ -0,0 +1,3 @@
# NATS NUID Governance
NATS NUID is part of the NATS project and is subject to the [NATS Governance](https://github.com/nats-io/nats-general/blob/master/GOVERNANCE.md).

View File

@ -1,21 +1,201 @@
The MIT License (MIT)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2012-2016 Apcera Inc.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. Definitions.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@ -0,0 +1,6 @@
# Maintainers
Maintainership is on a per project basis.
### Core-maintainers
- Derek Collison <derek@nats.io> [@derekcollison](https://github.com/derekcollison)

View File

@ -1,9 +1,9 @@
# NUID
[![License MIT](https://img.shields.io/npm/l/express.svg)](http://opensource.org/licenses/MIT)
[![License Apache 2](https://img.shields.io/badge/License-Apache2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
[![ReportCard](http://goreportcard.com/badge/nats-io/nuid)](http://goreportcard.com/report/nats-io/nuid)
[![Build Status](https://travis-ci.org/nats-io/nuid.svg?branch=master)](http://travis-ci.org/nats-io/nuid)
[![Release](https://img.shields.io/badge/release-v1.0.0-1eb0fc.svg)](https://github.com/nats-io/nuid/releases/tag/v1.0.0)
[![Release](https://img.shields.io/badge/release-v1.0.1-1eb0fc.svg)](https://github.com/nats-io/nuid/releases/tag/v1.0.1)
[![GoDoc](http://godoc.org/github.com/nats-io/nuid?status.png)](http://godoc.org/github.com/nats-io/nuid)
[![Coverage Status](https://coveralls.io/repos/github/nats-io/nuid/badge.svg?branch=master)](https://coveralls.io/github/nats-io/nuid?branch=master)
@ -35,32 +35,13 @@ NUID needs to be very fast to generate and be truly unique, all while being entr
NUID uses 12 bytes of crypto generated data (entropy draining), and 10 bytes of pseudo-random
sequential data that increments with a pseudo-random increment.
Total length of a NUID string is 22 bytes of base 36 ascii text, so 36^22 or
17324272922341479351919144385642496 possibilities.
Total length of a NUID string is 22 bytes of base 62 ascii text, so 62^22 or
2707803647802660400290261537185326956544 possibilities.
NUID can generate identifiers as fast as 60ns, or ~16 million per second. There is an associated
benchmark you can use to test performance on your own hardware.
## License
(The MIT License)
Copyright (c) 2016 Apcera Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
Unless otherwise noted, the NATS source files are distributed
under the Apache Version 2.0 license found in the LICENSE file.

View File

@ -1,4 +1,15 @@
// Copyright 2016 Apcera Inc. All rights reserved.
// Copyright 2016-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.
// A unique identifier generator that is high performance, very fast, and tries to be entropy pool friendly.
package nuid
@ -20,7 +31,7 @@ import (
// Total is 22 bytes of base 62 ascii text :)
// Version of the library
const Version = "1.0.0"
const Version = "1.0.1"
const (
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
@ -94,7 +105,7 @@ func (n *NUID) Next() string {
bs := b[:preLen]
copy(bs, n.pre)
// copy in the seq in base36.
// copy in the seq in base62.
for i, l := len(b), seq; i > preLen; l /= base {
i -= 1
b[i] = digits[l%base]