Example #1
0
func (m *RethinkManager) Watch(ctx context.Context) {
	go pkg.Retry(time.Second*15, time.Minute, func() error {
		connections, err := m.Table.Changes().Run(m.Session)
		if err != nil {
			return errors.New(err)
		}
		defer connections.Close()

		var update map[string]*rethinkSchema
		for connections.Next(&update) {
			newVal := update["new_val"]
			oldVal := update["old_val"]
			m.Lock()
			if newVal == nil && oldVal != nil {
				m.watcherRemove(oldVal)
			} else if newVal != nil && oldVal != nil {
				m.watcherRemove(oldVal)
				m.watcherInsert(newVal)
			} else {
				m.watcherInsert(newVal)
			}
			m.Unlock()
		}

		if connections.Err() != nil {
			err = errors.New(connections.Err())
			pkg.LogError(err)
			return err
		}
		return nil
	})
}
Example #2
0
func (m *RethinkManager) publishAdd(set string, keys []jose.JsonWebKey) error {
	raws := make([]string, len(keys))
	for k, key := range keys {
		out, err := json.Marshal(key)
		if err != nil {
			return errors.New(err)
		}
		encrypted, err := m.Cipher.Encrypt(out)
		if err != nil {
			return errors.New(err)
		}
		raws[k] = encrypted
	}

	for k, raw := range raws {
		if _, err := m.Table.Insert(&rethinkSchema{
			KID: keys[k].KeyID,
			Set: set,
			Key: raw,
		}).RunWrite(m.Session); err != nil {
			return errors.New(err)
		}
	}

	return nil
}
Example #3
0
func (m *RethinkManager) ColdStart() error {
	m.Keys = map[string]jose.JsonWebKeySet{}
	clients, err := m.Table.Run(m.Session)
	if err != nil {
		return errors.New(err)
	}

	var raw *rethinkSchema
	var key jose.JsonWebKey
	m.Lock()
	defer m.Unlock()
	for clients.Next(&raw) {
		pt, err := m.Cipher.Decrypt(raw.Key)
		if err != nil {
			return errors.New(err)
		}

		if err := json.Unmarshal(pt, &key); err != nil {
			return errors.New(err)
		}

		keys, ok := m.Keys[raw.Set]
		if !ok {
			keys = jose.JsonWebKeySet{}
		}
		keys.Keys = append(keys.Keys, key)
		m.Keys[raw.Set] = keys
	}

	return nil
}
Example #4
0
func (s *Store) Get(id string) (Policy, error) {
	var p DefaultPolicy
	var conditions []byte
	if err := s.db.QueryRow("SELECT id, description, effect, conditions FROM ladon_policy WHERE id=$1", id).Scan(&p.ID, &p.Description, &p.Effect, &conditions); err == sql.ErrNoRows {
		return nil, pkg.ErrNotFound
	} else if err != nil {
		return nil, errors.New(err)
	}

	if err := json.Unmarshal(conditions, &p.Conditions); err != nil {
		return nil, errors.New(err)
	}

	subjects, err := getLinked(s.db, "ladon_policy_subject", id)
	if err != nil {
		return nil, err
	}
	permissions, err := getLinked(s.db, "ladon_policy_permission", id)
	if err != nil {
		return nil, err
	}
	resources, err := getLinked(s.db, "ladon_policy_resource", id)
	if err != nil {
		return nil, err
	}

	p.Permissions = permissions
	p.Subjects = subjects
	p.Resources = resources
	return &p, nil
}
Example #5
0
// Generate : Generates a new authorize code or returns an error. set secret
func (j *JWTEnigma) Generate(claims *jwthelper.ClaimsContext, headers map[string]interface{}) (string, string, error) {
	// As per RFC, no overrides of header "alg"!
	if _, ok := headers["alg"]; ok {
		return "", "", errors.New("You may not override the alg header key.")
	}

	// As per RFC, no overrides of header "typ"!
	if _, ok := headers["typ"]; ok {
		return "", "", errors.New("You may not override the typ header key.")
	}

	token := jwt.New(jwt.SigningMethodRS256)
	token.Claims = *claims
	token.Header = merge(token.Header, headers)
	rsaKey, err := jwt.ParseRSAPrivateKeyFromPEM(j.PrivateKey)

	if err != nil {
		return "", "", err
	}

	var sig, sstr string

	if sstr, err = token.SigningString(); err != nil {
		return "", "", err
	}

	if sig, err = token.Method.Sign(sstr, rsaKey); err != nil {
		return "", "", err
	}

	return fmt.Sprintf("%s.%s", sstr, sig), sig, nil
}
Example #6
0
func (h *Handler) Create(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	var p = ladon.DefaultPolicy{
		Conditions: ladon.Conditions{},
	}
	ctx := herodot.NewContext()

	if _, err := h.W.HTTPActionAllowed(ctx, r, &ladon.Request{
		Resource: policyResource,
		Action:   "create",
	}, scope); err != nil {
		h.H.WriteError(ctx, w, r, err)
		return
	}

	if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
		h.H.WriteError(ctx, w, r, errors.New(err))
		return
	}

	if p.ID == "" {
		p.ID = uuid.New()
	}

	if err := h.Manager.Create(&p); err != nil {
		h.H.WriteError(ctx, w, r, errors.New(err))
		return
	}
	h.H.WriteCreated(ctx, w, r, "/policies/"+p.ID, &p)
}
Example #7
0
func (s *DefaultConsentStrategy) IssueChallenge(authorizeRequest fosite.AuthorizeRequester, redirectURL string) (string, error) {
	token := jwt.New(jwt.SigningMethodRS256)
	token.Claims = map[string]interface{}{
		"jti":   uuid.New(),
		"scp":   authorizeRequest.GetScopes(),
		"aud":   authorizeRequest.GetClient().GetID(),
		"exp":   time.Now().Add(time.Hour).Unix(),
		"redir": redirectURL,
	}

	ks, err := s.KeyManager.GetKey(ConsentChallengeKey, "private")
	if err != nil {
		return "", errors.New(err)
	}

	rsaKey, ok := jwk.First(ks.Keys).Key.(*rsa.PrivateKey)
	if !ok {
		return "", errors.New("Could not convert to RSA Private Key")
	}

	var signature, encoded string
	if encoded, err = token.SigningString(); err != nil {
		return "", errors.New(err)
	} else if signature, err = token.Method.Sign(encoded, rsaKey); err != nil {
		return "", errors.New(err)
	}

	return fmt.Sprintf("%s.%s", encoded, signature), nil

}
Example #8
0
func (w *LocalWarden) actionAllowed(ctx context.Context, a *ladon.Request, scopes []string, oauthRequest fosite.AccessRequester, session *oauth2.Session) (*Context, error) {
	session = oauthRequest.GetSession().(*oauth2.Session)
	if a.Subject != "" && a.Subject != session.Subject {
		return nil, errors.New("Subject mismatch " + a.Subject + " - " + session.Subject)
	}

	if !matchScopes(oauthRequest.GetGrantedScopes(), scopes, session, oauthRequest.GetClient()) {
		return nil, errors.New(herodot.ErrForbidden)
	}

	a.Subject = session.Subject
	if err := w.Warden.IsAllowed(a); err != nil {
		return nil, err
	}

	logrus.WithFields(logrus.Fields{
		"scopes":   scopes,
		"subject":  a.Subject,
		"audience": oauthRequest.GetClient().GetID(),
		"request":  a,
	}).Infof("Access granted")

	return &Context{
		Subject:       session.Subject,
		GrantedScopes: oauthRequest.GetGrantedScopes(),
		Issuer:        w.Issuer,
		Audience:      oauthRequest.GetClient().GetID(),
		IssuedAt:      oauthRequest.GetRequestedAt(),
	}, nil
}
Example #9
0
// HandleTokenEndpointRequest implements https://tools.ietf.org/html/rfc6749#section-6
func (c *RefreshTokenGrantHandler) HandleTokenEndpointRequest(ctx context.Context, req *http.Request, requester fosite.AccessRequester, responder fosite.AccessResponder, session interface{}) error {
	if requester.GetGrantType() != "refresh_token" {
		return nil
	}

	access, err := c.Enigma.GenerateChallenge(requester.GetClient().GetHashedSecret())
	if err != nil {
		return errors.New(fosite.ErrServerError)
	} else if err := c.Store.CreateAccessTokenSession(access.Signature, requester, &core.TokenSession{Extra: session}); err != nil {
		return errors.New(fosite.ErrServerError)
	}

	refresh, err := c.Enigma.GenerateChallenge(requester.GetClient().GetHashedSecret())
	if err != nil {
		return errors.New(fosite.ErrServerError)
	} else if err := c.Store.CreateRefreshTokenSession(refresh.Signature, requester, &core.TokenSession{Extra: session}); err != nil {
		return errors.New(fosite.ErrServerError)
	}

	challenge := new(enigma.Challenge)
	challenge.FromString(req.Form.Get("refresh_token"))
	if err := c.Store.DeleteRefreshTokenSession(challenge.Signature); err != nil {
		return errors.New(fosite.ErrServerError)
	}

	responder.SetAccessToken(access.String())
	responder.SetTokenType("bearer")
	responder.SetExtra("expires_in", strconv.Itoa(int(c.AccessTokenLifespan/time.Second)))
	responder.SetExtra("scope", strings.Join(requester.GetGrantedScopes(), " "))
	responder.SetExtra("refresh_token", refresh.String())
	return nil
}
Example #10
0
func isValidAuthorizeRequest(c *HTTPClient, ar *AuthorizeRequest, retry bool) (bool, error) {
	request := gorequest.New()
	resp, body, errs := request.Post(pkg.JoinURL(c.ep, "/guard/allowed")).SetBasicAuth(c.clientConfig.ClientID, c.clientConfig.ClientSecret).Set("Content-Type", "application/json").Send(*ar).End()
	if len(errs) > 0 {
		return false, errors.Errorf("Got errors: %v", errs)
	} else if retry && resp.StatusCode == http.StatusUnauthorized {
		var err error
		if c.clientToken, err = c.clientConfig.Token(oauth2.NoContext); err != nil {
			return false, errors.New(err)
		} else if c.clientToken == nil {
			return false, errors.New("Access token could not be retrieved")
		}
		return isValidAuthorizeRequest(c, ar, false)
	} else if resp.StatusCode != http.StatusOK {
		return false, errors.Errorf("Status code %d is not 200: %s", resp.StatusCode, body)
	}

	if err := json.Unmarshal([]byte(body), &isAllowed); err != nil {
		return false, errors.Errorf("Could not unmarshall body because %s", err.Error())
	}

	if !isAllowed.Allowed {
		return false, errors.New("Authroization denied")
	}
	return isAllowed.Allowed, nil
}
Example #11
0
func (items RDBItems) watch(ctx context.Context, sess *r.Session, lock sync.RWMutex, table r.Term) {
	go pkg.Retry(time.Second*15, time.Minute, func() error {
		changes, err := table.Changes().Run(sess)
		if err != nil {
			pkg.LogError(errors.New(err))
			return errors.New(err)
		}
		defer changes.Close()

		var update = map[string]*RdbSchema{}
		for changes.Next(&update) {
			newVal := update["new_val"]
			oldVal := update["old_val"]
			lock.Lock()
			if newVal == nil && oldVal != nil {
				delete(items, oldVal.ID)
			} else if newVal != nil && oldVal != nil {
				delete(items, oldVal.ID)
				items[newVal.ID] = newVal
			} else {
				items[newVal.ID] = newVal
			}
			lock.Unlock()
		}

		if changes.Err() != nil {
			err = errors.New(changes.Err())
			pkg.LogError(err)
			return err
		}

		return nil
	})
}
Example #12
0
func (c *AEAD) Decrypt(ciphertext string) ([]byte, error) {
	if len(c.Key) < 32 {
		return []byte{}, errors.Errorf("Key must be longer 32 bytes, got %d bytes", len(c.Key))
	}

	raw, err := base64.URLEncoding.DecodeString(ciphertext)
	if err != nil {
		return []byte{}, errors.New(err)
	}

	n := len(raw)
	block, err := aes.NewCipher(c.Key)
	if err != nil {
		return []byte{}, errors.New(err)
	}

	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		return []byte{}, errors.New(err)
	}

	plaintext, err := aesgcm.Open(nil, raw[n-12:n], raw[:n-12], nil)
	if err != nil {
		return []byte{}, errors.New(err)
	}

	return plaintext, nil
}
Example #13
0
// ValidateAuthorizeCodeSignature returns an AuthorizeCode, if the code argument is a valid authorize code
// and the signature matches the key.
func (c *HMACSHAEnigma) ValidateChallenge(secret []byte, t *Challenge) (err error) {
	if t.Key == "" || t.Signature == "" {
		return errors.New("Key and signature must both be not empty")
	}

	signature, err := b64.DecodeString(t.Signature)
	if err != nil {
		return err
	}

	key, err := b64.DecodeString(t.Key)
	if err != nil {
		return err
	}

	useSecret := append([]byte{}, c.GlobalSecret...)
	mac := hmac.New(sha256.New, append(useSecret, secret...))
	_, err = mac.Write(key)
	if err != nil {
		return errors.New(err)
	}

	if !hmac.Equal(signature, mac.Sum([]byte{})) {
		// Hash is invalid
		return errors.New("Key and signature do not match")
	}

	return nil
}
Example #14
0
func (m *RethinkManager) Watch(ctx context.Context) {
	go pkg.Retry(time.Second*15, time.Minute, func() error {
		clients, err := m.Table.Changes().Run(m.Session)
		if err != nil {
			return errors.New(err)
		}
		defer clients.Close()

		var update map[string]*fosite.DefaultClient
		for clients.Next(&update) {
			newVal := update["new_val"]
			oldVal := update["old_val"]
			m.Lock()
			if newVal == nil && oldVal != nil {
				delete(m.Clients, oldVal.GetID())
			} else if newVal != nil && oldVal != nil {
				delete(m.Clients, oldVal.GetID())
				m.Clients[newVal.GetID()] = newVal
			} else {
				m.Clients[newVal.GetID()] = newVal
			}
			m.Unlock()
		}

		if clients.Err() != nil {
			err = errors.New(clients.Err())
			pkg.LogError(err)
			return err
		}
		return nil
	})
}
Example #15
0
func (c *AEAD) Encrypt(plaintext []byte) (string, error) {
	// The key argument should be the AES key, either 16 or 32 bytes
	// to select AES-128 or AES-256.
	if len(c.Key) < 32 {
		return "", errors.Errorf("Key must be longer 32 bytes, got %d bytes", len(c.Key))
	}

	block, err := aes.NewCipher(c.Key[:32])
	if err != nil {
		return "", errors.New(err)
	}

	nonce := make([]byte, 12)
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return "", errors.New(err)
	}

	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		return "", errors.New(err)
	}

	ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
	return base64.URLEncoding.EncodeToString(append(ciphertext, nonce...)), nil
}
Example #16
0
func (c *AuthorizeExplicitGrantTypeHandler) HandleAuthorizeEndpointRequest(_ context.Context, req *http.Request, ar AuthorizeRequester, resp AuthorizeResponder, session interface{}) error {
	// This let's us define multiple response types, for example open id connect's id_token
	if ar.GetResponseTypes().Has("code") {
		// Generate the code
		code, err := c.Enigma.GenerateChallenge(ar.GetClient().GetHashedSecret())
		if err != nil {
			return errors.New(ErrServerError)
		}

		if err := c.Store.CreateAuthorizeCodeSession(code.Signature, ar, &AuthorizeSession{
			Extra:              session,
			RequestRedirectURI: req.Form.Get("redirect_uri"),
		}); err != nil {
			return errors.New(ErrServerError)
		}

		resp.AddQuery("code", code.String())
		resp.AddQuery("state", ar.GetState())
		resp.AddQuery("scope", strings.Join(ar.GetGrantedScopes(), " "))
		ar.SetResponseTypeHandled("code")
		return nil
	}

	return nil
}
Example #17
0
func (s *SuperAgent) Get(o interface{}) error {
	req, err := http.NewRequest("GET", s.URL, nil)
	if err != nil {
		return errors.New(err)
	} else if o == nil {
		return errors.New("Can not pass nil")
	}

	if err := s.doDry(req); err != nil {
		return err
	}

	resp, err := s.Client.Do(req)
	if err != nil {
		return errors.New(err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := ioutil.ReadAll(resp.Body)
		return errors.Errorf("Expected status code %d, got %d.\n%s\n", http.StatusOK, resp.StatusCode, body)
	} else if err := json.NewDecoder(resp.Body).Decode(o); err != nil {
		return errors.New(err)
	}

	return nil
}
Example #18
0
// ValidateTokenEndpointRequest implements https://tools.ietf.org/html/rfc6749#section-6
func (c *RefreshTokenGrantHandler) ValidateTokenEndpointRequest(_ context.Context, req *http.Request, request fosite.AccessRequester, session interface{}) error {
	// grant_type REQUIRED.
	// Value MUST be set to "client_credentials".
	if request.GetGrantType() != "refresh_token" {
		return nil
	}

	// The authorization server MUST ... validate the refresh token.
	challenge := new(enigma.Challenge)
	challenge.FromString(req.Form.Get("refresh_token"))
	if err := c.Enigma.ValidateChallenge(request.GetClient().GetHashedSecret(), challenge); err != nil {
		return errors.New(fosite.ErrInvalidRequest)
	}

	ar, err := c.Store.GetRefreshTokenSession(challenge.Signature, &core.TokenSession{Extra: session})
	if err == pkg.ErrNotFound {
		return errors.New(fosite.ErrInvalidRequest)
	} else if err != nil {
		return errors.New(fosite.ErrServerError)
	}

	// The authorization server MUST ... and ensure that the refresh token was issued to the authenticated client
	if ar.GetClient().GetID() != request.GetClient().GetID() {
		return errors.New(fosite.ErrInvalidRequest)
	}

	request.SetGrantTypeHandled("refresh_token")
	return nil
}
Example #19
0
// CursorInt64 parses this query's Cursor string as an int64
func (p PageQuery) CursorInt64() (int64, error) {
	if p.Cursor == "" {
		switch p.Order {
		case OrderAscending:
			return 0, nil
		case OrderDescending:
			return math.MaxInt64, nil
		default:
			return 0, errors.New(ErrInvalidOrder)
		}
	}

	i, err := strconv.ParseInt(p.Cursor, 10, 64)

	if err != nil {
		return 0, errors.New(ErrInvalidCursor)
	}

	if i < 0 {
		return 0, errors.New(ErrInvalidCursor)
	}

	return i, nil

}
Example #20
0
func isValidAuthenticationRequest(c *HTTPClient, token string, retry bool) (bool, error) {
	data := url.Values{}
	data.Set("token", token)
	request := gorequest.New()
	resp, body, errs := request.Post(pkg.JoinURL(c.ep, "/oauth2/introspect")).Type("form").SetBasicAuth(c.clientConfig.ClientID, c.clientConfig.ClientSecret).SendString(data.Encode()).End()
	if len(errs) > 0 {
		return false, errors.Errorf("Got errors: %v", errs)
	} else if resp.StatusCode != http.StatusOK {
		return false, errors.Errorf("Status code %d is not 200: %s", resp.StatusCode, body)
	}

	if retry && resp.StatusCode == http.StatusUnauthorized {
		var err error
		if c.clientToken, err = c.clientConfig.Token(oauth2.NoContext); err != nil {
			return false, errors.New(err)
		} else if c.clientToken == nil {
			return false, errors.New("Access token could not be retrieved")
		}
		return isValidAuthenticationRequest(c, token, false)
	} else if resp.StatusCode != http.StatusOK {
		return false, fmt.Errorf("Status code %d is not 200", resp.StatusCode)
	}

	var introspect struct {
		Active bool `json:"active"`
	}

	if err := json.Unmarshal([]byte(body), &introspect); err != nil {
		return false, err
	} else if !introspect.Active {
		return false, errors.New("Authentication denied")
	}
	return introspect.Active, nil
}
Example #21
0
func (c *AuthorizeImplicitGrantTypeHandler) HandleAuthorizeEndpointRequest(_ context.Context, req *http.Request, ar AuthorizeRequester, resp AuthorizeResponder, session interface{}) error {
	// This let's us define multiple response types, for example open id connect's id_token
	if ar.GetResponseTypes().Has("token") {
		// Generate the code
		access, err := c.Enigma.GenerateChallenge(ar.GetClient().GetHashedSecret())
		if err != nil {
			return errors.New(ErrServerError)
		} else if err := c.Store.CreateImplicitAccessTokenSession(access.Signature, ar, &core.AuthorizeSession{
			Extra:              session,
			RequestRedirectURI: req.Form.Get("redirect_uri"),
		}); err != nil {
			return errors.New(ErrServerError)
		}

		resp.AddFragment("access_token", access.String())
		resp.AddFragment("expires_in", strconv.Itoa(int(c.AccessTokenLifespan/time.Second)))
		resp.AddFragment("token_type", "bearer")
		resp.AddFragment("state", ar.GetState())
		resp.AddFragment("scope", strings.Join(ar.GetGrantedScopes(), "+"))
		ar.SetResponseTypeHandled("token")
		return nil
	}

	return nil
}
Example #22
0
// ValidateTokenEndpointRequest implements https://tools.ietf.org/html/rfc6749#section-6
func (c *RefreshTokenGrantHandler) ValidateTokenEndpointRequest(ctx context.Context, req *http.Request, request fosite.AccessRequester) error {
	// grant_type REQUIRED.
	// Value MUST be set to "client_credentials".
	if request.GetGrantType() != "refresh_token" {
		return nil
	}

	// The authorization server MUST ... validate the refresh token.
	signature, err := c.RefreshTokenStrategy.ValidateRefreshToken(req.Form.Get("refresh_token"), ctx, req, request)
	if err != nil {
		return errors.New(fosite.ErrInvalidRequest)
	}

	accessRequest, err := c.Store.GetRefreshTokenSession(signature, nil)
	if err == pkg.ErrNotFound {
		return errors.New(fosite.ErrInvalidRequest)
	} else if err != nil {
		return errors.New(fosite.ErrServerError)
	}

	// The authorization server MUST ... and ensure that the refresh token was issued to the authenticated client
	if accessRequest.GetClient().GetID() != request.GetClient().GetID() {
		return errors.New(fosite.ErrInvalidRequest)
	}

	request.SetGrantTypeHandled("refresh_token")
	return nil
}
Example #23
0
// GetContinuations returns two new PageQuery structs, a next and previous
// query.
func (p PageQuery) GetContinuations(records interface{}) (next PageQuery, prev PageQuery, err error) {
	next = p
	prev = p.Invert()

	rv := reflect.ValueOf(records)
	l := rv.Len()

	if l <= 0 {
		return
	}

	first, ok := rv.Index(0).Interface().(Pageable)
	if !ok {
		err = errors.New(ErrNotPageable)
	}

	last, ok := rv.Index(l - 1).Interface().(Pageable)
	if !ok {
		err = errors.New(ErrNotPageable)
	}

	next.Cursor = last.PagingToken()
	prev.Cursor = first.PagingToken()

	return
}
Example #24
0
// NewPageQuery creates a new PageQuery struct, ensuring the order, limit, and
// cursor are set to the appropriate defaults and are valid.
func NewPageQuery(
	cursor string,
	order string,
	limit uint64,
) (result PageQuery, err error) {

	// Set order
	switch order {
	case "":
		result.Order = OrderAscending
	case OrderAscending, OrderDescending:
		result.Order = order
	default:
		err = errors.New(ErrInvalidOrder)
		return
	}

	result.Cursor = cursor

	// Set limit
	switch {
	case limit == 0:
		result.Limit = DefaultPageSize
	case limit < 0:
		err = errors.New(ErrInvalidLimit)
		return
	case limit > MaxPageSize:
		err = errors.New(ErrInvalidLimit)
		return
	default:
		result.Limit = limit
	}

	return
}
Example #25
0
func (h *Handler) UpdateKeySet(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	var ctx = context.Background()
	var requests joseWebKeySetRequest
	var keySet = new(jose.JsonWebKeySet)
	var set = ps.ByName("set")

	if _, err := h.W.HTTPActionAllowed(ctx, r, &ladon.Request{
		Resource: "rn:hydra:keys:" + set,
		Action:   "update",
	}, "hydra.keys.update"); err != nil {
		h.H.WriteError(ctx, w, r, err)
		return
	}

	if err := json.NewDecoder(r.Body).Decode(&requests); err != nil {
		h.H.WriteError(ctx, w, r, errors.New(err))
		return
	}

	for _, request := range requests.Keys {
		key := &jose.JsonWebKey{}
		if err := key.UnmarshalJSON(request); err != nil {
			h.H.WriteError(ctx, w, r, errors.New(err))
		}
		keySet.Keys = append(keySet.Keys, *key)
	}

	if err := h.Manager.AddKeySet(set, keySet); err != nil {
		h.H.WriteError(ctx, w, r, err)
		return
	}

	h.H.Write(ctx, w, r, keySet)
}
Example #26
0
func (h *Handler) IntrospectHandler(w http.ResponseWriter, r *http.Request) {
	auth, err := osin.CheckBasicAuth(r)
	if _, err := h.OAuthStore.GetClient(auth.Username); err != nil {
		pkg.HttpError(w, errors.New("Unauthorized"), http.StatusUnauthorized)
		return
	} else if auth == nil {
		pkg.HttpError(w, errors.New("Unauthorized"), http.StatusUnauthorized)
		return
	}

	client, err := h.OAuthStore.GetClient(auth.Username)
	if err != nil {
		pkg.HttpError(w, errors.New("Unauthorized"), http.StatusUnauthorized)
		return
	} else if client.GetSecret() != auth.Password {
		pkg.HttpError(w, errors.New("Unauthorized"), http.StatusUnauthorized)
		return
	}

	result := make(map[string]interface{})
	result["active"] = false

	r.ParseForm()
	if r.Form.Get("token") == "" {
		log.WithField("introspect", "fail").Warn("No token given.")
		result["error"] = "No token given."
		pkg.WriteJSON(w, result)
		return
	}

	token, err := h.JWT.VerifyToken([]byte(r.Form.Get("token")))
	if err != nil {
		log.WithField("introspect", "fail").Warn("Token is invalid.")
		pkg.WriteJSON(w, result)
		return
	}

	claims := jwt.ClaimsCarrier(token.Claims)
	if claims.GetAudience() != auth.Username {
		log.WithFields(log.Fields{
			"introspect":       "fail",
			"actualAudience":   auth.Username,
			"expectedAudience": claims.GetAudience(),
		}).Warn(`Token audience mismatch.`)
		pkg.WriteJSON(w, result)
		return
	}

	if claims.GetSubject() == "" {
		log.WithFields(log.Fields{
			"introspect": "fail",
		}).Warn(`Token claims no subject.`)
		pkg.WriteJSON(w, result)
		return
	}

	result = token.Claims
	result["active"] = token.Valid
	pkg.WriteJSON(w, result)
}
Example #27
0
func deploy(description string) error {
	args := []string{"deploy"}

	environment := os.Getenv("WERCKER_DISTELLI_ENVIRONMENT")
	host := os.Getenv("WERCKER_DISTELLI_HOST")

	if environment != "" {
		if host != "" {
			return errors.New(DeployConflict)
		}
		args = append(args, "-e", environment)
	} else if host != "" {
		args = append(args, "-h", host)
	} else {
		return errors.New(DeployMissing)
	}

	_, basename, err := checkManifest()
	if err != nil {
		return err
	}

	args = append(args, "-y", "-f", basename, "-m", description)

	releaseID, err := loadReleaseID()
	if err != nil {
		return err
	}
	if releaseID != "" {
		args = append(args, "-r", releaseID)
	}

	wait := strings.ToLower(os.Getenv("WERCKER_DISTELLI_WAIT")) != "false"
	if !wait {
		args = append(args, "-q")
	}

	// A lovely piece of excrement to satisfy the type system.
	stupidity := make([]interface{}, len(args))
	for i, arg := range args {
		stupidity[i] = arg
	}
	log.Println(stupidity...)

	buffer, err := invoke(args...)
	if err != nil {
		return errors.WrapPrefix(err, "Error invoking distelli", 0)
	}
	output := buffer.String()

	if strings.Contains(output, "Deployment Failed") {
		return errors.Errorf(output)
	}

	log.Printf(output)
	return nil
}
Example #28
0
func (s *Storage) saveRefresh(tx *sql.Tx, refresh, access string) (err error) {
	_, err = tx.Exec("INSERT INTO refresh (token, access) VALUES ($1, $2)", refresh, access)
	if err != nil {
		if rbe := tx.Rollback(); rbe != nil {
			return errors.New(rbe)
		}
		return errors.New(err)
	}
	return nil
}
Example #29
0
func (c *HTTPClient) IsRequestAllowed(req *http.Request, resource, permission, owner string) (bool, error) {
	var token *osin.BearerAuth
	if token = osin.CheckBearerAuth(req); token == nil {
		return false, errors.New("No token given.")
	} else if token.Code == "" {
		return false, errors.New("No token given.")
	}
	env := middleware.NewEnv(req)
	env.Owner(owner)
	return c.IsAllowed(&AuthorizeRequest{Token: token.Code, Resource: resource, Permission: permission, Context: env.Ctx()})
}
Example #30
0
func (m *RethinkManager) DeleteKey(set, kid string) error {
	keys, err := m.GetKey(set, kid)
	if err != nil {
		return errors.New(err)
	}

	if err := m.publishDelete(set, keys.Keys); err != nil {
		return errors.New(err)
	}
	return nil
}