session that handles legacy tokens from file

This commit is contained in:
Brad Rydzewski 2019-06-06 13:13:08 -07:00
parent f4313534bd
commit c393b74f63
7 changed files with 218 additions and 6 deletions

3
go.mod
View file

@ -12,6 +12,7 @@ require (
github.com/davecgh/go-spew v1.1.1
github.com/dchest/authcookie v0.0.0-20120917135355-fbdef6e99866
github.com/dchest/uniuri v0.0.0-20160212164326-8902c56451e9
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/docker/distribution v2.7.1+incompatible
github.com/docker/go-connections v0.3.0
github.com/docker/go-units v0.3.3
@ -22,7 +23,7 @@ require (
github.com/drone/envsubst v1.0.1
github.com/drone/go-license v1.0.2
github.com/drone/go-login v1.0.4-0.20190311170324-2a4df4f242a2
github.com/drone/go-scm v1.4.1-0.20190418181654-1e77204716f6
github.com/drone/go-scm v1.5.0
github.com/drone/signal v1.0.0
github.com/dustin/go-humanize v1.0.0
github.com/ghodss/yaml v1.0.0

5
go.sum
View file

@ -26,6 +26,8 @@ github.com/dchest/authcookie v0.0.0-20120917135355-fbdef6e99866 h1:98WJ4YCdjmB7u
github.com/dchest/authcookie v0.0.0-20120917135355-fbdef6e99866/go.mod h1:x7AK2h2QzaXVEFi1tbMYMDuvHcCEr1QdMDrg3hkW24Q=
github.com/dchest/uniuri v0.0.0-20160212164326-8902c56451e9 h1:74lLNRzvsdIlkTgfDSMuaPjBr4cf6k7pwQQANm/yLKU=
github.com/dchest/uniuri v0.0.0-20160212164326-8902c56451e9/go.mod h1:GgB8SF9nRG+GqaDtLcwJZsQFhcogVCJ79j4EdT0c2V4=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/docker/distribution v0.0.0-20170726174610-edc3ab29cdff/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docker/distribution v2.7.1+incompatible h1:a5mlkVzth6W5A4fOsS3D2EO5BUmsJpcB+cRlLU7cSug=
github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
@ -93,6 +95,8 @@ github.com/drone/go-scm v1.4.0 h1:sYkPvIQb0tVuct/zX+KfAn88I6qPnSkoktRD4hUDkzY=
github.com/drone/go-scm v1.4.0/go.mod h1:YT4FxQ3U/ltdCrBJR9B0tRpJ1bYA/PM3NyaLE/rYIvw=
github.com/drone/go-scm v1.4.1-0.20190418181654-1e77204716f6 h1:xQ0riJTnWFLZcpXry5RVOk18DBJPhUkQjIALQCDdwZ4=
github.com/drone/go-scm v1.4.1-0.20190418181654-1e77204716f6/go.mod h1:YT4FxQ3U/ltdCrBJR9B0tRpJ1bYA/PM3NyaLE/rYIvw=
github.com/drone/go-scm v1.5.0 h1:Hn3bFYsUgOEUCx2wt2II9CxkTfev2h+tPheuYHp7ehg=
github.com/drone/go-scm v1.5.0/go.mod h1:YT4FxQ3U/ltdCrBJR9B0tRpJ1bYA/PM3NyaLE/rYIvw=
github.com/drone/signal v1.0.0 h1:NrnM2M/4yAuU/tXs6RP1a1ZfxnaHwYkd0kJurA1p6uI=
github.com/drone/signal v1.0.0/go.mod h1:S8t92eFT0g4WUgEc/LxG+LCuiskpMNsG0ajAMGnyZpc=
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
@ -144,6 +148,7 @@ github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uP
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-retryablehttp v0.0.0-20180718195005-e651d75abec6 h1:qCv4319q2q7XKn0MQbi8p37hsJ+9Xo8e6yojA73JVxk=
github.com/hashicorp/go-retryablehttp v0.0.0-20180718195005-e651d75abec6/go.mod h1:fXcdFsQoipQa7mwORhKad5jmDCeSy/RCGzWA08PO0lM=
github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU=
github.com/hashicorp/golang-lru v0.5.0 h1:CL2msUPvZTLb5O648aiLNJw3hnBxN2+1Jq8rCOH9wdo=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/nomad v0.0.0-20190125003214-134391155854 h1:L7WhLZt2ory/kQWxqkMwOiBpIoa4BWoadN7yx8LHEtk=

View file

@ -21,6 +21,7 @@ type Config struct {
Secure bool
Secret string
Timeout time.Duration
MappingFile string
}
// NewConfig returns a new session configuration.

108
session/legacy.go Normal file
View file

@ -0,0 +1,108 @@
// Copyright 2019 Drone IO, Inc.
//
// 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 session
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"github.com/drone/drone/core"
"github.com/dgrijalva/jwt-go"
)
type legacy struct {
*session
mapping map[string]string
}
// Legacy returns a session manager that is capable of mapping
// legacy tokens to 1.0 users using a mapping file.
func Legacy(users core.UserStore, config Config) (core.Session, error) {
base := &session{
secret: []byte(config.Secret),
secure: config.Secure,
timeout: config.Timeout,
users: users,
}
out, err := ioutil.ReadFile(config.MappingFile)
if err != nil {
return nil, err
}
mapping := map[string]string{}
err = json.Unmarshal(out, &mapping)
if err != nil {
return nil, err
}
return &legacy{base, mapping}, nil
}
func (s *legacy) Get(r *http.Request) (*core.User, error) {
switch {
case isAuthorizationToken(r):
return s.fromToken(r)
case isAuthorizationParameter(r):
return s.fromToken(r)
default:
return s.fromSession(r)
}
}
func (s *legacy) fromToken(r *http.Request) (*core.User, error) {
extracted := extractToken(r)
// determine if the token is a legacy token based on length.
// legacy tokens are > 64 characters.
if len(extracted) < 64 {
return s.users.FindToken(r.Context(), extracted)
}
token, err := jwt.Parse(extracted, func(token *jwt.Token) (interface{}, error) {
// validate the signing method
_, ok := token.Method.(*jwt.SigningMethodHMAC)
if !ok {
return nil, errors.New("Legacy token: invalid signature")
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, errors.New("Legacy token: invalid claim format")
}
// extract the username claim
claim, ok := claims["text"]
if !ok {
return nil, errors.New("Legacy token: invalid format")
}
// lookup the username to get the secret
secret, ok := s.mapping[claim.(string)]
if !ok {
return nil, errors.New("Legacy token: cannot lookup user")
}
return []byte(secret), nil
})
if err != nil {
return nil, err
}
return s.users.FindLogin(
r.Context(),
token.Claims.(jwt.MapClaims)["text"].(string),
)
}

93
session/legacy_test.go Normal file
View file

@ -0,0 +1,93 @@
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by the Drone Non-Commercial License
// that can be found in the LICENSE file.
// +build !oss
package session
import (
"net/http/httptest"
"testing"
"time"
"github.com/drone/drone/core"
"github.com/drone/drone/mock"
"github.com/golang/mock/gomock"
)
func TestLegacyGet_NotLegacy(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
mockUser := &core.User{
Login: "octocat",
Hash: "ulSxuA0FKjNiOFIchk18NNvC6ygSxdtKjiOAS",
}
users := mock.NewMockUserStore(controller)
users.EXPECT().FindToken(gomock.Any(), mockUser.Hash).Return(mockUser, nil)
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set("Authorization", "Bearer ulSxuA0FKjNiOFIchk18NNvC6ygSxdtKjiOAS")
session, _ := Legacy(users, Config{Secure: false, Timeout: time.Hour, MappingFile: "testdata/mapping.json"})
user, _ := session.Get(r)
if user != mockUser {
t.Errorf("Want authenticated user")
}
}
func TestLegacyGet(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
mockUser := &core.User{
Login: "octocat",
Hash: "ulSxuA0FKjNiOFIchk18NNvC6ygSxdtKjiOAS",
}
users := mock.NewMockUserStore(controller)
users.EXPECT().FindLogin(gomock.Any(), gomock.Any()).Return(mockUser, nil)
r := httptest.NewRequest("GET", "/?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwidGV4dCI6Im9jdG9jYXQiLCJpYXQiOjE1MTYyMzkwMjJ9.jf17GpOuKu-KAhuvxtjVvmZfwyeC7mEpKNiM6_cGOvo", nil)
session, _ := Legacy(users, Config{Secure: false, Timeout: time.Hour, MappingFile: "testdata/mapping.json"})
user, err := session.Get(r)
if err != nil {
t.Error(err)
return
}
if user != mockUser {
t.Errorf("Want authenticated user")
}
}
func TestLegacyGet_UserNotFound(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
users := mock.NewMockUserStore(controller)
r := httptest.NewRequest("GET", "/?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwidGV4dCI6ImJpbGx5aWRvbCIsImlhdCI6MTUxNjIzOTAyMn0.yxTCucstDM7BaixXBMAJCXup9zBaFr02Kalv_PqCDM4", nil)
session, _ := Legacy(users, Config{Secure: false, Timeout: time.Hour, MappingFile: "testdata/mapping.json"})
_, err := session.Get(r)
if err == nil || err.Error() != "Legacy token: cannot lookup user" {
t.Errorf("Expect user lookup error, got %v", err)
return
}
}
func TestLegacyGet_InvalidSignature(t *testing.T) {
controller := gomock.NewController(t)
defer controller.Finish()
users := mock.NewMockUserStore(controller)
r := httptest.NewRequest("GET", "/?access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwidGV4dCI6InNwYWNlZ2hvc3QiLCJpYXQiOjE1MTYyMzkwMjJ9.jlGcn2WI_oEZyLqYrvNvDXNbG3H3rqMyqQI2Gc6CHIY", nil)
session, _ := Legacy(users, Config{Secure: false, Timeout: time.Hour, MappingFile: "testdata/mapping.json"})
_, err := session.Get(r)
if err == nil || err.Error() != "signature is invalid" {
t.Errorf("Expect user lookup error, got %v", err)
return
}
}

View file

@ -111,7 +111,7 @@ func TestGet_Cookie(t *testing.T) {
Name: "_session_",
Value: s,
})
session := New(users, Config{false, secret, time.Hour})
session := New(users, Config{Secure: false, Secret: secret, Timeout: time.Hour})
user, err := session.Get(r)
if err != nil {
t.Error(err)
@ -162,7 +162,7 @@ func TestGet_Cookie_UserNotFound(t *testing.T) {
Value: s,
})
session := New(users, Config{false, secret, time.Hour})
session := New(users, Config{Secure: false, Secret: secret, Timeout: time.Hour})
user, _ := session.Get(r)
if user != nil {
t.Errorf("Expect empty session")

4
session/testdata/mapping.json vendored Normal file
View file

@ -0,0 +1,4 @@
{
"octocat": "this-is-a-test-secret",
"spaceghost": "this-is-an-invalid-secret"
}