use UTC everywhere in server

This commit is contained in:
Pascal Fischer 2023-04-03 15:09:35 +02:00
parent b05e30ac5a
commit 489892553a
24 changed files with 150 additions and 127 deletions

View File

@ -1151,7 +1151,7 @@ func (am *DefaultAccountManager) MarkPATUsed(tokenID string) error {
return fmt.Errorf("token not found") return fmt.Errorf("token not found")
} }
pat.LastUsed = time.Now() pat.LastUsed = time.Now().UTC()
return am.Store.SaveAccount(account) return am.Store.SaveAccount(account)
} }

View File

@ -127,12 +127,12 @@ func TestAccount_GetPeerNetworkMap(t *testing.T) {
Name: peerID1, Name: peerID1,
DNSLabel: peerID1, DNSLabel: peerID1,
Status: &PeerStatus{ Status: &PeerStatus{
LastSeen: time.Now(), LastSeen: time.Now().UTC(),
Connected: false, Connected: false,
LoginExpired: true, LoginExpired: true,
}, },
UserID: userID, UserID: userID,
LastLogin: time.Now().Add(-time.Hour * 24 * 30 * 30), LastLogin: time.Now().UTC().Add(-time.Hour * 24 * 30 * 30),
}, },
"peer-2": { "peer-2": {
ID: peerID2, ID: peerID2,
@ -141,12 +141,12 @@ func TestAccount_GetPeerNetworkMap(t *testing.T) {
Name: peerID2, Name: peerID2,
DNSLabel: peerID2, DNSLabel: peerID2,
Status: &PeerStatus{ Status: &PeerStatus{
LastSeen: time.Now(), LastSeen: time.Now().UTC(),
Connected: false, Connected: false,
LoginExpired: false, LoginExpired: false,
}, },
UserID: userID, UserID: userID,
LastLogin: time.Now(), LastLogin: time.Now().UTC(),
LoginExpirationEnabled: true, LoginExpirationEnabled: true,
}, },
}, },
@ -165,12 +165,12 @@ func TestAccount_GetPeerNetworkMap(t *testing.T) {
Name: peerID1, Name: peerID1,
DNSLabel: peerID1, DNSLabel: peerID1,
Status: &PeerStatus{ Status: &PeerStatus{
LastSeen: time.Now(), LastSeen: time.Now().UTC(),
Connected: false, Connected: false,
LoginExpired: true, LoginExpired: true,
}, },
UserID: userID, UserID: userID,
LastLogin: time.Now().Add(-time.Hour * 24 * 30 * 30), LastLogin: time.Now().UTC().Add(-time.Hour * 24 * 30 * 30),
LoginExpirationEnabled: true, LoginExpirationEnabled: true,
}, },
"peer-2": { "peer-2": {
@ -180,12 +180,12 @@ func TestAccount_GetPeerNetworkMap(t *testing.T) {
Name: peerID2, Name: peerID2,
DNSLabel: peerID2, DNSLabel: peerID2,
Status: &PeerStatus{ Status: &PeerStatus{
LastSeen: time.Now(), LastSeen: time.Now().UTC(),
Connected: false, Connected: false,
LoginExpired: true, LoginExpired: true,
}, },
UserID: userID, UserID: userID,
LastLogin: time.Now().Add(-time.Hour * 24 * 30 * 30), LastLogin: time.Now().UTC().Add(-time.Hour * 24 * 30 * 30),
LoginExpirationEnabled: true, LoginExpirationEnabled: true,
}, },
}, },
@ -1288,10 +1288,10 @@ func TestAccount_Copy(t *testing.T) {
ID: "pat1", ID: "pat1",
Name: "First PAT", Name: "First PAT",
HashedToken: "SoMeHaShEdToKeN", HashedToken: "SoMeHaShEdToKeN",
ExpirationDate: time.Now().AddDate(0, 0, 7), ExpirationDate: time.Now().UTC().AddDate(0, 0, 7),
CreatedBy: "user1", CreatedBy: "user1",
CreatedAt: time.Now(), CreatedAt: time.Now().UTC(),
LastUsed: time.Now(), LastUsed: time.Now().UTC(),
}, },
}, },
}, },
@ -1569,22 +1569,22 @@ func TestAccount_GetExpiredPeers(t *testing.T) {
ID: "peer-1", ID: "peer-1",
LoginExpirationEnabled: true, LoginExpirationEnabled: true,
Status: &PeerStatus{ Status: &PeerStatus{
LastSeen: time.Now(), LastSeen: time.Now().UTC(),
Connected: true, Connected: true,
LoginExpired: false, LoginExpired: false,
}, },
LastLogin: time.Now().Add(-30 * time.Minute), LastLogin: time.Now().UTC().Add(-30 * time.Minute),
UserID: userID, UserID: userID,
}, },
"peer-2": { "peer-2": {
ID: "peer-2", ID: "peer-2",
LoginExpirationEnabled: true, LoginExpirationEnabled: true,
Status: &PeerStatus{ Status: &PeerStatus{
LastSeen: time.Now(), LastSeen: time.Now().UTC(),
Connected: true, Connected: true,
LoginExpired: false, LoginExpired: false,
}, },
LastLogin: time.Now().Add(-2 * time.Hour), LastLogin: time.Now().UTC().Add(-2 * time.Hour),
UserID: userID, UserID: userID,
}, },
@ -1592,11 +1592,11 @@ func TestAccount_GetExpiredPeers(t *testing.T) {
ID: "peer-3", ID: "peer-3",
LoginExpirationEnabled: true, LoginExpirationEnabled: true,
Status: &PeerStatus{ Status: &PeerStatus{
LastSeen: time.Now(), LastSeen: time.Now().UTC(),
Connected: true, Connected: true,
LoginExpired: false, LoginExpired: false,
}, },
LastLogin: time.Now().Add(-1 * time.Hour), LastLogin: time.Now().UTC().Add(-1 * time.Hour),
UserID: userID, UserID: userID,
}, },
}, },
@ -1797,7 +1797,7 @@ func TestAccount_GetNextPeerExpiration(t *testing.T) {
LoginExpired: false, LoginExpired: false,
}, },
LoginExpirationEnabled: true, LoginExpirationEnabled: true,
LastLogin: time.Now(), LastLogin: time.Now().UTC(),
UserID: userID, UserID: userID,
}, },
"peer-2": { "peer-2": {

View File

@ -2,10 +2,12 @@ package sqlite
import ( import (
"fmt" "fmt"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/stretchr/testify/assert"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/netbirdio/netbird/management/server/activity"
) )
func TestNewSQLiteStore(t *testing.T) { func TestNewSQLiteStore(t *testing.T) {
@ -21,7 +23,7 @@ func TestNewSQLiteStore(t *testing.T) {
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
_, err = store.Save(&activity.Event{ _, err = store.Save(&activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.PeerAddedByUser, Activity: activity.PeerAddedByUser,
InitiatorID: "user_" + fmt.Sprint(i), InitiatorID: "user_" + fmt.Sprint(i),
TargetID: "peer_" + fmt.Sprint(i), TargetID: "peer_" + fmt.Sprint(i),

View File

@ -2,9 +2,11 @@ package server
import ( import (
"fmt" "fmt"
"github.com/netbirdio/netbird/management/server/activity"
log "github.com/sirupsen/logrus"
"time" "time"
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/management/server/activity"
) )
// GetEvents returns a list of activity events of an account // GetEvents returns a list of activity events of an account
@ -39,7 +41,7 @@ func (am *DefaultAccountManager) storeEvent(initiatorID, targetID, accountID str
go func() { go func() {
_, err := am.eventStore.Save(&activity.Event{ _, err := am.eventStore.Save(&activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activityID, Activity: activityID,
InitiatorID: initiatorID, InitiatorID: initiatorID,
TargetID: targetID, TargetID: targetID,

View File

@ -1,17 +1,19 @@
package server package server
import ( import (
"github.com/netbirdio/netbird/management/server/activity"
"github.com/stretchr/testify/assert"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/netbirdio/netbird/management/server/activity"
) )
func generateAndStoreEvents(t *testing.T, manager *DefaultAccountManager, typ activity.Activity, initiatorID, targetID, func generateAndStoreEvents(t *testing.T, manager *DefaultAccountManager, typ activity.Activity, initiatorID, targetID,
accountID string, count int) { accountID string, count int) {
for i := 0; i < count; i++ { for i := 0; i < count; i++ {
_, err := manager.eventStore.Save(&activity.Event{ _, err := manager.eventStore.Save(&activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: typ, Activity: typ,
InitiatorID: initiatorID, InitiatorID: initiatorID,
TargetID: targetID, TargetID: targetID,

View File

@ -173,7 +173,7 @@ func restore(file string) (*FileStore, error) {
for key, peer := range account.Peers { for key, peer := range account.Peers {
// set LastLogin for the peers that were onboarded before the peer login expiration feature // set LastLogin for the peers that were onboarded before the peer login expiration feature
if peer.LastLogin.IsZero() { if peer.LastLogin.IsZero() {
peer.LastLogin = time.Now() peer.LastLogin = time.Now().UTC()
} }
if peer.ID != "" { if peer.ID != "" {
continue continue
@ -227,7 +227,7 @@ func (s *FileStore) persist(file string) error {
// AcquireGlobalLock acquires global lock across all the accounts and returns a function that releases the lock // AcquireGlobalLock acquires global lock across all the accounts and returns a function that releases the lock
func (s *FileStore) AcquireGlobalLock() (unlock func()) { func (s *FileStore) AcquireGlobalLock() (unlock func()) {
log.Debugf("acquiring global lock") log.Debugf("acquiring global lock")
start := time.Now() start := time.Now().UTC()
s.globalAccountLock.Lock() s.globalAccountLock.Lock()
unlock = func() { unlock = func() {
@ -241,7 +241,7 @@ func (s *FileStore) AcquireGlobalLock() (unlock func()) {
// AcquireAccountLock acquires account lock and returns a function that releases the lock // AcquireAccountLock acquires account lock and returns a function that releases the lock
func (s *FileStore) AcquireAccountLock(accountID string) (unlock func()) { func (s *FileStore) AcquireAccountLock(accountID string) (unlock func()) {
log.Debugf("acquiring lock for account %s", accountID) log.Debugf("acquiring lock for account %s", accountID)
start := time.Now() start := time.Now().UTC()
value, _ := s.accountLocks.LoadOrStore(accountID, &sync.Mutex{}) value, _ := s.accountLocks.LoadOrStore(accountID, &sync.Mutex{})
mtx := value.(*sync.Mutex) mtx := value.(*sync.Mutex)
mtx.Lock() mtx.Lock()

View File

@ -95,7 +95,7 @@ func TestSaveAccount(t *testing.T) {
IP: net.IP{127, 0, 0, 1}, IP: net.IP{127, 0, 0, 1},
Meta: PeerSystemMeta{}, Meta: PeerSystemMeta{},
Name: "peer name", Name: "peer name",
Status: &PeerStatus{Connected: true, LastSeen: time.Now()}, Status: &PeerStatus{Connected: true, LastSeen: time.Now().UTC()},
} }
// SaveAccount should trigger persist // SaveAccount should trigger persist
@ -131,7 +131,7 @@ func TestStore(t *testing.T) {
IP: net.IP{127, 0, 0, 1}, IP: net.IP{127, 0, 0, 1},
Meta: PeerSystemMeta{}, Meta: PeerSystemMeta{},
Name: "peer name", Name: "peer name",
Status: &PeerStatus{Connected: true, LastSeen: time.Now()}, Status: &PeerStatus{Connected: true, LastSeen: time.Now().UTC()},
} }
account.Groups["all"] = &Group{ account.Groups["all"] = &Group{
ID: "all", ID: "all",
@ -514,7 +514,7 @@ func TestFileStore_SavePeerStatus(t *testing.T) {
} }
// save status of non-existing peer // save status of non-existing peer
newStatus := PeerStatus{Connected: true, LastSeen: time.Now()} newStatus := PeerStatus{Connected: true, LastSeen: time.Now().UTC()}
err = store.SavePeerStatus(account.Id, "non-existing-peer", newStatus) err = store.SavePeerStatus(account.Id, "non-existing-peer", newStatus)
assert.Error(t, err) assert.Error(t, err)
@ -526,7 +526,7 @@ func TestFileStore_SavePeerStatus(t *testing.T) {
IP: net.IP{127, 0, 0, 1}, IP: net.IP{127, 0, 0, 1},
Meta: PeerSystemMeta{}, Meta: PeerSystemMeta{},
Name: "peer name", Name: "peer name",
Status: &PeerStatus{Connected: false, LastSeen: time.Now()}, Status: &PeerStatus{Connected: false, LastSeen: time.Now().UTC()},
} }
err = store.SaveAccount(account) err = store.SaveAccount(account)

View File

@ -98,7 +98,7 @@ func (s *GRPCServer) GetServerKey(ctx context.Context, req *proto.Empty) (*proto
if s.appMetrics != nil { if s.appMetrics != nil {
s.appMetrics.GRPCMetrics().CountGetKeyRequest() s.appMetrics.GRPCMetrics().CountGetKeyRequest()
} }
now := time.Now().Add(24 * time.Hour) now := time.Now().UTC().Add(24 * time.Hour)
secs := int64(now.Second()) secs := int64(now.Second())
nanos := int32(now.Nanosecond()) nanos := int32(now.Nanosecond())
expiresAt := &timestamp.Timestamp{Seconds: secs, Nanos: nanos} expiresAt := &timestamp.Timestamp{Seconds: secs, Nanos: nanos}

View File

@ -54,7 +54,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
ID := uint64(1) ID := uint64(1)
events := make([]*activity.Event, 0) events := make([]*activity.Event, 0)
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.PeerAddedByUser, Activity: activity.PeerAddedByUser,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,
@ -64,7 +64,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
}) })
ID++ ID++
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.UserJoined, Activity: activity.UserJoined,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,
@ -74,7 +74,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
}) })
ID++ ID++
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.GroupCreated, Activity: activity.GroupCreated,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,
@ -84,7 +84,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
}) })
ID++ ID++
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.SetupKeyUpdated, Activity: activity.SetupKeyUpdated,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,
@ -94,7 +94,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
}) })
ID++ ID++
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.SetupKeyUpdated, Activity: activity.SetupKeyUpdated,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,
@ -104,7 +104,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
}) })
ID++ ID++
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.SetupKeyRevoked, Activity: activity.SetupKeyRevoked,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,
@ -114,7 +114,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
}) })
ID++ ID++
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.SetupKeyOverused, Activity: activity.SetupKeyOverused,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,
@ -124,7 +124,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
}) })
ID++ ID++
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.SetupKeyCreated, Activity: activity.SetupKeyCreated,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,
@ -134,7 +134,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
}) })
ID++ ID++
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.RuleAdded, Activity: activity.RuleAdded,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,
@ -144,7 +144,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
}) })
ID++ ID++
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.RuleRemoved, Activity: activity.RuleRemoved,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,
@ -154,7 +154,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
}) })
ID++ ID++
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.RuleUpdated, Activity: activity.RuleUpdated,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,
@ -164,7 +164,7 @@ func generateEvents(accountID, userID string) []*activity.Event {
}) })
ID++ ID++
events = append(events, &activity.Event{ events = append(events, &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
Activity: activity.PeerAddedWithSetupKey, Activity: activity.PeerAddedWithSetupKey,
ID: ID, ID: ID,
InitiatorID: userID, InitiatorID: userID,

View File

@ -117,7 +117,7 @@ func (m *AuthMiddleware) CheckPATFromRequest(w http.ResponseWriter, r *http.Requ
if err != nil { if err != nil {
return fmt.Errorf("invalid Token: %w", err) return fmt.Errorf("invalid Token: %w", err)
} }
if time.Now().After(pat.ExpirationDate) { if time.Now().UTC().After(pat.ExpirationDate) {
return fmt.Errorf("token expired") return fmt.Errorf("token expired")
} }

View File

@ -34,10 +34,10 @@ var testAccount = &server.Account{
ID: tokenID, ID: tokenID,
Name: "My first token", Name: "My first token",
HashedToken: "someHash", HashedToken: "someHash",
ExpirationDate: time.Now().AddDate(0, 0, 7), ExpirationDate: time.Now().UTC().AddDate(0, 0, 7),
CreatedBy: userID, CreatedBy: userID,
CreatedAt: time.Now(), CreatedAt: time.Now().UTC(),
LastUsed: time.Now(), LastUsed: time.Now().UTC(),
}, },
}, },
}, },

