Skip to content
This repository was archived by the owner on Aug 15, 2022. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions go/src/github.com/koding/kite/.travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ language: go
sudo: false
go:
- 1.4.3
- 1.5.4
- 1.6.2
- 1.6.3
- 1.7
install:
- go get -d -v -t ./...
script:
Expand Down
5 changes: 4 additions & 1 deletion go/src/github.com/koding/kite/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,10 @@ func (c *Client) sendHub() {

err := session.Send(string(msg.p))
if err != nil {
c.LocalKite.Log.Error("error sending: %s", err)
// TODO(rjeczalik): temporary workaround for koding/koding#8711
if err != sockjs.ErrSessionNotOpen {
c.LocalKite.Log.Error("error sending: %s", err)
}

if msg.errC != nil {
msg.errC <- err
Expand Down
25 changes: 18 additions & 7 deletions go/src/github.com/koding/kite/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,32 @@ var ErrKeyNotTrusted = errors.New("kontrol key is not trusted")

// Error is the type of the kite related errors returned from kite package.
type Error struct {
Type string `json:"type"`
Message string `json:"message"`
CodeVal string `json:"code"`
Type string `json:"type"`
Message string `json:"message"`
CodeVal string `json:"code"`
RequestID string `json:"id"`
}

func (e Error) Code() string {
return e.CodeVal
}

func (e Error) Error() string {
if e.Type == "genericError" || e.Type == "" {
return e.Message
s := e.Message

if e.Type != "genericError" && e.Type != "" {
s = e.Type + ": " + e.Message
}

if e.RequestID != "" {
return s + " (" + e.RequestID + ")"
}

return fmt.Sprintf("%s: %s", e.Type, e.Message)
return s
}

// createError creates a new kite.Error for the given r variable
func createError(r interface{}) *Error {
func createError(req *Request, r interface{}) *Error {
if r == nil {
return nil
}
Expand All @@ -52,5 +59,9 @@ func createError(r interface{}) *Error {
}
}

if kiteErr.RequestID == "" && req != nil {
kiteErr.RequestID = req.ID
}

return kiteErr
}
1 change: 1 addition & 0 deletions go/src/github.com/koding/kite/kite.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ type Kite struct {
handlers map[string]*Method // method map for exported methods
preHandlers []Handler // a list of handlers that are executed before any handler
postHandlers []Handler // a list of handlers that are executed after any handler
finalFuncs []FinalFunc // a list of funcs executed after any handler regardless of the error

// MethodHandling defines how the kite is returning the response for
// multiple handlers
Expand Down
38 changes: 36 additions & 2 deletions go/src/github.com/koding/kite/kite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package kite
import (
"errors"
"fmt"
"math"
"math/rand"
"os"
"strconv"
Expand Down Expand Up @@ -201,7 +202,7 @@ func TestConcurrency(t *testing.T) {
}

func TestNoConcurrentCallbacks(t *testing.T) {
const timeout = 5 * time.Second
const timeout = 2 * time.Second

type Callback struct {
Index int
Expand Down Expand Up @@ -311,6 +312,18 @@ func TestKite(t *testing.T) {
mathKite.HandleFunc("square", Square)
mathKite.HandleFunc("squareCB", SquareCB)
mathKite.HandleFunc("sleep", Sleep)
mathKite.HandleFunc("sqrt", Sqrt)
mathKite.FinalFunc(func(r *Request, resp interface{}, err error) (interface{}, error) {
if r.Method != "sqrt" || err != ErrNegative {
return resp, err
}

a := r.Args.One().MustFloat64()

// JSON does not marshal complex128,
// for test purpose we use just string
return fmt.Sprintf("%di", int(math.Sqrt(-a)+0.5)), nil
})
go mathKite.Run()
<-mathKite.ServerReadyNotify()
defer mathKite.Close()
Expand All @@ -333,7 +346,16 @@ func TestKite(t *testing.T) {
}
defer remote.Close()

result, err := remote.TellWithTimeout("square", 4*time.Second, 2)
result, err := remote.TellWithTimeout("sqrt", 4*time.Second, -4)
if err != nil {
t.Fatal(err)
}

if s, err := result.String(); err != nil || s != "2i" {
t.Fatalf("want 2i, got %v (%v)", result, err)
}

result, err = remote.TellWithTimeout("square", 4*time.Second, 2)
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -410,6 +432,18 @@ func Square(r *Request) (interface{}, error) {
return result, nil
}

var ErrNegative = errors.New("negative argument")

func Sqrt(r *Request) (interface{}, error) {
a := r.Args.One().MustFloat64()

if a < 0 {
return nil, ErrNegative
}

return math.Sqrt(a), nil
}

// Calls the callback with the result. For testing requests with Callback.
func SquareCB(r *Request) (interface{}, error) {
args := r.Args.MustSliceOfLength(2)
Expand Down
178 changes: 178 additions & 0 deletions go/src/github.com/koding/kite/kitetest/kitetest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
package kitetest

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"os/user"
"time"

"github.com/dgrijalva/jwt-go"
"github.com/koding/kite/protocol"
"github.com/satori/go.uuid"
)

// KeyPair represents PEM encoded RSA key pair.
type KeyPair struct {
Public []byte
Private []byte
}

// KiteKey represents JWT token used in kite authentication,
// also known as kite.key.
type KiteKey struct {
ID string `json:"keyID,omitempty"`
Issuer string `json:"issuer,omitempty"`
Username string `json:"username,omitempty"`
IssuedAt int64 `json:"issuedAt,omitempty"`
KontrolURL string `json:"kontrolURL,omitempty"`
URL string `json:"url,omitempty"`
Kite protocol.Kite `json:"kite,omitempty"`
}

func (k *KiteKey) id() string {
if k.ID != "" {
return k.ID
}
return uuid.NewV4().String()
}

func (k *KiteKey) issuer() string {
if k.Issuer != "" {
return k.Issuer
}
return "koding"
}

func (k *KiteKey) username() string {
if k.Username != "" {
return k.Username
}

u, err := user.Current()
if err != nil {
panic(err)
}

return u.Username
}

func (k *KiteKey) issuedAt() int64 {
if k.IssuedAt != 0 {
return k.IssuedAt
}
return time.Now().UTC().Unix()
}

func (k *KiteKey) kontrolURL() string {
if k.KontrolURL != "" {
return k.KontrolURL
}
return "https://koding.com/kontrol/kite"
}

// GenerateKeyPair
func GenerateKeyPair() (*KeyPair, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}

pub, err := x509.MarshalPKIXPublicKey(&priv.PublicKey)
if err != nil {
return nil, err
}

return &KeyPair{
Private: pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(priv),
}),
Public: pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: pub,
}),
}, nil
}

// GenerateKiteKey
func GenerateKiteKey(k *KiteKey, keys *KeyPair) (*jwt.Token, error) {
var err error

if keys == nil {
keys, err = GenerateKeyPair()
if err != nil {
return nil, err
}
}

kiteKey := jwt.New(jwt.GetSigningMethod("RS256"))

kiteKey.Claims = jwt.MapClaims{
"iss": k.issuer(),
"sub": k.username(),
"iat": k.issuedAt(),
"jti": k.id(),
"kontrolURL": k.kontrolURL(),
"kontrolKey": string(keys.Public),
}

privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(keys.Private)
if err != nil {
return nil, err
}

kiteKey.Raw, err = kiteKey.SignedString(privateKey)
if err != nil {
return nil, err
}

kiteKey.Valid = true

return kiteKey, nil
}

// TokenExtractor is used to extract kite ID from the given JWT token.
type TokenExtractor struct {
Token *jwt.Token
KiteID string
}

var errTokenExtractor = errors.New("extraction ok")

// Extract is a jwt.Keyfunc that extracts kite ID.
func (te *TokenExtractor) Extract(tok *jwt.Token) (interface{}, error) {
var id string
var ok bool

switch claims := tok.Claims.(type) {
case *jwt.StandardClaims:
id, ok = claims.Id, true
case jwt.MapClaims:
id, ok = claims["jti"].(string)
}

if !ok || id == "" {
return nil, errors.New("no kite ID")
}

te.KiteID = id
te.Token = tok

return nil, errTokenExtractor
}

// ExtractKiteID extracts kite ID from the raw JWT token.
func ExtractKiteID(token string) (string, error) {
te := &TokenExtractor{}

_, err := jwt.Parse(token, te.Extract)

if e, ok := err.(*jwt.ValidationError); ok && e.Error() == errTokenExtractor.Error() {
return te.KiteID, nil
}

return "", err
}
4 changes: 3 additions & 1 deletion go/src/github.com/koding/kite/kontrol/001-schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,7 @@ CREATE ROLE kontrol;

-- create user
-- please change this password according to your conventions
CREATE USER kontrolapplication PASSWORD 'kontrolapplication';
CREATE USER kontrolapplication PASSWORD 'somerandompassword';

GRANT kontrol TO kontrolapplication;

Loading