forked from pydio/cells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
token-handler.go
177 lines (159 loc) · 5.01 KB
/
token-handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package grpc
import (
"context"
"crypto/rand"
"encoding/base64"
"io"
"sync"
"time"
"github.com/micro/go-micro/errors"
"github.com/ory/fosite/token/hmac"
"github.com/ory/fosite/token/jwt"
"go.uber.org/zap"
"github.com/pborman/uuid"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/config"
"github.com/pydio/cells/common/log"
"github.com/pydio/cells/common/proto/auth"
servicecontext "github.com/pydio/cells/common/service/context"
"github.com/pydio/cells/common/utils/permissions"
"github.com/pydio/cells/idm/oauth"
json "github.com/pydio/cells/x/jsonx"
)
var tokensKey []byte
type PatScopeClaims struct {
Scopes []string `json:"scopes"`
}
type PatHandler struct {
strategy *hmac.HMACStrategy
}
func (p *PatHandler) getDao(ctx context.Context) oauth.DAO {
return servicecontext.GetDAO(ctx).(oauth.DAO)
}
func (p *PatHandler) getStrategy() *hmac.HMACStrategy {
if p.strategy == nil {
p.strategy = &hmac.HMACStrategy{
TokenEntropy: 32,
GlobalSecret: p.getKey(),
RotatedGlobalSecrets: nil,
Mutex: sync.Mutex{},
}
}
return p.strategy
}
func (p *PatHandler) getKey() []byte {
if len(tokensKey) > 0 {
return tokensKey
}
cVal := config.Get("defaults", "personalTokens", "secureKey")
if cVal.String() == "" {
tokensKey = p.generateRandomKey(32)
strKey := base64.StdEncoding.EncodeToString(tokensKey)
cVal.Set(strKey)
config.Save(common.PydioSystemUsername, "Creating random key for personal tokens service")
} else if t, e := base64.StdEncoding.DecodeString(cVal.String()); e == nil {
tokensKey = t
} else {
log.Logger(context.Background()).Error("Could not read generated key for personal tokens!", zap.Error(e))
}
return tokensKey
}
func (p *PatHandler) Verify(ctx context.Context, request *auth.VerifyTokenRequest, response *auth.VerifyTokenResponse) error {
dao := p.getDao(ctx)
if err := p.getStrategy().Validate(request.Token); err != nil {
return errors.Unauthorized("token.invalid", "Cannot validate token")
}
pat, e := dao.Load(request.Token)
if e != nil {
return errors.Unauthorized("token.not.found", "Cannot find corresponding Personal Access Token")
}
// Check Expiration Date
if time.Unix(pat.ExpiresAt, 0).Before(time.Now()) {
return errors.Unauthorized("token.expired", "Personal token is expired")
}
if pat.AutoRefreshWindow > 0 {
// Recompute expire date
pat.ExpiresAt = time.Now().Add(time.Duration(pat.AutoRefreshWindow) * time.Second).Unix()
if er := dao.Store(request.Token, pat, true); er != nil {
return errors.BadRequest("internal.error", "Cannot store updated token "+er.Error())
}
}
cl := jwt.IDTokenClaims{
Subject: pat.UserUuid,
Issuer: "local",
ExpiresAt: time.Unix(pat.ExpiresAt, 0),
Audience: []string{common.ServiceGrpcNamespace_ + common.ServiceToken},
}
if len(pat.Scopes) > 0 {
cl.Extra = map[string]interface{}{
"scopes": pat.Scopes,
}
}
m, _ := json.Marshal(cl)
response.Success = true
response.Data = m
return nil
}
func (p *PatHandler) Generate(ctx context.Context, request *auth.PatGenerateRequest, response *auth.PatGenerateResponse) error {
dao := p.getDao(ctx)
token := &auth.PersonalAccessToken{
Uuid: uuid.New(),
Type: request.Type,
Label: request.Label,
UserUuid: request.UserUuid,
UserLogin: request.UserLogin,
Scopes: request.Scopes,
AutoRefreshWindow: request.AutoRefreshWindow,
ExpiresAt: request.ExpiresAt,
}
if request.AutoRefreshWindow > 0 {
request.ExpiresAt = time.Now().Add(time.Duration(request.AutoRefreshWindow) * time.Second).Unix()
token.ExpiresAt = request.ExpiresAt
} else if request.ExpiresAt > 0 {
token.ExpiresAt = request.ExpiresAt
} else {
return errors.BadRequest("missing.parameters", "Please provide one of ExpiresAt or AutoRefreshWindow")
}
token.CreatedAt = time.Now().Unix()
if uName, _ := permissions.FindUserNameInContext(ctx); uName != "" {
token.CreatedBy = uName
}
accessToken, _, err := p.getStrategy().Generate()
if err != nil {
return err
}
if err := dao.Store(accessToken, token, false); err != nil {
return err
}
response.TokenUuid = token.Uuid
response.AccessToken = accessToken
return nil
}
func (p *PatHandler) Revoke(ctx context.Context, request *auth.PatRevokeRequest, response *auth.PatRevokeResponse) error {
dao := p.getDao(ctx)
return dao.Delete(request.GetUuid())
}
func (p *PatHandler) List(ctx context.Context, request *auth.PatListRequest, response *auth.PatListResponse) error {
dao := p.getDao(ctx)
tt, er := dao.List(request.Type, request.ByUserLogin)
if er != nil {
return nil
}
response.Tokens = tt
return nil
}
func (p *PatHandler) PruneTokens(ctx context.Context, request *auth.PruneTokensRequest, response *auth.PruneTokensResponse) error {
i, e := p.getDao(ctx).PruneExpired()
if e != nil {
return e
}
response.Count = int32(i)
return nil
}
func (p *PatHandler) generateRandomKey(length int) []byte {
k := make([]byte, length)
if _, err := io.ReadFull(rand.Reader, k); err != nil {
return nil
}
return k
}