View File

@ -41,19 +41,19 @@ var testAccount = &server.Account{
ID: existingTokenID, ID: existingTokenID,
Name: "My first token", Name: "My first token",
HashedToken: "someHash", HashedToken: "someHash",
ExpirationDate: time.Now().AddDate(0, 0, 7), ExpirationDate: time.Now().UTC().AddDate(0, 0, 7),
CreatedBy: existingUserID, CreatedBy: existingUserID,
CreatedAt: time.Now(), CreatedAt: time.Now().UTC(),
LastUsed: time.Now(), LastUsed: time.Now().UTC(),
}, },
"token2": { "token2": {
ID: "token2", ID: "token2",
Name: "My second token", Name: "My second token",
HashedToken: "someOtherHash", HashedToken: "someOtherHash",
ExpirationDate: time.Now().AddDate(0, 0, 7), ExpirationDate: time.Now().UTC().AddDate(0, 0, 7),
CreatedBy: existingUserID, CreatedBy: existingUserID,
CreatedAt: time.Now(), CreatedAt: time.Now().UTC(),
LastUsed: time.Now(), LastUsed: time.Now().UTC(),
}, },
}, },
}, },

View File

@ -6,7 +6,6 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/netbirdio/netbird/management/server/telemetry"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
@ -15,6 +14,8 @@ import (
"sync" "sync"
"time" "time"
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/golang-jwt/jwt" "github.com/golang-jwt/jwt"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
@ -151,7 +152,7 @@ func NewAuth0Manager(config Auth0ClientConfig, appMetrics telemetry.AppMetrics)
// jwtStillValid returns true if the token still valid and have enough time to be used and get a response from Auth0 // jwtStillValid returns true if the token still valid and have enough time to be used and get a response from Auth0
func (c *Auth0Credentials) jwtStillValid() bool { func (c *Auth0Credentials) jwtStillValid() bool {
return !c.jwtToken.expiresInTime.IsZero() && time.Now().Add(5*time.Second).Before(c.jwtToken.expiresInTime) return !c.jwtToken.expiresInTime.IsZero() && time.Now().UTC().Add(5*time.Second).Before(c.jwtToken.expiresInTime)
} }
// requestJWTToken performs request to get jwt token // requestJWTToken performs request to get jwt token

View File

@ -3,14 +3,16 @@ package idp
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/stretchr/testify/require"
"io" "io"
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/golang-jwt/jwt" "github.com/golang-jwt/jwt"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -63,7 +65,7 @@ func (mc *mockAuth0Credentials) Authenticate() (JWTToken, error) {
} }
func newTestJWT(t *testing.T, expInt int) string { func newTestJWT(t *testing.T, expInt int) string {
now := time.Now() now := time.Now().UTC()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"iat": now.Unix(), "iat": now.Unix(),
"exp": now.Add(time.Duration(expInt) * time.Second).Unix(), "exp": now.Add(time.Duration(expInt) * time.Second).Unix(),
@ -207,13 +209,13 @@ func TestAuth0_JwtStillValid(t *testing.T) {
} }
jwtStillValidTestCase1 := jwtStillValidTest{ jwtStillValidTestCase1 := jwtStillValidTest{
name: "JWT still valid", name: "JWT still valid",
inputTime: time.Now().Add(10 * time.Second), inputTime: time.Now().UTC().Add(10 * time.Second),
expectedResult: true, expectedResult: true,
message: "should be true", message: "should be true",
} }
jwtStillValidTestCase2 := jwtStillValidTest{ jwtStillValidTestCase2 := jwtStillValidTest{
name: "JWT is invalid", name: "JWT is invalid",
inputTime: time.Now(), inputTime: time.Now().UTC(),
expectedResult: false, expectedResult: false,
message: "should be false", message: "should be false",
} }
@ -249,7 +251,7 @@ func TestAuth0_Authenticate(t *testing.T) {
authenticateTestCase1 := authenticateTest{ authenticateTestCase1 := authenticateTest{
name: "Get Cached token", name: "Get Cached token",
inputExpireToken: time.Now().Add(30 * time.Second), inputExpireToken: time.Now().UTC().Add(30 * time.Second),
helper: JsonParser{}, helper: JsonParser{},
// expectedFuncExitErrDiff: fmt.Errorf("unable to get token, statusCode 400"), // expectedFuncExitErrDiff: fmt.Errorf("unable to get token, statusCode 400"),
expectedCode: 200, expectedCode: 200,

View File

@ -13,8 +13,9 @@ import (
"time" "time"
"github.com/golang-jwt/jwt" "github.com/golang-jwt/jwt"
"github.com/netbirdio/netbird/management/server/telemetry"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/management/server/telemetry"
) )
const ( const (
@ -118,7 +119,7 @@ func NewKeycloakManager(config KeycloakClientConfig, appMetrics telemetry.AppMet
// jwtStillValid returns true if the token still valid and have enough time to be used and get a response from keycloak. // jwtStillValid returns true if the token still valid and have enough time to be used and get a response from keycloak.
func (kc *KeycloakCredentials) jwtStillValid() bool { func (kc *KeycloakCredentials) jwtStillValid() bool {
return !kc.jwtToken.expiresInTime.IsZero() && time.Now().Add(5*time.Second).Before(kc.jwtToken.expiresInTime) return !kc.jwtToken.expiresInTime.IsZero() && time.Now().UTC().Add(5*time.Second).Before(kc.jwtToken.expiresInTime)
} }
// requestJWTToken performs request to get jwt token. // requestJWTToken performs request to get jwt token.

View File

@ -7,9 +7,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/netbirdio/netbird/management/server/telemetry"
) )
func TestNewKeycloakManager(t *testing.T) { func TestNewKeycloakManager(t *testing.T) {
@ -198,13 +199,13 @@ func TestKeycloakJwtStillValid(t *testing.T) {
jwtStillValidTestCase1 := jwtStillValidTest{ jwtStillValidTestCase1 := jwtStillValidTest{
name: "JWT still valid", name: "JWT still valid",
inputTime: time.Now().Add(10 * time.Second), inputTime: time.Now().UTC().Add(10 * time.Second),
expectedResult: true, expectedResult: true,
message: "should be true", message: "should be true",
} }
jwtStillValidTestCase2 := jwtStillValidTest{ jwtStillValidTestCase2 := jwtStillValidTest{
name: "JWT is invalid", name: "JWT is invalid",
inputTime: time.Now(), inputTime: time.Now().UTC(),
expectedResult: false, expectedResult: false,
message: "should be false", message: "should be false",
} }
@ -239,7 +240,7 @@ func TestKeycloakAuthenticate(t *testing.T) {
authenticateTestCase1 := authenticateTest{ authenticateTestCase1 := authenticateTest{
name: "Get Cached token", name: "Get Cached token",
inputExpireToken: time.Now().Add(30 * time.Second), inputExpireToken: time.Now().UTC().Add(30 * time.Second),
helper: JsonParser{}, helper: JsonParser{},
expectedFuncExitErrDiff: nil, expectedFuncExitErrDiff: nil,
expectedCode: 200, expectedCode: 200,

View File

@ -12,20 +12,23 @@ import (
"github.com/netbirdio/netbird/management/server/activity" "github.com/netbirdio/netbird/management/server/activity"
server "github.com/netbirdio/netbird/management/server"
"google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/credentials/insecure"
"github.com/netbirdio/netbird/management/server"
pb "github.com/golang/protobuf/proto" //nolint pb "github.com/golang/protobuf/proto" //nolint
"github.com/netbirdio/netbird/encryption"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
mgmtProto "github.com/netbirdio/netbird/management/proto" "github.com/netbirdio/netbird/encryption"
"github.com/netbirdio/netbird/util"
. "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes" "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"google.golang.org/grpc" "google.golang.org/grpc"
"google.golang.org/grpc/keepalive" "google.golang.org/grpc/keepalive"
mgmtProto "github.com/netbirdio/netbird/management/proto"
"github.com/netbirdio/netbird/util"
) )
const ( const (
@ -368,7 +371,7 @@ var _ = Describe("Management service", func() {
for i := 0; i < additionalPeers; i++ { for i := 0; i < additionalPeers; i++ {
key, _ := wgtypes.GenerateKey() key, _ := wgtypes.GenerateKey()
loginPeerWithValidSetupKey(serverPubKey, key, client) loginPeerWithValidSetupKey(serverPubKey, key, client)
rand.Seed(time.Now().UnixNano()) rand.Seed(time.Now().UTC().UnixNano())
n := rand.Intn(200) n := rand.Intn(200)
time.Sleep(time.Duration(n) * time.Millisecond) time.Sleep(time.Duration(n) * time.Millisecond)
} }

View File

@ -67,7 +67,7 @@ type Worker struct {
// NewWorker returns a metrics worker // NewWorker returns a metrics worker
func NewWorker(ctx context.Context, id string, dataSource DataSource, connManager ConnManager) *Worker { func NewWorker(ctx context.Context, id string, dataSource DataSource, connManager ConnManager) *Worker {
currentTime := time.Now() currentTime := time.Now().UTC()
return &Worker{ return &Worker{
ctx: ctx, ctx: ctx,
id: id, id: id,
@ -90,7 +90,7 @@ func (w *Worker) Run() {
if err != nil { if err != nil {
log.Error(err) log.Error(err)
} }
w.lastRun = time.Now() w.lastRun = time.Now().UTC()
} }
} }
} }
@ -149,7 +149,7 @@ func (w *Worker) generatePayload(apiKey string) pushPayload {
DistinctID: w.id, DistinctID: w.id,
Event: PayloadEvent, Event: PayloadEvent,
Properties: properties, Properties: properties,
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
} }
} }
@ -172,7 +172,7 @@ func (w *Worker) generateProperties() properties {
peerActiveVersions []string peerActiveVersions []string
osUIClients map[string]int osUIClients map[string]int
) )
start := time.Now() start := time.Now().UTC()
metricsProperties := make(properties) metricsProperties := make(properties)
osPeers = make(map[string]int) osPeers = make(map[string]int)
osUIClients = make(map[string]int) osUIClients = make(map[string]int)

View File

@ -1,15 +1,17 @@
package server package server
import ( import (
"github.com/c-robinson/iplib"
nbdns "github.com/netbirdio/netbird/dns"
"github.com/netbirdio/netbird/management/server/status"
"github.com/netbirdio/netbird/route"
"github.com/rs/xid"
"math/rand" "math/rand"
"net" "net"
"sync" "sync"
"time" "time"
"github.com/c-robinson/iplib"
"github.com/rs/xid"
nbdns "github.com/netbirdio/netbird/dns"
"github.com/netbirdio/netbird/management/server/status"
"github.com/netbirdio/netbird/route"
) )
const ( const (
@ -48,7 +50,7 @@ func NewNetwork() *Network {
n := iplib.NewNet4(net.ParseIP("100.64.0.0"), NetSize) n := iplib.NewNet4(net.ParseIP("100.64.0.0"), NetSize)
sub, _ := n.Subnet(SubnetSize) sub, _ := n.Subnet(SubnetSize)
s := rand.NewSource(time.Now().Unix()) s := rand.NewSource(time.Now().UTC().Unix())
r := rand.New(s) r := rand.New(s)
intn := r.Intn(len(sub)) intn := r.Intn(len(sub))
@ -99,7 +101,7 @@ func AllocatePeerIP(ipNet net.IPNet, takenIps []net.IP) (net.IP, error) {
} }
// pick a random IP // pick a random IP
s := rand.NewSource(time.Now().Unix()) s := rand.NewSource(time.Now().UTC().Unix())
r := rand.New(s) r := rand.New(s)
intn := r.Intn(len(ips)) intn := r.Intn(len(ips))

View File

@ -6,9 +6,10 @@ import (
"strings" "strings"
"time" "time"
"github.com/rs/xid"
"github.com/netbirdio/netbird/management/server/activity" "github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/status" "github.com/netbirdio/netbird/management/server/status"
"github.com/rs/xid"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
@ -143,7 +144,7 @@ func (p *Peer) LoginExpired(expiresIn time.Duration) (bool, time.Duration) {
return false, 0 return false, 0
} }
expiresAt := p.LastLogin.Add(expiresIn) expiresAt := p.LastLogin.Add(expiresIn)
now := time.Now() now := time.Now().UTC()
timeLeft := expiresAt.Sub(now) timeLeft := expiresAt.Sub(now)
return timeLeft <= 0, timeLeft return timeLeft <= 0, timeLeft
} }
@ -245,7 +246,7 @@ func (am *DefaultAccountManager) MarkPeerConnected(peerPubKey string, connected
oldStatus := peer.Status.Copy() oldStatus := peer.Status.Copy()
newStatus := oldStatus newStatus := oldStatus
newStatus.LastSeen = time.Now() newStatus.LastSeen = time.Now().UTC()
newStatus.Connected = connected newStatus.Connected = connected
// whenever peer got connected that means that it logged in successfully // whenever peer got connected that means that it logged in successfully
if newStatus.Connected { if newStatus.Connected {
@ -477,7 +478,7 @@ func (am *DefaultAccountManager) AddPeer(setupKey, userID string, peer *Peer) (*
} }
opEvent := &activity.Event{ opEvent := &activity.Event{
Timestamp: time.Now(), Timestamp: time.Now().UTC(),
AccountID: account.Id, AccountID: account.Id,
} }
@ -524,10 +525,10 @@ func (am *DefaultAccountManager) AddPeer(setupKey, userID string, peer *Peer) (*
Name: peer.Meta.Hostname, Name: peer.Meta.Hostname,
DNSLabel: newLabel, DNSLabel: newLabel,
UserID: userID, UserID: userID,
Status: &PeerStatus{Connected: false, LastSeen: time.Now()}, Status: &PeerStatus{Connected: false, LastSeen: time.Now().UTC()},
SSHEnabled: false, SSHEnabled: false,
SSHKey: peer.SSHKey, SSHKey: peer.SSHKey,
LastLogin: time.Now(), LastLogin: time.Now().UTC(),
LoginExpirationEnabled: addedByUser, LoginExpirationEnabled: addedByUser,
} }
@ -704,7 +705,7 @@ func updatePeerLastLogin(peer *Peer, account *Account) {
// UpdateLastLogin and set login expired false // UpdateLastLogin and set login expired false
func (p *Peer) UpdateLastLogin() *Peer { func (p *Peer) UpdateLastLogin() *Peer {
p.LastLogin = time.Now() p.LastLogin = time.Now().UTC()
newStatus := p.Status.Copy() newStatus := p.Status.Copy()
newStatus.LoginExpired = false newStatus.LoginExpired = false
p.Status = newStatus p.Status = newStatus

View File

@ -21,7 +21,7 @@ func TestPeer_LoginExpired(t *testing.T) {
{ {
name: "Peer Login Expiration Disabled. Peer Login Should Not Expire", name: "Peer Login Expiration Disabled. Peer Login Should Not Expire",
expirationEnabled: false, expirationEnabled: false,
lastLogin: time.Now().Add(-25 * time.Hour), lastLogin: time.Now().UTC().Add(-25 * time.Hour),
accountSettings: &Settings{ accountSettings: &Settings{
PeerLoginExpirationEnabled: true, PeerLoginExpirationEnabled: true,
PeerLoginExpiration: time.Hour, PeerLoginExpiration: time.Hour,
@ -31,7 +31,7 @@ func TestPeer_LoginExpired(t *testing.T) {
{ {
name: "Peer Login Should Expire", name: "Peer Login Should Expire",
expirationEnabled: true, expirationEnabled: true,
lastLogin: time.Now().Add(-25 * time.Hour), lastLogin: time.Now().UTC().Add(-25 * time.Hour),
accountSettings: &Settings{ accountSettings: &Settings{
PeerLoginExpirationEnabled: true, PeerLoginExpirationEnabled: true,
PeerLoginExpiration: time.Hour, PeerLoginExpiration: time.Hour,
@ -41,7 +41,7 @@ func TestPeer_LoginExpired(t *testing.T) {
{ {
name: "Peer Login Should Not Expire", name: "Peer Login Should Not Expire",
expirationEnabled: true, expirationEnabled: true,
lastLogin: time.Now(), lastLogin: time.Now().UTC(),
accountSettings: &Settings{ accountSettings: &Settings{
PeerLoginExpirationEnabled: true, PeerLoginExpirationEnabled: true,
PeerLoginExpiration: time.Hour, PeerLoginExpiration: time.Hour,

View File

@ -1,15 +1,17 @@
package server package server
import ( import (
"github.com/google/uuid"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/status"
log "github.com/sirupsen/logrus"
"hash/fnv" "hash/fnv"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"unicode/utf8" "unicode/utf8"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/netbirdio/netbird/management/server/status"
) )
const ( const (
@ -130,7 +132,7 @@ func (key *SetupKey) HiddenCopy(length int) *SetupKey {
func (key *SetupKey) IncrementUsage() *SetupKey { func (key *SetupKey) IncrementUsage() *SetupKey {
c := key.Copy() c := key.Copy()
c.UsedTimes = c.UsedTimes + 1 c.UsedTimes = c.UsedTimes + 1
c.LastUsed = time.Now() c.LastUsed = time.Now().UTC()
return c return c
} }
@ -146,7 +148,7 @@ func (key *SetupKey) IsRevoked() bool {
// IsExpired if key was expired // IsExpired if key was expired
func (key *SetupKey) IsExpired() bool { func (key *SetupKey) IsExpired() bool {
return time.Now().After(key.ExpiresAt) return time.Now().UTC().After(key.ExpiresAt)
} }
// IsOverUsed if the key was used too many times. SetupKey.UsageLimit == 0 indicates the unlimited usage. // IsOverUsed if the key was used too many times. SetupKey.UsageLimit == 0 indicates the unlimited usage.
@ -171,9 +173,9 @@ func GenerateSetupKey(name string, t SetupKeyType, validFor time.Duration, autoG
Key: key, Key: key,
Name: name, Name: name,
Type: t, Type: t,
CreatedAt: time.Now(), CreatedAt: time.Now().UTC(),
ExpiresAt: time.Now().Add(validFor), ExpiresAt: time.Now().UTC().Add(validFor),
UpdatedAt: time.Now(), UpdatedAt: time.Now().UTC(),
Revoked: false, Revoked: false,
UsedTimes: 0, UsedTimes: 0,
AutoGroups: autoGroups, AutoGroups: autoGroups,
@ -274,7 +276,7 @@ func (am *DefaultAccountManager) SaveSetupKey(accountID string, keyToSave *Setup
newKey.Name = keyToSave.Name newKey.Name = keyToSave.Name
newKey.AutoGroups = keyToSave.AutoGroups newKey.AutoGroups = keyToSave.AutoGroups
newKey.Revoked = keyToSave.Revoked newKey.Revoked = keyToSave.Revoked
newKey.UpdatedAt = time.Now() newKey.UpdatedAt = time.Now().UTC()
account.SetupKeys[newKey.Key] = newKey account.SetupKeys[newKey.Key] = newKey

View File

@ -2,12 +2,14 @@ package server
import ( import (
"fmt" "fmt"
"github.com/google/uuid"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/stretchr/testify/assert"
"strconv" "strconv"
"testing" "testing"
"time" "time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/netbirdio/netbird/management/server/activity"
) )
func TestDefaultAccountManager_SaveSetupKey(t *testing.T) { func TestDefaultAccountManager_SaveSetupKey(t *testing.T) {
@ -54,7 +56,7 @@ func TestDefaultAccountManager_SaveSetupKey(t *testing.T) {
} }
assertKey(t, newKey, newKeyName, revoked, "reusable", 0, key.CreatedAt, key.ExpiresAt, assertKey(t, newKey, newKeyName, revoked, "reusable", 0, key.CreatedAt, key.ExpiresAt,
key.Id, time.Now(), autoGroups) key.Id, time.Now().UTC(), autoGroups)
// check the corresponding events that should have been generated // check the corresponding events that should have been generated
ev := getEvent(t, account.Id, manager, activity.SetupKeyRevoked) ev := getEvent(t, account.Id, manager, activity.SetupKeyRevoked)
@ -111,7 +113,7 @@ func TestDefaultAccountManager_CreateSetupKey(t *testing.T) {
expectedFailure bool // indicates whether key creation should fail expectedFailure bool // indicates whether key creation should fail
} }
now := time.Now() now := time.Now().UTC()
expiresIn := time.Hour expiresIn := time.Hour
testCase1 := testCase{ testCase1 := testCase{
name: "Should Create Setup Key successfully", name: "Should Create Setup Key successfully",
@ -169,9 +171,9 @@ func TestGenerateDefaultSetupKey(t *testing.T) {
expectedRevoke := false expectedRevoke := false
expectedType := "reusable" expectedType := "reusable"
expectedUsedTimes := 0 expectedUsedTimes := 0
expectedCreatedAt := time.Now() expectedCreatedAt := time.Now().UTC()
expectedUpdatedAt := time.Now() expectedUpdatedAt := time.Now().UTC()
expectedExpiresAt := time.Now().Add(24 * 30 * time.Hour) expectedExpiresAt := time.Now().UTC().Add(24 * 30 * time.Hour)
var expectedAutoGroups []string var expectedAutoGroups []string
key := GenerateDefaultSetupKey() key := GenerateDefaultSetupKey()
@ -186,9 +188,9 @@ func TestGenerateSetupKey(t *testing.T) {
expectedRevoke := false expectedRevoke := false
expectedType := "one-off" expectedType := "one-off"
expectedUsedTimes := 0 expectedUsedTimes := 0
expectedCreatedAt := time.Now() expectedCreatedAt := time.Now().UTC()
expectedExpiresAt := time.Now().Add(time.Hour) expectedExpiresAt := time.Now().UTC().Add(time.Hour)
expectedUpdatedAt := time.Now() expectedUpdatedAt := time.Now().UTC()
var expectedAutoGroups []string var expectedAutoGroups []string
key := GenerateSetupKey(expectedName, SetupKeyOneOff, time.Hour, []string{}, SetupKeyUnlimitedUsage) key := GenerateSetupKey(expectedName, SetupKeyOneOff, time.Hour, []string{}, SetupKeyUnlimitedUsage)

View File

@ -5,10 +5,12 @@ import (
"crypto/sha1" "crypto/sha1"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"github.com/netbirdio/netbird/management/proto"
log "github.com/sirupsen/logrus"
"sync" "sync"
"time" "time"
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/management/proto"
) )
// TURNCredentialsManager used to manage TURN credentials // TURNCredentialsManager used to manage TURN credentials
@ -44,7 +46,7 @@ func NewTimeBasedAuthSecretsManager(updateManager *PeersUpdateManager, config *T
func (m *TimeBasedAuthSecretsManager) GenerateCredentials() TURNCredentials { func (m *TimeBasedAuthSecretsManager) GenerateCredentials() TURNCredentials {
mac := hmac.New(sha1.New, []byte(m.config.Secret)) mac := hmac.New(sha1.New, []byte(m.config.Secret))
timeAuth := time.Now().Add(m.config.CredentialsTTL.Duration).Unix() timeAuth := time.Now().UTC().Add(m.config.CredentialsTTL.Duration).Unix()
username := fmt.Sprint(timeAuth) username := fmt.Sprint(timeAuth)