Refactoring auth package and move into API
Signed-off-by: Evgeniy Kulikov <kim@nspcc.ru>
This commit is contained in:
parent
d8d6dc7593
commit
b9972042fc
4 changed files with 90 additions and 93 deletions
|
@ -3,7 +3,8 @@ package auth
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/ecdsa"
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
@ -13,10 +14,11 @@ import (
|
||||||
|
|
||||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||||
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
|
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
|
||||||
|
sdk "github.com/nspcc-dev/cdn-neofs-sdk"
|
||||||
|
"github.com/nspcc-dev/cdn-neofs-sdk/creds/accessbox"
|
||||||
|
"github.com/nspcc-dev/cdn-neofs-sdk/creds/hcs"
|
||||||
|
"github.com/nspcc-dev/neofs-api-go/pkg/object"
|
||||||
"github.com/nspcc-dev/neofs-api-go/pkg/token"
|
"github.com/nspcc-dev/neofs-api-go/pkg/token"
|
||||||
"github.com/nspcc-dev/neofs-authmate/accessbox/hcs"
|
|
||||||
"github.com/nspcc-dev/neofs-authmate/agents/s3"
|
|
||||||
manager "github.com/nspcc-dev/neofs-authmate/manager/neofs"
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
)
|
)
|
||||||
|
@ -24,92 +26,116 @@ import (
|
||||||
var authorizationFieldRegexp = regexp.MustCompile(`AWS4-HMAC-SHA256 Credential=(?P<access_key_id_cid>[^/]+)/(?P<access_key_id_oid>[^/]+)/(?P<date>[^/]+)/(?P<region>[^/]*)/(?P<service>[^/]+)/aws4_request,\s*SignedHeaders=(?P<signed_header_fields>.+),\s*Signature=(?P<v4_signature>.+)`)
|
var authorizationFieldRegexp = regexp.MustCompile(`AWS4-HMAC-SHA256 Credential=(?P<access_key_id_cid>[^/]+)/(?P<access_key_id_oid>[^/]+)/(?P<date>[^/]+)/(?P<region>[^/]*)/(?P<service>[^/]+)/aws4_request,\s*SignedHeaders=(?P<signed_header_fields>.+),\s*Signature=(?P<v4_signature>.+)`)
|
||||||
|
|
||||||
type (
|
type (
|
||||||
Center struct {
|
Center interface {
|
||||||
man *manager.Manager
|
Authenticate(request *http.Request) (*token.BearerToken, error)
|
||||||
reg *regexpSubmatcher
|
}
|
||||||
|
|
||||||
keys *hcs.X25519Keys
|
center struct {
|
||||||
|
cli sdk.Client
|
||||||
|
key hcs.PrivateKey
|
||||||
|
reg *regexpSubmatcher
|
||||||
}
|
}
|
||||||
|
|
||||||
Params struct {
|
Params struct {
|
||||||
Timeout time.Duration
|
Client sdk.Client
|
||||||
|
Logger *zap.Logger
|
||||||
Log *zap.Logger
|
Credential hcs.Credentials
|
||||||
Con manager.Connector
|
|
||||||
|
|
||||||
GAKey *hcs.X25519Keys
|
|
||||||
NFKey *ecdsa.PrivateKey
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
// New creates an instance of AuthCenter.
|
// New creates an instance of AuthCenter.
|
||||||
func New(ctx context.Context, p *Params) (*Center, error) {
|
func New(cli sdk.Client, key hcs.PrivateKey) Center {
|
||||||
m, err := manager.New(ctx,
|
return ¢er{
|
||||||
manager.WithKey(p.NFKey),
|
cli: cli,
|
||||||
manager.WithLogger(p.Log),
|
key: key,
|
||||||
manager.WithConnector(p.Con))
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &Center{
|
|
||||||
man: m,
|
|
||||||
reg: ®expSubmatcher{re: authorizationFieldRegexp},
|
reg: ®expSubmatcher{re: authorizationFieldRegexp},
|
||||||
|
}
|
||||||
keys: p.GAKey,
|
|
||||||
}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (center *Center) AuthenticationPassed(request *http.Request) (*token.BearerToken, error) {
|
func (c *center) Authenticate(r *http.Request) (*token.BearerToken, error) {
|
||||||
queryValues := request.URL.Query()
|
queryValues := r.URL.Query()
|
||||||
if queryValues.Get("X-Amz-Algorithm") == "AWS4-HMAC-SHA256" {
|
if queryValues.Get("X-Amz-Algorithm") == "AWS4-HMAC-SHA256" {
|
||||||
return nil, errors.New("pre-signed form of request is not supported")
|
return nil, errors.New("pre-signed form of request is not supported")
|
||||||
}
|
}
|
||||||
authHeaderField := request.Header["Authorization"]
|
|
||||||
|
authHeaderField := r.Header["Authorization"]
|
||||||
if len(authHeaderField) != 1 {
|
if len(authHeaderField) != 1 {
|
||||||
return nil, errors.New("unsupported request: wrong length of Authorization header field")
|
return nil, errors.New("unsupported request: wrong length of Authorization header field")
|
||||||
}
|
}
|
||||||
sms1 := center.reg.getSubmatches(authHeaderField[0])
|
|
||||||
|
sms1 := c.reg.getSubmatches(authHeaderField[0])
|
||||||
if len(sms1) != 7 {
|
if len(sms1) != 7 {
|
||||||
return nil, errors.New("bad Authorization header field")
|
return nil, errors.New("bad Authorization header field")
|
||||||
}
|
}
|
||||||
|
|
||||||
signedHeaderFieldsNames := strings.Split(sms1["signed_header_fields"], ";")
|
signedHeaderFieldsNames := strings.Split(sms1["signed_header_fields"], ";")
|
||||||
if len(signedHeaderFieldsNames) == 0 {
|
if len(signedHeaderFieldsNames) == 0 {
|
||||||
return nil, errors.New("wrong format of signed headers part")
|
return nil, errors.New("wrong format of signed headers part")
|
||||||
}
|
}
|
||||||
signatureDateTime, err := time.Parse("20060102T150405Z", request.Header.Get("X-Amz-Date"))
|
|
||||||
|
signatureDateTime, err := time.Parse("20060102T150405Z", r.Header.Get("X-Amz-Date"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to parse x-amz-date header field")
|
return nil, errors.Wrap(err, "failed to parse x-amz-date header field")
|
||||||
}
|
}
|
||||||
|
|
||||||
accessKeyID := fmt.Sprintf("%s/%s", sms1["access_key_id_cid"], sms1["access_key_id_oid"])
|
accessKeyID := fmt.Sprintf("%s/%s", sms1["access_key_id_cid"], sms1["access_key_id_oid"])
|
||||||
res, err := s3.NewAgent(center.man).ObtainSecret(request.Context(), center.keys, accessKeyID)
|
|
||||||
if err != nil {
|
address := object.NewAddress()
|
||||||
return nil, errors.Wrap(err, "failed to fetch bearer token")
|
if err = address.Parse(accessKeyID); err != nil {
|
||||||
|
return nil, errors.Wrapf(err, "could not parse AccessBox address: %s", accessKeyID)
|
||||||
}
|
}
|
||||||
otherRequest := request.Clone(context.TODO())
|
|
||||||
|
buf := new(bytes.Buffer)
|
||||||
|
if _, err = c.cli.Object().Get(r.Context(), address, sdk.WithGetWriter(buf)); err != nil {
|
||||||
|
return nil, errors.Wrapf(err, "could not fetch AccessBox: %s (%s / %s)",
|
||||||
|
accessKeyID,
|
||||||
|
address.ContainerID(),
|
||||||
|
address.ObjectID())
|
||||||
|
}
|
||||||
|
|
||||||
|
box := accessbox.NewBearerBox(nil)
|
||||||
|
if err = accessbox.NewDecoder(buf, c.key).Decode(box); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := box.Token().Marshal()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
hash := sha256.Sum256(data)
|
||||||
|
secret := hex.EncodeToString(hash[:])
|
||||||
|
|
||||||
|
otherRequest := r.Clone(context.TODO())
|
||||||
otherRequest.Header = map[string][]string{}
|
otherRequest.Header = map[string][]string{}
|
||||||
for hfn, hfvs := range request.Header {
|
|
||||||
|
for hfn, hfvs := range r.Header {
|
||||||
for _, shfn := range signedHeaderFieldsNames {
|
for _, shfn := range signedHeaderFieldsNames {
|
||||||
if strings.EqualFold(hfn, shfn) {
|
if strings.EqualFold(hfn, shfn) {
|
||||||
otherRequest.Header[hfn] = hfvs
|
otherRequest.Header[hfn] = hfvs
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
awsCreds := credentials.NewStaticCredentials(accessKeyID, res.SecretAccessKey, "")
|
|
||||||
|
awsCreds := credentials.NewStaticCredentials(accessKeyID, secret, "")
|
||||||
signer := v4.NewSigner(awsCreds)
|
signer := v4.NewSigner(awsCreds)
|
||||||
body, err := readAndKeepBody(request)
|
|
||||||
|
body, err := readAndKeepBody(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to read out request body")
|
return nil, errors.Wrap(err, "failed to read out request body")
|
||||||
}
|
}
|
||||||
_, err = signer.Sign(otherRequest, body, sms1["service"], sms1["region"], signatureDateTime)
|
|
||||||
|
hdr, err := signer.Sign(otherRequest, body, sms1["service"], sms1["region"], signatureDateTime)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "failed to sign temporary HTTP request")
|
return nil, errors.Wrap(err, "failed to sign temporary HTTP request")
|
||||||
}
|
}
|
||||||
sms2 := center.reg.getSubmatches(otherRequest.Header.Get("Authorization"))
|
|
||||||
|
sms2 := c.reg.getSubmatches(hdr.Get("Authorization"))
|
||||||
if sms1["v4_signature"] != sms2["v4_signature"] {
|
if sms1["v4_signature"] != sms2["v4_signature"] {
|
||||||
return nil, errors.Wrap(err, "failed to pass authentication procedure")
|
return nil, errors.Wrap(err, "failed to pass authentication procedure")
|
||||||
}
|
}
|
||||||
return res.BearerToken, nil
|
|
||||||
|
return box.Token(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Make this write into a smart buffer backed by a file on a fast drive.
|
// TODO: Make this write into a smart buffer backed by a file on a fast drive.
|
20
api/auth/regexp-utils.go
Normal file
20
api/auth/regexp-utils.go
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
package auth
|
||||||
|
|
||||||
|
import "regexp"
|
||||||
|
|
||||||
|
type regexpSubmatcher struct {
|
||||||
|
re *regexp.Regexp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *regexpSubmatcher) getSubmatches(target string) map[string]string {
|
||||||
|
matches := r.re.FindStringSubmatch(target)
|
||||||
|
l := len(matches)
|
||||||
|
|
||||||
|
sub := make(map[string]string, l)
|
||||||
|
for i, name := range r.re.SubexpNames() {
|
||||||
|
if i > 0 && i <= l {
|
||||||
|
sub[name] = matches[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sub
|
||||||
|
}
|
|
@ -1,30 +0,0 @@
|
||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/nspcc-dev/neofs-api-go/pkg/token"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type contextKey string
|
|
||||||
|
|
||||||
const bearerTokenContextKey contextKey = "bearer-token"
|
|
||||||
|
|
||||||
// GetBearerToken returns a bearer token embedded into a context or error, if any.
|
|
||||||
func GetBearerToken(ctx context.Context) (*token.BearerToken, error) {
|
|
||||||
bt := ctx.Value(bearerTokenContextKey)
|
|
||||||
if bt == nil {
|
|
||||||
return nil, errors.New("got nil bearer token")
|
|
||||||
}
|
|
||||||
v, ok := bt.(*token.BearerToken)
|
|
||||||
if !ok {
|
|
||||||
return nil, errors.Errorf("extracted unexpected type other than bearer token's: %T", v)
|
|
||||||
}
|
|
||||||
return v, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetBearerToken return a context with embedded bearer token.
|
|
||||||
func SetBearerToken(ctx context.Context, bearerToken *token.BearerToken) context.Context {
|
|
||||||
return context.WithValue(ctx, bearerTokenContextKey, bearerToken)
|
|
||||||
}
|
|
|
@ -1,19 +0,0 @@
|
||||||
package auth
|
|
||||||
|
|
||||||
import "regexp"
|
|
||||||
|
|
||||||
type regexpSubmatcher struct {
|
|
||||||
re *regexp.Regexp
|
|
||||||
}
|
|
||||||
|
|
||||||
func (resm *regexpSubmatcher) getSubmatches(target string) map[string]string {
|
|
||||||
matches := resm.re.FindStringSubmatch(target)
|
|
||||||
l := len(matches)
|
|
||||||
submatches := make(map[string]string, l)
|
|
||||||
for i, name := range resm.re.SubexpNames() {
|
|
||||||
if i > 0 && i <= l {
|
|
||||||
submatches[name] = matches[i]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return submatches
|
|
||||||
}
|
|
Loading…
Reference in a new issue