@@ -9,12 +9,11 @@ import (
9
9
"github.com/pkg/errors"
10
10
"github.com/sirupsen/logrus"
11
11
12
+ "github.com/crowdsecurity/crowdsec/pkg/apiclient"
12
13
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
13
14
"github.com/crowdsecurity/crowdsec/pkg/database/ent/configitem"
14
15
)
15
16
16
- const apicTokenKey = "apic_token"
17
-
18
17
func (c * Client ) GetConfigItem (ctx context.Context , key string ) (string , error ) {
19
18
result , err := c .Ent .ConfigItem .Query ().Where (configitem .NameEQ (key )).First (ctx )
20
19
@@ -53,7 +52,7 @@ func (c *Client) SetConfigItem(ctx context.Context, key string, value string) er
53
52
// - it is a properly formatted JWT with an "exp" claim,
54
53
// - it is not expired or near expiry.
55
54
func (c * Client ) LoadAPICToken (ctx context.Context , logger logrus.FieldLogger ) (string , time.Time , bool ) {
56
- token , err := c .GetConfigItem (ctx , apicTokenKey )
55
+ token , err := c .GetConfigItem (ctx , apiclient . TokenDBField ) // TokenKey is a constant string representing the key for the token in the database
57
56
if err != nil {
58
57
logger .Debugf ("error fetching token from DB: %s" , err )
59
58
return "" , time.Time {}, false
@@ -78,6 +77,18 @@ func (c *Client) LoadAPICToken(ctx context.Context, logger logrus.FieldLogger) (
78
77
return "" , time.Time {}, false
79
78
}
80
79
80
+ iatFloat , ok := claims ["iat" ].(float64 )
81
+ if ! ok {
82
+ logger .Debug ("token missing 'iat' claim" )
83
+ return "" , time.Time {}, false
84
+ }
85
+
86
+ iat := time .Unix (int64 (iatFloat ), 0 )
87
+ if time .Now ().UTC ().After (iat .Add (1 * time .Minute )) {
88
+ logger .Debug ("token is more than 1 minute old, not using it" )
89
+ return "" , time.Time {}, false
90
+ }
91
+
81
92
expFloat , ok := claims ["exp" ].(float64 )
82
93
if ! ok {
83
94
logger .Debug ("token missing 'exp' claim" )
@@ -94,8 +105,8 @@ func (c *Client) LoadAPICToken(ctx context.Context, logger logrus.FieldLogger) (
94
105
}
95
106
96
107
// SaveAPICToken stores the given JWT token in the local database under the appropriate config item.
97
- func (c * Client ) SaveAPICToken (ctx context.Context , token string ) error {
98
- if err := c .SetConfigItem (ctx , apicTokenKey , token ); err != nil {
108
+ func (c * Client ) SaveAPICToken (ctx context.Context , tokenKey string , token string ) error {
109
+ if err := c .SetConfigItem (ctx , tokenKey , token ); err != nil {
99
110
return fmt .Errorf ("saving token to db: %w" , err )
100
111
}
101
112
0 commit comments