Skip to content

Commit

Permalink
Support for Couchdb JWT Authentation
Browse files Browse the repository at this point in the history
Added support for couchdb JWT Authentatication from peer via RSA256 algorithm

Signed-off-by: Aviral Agrawal <[email protected]>
  • Loading branch information
aviralagrawalDLT committed Jan 16, 2023
1 parent ca5272b commit df05159
Show file tree
Hide file tree
Showing 32 changed files with 2,327 additions and 3 deletions.
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
4 changes: 4 additions & 0 deletions vendor/github.com/golang-jwt/jwt/v4/.gitignore

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.

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

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

0 comments on commit df05159

Please sign in to comment.