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")
}
pat.LastUsed = time.Now()
pat.LastUsed = time.Now().UTC()
return am.Store.SaveAccount(account)
}

View File

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

View File

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

View File

@ -2,9 +2,11 @@ package server
import (
"fmt"
"github.com/netbirdio/netbird/management/server/activity"
log "github.com/sirupsen/logrus"
"time"
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/management/server/activity"
)
// GetEvents returns a list of activity events of an account
@ -39,7 +41,7 @@ func (am *DefaultAccountManager) storeEvent(initiatorID, targetID, accountID str
go func() {
_, err := am.eventStore.Save(&activity.Event{
Timestamp: time.Now(),
Timestamp: time.Now().UTC(),
Activity: activityID,
InitiatorID: initiatorID,
TargetID: targetID,
@ -47,7 +49,7 @@ func (am *DefaultAccountManager) storeEvent(initiatorID, targetID, accountID str
Meta: meta,
})
if err != nil {
//todo add metric
// todo add metric
log.Errorf("received an error while storing an activity event, error: %s", err)
}
}()

View File

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

View File

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

View File

@ -95,7 +95,7 @@ func TestSaveAccount(t *testing.T) {
IP: net.IP{127, 0, 0, 1},
Meta: PeerSystemMeta{},
Name: "peer name",
Status: &PeerStatus{Connected: true, LastSeen: time.Now()},
Status: &PeerStatus{Connected: true, LastSeen: time.Now().UTC()},
}
// SaveAccount should trigger persist
@ -131,7 +131,7 @@ func TestStore(t *testing.T) {
IP: net.IP{127, 0, 0, 1},
Meta: PeerSystemMeta{},
Name: "peer name",
Status: &PeerStatus{Connected: true, LastSeen: time.Now()},
Status: &PeerStatus{Connected: true, LastSeen: time.Now().UTC()},
}
account.Groups["all"] = &Group{
ID: "all",
@ -514,7 +514,7 @@ func TestFileStore_SavePeerStatus(t *testing.T) {
}
// 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)
assert.Error(t, err)
@ -526,7 +526,7 @@ func TestFileStore_SavePeerStatus(t *testing.T) {
IP: net.IP{127, 0, 0, 1},
Meta: PeerSystemMeta{},
Name: "peer name",
Status: &PeerStatus{Connected: false, LastSeen: time.Now()},
Status: &PeerStatus{Connected: false, LastSeen: time.Now().UTC()},
}
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 {
s.appMetrics.GRPCMetrics().CountGetKeyRequest()
}
now := time.Now().Add(24 * time.Hour)
now := time.Now().UTC().Add(24 * time.Hour)
secs := int64(now.Second())
nanos := int32(now.Nanosecond())
expiresAt := &timestamp.Timestamp{Seconds: secs, Nanos: nanos}

View File

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

View File

@ -117,7 +117,7 @@ func (m *AuthMiddleware) CheckPATFromRequest(w http.ResponseWriter, r *http.Requ
if err != nil {
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")
}

View File

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

View File

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

View File

@ -6,7 +6,6 @@ import (
"context"
"encoding/json"
"fmt"
"github.com/netbirdio/netbird/management/server/telemetry"
"io"
"net/http"
"net/url"
@ -15,6 +14,8 @@ import (
"sync"
"time"
"github.com/netbirdio/netbird/management/server/telemetry"
"github.com/golang-jwt/jwt"
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
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

View File

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

View File

@ -13,8 +13,9 @@ import (
"time"
"github.com/golang-jwt/jwt"
"github.com/netbirdio/netbird/management/server/telemetry"
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/management/server/telemetry"
)
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.
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.

View File

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

View File

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

View File

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

View File

@ -1,15 +1,17 @@
package server
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"
"net"
"sync"
"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 (
@ -48,7 +50,7 @@ func NewNetwork() *Network {
n := iplib.NewNet4(net.ParseIP("100.64.0.0"), NetSize)
sub, _ := n.Subnet(SubnetSize)
s := rand.NewSource(time.Now().Unix())
s := rand.NewSource(time.Now().UTC().Unix())
r := rand.New(s)
intn := r.Intn(len(sub))
@ -99,7 +101,7 @@ func AllocatePeerIP(ipNet net.IPNet, takenIps []net.IP) (net.IP, error) {
}
// pick a random IP
s := rand.NewSource(time.Now().Unix())
s := rand.NewSource(time.Now().UTC().Unix())
r := rand.New(s)
intn := r.Intn(len(ips))

View File

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

View File

@ -1,15 +1,17 @@
package server
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"
"strconv"
"strings"
"time"
"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 (
@ -130,7 +132,7 @@ func (key *SetupKey) HiddenCopy(length int) *SetupKey {
func (key *SetupKey) IncrementUsage() *SetupKey {
c := key.Copy()
c.UsedTimes = c.UsedTimes + 1
c.LastUsed = time.Now()
c.LastUsed = time.Now().UTC()
return c
}
@ -146,7 +148,7 @@ func (key *SetupKey) IsRevoked() bool {
// IsExpired if key was expired
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.
@ -171,9 +173,9 @@ func GenerateSetupKey(name string, t SetupKeyType, validFor time.Duration, autoG
Key: key,
Name: name,
Type: t,
CreatedAt: time.Now(),
ExpiresAt: time.Now().Add(validFor),
UpdatedAt: time.Now(),
CreatedAt: time.Now().UTC(),
ExpiresAt: time.Now().UTC().Add(validFor),
UpdatedAt: time.Now().UTC(),
Revoked: false,
UsedTimes: 0,
AutoGroups: autoGroups,
@ -274,7 +276,7 @@ func (am *DefaultAccountManager) SaveSetupKey(accountID string, keyToSave *Setup
newKey.Name = keyToSave.Name
newKey.AutoGroups = keyToSave.AutoGroups
newKey.Revoked = keyToSave.Revoked
newKey.UpdatedAt = time.Now()
newKey.UpdatedAt = time.Now().UTC()
account.SetupKeys[newKey.Key] = newKey

View File

@ -2,12 +2,14 @@ package server
import (
"fmt"
"github.com/google/uuid"
"github.com/netbirdio/netbird/management/server/activity"
"github.com/stretchr/testify/assert"
"strconv"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/netbirdio/netbird/management/server/activity"
)
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,
key.Id, time.Now(), autoGroups)
key.Id, time.Now().UTC(), autoGroups)
// check the corresponding events that should have been generated
ev := getEvent(t, account.Id, manager, activity.SetupKeyRevoked)
@ -108,10 +110,10 @@ func TestDefaultAccountManager_CreateSetupKey(t *testing.T) {
expectedCreatedAt time.Time
expectedUpdatedAt time.Time
expectedExpiresAt time.Time
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
testCase1 := testCase{
name: "Should Create Setup Key successfully",
@ -169,9 +171,9 @@ func TestGenerateDefaultSetupKey(t *testing.T) {
expectedRevoke := false
expectedType := "reusable"
expectedUsedTimes := 0
expectedCreatedAt := time.Now()
expectedUpdatedAt := time.Now()
expectedExpiresAt := time.Now().Add(24 * 30 * time.Hour)
expectedCreatedAt := time.Now().UTC()
expectedUpdatedAt := time.Now().UTC()
expectedExpiresAt := time.Now().UTC().Add(24 * 30 * time.Hour)
var expectedAutoGroups []string
key := GenerateDefaultSetupKey()
@ -186,9 +188,9 @@ func TestGenerateSetupKey(t *testing.T) {
expectedRevoke := false
expectedType := "one-off"
expectedUsedTimes := 0
expectedCreatedAt := time.Now()
expectedExpiresAt := time.Now().Add(time.Hour)
expectedUpdatedAt := time.Now()
expectedCreatedAt := time.Now().UTC()
expectedExpiresAt := time.Now().UTC().Add(time.Hour)
expectedUpdatedAt := time.Now().UTC()
var expectedAutoGroups []string
key := GenerateSetupKey(expectedName, SetupKeyOneOff, time.Hour, []string{}, SetupKeyUnlimitedUsage)

View File

@ -5,10 +5,12 @@ import (
"crypto/sha1"
"encoding/base64"
"fmt"
"github.com/netbirdio/netbird/management/proto"
log "github.com/sirupsen/logrus"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/management/proto"
)
// TURNCredentialsManager used to manage TURN credentials
@ -44,7 +46,7 @@ func NewTimeBasedAuthSecretsManager(updateManager *PeersUpdateManager, config *T
func (m *TimeBasedAuthSecretsManager) GenerateCredentials() TURNCredentials {
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)
@ -88,7 +90,7 @@ func (m *TimeBasedAuthSecretsManager) SetupRefresh(peerID string) {
log.Debugf("starting turn refresh for %s", peerID)
go func() {
//we don't want to regenerate credentials right on expiration, so we do it slightly before (at 3/4 of TTL)
// we don't want to regenerate credentials right on expiration, so we do it slightly before (at 3/4 of TTL)
ticker := time.NewTicker(m.config.CredentialsTTL.Duration / 4 * 3)
for {