cubefs

Форк
0
103 строки · 2.5 Кб
1
// Copyright 2022 The CubeFS Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12
// implied. See the License for the specific language governing
13
// permissions and limitations under the License.
14

15
package auth
16

17
import (
18
	"bytes"
19
	"crypto/md5"
20
	"encoding/base64"
21
	"encoding/binary"
22
	"errors"
23
	"net/http"
24
)
25

26
const (
27
	// md5 need 16 byte
28
	TokenKeyLenth = 16
29

30
	// #nosec G101
31
	TokenHeaderKey = "BLOB-STORE-AUTH-TOKEN"
32
)
33

34
var errMismatchToken = errors.New("mismatch token")
35

36
type Config struct {
37
	EnableAuth bool   `json:"enable_auth"`
38
	Secret     string `json:"secret"`
39
}
40

41
// simply: use timestamp as a token calculate param
42
type authInfo struct {
43
	timestamp int64
44
	token     []byte
45
	// other auth content
46
	others []byte
47
}
48

49
func encodeAuthInfo(info *authInfo) (ret string, err error) {
50
	w := bytes.NewBuffer([]byte{})
51
	if err = binary.Write(w, binary.LittleEndian, &info.timestamp); err != nil {
52
		return
53
	}
54
	if err = binary.Write(w, binary.LittleEndian, &info.token); err != nil {
55
		return
56
	}
57
	return base64.URLEncoding.EncodeToString(w.Bytes()), nil
58
}
59

60
func decodeAuthInfo(encodeStr string) (info *authInfo, err error) {
61
	info = new(authInfo)
62
	b, err := base64.URLEncoding.DecodeString(encodeStr)
63
	if err != nil {
64
		return
65
	}
66

67
	info.token = make([]byte, TokenKeyLenth)
68
	r := bytes.NewBuffer(b)
69
	if err = binary.Read(r, binary.LittleEndian, &info.timestamp); err != nil {
70
		return
71
	}
72
	if err = binary.Read(r, binary.LittleEndian, &info.token); err != nil {
73
		return
74
	}
75
	return
76
}
77

78
// calculate auth token with params and secret
79
func calculate(info *authInfo, secret []byte) (err error) {
80
	hash := md5.New()
81
	b := make([]byte, 8)
82
	binary.LittleEndian.PutUint64(b, uint64(info.timestamp))
83
	hash.Write(info.others)
84
	hash.Write(b)
85
	hash.Write(secret)
86
	info.token = hash.Sum(nil)
87
	return
88
}
89

90
// verify auth token with params and secret
91
func verify(info *authInfo, secret []byte) (err error) {
92
	checkAuthInfo := &authInfo{timestamp: info.timestamp, others: info.others}
93
	calculate(checkAuthInfo, secret)
94
	if !bytes.Equal(checkAuthInfo.token, info.token) {
95
		return errMismatchToken
96
	}
97
	return
98
}
99

100
func genEncodeStr(req *http.Request) []byte {
101
	calStr := req.URL.Path + req.URL.RawQuery
102
	return []byte(calStr)
103
}
104

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.