Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Couchdb JWT Authentation #3929

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
61 changes: 59 additions & 2 deletions core/ledger/kvledger/txmgmt/statedb/statecouchdb/couchdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"time"
"unicode/utf8"

"github.com/golang-jwt/jwt/v4"
"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/core/ledger"
"github.com/pkg/errors"
Expand Down Expand Up @@ -200,6 +201,11 @@ type databaseSecurity struct {
} `json:"members"`
}

// JWT contains the definition of a JWT object
type JWT struct {
privateKey []byte
}

// couchDoc defines the structure for a JSON document value
type couchDoc struct {
jsonValue []byte
Expand Down Expand Up @@ -1627,12 +1633,14 @@ func (couchInstance *couchInstance) handleRequest(ctx context.Context, method, d
req.Header.Set("Accept", "multipart/related")
}

// If username and password are set the use basic auth
// If username and password are set the use basic auth otherwise if JWT private key and JWT username is set use the jwt token authorization
if couchInstance.conf.Username != "" && couchInstance.conf.Password != "" {
// req.Header.Set("Authorization", "Basic YWRtaW46YWRtaW5w")
req.SetBasicAuth(couchInstance.conf.Username, couchInstance.conf.Password)
} else if couchInstance.conf.JwtPrivateKey != "" && couchInstance.conf.JwtUserName != "" {
token := generateToken(couchInstance.conf.JwtPrivateKey, couchInstance.conf.JwtUserName)
req.Header.Add("Authorization", "Bearer "+token)
}

// Execute http request
resp, errResp = couchInstance.client.Do(req)

Expand Down Expand Up @@ -1803,3 +1811,52 @@ func printDocumentIds(documentPointers []*couchDoc) (string, error) {
}
return strings.Join(documentIds, ","), nil
}

func NewJWT(privateKey []byte) JWT {
return JWT{
privateKey: privateKey,
}
}

// Generate a JWT token for a JWT object
func (j JWT) Create(ttl time.Duration, jwtUserName string) (string, error) {
key, err := jwt.ParseRSAPrivateKeyFromPEM(j.privateKey)
if err != nil {
return "", fmt.Errorf("Error Parsing RSA Private key from PEM %s", err)
}

now := time.Now().UTC()

claims := make(jwt.MapClaims)
claims["_couchdb.roles"] = []string{"_admin"}
claims["exp"] = now.Add(ttl).Unix() // The expiration time after which the token must be disregarded.
claims["alg"] = "RS256"
claims["sub"] = jwtUserName // Couchdb Server Admin user name

token, err := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(key)
if err != nil {
return "", fmt.Errorf("Error Generating JWT token %s", err)
}

couchdbLogger.Debugf("JWT token generated: %s", token)

return token, nil
}

// Generate a new JWT token
func generateToken(privateKeyPath string, jwtUserName string) string {
// Read JWT Private key
prvKey, err := ioutil.ReadFile(privateKeyPath)
if err != nil {
couchdbLogger.Errorf("Error in reading JWT Private key: %s", err)
}
// Create a new JWT object with private key
jwtToken := NewJWT(prvKey)

// Generate a new JWT token with the object created. For now duration is arbitarly set high to avoid token expiration issue on call
token, err := jwtToken.Create(time.Duration(24)*time.Hour, jwtUserName)
if err != nil {
couchdbLogger.Errorf("Error from jwtToken.create method: %s", err)
}
return token
}
4 changes: 4 additions & 0 deletions core/ledger/ledger_interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ type CouchDBConfig struct {
Username string
// Password is the password for Username.
Password string
// Path of JWT Private Key
JwtPrivateKey string
// Username to authenticate with Couchdb. This username must have read and write access permissions
JwtUserName string
// MaxRetries is the maximum number of times to retry CouchDB operations on
// failure.
MaxRetries int
Expand Down
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@ require (
gopkg.in/yaml.v2 v2.4.0
)

require google.golang.org/protobuf v1.28.1
require (
github.com/golang-jwt/jwt/v4 v4.4.3
google.golang.org/protobuf v1.28.1
)

require (
github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,8 @@ github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zV
github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt/v4 v4.4.3 h1:Hxl6lhQFj4AnOX6MLrsCb/+7tCj7DxP7VA+2rDIq5AU=
github.com/golang-jwt/jwt/v4 v4.4.3/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
Expand Down
2 changes: 2 additions & 0 deletions internal/peer/node/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ func ledgerConfig() *ledger.Config {
Address: viper.GetString("ledger.state.couchDBConfig.couchDBAddress"),
Username: viper.GetString("ledger.state.couchDBConfig.username"),
Password: viper.GetString("ledger.state.couchDBConfig.password"),
JwtPrivateKey: viper.GetString("ledger.state.couchDBConfig.jwtPrivateKey"),
JwtUserName: viper.GetString("ledger.state.couchDBConfig.jwtUserName"),
MaxRetries: viper.GetInt("ledger.state.couchDBConfig.maxRetries"),
MaxRetriesOnStartup: viper.GetInt("ledger.state.couchDBConfig.maxRetriesOnStartup"),
RequestTimeout: viper.GetDuration("ledger.state.couchDBConfig.requestTimeout"),
Expand Down
4 changes: 4 additions & 0 deletions sampleconfig/core.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,10 @@ ledger:
# If it is stored here, the file must be access control protected
# to prevent unintended users from discovering the password.
password:
# Path of JWT Private key file
jwtPrivateKey:
# This username must have read and write authority on CouchDB
jwtUserName:
# Number of retries for CouchDB errors
maxRetries: 3
# Number of retries for CouchDB errors during peer startup.
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions vendor/github.com/golang-jwt/jwt/v4/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

138 changes: 138 additions & 0 deletions vendor/github.com/golang-jwt/jwt/v4/README.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions vendor/github.com/golang-jwt/jwt/v4/SECURITY.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading