2021-07-30 17:46:38 +02:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2022-06-05 21:36:42 +02:00
|
|
|
"context"
|
2022-05-09 14:30:20 +02:00
|
|
|
"fmt"
|
2022-10-13 18:26:31 +02:00
|
|
|
"github.com/eko/gocache/v3/cache"
|
|
|
|
cacheStore "github.com/eko/gocache/v3/store"
|
2022-09-30 13:47:11 +02:00
|
|
|
nbdns "github.com/netbirdio/netbird/dns"
|
2022-03-26 12:08:54 +01:00
|
|
|
"github.com/netbirdio/netbird/management/server/idp"
|
|
|
|
"github.com/netbirdio/netbird/management/server/jwtclaims"
|
2022-08-18 18:22:15 +02:00
|
|
|
"github.com/netbirdio/netbird/route"
|
2022-06-05 21:36:42 +02:00
|
|
|
gocache "github.com/patrickmn/go-cache"
|
2021-12-27 13:17:15 +01:00
|
|
|
"github.com/rs/xid"
|
2021-08-01 19:06:01 +02:00
|
|
|
log "github.com/sirupsen/logrus"
|
2021-07-30 17:46:38 +02:00
|
|
|
"google.golang.org/grpc/codes"
|
|
|
|
"google.golang.org/grpc/status"
|
2022-06-06 12:05:44 +02:00
|
|
|
"math/rand"
|
2022-11-07 12:10:56 +01:00
|
|
|
"net/netip"
|
2022-06-05 21:36:42 +02:00
|
|
|
"reflect"
|
2022-09-29 10:51:18 +02:00
|
|
|
"regexp"
|
2022-06-05 21:36:42 +02:00
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
2021-07-30 17:46:38 +02:00
|
|
|
)
|
|
|
|
|
2022-03-01 15:22:18 +01:00
|
|
|
const (
|
2022-06-06 12:05:44 +02:00
|
|
|
PublicCategory = "public"
|
|
|
|
PrivateCategory = "private"
|
|
|
|
UnknownCategory = "unknown"
|
|
|
|
CacheExpirationMax = 7 * 24 * 3600 * time.Second // 7 days
|
|
|
|
CacheExpirationMin = 3 * 24 * 3600 * time.Second // 3 days
|
2022-03-01 15:22:18 +01:00
|
|
|
)
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
func cacheEntryExpiration() time.Duration {
|
|
|
|
r := rand.Intn(int(CacheExpirationMax.Milliseconds()-CacheExpirationMin.Milliseconds())) + int(CacheExpirationMin.Milliseconds())
|
|
|
|
return time.Duration(r) * time.Millisecond
|
|
|
|
}
|
|
|
|
|
2022-02-22 11:28:19 +01:00
|
|
|
type AccountManager interface {
|
|
|
|
GetOrCreateAccountByUser(userId, domain string) (*Account, error)
|
|
|
|
GetAccountByUser(userId string) (*Account, error)
|
2022-09-11 23:16:40 +02:00
|
|
|
CreateSetupKey(
|
2022-05-21 15:21:39 +02:00
|
|
|
accountId string,
|
|
|
|
keyName string,
|
|
|
|
keyType SetupKeyType,
|
2022-06-14 10:32:54 +02:00
|
|
|
expiresIn time.Duration,
|
2022-09-11 23:16:40 +02:00
|
|
|
autoGroups []string,
|
2022-05-21 15:21:39 +02:00
|
|
|
) (*SetupKey, error)
|
2022-09-11 23:16:40 +02:00
|
|
|
SaveSetupKey(accountID string, key *SetupKey) (*SetupKey, error)
|
2022-10-13 18:26:31 +02:00
|
|
|
CreateUser(accountID string, key *UserInfo) (*UserInfo, error)
|
2022-11-05 10:24:50 +01:00
|
|
|
ListSetupKeys(accountID, userID string) ([]*SetupKey, error)
|
2022-09-22 09:06:32 +02:00
|
|
|
SaveUser(accountID string, key *User) (*UserInfo, error)
|
2022-11-05 10:24:50 +01:00
|
|
|
GetSetupKey(accountID, userID, keyID string) (*SetupKey, error)
|
2022-02-22 11:28:19 +01:00
|
|
|
GetAccountById(accountId string) (*Account, error)
|
|
|
|
GetAccountByUserOrAccountId(userId, accountId, domain string) (*Account, error)
|
2022-10-13 18:26:31 +02:00
|
|
|
GetAccountFromToken(claims jwtclaims.AuthorizationClaims) (*Account, error)
|
2022-05-25 18:26:50 +02:00
|
|
|
IsUserAdmin(claims jwtclaims.AuthorizationClaims) (bool, error)
|
2022-02-22 11:28:19 +01:00
|
|
|
AccountExists(accountId string) (*bool, error)
|
|
|
|
GetPeer(peerKey string) (*Peer, error)
|
2022-11-05 10:24:50 +01:00
|
|
|
GetPeers(accountID, userID string) ([]*Peer, error)
|
2022-02-22 11:28:19 +01:00
|
|
|
MarkPeerConnected(peerKey string, connected bool) error
|
|
|
|
DeletePeer(accountId string, peerKey string) (*Peer, error)
|
|
|
|
GetPeerByIP(accountId string, peerIP string) (*Peer, error)
|
2022-08-18 18:22:15 +02:00
|
|
|
UpdatePeer(accountID string, peer *Peer) (*Peer, error)
|
2022-02-22 11:28:19 +01:00
|
|
|
GetNetworkMap(peerKey string) (*NetworkMap, error)
|
2022-06-24 21:30:51 +02:00
|
|
|
GetPeerNetwork(peerKey string) (*Network, error)
|
2022-05-05 20:02:15 +02:00
|
|
|
AddPeer(setupKey string, userId string, peer *Peer) (*Peer, error)
|
2022-05-23 13:03:57 +02:00
|
|
|
UpdatePeerMeta(peerKey string, meta PeerSystemMeta) error
|
2022-06-23 17:04:53 +02:00
|
|
|
UpdatePeerSSHKey(peerKey string, sshKey string) error
|
2022-11-05 10:24:50 +01:00
|
|
|
GetUsersFromAccount(accountID, userID string) ([]*UserInfo, error)
|
2022-05-03 16:02:51 +02:00
|
|
|
GetGroup(accountId, groupID string) (*Group, error)
|
|
|
|
SaveGroup(accountId string, group *Group) error
|
2022-06-14 10:32:54 +02:00
|
|
|
UpdateGroup(accountID string, groupID string, operations []GroupUpdateOperation) (*Group, error)
|
2022-05-03 16:02:51 +02:00
|
|
|
DeleteGroup(accountId, groupID string) error
|
|
|
|
ListGroups(accountId string) ([]*Group, error)
|
|
|
|
GroupAddPeer(accountId, groupID, peerKey string) error
|
|
|
|
GroupDeletePeer(accountId, groupID, peerKey string) error
|
|
|
|
GroupListPeers(accountId, groupID string) ([]*Peer, error)
|
2022-11-05 10:24:50 +01:00
|
|
|
GetRule(accountID, ruleID, userID string) (*Rule, error)
|
2022-05-21 15:21:39 +02:00
|
|
|
SaveRule(accountID string, rule *Rule) error
|
2022-06-14 10:32:54 +02:00
|
|
|
UpdateRule(accountID string, ruleID string, operations []RuleUpdateOperation) (*Rule, error)
|
2022-05-21 15:21:39 +02:00
|
|
|
DeleteRule(accountId, ruleID string) error
|
2022-11-05 10:24:50 +01:00
|
|
|
ListRules(accountID, userID string) ([]*Rule, error)
|
|
|
|
GetRoute(accountID, routeID, userID string) (*route.Route, error)
|
2022-08-22 14:10:24 +02:00
|
|
|
CreateRoute(accountID string, prefix, peer, description, netID string, masquerade bool, metric int, enabled bool) (*route.Route, error)
|
2022-08-18 18:22:15 +02:00
|
|
|
SaveRoute(accountID string, route *route.Route) error
|
|
|
|
UpdateRoute(accountID string, routeID string, operations []RouteUpdateOperation) (*route.Route, error)
|
|
|
|
DeleteRoute(accountID, routeID string) error
|
2022-11-05 10:24:50 +01:00
|
|
|
ListRoutes(accountID, userID string) ([]*route.Route, error)
|
2022-09-30 13:47:11 +02:00
|
|
|
GetNameServerGroup(accountID, nsGroupID string) (*nbdns.NameServerGroup, error)
|
2022-11-03 18:39:37 +01:00
|
|
|
CreateNameServerGroup(accountID string, name, description string, nameServerList []nbdns.NameServer, groups []string, primary bool, domains []string, enabled bool) (*nbdns.NameServerGroup, error)
|
2022-09-30 13:47:11 +02:00
|
|
|
SaveNameServerGroup(accountID string, nsGroupToSave *nbdns.NameServerGroup) error
|
|
|
|
UpdateNameServerGroup(accountID, nsGroupID string, operations []NameServerGroupUpdateOperation) (*nbdns.NameServerGroup, error)
|
|
|
|
DeleteNameServerGroup(accountID, nsGroupID string) error
|
|
|
|
ListNameServerGroups(accountID string) ([]*nbdns.NameServerGroup, error)
|
2022-02-22 11:28:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
type DefaultAccountManager struct {
|
2021-07-30 17:46:38 +02:00
|
|
|
Store Store
|
2022-10-13 18:26:31 +02:00
|
|
|
// mux to synchronise account operations (e.g. generating Peer IP address inside the Network)
|
|
|
|
mux sync.Mutex
|
|
|
|
// cacheMux and cacheLoading helps to make sure that only a single cache reload runs at a time per accountID
|
|
|
|
cacheMux sync.Mutex
|
|
|
|
// cacheLoading keeps the accountIDs that are currently reloading. The accountID has to be removed once cache has been reloaded
|
|
|
|
cacheLoading map[string]chan struct{}
|
2021-09-07 18:36:46 +02:00
|
|
|
peersUpdateManager *PeersUpdateManager
|
2022-01-24 11:21:30 +01:00
|
|
|
idpManager idp.Manager
|
2022-10-13 18:26:31 +02:00
|
|
|
cacheManager cache.CacheInterface[[]*idp.UserData]
|
2022-06-05 21:36:42 +02:00
|
|
|
ctx context.Context
|
2022-10-19 17:43:28 +02:00
|
|
|
|
|
|
|
// singleAccountMode indicates whether the instance has a single account.
|
|
|
|
// If true, then every new user will end up under the same account.
|
|
|
|
// This value will be set to false if management service has more than one account.
|
|
|
|
singleAccountMode bool
|
|
|
|
// singleAccountModeDomain is a domain to use in singleAccountMode setup
|
|
|
|
singleAccountModeDomain string
|
2022-11-07 15:38:21 +01:00
|
|
|
// dnsDomain is used for peer resolution. This is appended to the peer's name
|
|
|
|
dnsDomain string
|
2021-07-30 17:46:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Account represents a unique account of the system
|
|
|
|
type Account struct {
|
2021-12-27 13:17:15 +01:00
|
|
|
Id string
|
|
|
|
// User.Id it was created by
|
2022-03-01 15:22:18 +01:00
|
|
|
CreatedBy string
|
|
|
|
Domain string
|
|
|
|
DomainCategory string
|
|
|
|
IsDomainPrimaryAccount bool
|
|
|
|
SetupKeys map[string]*SetupKey
|
|
|
|
Network *Network
|
|
|
|
Peers map[string]*Peer
|
|
|
|
Users map[string]*User
|
2022-05-03 16:02:51 +02:00
|
|
|
Groups map[string]*Group
|
2022-05-21 15:21:39 +02:00
|
|
|
Rules map[string]*Rule
|
2022-08-18 18:22:15 +02:00
|
|
|
Routes map[string]*route.Route
|
2022-09-30 13:47:11 +02:00
|
|
|
NameServerGroups map[string]*nbdns.NameServerGroup
|
2021-12-27 13:17:15 +01:00
|
|
|
}
|
|
|
|
|
2022-05-05 08:58:34 +02:00
|
|
|
type UserInfo struct {
|
2022-09-22 09:06:32 +02:00
|
|
|
ID string `json:"id"`
|
|
|
|
Email string `json:"email"`
|
|
|
|
Name string `json:"name"`
|
|
|
|
Role string `json:"role"`
|
|
|
|
AutoGroups []string `json:"auto_groups"`
|
2022-10-13 18:26:31 +02:00
|
|
|
Status string `json:"-"`
|
2022-05-05 08:58:34 +02:00
|
|
|
}
|
|
|
|
|
2022-11-07 12:10:56 +01:00
|
|
|
// GetPeersRoutes returns all active routes of provided peers
|
|
|
|
func (a *Account) GetPeersRoutes(givenPeers []*Peer) []*route.Route {
|
|
|
|
//TODO Peer.ID migration: we will need to replace search by Peer.ID here
|
|
|
|
routes := make([]*route.Route, 0)
|
|
|
|
for _, peer := range givenPeers {
|
|
|
|
peerRoutes := a.GetPeerRoutes(peer.Key)
|
|
|
|
activeRoutes := make([]*route.Route, 0)
|
|
|
|
for _, pr := range peerRoutes {
|
|
|
|
if pr.Enabled {
|
|
|
|
activeRoutes = append(activeRoutes, pr)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(activeRoutes) > 0 {
|
|
|
|
routes = append(routes, activeRoutes...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return routes
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetPeerRoutes returns a list of routes of a given peer
|
|
|
|
func (a *Account) GetPeerRoutes(peerPubKey string) []*route.Route {
|
|
|
|
//TODO Peer.ID migration: we will need to replace search by Peer.ID here
|
|
|
|
var routes []*route.Route
|
|
|
|
for _, r := range a.Routes {
|
|
|
|
if r.Peer == peerPubKey {
|
|
|
|
routes = append(routes, r)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return routes
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetRoutesByPrefix return list of routes by account and route prefix
|
|
|
|
func (a *Account) GetRoutesByPrefix(prefix netip.Prefix) []*route.Route {
|
|
|
|
|
|
|
|
var routes []*route.Route
|
|
|
|
for _, r := range a.Routes {
|
|
|
|
if r.Network.String() == prefix.String() {
|
|
|
|
routes = append(routes, r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return routes
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetPeerRules returns a list of source or destination rules of a given peer.
|
|
|
|
func (a *Account) GetPeerRules(peerPubKey string) (srcRules []*Rule, dstRules []*Rule) {
|
|
|
|
|
|
|
|
// Rules are group based so there is no direct access to peers.
|
|
|
|
// First, find all groups that the given peer belongs to
|
|
|
|
peerGroups := make(map[string]struct{})
|
|
|
|
|
|
|
|
for s, group := range a.Groups {
|
|
|
|
for _, peer := range group.Peers {
|
|
|
|
if peerPubKey == peer {
|
|
|
|
peerGroups[s] = struct{}{}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Second, find all rules that have discovered source and destination groups
|
|
|
|
srcRulesMap := make(map[string]*Rule)
|
|
|
|
dstRulesMap := make(map[string]*Rule)
|
|
|
|
for _, rule := range a.Rules {
|
|
|
|
for _, g := range rule.Source {
|
|
|
|
if _, ok := peerGroups[g]; ok && srcRulesMap[rule.ID] == nil {
|
|
|
|
srcRules = append(srcRules, rule)
|
|
|
|
srcRulesMap[rule.ID] = rule
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, g := range rule.Destination {
|
|
|
|
if _, ok := peerGroups[g]; ok && dstRulesMap[rule.ID] == nil {
|
|
|
|
dstRules = append(dstRules, rule)
|
|
|
|
dstRulesMap[rule.ID] = rule
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return srcRules, dstRules
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetPeers returns a list of all Account peers
|
|
|
|
func (a *Account) GetPeers() []*Peer {
|
|
|
|
var peers []*Peer
|
|
|
|
for _, peer := range a.Peers {
|
|
|
|
peers = append(peers, peer)
|
|
|
|
}
|
|
|
|
return peers
|
|
|
|
}
|
|
|
|
|
|
|
|
// UpdatePeer saves new or replaces existing peer
|
|
|
|
func (a *Account) UpdatePeer(update *Peer) {
|
|
|
|
//TODO Peer.ID migration: we will need to replace search by Peer.ID here
|
|
|
|
a.Peers[update.Key] = update
|
|
|
|
}
|
|
|
|
|
|
|
|
// DeletePeer deletes peer from the account cleaning up all the references
|
|
|
|
func (a *Account) DeletePeer(peerPubKey string) {
|
|
|
|
// TODO Peer.ID migration: we will need to replace search by Peer.ID here
|
|
|
|
|
|
|
|
// delete peer from groups
|
|
|
|
for _, g := range a.Groups {
|
|
|
|
for i, pk := range g.Peers {
|
|
|
|
if pk == peerPubKey {
|
|
|
|
g.Peers = append(g.Peers[:i], g.Peers[i+1:]...)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
delete(a.Peers, peerPubKey)
|
|
|
|
a.Network.IncSerial()
|
|
|
|
}
|
|
|
|
|
|
|
|
// FindPeerByPubKey looks for a Peer by provided WireGuard public key in the Account or returns error if it wasn't found.
|
|
|
|
// It will return an object copy of the peer.
|
|
|
|
func (a *Account) FindPeerByPubKey(peerPubKey string) (*Peer, error) {
|
|
|
|
for _, peer := range a.Peers {
|
|
|
|
if peer.Key == peerPubKey {
|
|
|
|
return peer.Copy(), nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, status.Errorf(codes.NotFound, "peer with the public key %s not found", peerPubKey)
|
|
|
|
}
|
|
|
|
|
2022-11-05 10:24:50 +01:00
|
|
|
// FindUser looks for a given user in the Account or returns error if user wasn't found.
|
|
|
|
func (a *Account) FindUser(userID string) (*User, error) {
|
|
|
|
user := a.Users[userID]
|
|
|
|
if user == nil {
|
|
|
|
return nil, Errorf(UserNotFound, "user %s not found", userID)
|
|
|
|
}
|
|
|
|
|
|
|
|
return user, nil
|
|
|
|
}
|
|
|
|
|
2022-11-07 15:38:21 +01:00
|
|
|
// getPeerDNSLabels return the account's peers' dns labels
|
|
|
|
func (a *Account) getPeerDNSLabels() lookupMap {
|
|
|
|
existingLabels := make(lookupMap)
|
|
|
|
for _, peer := range a.Peers {
|
|
|
|
if peer.DNSLabel != "" {
|
|
|
|
existingLabels[peer.DNSLabel] = struct{}{}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return existingLabels
|
|
|
|
}
|
|
|
|
|
2021-12-27 13:17:15 +01:00
|
|
|
func (a *Account) Copy() *Account {
|
|
|
|
peers := map[string]*Peer{}
|
|
|
|
for id, peer := range a.Peers {
|
|
|
|
peers[id] = peer.Copy()
|
|
|
|
}
|
|
|
|
|
|
|
|
users := map[string]*User{}
|
|
|
|
for id, user := range a.Users {
|
|
|
|
users[id] = user.Copy()
|
|
|
|
}
|
|
|
|
|
|
|
|
setupKeys := map[string]*SetupKey{}
|
|
|
|
for id, key := range a.SetupKeys {
|
|
|
|
setupKeys[id] = key.Copy()
|
|
|
|
}
|
|
|
|
|
2022-05-21 15:21:39 +02:00
|
|
|
groups := map[string]*Group{}
|
|
|
|
for id, group := range a.Groups {
|
|
|
|
groups[id] = group.Copy()
|
|
|
|
}
|
|
|
|
|
|
|
|
rules := map[string]*Rule{}
|
|
|
|
for id, rule := range a.Rules {
|
|
|
|
rules[id] = rule.Copy()
|
|
|
|
}
|
|
|
|
|
2022-09-30 13:47:11 +02:00
|
|
|
routes := map[string]*route.Route{}
|
|
|
|
for id, route := range a.Routes {
|
|
|
|
routes[id] = route.Copy()
|
|
|
|
}
|
|
|
|
|
|
|
|
nsGroups := map[string]*nbdns.NameServerGroup{}
|
|
|
|
for id, nsGroup := range a.NameServerGroups {
|
|
|
|
nsGroups[id] = nsGroup.Copy()
|
|
|
|
}
|
|
|
|
|
2021-12-27 13:17:15 +01:00
|
|
|
return &Account{
|
2022-11-07 12:10:56 +01:00
|
|
|
Id: a.Id,
|
|
|
|
CreatedBy: a.CreatedBy,
|
|
|
|
Domain: a.Domain,
|
|
|
|
DomainCategory: a.DomainCategory,
|
|
|
|
IsDomainPrimaryAccount: a.IsDomainPrimaryAccount,
|
|
|
|
SetupKeys: setupKeys,
|
|
|
|
Network: a.Network.Copy(),
|
|
|
|
Peers: peers,
|
|
|
|
Users: users,
|
|
|
|
Groups: groups,
|
|
|
|
Rules: rules,
|
|
|
|
Routes: routes,
|
|
|
|
NameServerGroups: nsGroups,
|
2021-12-27 13:17:15 +01:00
|
|
|
}
|
2021-07-30 17:46:38 +02:00
|
|
|
}
|
|
|
|
|
2022-05-21 15:21:39 +02:00
|
|
|
func (a *Account) GetGroupAll() (*Group, error) {
|
|
|
|
for _, g := range a.Groups {
|
|
|
|
if g.Name == "All" {
|
|
|
|
return g, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("no group ALL found")
|
|
|
|
}
|
|
|
|
|
|
|
|
// BuildManager creates a new DefaultAccountManager with a provided Store
|
2022-10-19 17:43:28 +02:00
|
|
|
func BuildManager(store Store, peersUpdateManager *PeersUpdateManager, idpManager idp.Manager,
|
2022-11-07 15:38:21 +01:00
|
|
|
singleAccountModeDomain string, dnsDomain string) (*DefaultAccountManager, error) {
|
2022-06-05 21:36:42 +02:00
|
|
|
am := &DefaultAccountManager{
|
2021-09-07 18:36:46 +02:00
|
|
|
Store: store,
|
|
|
|
mux: sync.Mutex{},
|
|
|
|
peersUpdateManager: peersUpdateManager,
|
2022-01-24 11:21:30 +01:00
|
|
|
idpManager: idpManager,
|
2022-06-05 21:36:42 +02:00
|
|
|
ctx: context.Background(),
|
2022-10-13 18:26:31 +02:00
|
|
|
cacheMux: sync.Mutex{},
|
|
|
|
cacheLoading: map[string]chan struct{}{},
|
2022-11-07 15:38:21 +01:00
|
|
|
dnsDomain: dnsDomain,
|
2021-07-30 17:46:38 +02:00
|
|
|
}
|
2022-10-19 17:43:28 +02:00
|
|
|
allAccounts := store.GetAllAccounts()
|
|
|
|
// enable single account mode only if configured by user and number of existing accounts is not grater than 1
|
|
|
|
am.singleAccountMode = singleAccountModeDomain != "" && len(allAccounts) <= 1
|
|
|
|
if am.singleAccountMode {
|
|
|
|
am.singleAccountModeDomain = singleAccountModeDomain
|
|
|
|
log.Infof("single account mode enabled, accounts number %d", len(allAccounts))
|
|
|
|
} else {
|
|
|
|
log.Infof("single account mode disabled, accounts number %d", len(allAccounts))
|
|
|
|
}
|
2022-05-21 15:21:39 +02:00
|
|
|
|
2022-10-19 17:43:28 +02:00
|
|
|
// if account doesn't have a default group
|
2022-06-06 13:45:59 +02:00
|
|
|
// we create 'all' group and add all peers into it
|
|
|
|
// also we create default rule with source as destination
|
2022-10-19 17:43:28 +02:00
|
|
|
for _, account := range allAccounts {
|
2022-11-07 15:38:21 +01:00
|
|
|
shouldSave := false
|
|
|
|
|
2022-06-06 13:45:59 +02:00
|
|
|
_, err := account.GetGroupAll()
|
|
|
|
if err != nil {
|
2022-06-09 13:14:34 +02:00
|
|
|
addAllGroup(account)
|
2022-11-07 15:38:21 +01:00
|
|
|
shouldSave = true
|
|
|
|
}
|
|
|
|
|
|
|
|
existingLabels := account.getPeerDNSLabels()
|
|
|
|
if len(existingLabels) != len(account.Peers) {
|
|
|
|
addPeerLabelsToAccount(account, existingLabels)
|
|
|
|
shouldSave = true
|
|
|
|
}
|
|
|
|
|
|
|
|
if shouldSave {
|
|
|
|
err = store.SaveAccount(account)
|
|
|
|
if err != nil {
|
2022-06-06 13:45:59 +02:00
|
|
|
return nil, err
|
|
|
|
}
|
2022-05-21 15:21:39 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-19 17:43:28 +02:00
|
|
|
goCacheClient := gocache.New(CacheExpirationMax, 30*time.Minute)
|
|
|
|
goCacheStore := cacheStore.NewGoCache(goCacheClient)
|
2022-06-05 21:36:42 +02:00
|
|
|
|
2022-10-19 17:43:28 +02:00
|
|
|
am.cacheManager = cache.NewLoadable[[]*idp.UserData](am.loadAccount, cache.New[[]*idp.UserData](goCacheStore))
|
2022-06-06 12:05:44 +02:00
|
|
|
|
|
|
|
if !isNil(am.idpManager) {
|
|
|
|
go func() {
|
|
|
|
err := am.warmupIDPCache()
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("failed warming up cache due to error: %v", err)
|
|
|
|
//todo retry?
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
2022-06-05 21:36:42 +02:00
|
|
|
return am, nil
|
|
|
|
|
2021-07-30 17:46:38 +02:00
|
|
|
}
|
|
|
|
|
2022-06-20 18:20:43 +02:00
|
|
|
// newAccount creates a new Account with a generated ID and generated default setup keys.
|
|
|
|
// If ID is already in use (due to collision) we try one more time before returning error
|
|
|
|
func (am *DefaultAccountManager) newAccount(userID, domain string) (*Account, error) {
|
|
|
|
for i := 0; i < 2; i++ {
|
|
|
|
accountId := xid.New().String()
|
|
|
|
|
|
|
|
_, err := am.Store.GetAccount(accountId)
|
|
|
|
statusErr, _ := status.FromError(err)
|
|
|
|
if err == nil {
|
|
|
|
log.Warnf("an account with ID already exists, retrying...")
|
|
|
|
continue
|
|
|
|
} else if statusErr.Code() == codes.NotFound {
|
|
|
|
return newAccountWithId(accountId, userID, domain), nil
|
|
|
|
} else {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, status.Errorf(codes.Internal, "error while creating new account")
|
|
|
|
}
|
|
|
|
|
2022-06-06 12:05:44 +02:00
|
|
|
func (am *DefaultAccountManager) warmupIDPCache() error {
|
|
|
|
userData, err := am.idpManager.GetAllAccounts()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
for accountID, users := range userData {
|
2022-10-13 18:26:31 +02:00
|
|
|
err = am.cacheManager.Set(am.ctx, accountID, users, cacheStore.WithExpiration(cacheEntryExpiration()))
|
2022-06-06 12:05:44 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
log.Infof("warmed up IDP cache with %d entries", len(userData))
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-05-03 16:02:51 +02:00
|
|
|
// GetAccountById returns an existing account using its ID or error (NotFound) if doesn't exist
|
2022-02-22 11:28:19 +01:00
|
|
|
func (am *DefaultAccountManager) GetAccountById(accountId string) (*Account, error) {
|
2021-09-07 18:36:46 +02:00
|
|
|
am.mux.Lock()
|
|
|
|
defer am.mux.Unlock()
|
2021-08-12 12:49:10 +02:00
|
|
|
|
2021-09-07 18:36:46 +02:00
|
|
|
account, err := am.Store.GetAccount(accountId)
|
2021-08-12 12:49:10 +02:00
|
|
|
if err != nil {
|
2021-08-20 15:44:18 +02:00
|
|
|
return nil, status.Errorf(codes.NotFound, "account not found")
|
2021-08-12 12:49:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return account, nil
|
|
|
|
}
|
|
|
|
|
2022-05-03 16:02:51 +02:00
|
|
|
// GetAccountByUserOrAccountId look for an account by user or account Id, if no account is provided and
|
2022-01-24 11:21:30 +01:00
|
|
|
// user id doesn't have an account associated with it, one account is created
|
2022-05-21 15:21:39 +02:00
|
|
|
func (am *DefaultAccountManager) GetAccountByUserOrAccountId(
|
|
|
|
userId, accountId, domain string,
|
|
|
|
) (*Account, error) {
|
2022-01-24 11:21:30 +01:00
|
|
|
if accountId != "" {
|
2022-02-11 17:18:18 +01:00
|
|
|
return am.GetAccountById(accountId)
|
2022-01-24 11:21:30 +01:00
|
|
|
} else if userId != "" {
|
2022-02-11 17:18:18 +01:00
|
|
|
account, err := am.GetOrCreateAccountByUser(userId, domain)
|
2022-01-24 11:21:30 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, status.Errorf(codes.NotFound, "account not found using user id: %s", userId)
|
|
|
|
}
|
2022-10-13 18:26:31 +02:00
|
|
|
err = am.addAccountIDToIDPAppMeta(userId, account)
|
2022-03-01 15:22:18 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2022-01-24 11:21:30 +01:00
|
|
|
}
|
|
|
|
return account, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, status.Errorf(codes.NotFound, "no valid user or account Id provided")
|
|
|
|
}
|
|
|
|
|
2022-05-05 08:58:34 +02:00
|
|
|
func isNil(i idp.Manager) bool {
|
|
|
|
return i == nil || reflect.ValueOf(i).IsNil()
|
|
|
|
}
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
// addAccountIDToIDPAppMeta update user's app metadata in idp manager
|
|
|
|
func (am *DefaultAccountManager) addAccountIDToIDPAppMeta(userID string, account *Account) error {
|
2022-05-05 08:58:34 +02:00
|
|
|
if !isNil(am.idpManager) {
|
2022-10-13 18:26:31 +02:00
|
|
|
|
|
|
|
// user can be nil if it wasn't found (e.g., just created)
|
|
|
|
user, err := am.lookupUserInCache(userID, account)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if user != nil && user.AppMetadata.WTAccountID == account.Id {
|
|
|
|
// it was already set, so we skip the unnecessary update
|
|
|
|
log.Debugf("skipping IDP App Meta update because accountID %s has been already set for user %s",
|
|
|
|
account.Id, userID)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
err = am.idpManager.UpdateUserAppMetadata(userID, idp.AppMetadata{WTAccountID: account.Id})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-03-01 15:22:18 +01:00
|
|
|
if err != nil {
|
2022-05-03 16:02:51 +02:00
|
|
|
return status.Errorf(
|
|
|
|
codes.Internal,
|
|
|
|
"updating user's app metadata failed with: %v",
|
|
|
|
err,
|
|
|
|
)
|
2022-03-01 15:22:18 +01:00
|
|
|
}
|
2022-10-13 18:26:31 +02:00
|
|
|
// refresh cache to reflect the update
|
|
|
|
_, err = am.refreshCache(account.Id)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-03-01 15:22:18 +01:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
func (am *DefaultAccountManager) loadAccount(_ context.Context, accountID interface{}) ([]*idp.UserData, error) {
|
|
|
|
log.Debugf("account %s not found in cache, reloading", accountID)
|
2022-06-06 12:05:44 +02:00
|
|
|
return am.idpManager.GetAccount(fmt.Sprintf("%v", accountID))
|
2022-06-05 21:36:42 +02:00
|
|
|
}
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
func (am *DefaultAccountManager) lookupUserInCacheByEmail(email string, accountID string) (*idp.UserData, error) {
|
|
|
|
data, err := am.getAccountFromCache(accountID, false)
|
2022-09-22 09:06:32 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
for _, datum := range data {
|
|
|
|
if datum.Email == email {
|
2022-09-22 09:06:32 +02:00
|
|
|
return datum, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
return nil, nil
|
|
|
|
|
2022-09-22 09:06:32 +02:00
|
|
|
}
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
// lookupUserInCache looks up user in the IdP cache and returns it. If the user wasn't found, the function returns nil
|
|
|
|
func (am *DefaultAccountManager) lookupUserInCache(userID string, account *Account) (*idp.UserData, error) {
|
|
|
|
users := make(map[string]struct{}, len(account.Users))
|
|
|
|
for _, user := range account.Users {
|
|
|
|
users[user.Id] = struct{}{}
|
|
|
|
}
|
|
|
|
log.Debugf("looking up user %s of account %s in cache", userID, account.Id)
|
|
|
|
userData, err := am.lookupCache(users, account.Id)
|
2022-06-05 21:36:42 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
for _, datum := range userData {
|
|
|
|
if datum.ID == userID {
|
|
|
|
return datum, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (am *DefaultAccountManager) refreshCache(accountID string) ([]*idp.UserData, error) {
|
|
|
|
return am.getAccountFromCache(accountID, true)
|
|
|
|
}
|
|
|
|
|
|
|
|
// getAccountFromCache returns user data for a given account ensuring that cache load happens only once
|
|
|
|
func (am *DefaultAccountManager) getAccountFromCache(accountID string, forceReload bool) ([]*idp.UserData, error) {
|
|
|
|
am.cacheMux.Lock()
|
|
|
|
loadingChan := am.cacheLoading[accountID]
|
|
|
|
if loadingChan == nil {
|
|
|
|
loadingChan = make(chan struct{})
|
|
|
|
am.cacheLoading[accountID] = loadingChan
|
|
|
|
am.cacheMux.Unlock()
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
am.cacheMux.Lock()
|
|
|
|
delete(am.cacheLoading, accountID)
|
|
|
|
close(loadingChan)
|
|
|
|
am.cacheMux.Unlock()
|
|
|
|
}()
|
|
|
|
|
|
|
|
if forceReload {
|
|
|
|
err := am.cacheManager.Delete(am.ctx, accountID)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return am.cacheManager.Get(am.ctx, accountID)
|
|
|
|
}
|
|
|
|
am.cacheMux.Unlock()
|
|
|
|
|
|
|
|
log.Debugf("one request to get account %s is already running", accountID)
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-loadingChan:
|
|
|
|
// channel has been closed meaning cache was loaded => simply return from cache
|
|
|
|
return am.cacheManager.Get(am.ctx, accountID)
|
|
|
|
case <-time.After(5 * time.Second):
|
|
|
|
return nil, fmt.Errorf("timeout while waiting for account %s cache to reload", accountID)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (am *DefaultAccountManager) lookupCache(accountUsers map[string]struct{}, accountID string) ([]*idp.UserData, error) {
|
|
|
|
data, err := am.getAccountFromCache(accountID, false)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-06-05 21:36:42 +02:00
|
|
|
|
|
|
|
userDataMap := make(map[string]struct{})
|
2022-10-13 18:26:31 +02:00
|
|
|
for _, datum := range data {
|
2022-06-05 21:36:42 +02:00
|
|
|
userDataMap[datum.ID] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// check whether we need to reload the cache
|
|
|
|
// the accountUsers ID list is the source of truth and all the users should be in the cache
|
2022-10-13 18:26:31 +02:00
|
|
|
reload := len(accountUsers) != len(data)
|
2022-06-05 21:36:42 +02:00
|
|
|
for user := range accountUsers {
|
|
|
|
if _, ok := userDataMap[user]; !ok {
|
|
|
|
reload = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if reload {
|
|
|
|
// reload cache once avoiding loops
|
2022-10-13 18:26:31 +02:00
|
|
|
data, err = am.refreshCache(accountID)
|
2022-06-05 21:36:42 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
return data, err
|
2022-06-05 21:36:42 +02:00
|
|
|
}
|
|
|
|
|
2022-03-01 15:22:18 +01:00
|
|
|
// updateAccountDomainAttributes updates the account domain attributes and then, saves the account
|
2022-05-03 16:02:51 +02:00
|
|
|
func (am *DefaultAccountManager) updateAccountDomainAttributes(
|
|
|
|
account *Account,
|
|
|
|
claims jwtclaims.AuthorizationClaims,
|
|
|
|
primaryDomain bool,
|
|
|
|
) error {
|
2022-03-01 15:22:18 +01:00
|
|
|
account.IsDomainPrimaryAccount = primaryDomain
|
2022-06-20 18:20:43 +02:00
|
|
|
|
|
|
|
lowerDomain := strings.ToLower(claims.Domain)
|
|
|
|
userObj := account.Users[claims.UserId]
|
|
|
|
if account.Domain != lowerDomain && userObj.Role == UserRoleAdmin {
|
|
|
|
account.Domain = lowerDomain
|
|
|
|
}
|
|
|
|
// prevent updating category for different domain until admin logs in
|
|
|
|
if account.Domain == lowerDomain {
|
|
|
|
account.DomainCategory = claims.DomainCategory
|
|
|
|
}
|
|
|
|
|
2022-03-01 15:22:18 +01:00
|
|
|
err := am.Store.SaveAccount(account)
|
|
|
|
if err != nil {
|
|
|
|
return status.Errorf(codes.Internal, "failed saving updated account")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleExistingUserAccount handles existing User accounts and update its domain attributes.
|
|
|
|
//
|
|
|
|
// If there is no primary domain account yet, we set the account as primary for the domain. Otherwise,
|
|
|
|
// we compare the account's ID with the domain account ID, and if they don't match, we set the account as
|
|
|
|
// non-primary account for the domain. We don't merge accounts at this stage, because of cases when a domain
|
|
|
|
// was previously unclassified or classified as public so N users that logged int that time, has they own account
|
|
|
|
// and peers that shouldn't be lost.
|
2022-05-03 16:02:51 +02:00
|
|
|
func (am *DefaultAccountManager) handleExistingUserAccount(
|
|
|
|
existingAcc *Account,
|
|
|
|
domainAcc *Account,
|
|
|
|
claims jwtclaims.AuthorizationClaims,
|
|
|
|
) error {
|
2022-03-01 15:22:18 +01:00
|
|
|
var err error
|
|
|
|
|
2022-03-10 13:47:36 +01:00
|
|
|
if domainAcc != nil && existingAcc.Id != domainAcc.Id {
|
2022-03-01 15:22:18 +01:00
|
|
|
err = am.updateAccountDomainAttributes(existingAcc, claims, false)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-03-10 13:47:36 +01:00
|
|
|
} else {
|
|
|
|
err = am.updateAccountDomainAttributes(existingAcc, claims, true)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-03-01 15:22:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// we should register the account ID to this user's metadata in our IDP manager
|
2022-10-13 18:26:31 +02:00
|
|
|
err = am.addAccountIDToIDPAppMeta(claims.UserId, existingAcc)
|
2022-03-01 15:22:18 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleNewUserAccount validates if there is an existing primary account for the domain, if so it adds the new user to that account,
|
|
|
|
// otherwise it will create a new account and make it primary account for the domain.
|
2022-05-03 16:02:51 +02:00
|
|
|
func (am *DefaultAccountManager) handleNewUserAccount(
|
|
|
|
domainAcc *Account,
|
|
|
|
claims jwtclaims.AuthorizationClaims,
|
|
|
|
) (*Account, error) {
|
2022-03-01 15:22:18 +01:00
|
|
|
var (
|
2022-03-10 13:47:36 +01:00
|
|
|
account *Account
|
|
|
|
err error
|
2022-03-01 15:22:18 +01:00
|
|
|
)
|
|
|
|
lowerDomain := strings.ToLower(claims.Domain)
|
|
|
|
// if domain already has a primary account, add regular user
|
|
|
|
if domainAcc != nil {
|
|
|
|
account = domainAcc
|
|
|
|
account.Users[claims.UserId] = NewRegularUser(claims.UserId)
|
2022-05-09 14:30:20 +02:00
|
|
|
err = am.Store.SaveAccount(account)
|
|
|
|
if err != nil {
|
|
|
|
return nil, status.Errorf(codes.Internal, "failed saving updated account")
|
|
|
|
}
|
2022-03-01 15:22:18 +01:00
|
|
|
} else {
|
2022-06-20 18:20:43 +02:00
|
|
|
account, err = am.newAccount(claims.UserId, lowerDomain)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-03-10 13:47:36 +01:00
|
|
|
err = am.updateAccountDomainAttributes(account, claims, true)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-03-01 15:22:18 +01:00
|
|
|
}
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
err = am.addAccountIDToIDPAppMeta(claims.UserId, account)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return account, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// redeemInvite checks whether user has been invited and redeems the invite
|
|
|
|
func (am *DefaultAccountManager) redeemInvite(account *Account, userID string) error {
|
|
|
|
// only possible with the enabled IdP manager
|
|
|
|
if am.idpManager == nil {
|
|
|
|
log.Warnf("invites only work with enabled IdP manager")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
user, err := am.lookupUserInCache(userID, account)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if user == nil {
|
|
|
|
return status.Errorf(codes.NotFound, "user %s not found in the IdP", userID)
|
|
|
|
}
|
|
|
|
|
2022-10-19 17:51:41 +02:00
|
|
|
if user.AppMetadata.WTPendingInvite != nil && *user.AppMetadata.WTPendingInvite {
|
2022-10-13 18:26:31 +02:00
|
|
|
log.Infof("redeeming invite for user %s account %s", userID, account.Id)
|
|
|
|
// User has already logged in, meaning that IdP should have set wt_pending_invite to false.
|
|
|
|
// Our job is to just reload cache.
|
|
|
|
go func() {
|
|
|
|
_, err = am.refreshCache(account.Id)
|
|
|
|
if err != nil {
|
|
|
|
log.Warnf("failed reloading cache when redeeming user %s under account %s", userID, account.Id)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
log.Debugf("user %s of account %s redeemed invite", user.ID, account.Id)
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetAccountFromToken returns an account associated with this token
|
|
|
|
func (am *DefaultAccountManager) GetAccountFromToken(claims jwtclaims.AuthorizationClaims) (*Account, error) {
|
2022-10-19 17:43:28 +02:00
|
|
|
|
|
|
|
if am.singleAccountMode && am.singleAccountModeDomain != "" {
|
|
|
|
// This section is mostly related to self-hosted installations.
|
|
|
|
// We override incoming domain claims to group users under a single account.
|
|
|
|
claims.Domain = am.singleAccountModeDomain
|
|
|
|
claims.DomainCategory = PrivateCategory
|
|
|
|
log.Infof("overriding JWT Domain and DomainCategory claims since single account mode is enabled")
|
|
|
|
}
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
account, err := am.getAccountWithAuthorizationClaims(claims)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = am.redeemInvite(account, claims.UserId)
|
2022-03-01 15:22:18 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return account, nil
|
|
|
|
}
|
|
|
|
|
2022-10-13 18:26:31 +02:00
|
|
|
// getAccountWithAuthorizationClaims retrievs an account using JWT Claims.
|
2022-03-01 15:22:18 +01:00
|
|
|
// if domain is of the PrivateCategory category, it will evaluate
|
|
|
|
// if account is new, existing or if there is another account with the same domain
|
|
|
|
//
|
|
|
|
// Use cases:
|
|
|
|
//
|
|
|
|
// New user + New account + New domain -> create account, user role = admin (if private domain, index domain)
|
|
|
|
//
|
|
|
|
// New user + New account + Existing Private Domain -> add user to the existing account, user role = regular (not admin)
|
|
|
|
//
|
|
|
|
// New user + New account + Existing Public Domain -> create account, user role = admin
|
|
|
|
//
|
|
|
|
// Existing user + Existing account + Existing Domain -> Nothing changes (if private, index domain)
|
|
|
|
//
|
|
|
|
// Existing user + Existing account + Existing Indexed Domain -> Nothing changes
|
|
|
|
//
|
|
|
|
// Existing user + Existing account + Existing domain reclassified Domain as private -> Nothing changes (index domain)
|
2022-10-13 18:26:31 +02:00
|
|
|
func (am *DefaultAccountManager) getAccountWithAuthorizationClaims(
|
2022-05-03 16:02:51 +02:00
|
|
|
claims jwtclaims.AuthorizationClaims,
|
|
|
|
) (*Account, error) {
|
2022-03-01 15:22:18 +01:00
|
|
|
// if Account ID is part of the claims
|
|
|
|
// it means that we've already classified the domain and user has an account
|
2022-09-29 10:51:18 +02:00
|
|
|
if claims.DomainCategory != PrivateCategory || !isDomainValid(claims.Domain) {
|
2022-03-01 15:22:18 +01:00
|
|
|
return am.GetAccountByUserOrAccountId(claims.UserId, claims.AccountId, claims.Domain)
|
2022-03-09 13:31:42 +01:00
|
|
|
} else if claims.AccountId != "" {
|
2022-05-09 14:30:20 +02:00
|
|
|
accountFromID, err := am.GetAccountById(claims.AccountId)
|
2022-03-09 13:31:42 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-05-09 14:30:20 +02:00
|
|
|
if _, ok := accountFromID.Users[claims.UserId]; !ok {
|
|
|
|
return nil, fmt.Errorf("user %s is not part of the account id %s", claims.UserId, claims.AccountId)
|
|
|
|
}
|
2022-03-09 13:31:42 +01:00
|
|
|
if accountFromID.DomainCategory == PrivateCategory || claims.DomainCategory != PrivateCategory {
|
|
|
|
return accountFromID, nil
|
|
|
|
}
|
2022-03-01 15:22:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
am.mux.Lock()
|
|
|
|
defer am.mux.Unlock()
|
|
|
|
|
|
|
|
// We checked if the domain has a primary account already
|
|
|
|
domainAccount, err := am.Store.GetAccountByPrivateDomain(claims.Domain)
|
|
|
|
accStatus, _ := status.FromError(err)
|
|
|
|
if accStatus.Code() != codes.OK && accStatus.Code() != codes.NotFound {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-11-07 12:10:56 +01:00
|
|
|
account, err := am.Store.GetAccountByUser(claims.UserId)
|
2022-03-01 15:22:18 +01:00
|
|
|
if err == nil {
|
|
|
|
err = am.handleExistingUserAccount(account, domainAccount, claims)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return account, nil
|
|
|
|
} else if s, ok := status.FromError(err); ok && s.Code() == codes.NotFound {
|
|
|
|
return am.handleNewUserAccount(domainAccount, claims)
|
|
|
|
} else {
|
|
|
|
// other error
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-29 10:51:18 +02:00
|
|
|
func isDomainValid(domain string) bool {
|
|
|
|
re := regexp.MustCompile(`^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$`)
|
|
|
|
return re.Match([]byte(domain))
|
|
|
|
}
|
|
|
|
|
2022-05-03 16:02:51 +02:00
|
|
|
// AccountExists checks whether account exists (returns true) or not (returns false)
|
2022-02-22 11:28:19 +01:00
|
|
|
func (am *DefaultAccountManager) AccountExists(accountId string) (*bool, error) {
|
2021-09-07 18:36:46 +02:00
|
|
|
am.mux.Lock()
|
|
|
|
defer am.mux.Unlock()
|
2021-08-12 12:49:10 +02:00
|
|
|
|
|
|
|
var res bool
|
2021-09-07 18:36:46 +02:00
|
|
|
_, err := am.Store.GetAccount(accountId)
|
2021-08-12 12:49:10 +02:00
|
|
|
if err != nil {
|
|
|
|
if s, ok := status.FromError(err); ok && s.Code() == codes.NotFound {
|
|
|
|
res = false
|
|
|
|
return &res, nil
|
|
|
|
} else {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
res = true
|
|
|
|
return &res, nil
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:45:59 +02:00
|
|
|
// addAllGroup to account object if it doesn't exists
|
2022-06-09 13:14:34 +02:00
|
|
|
func addAllGroup(account *Account) {
|
2022-05-21 15:21:39 +02:00
|
|
|
if len(account.Groups) == 0 {
|
|
|
|
allGroup := &Group{
|
|
|
|
ID: xid.New().String(),
|
|
|
|
Name: "All",
|
|
|
|
}
|
|
|
|
for _, peer := range account.Peers {
|
|
|
|
allGroup.Peers = append(allGroup.Peers, peer.Key)
|
|
|
|
}
|
|
|
|
account.Groups = map[string]*Group{allGroup.ID: allGroup}
|
|
|
|
|
|
|
|
defaultRule := &Rule{
|
|
|
|
ID: xid.New().String(),
|
2022-06-14 10:32:54 +02:00
|
|
|
Name: DefaultRuleName,
|
|
|
|
Description: DefaultRuleDescription,
|
|
|
|
Disabled: false,
|
2022-05-21 15:21:39 +02:00
|
|
|
Source: []string{allGroup.ID},
|
|
|
|
Destination: []string{allGroup.ID},
|
|
|
|
}
|
|
|
|
account.Rules = map[string]*Rule{defaultRule.ID: defaultRule}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-12 12:49:10 +02:00
|
|
|
// newAccountWithId creates a new Account with a default SetupKey (doesn't store in a Store) and provided id
|
2022-02-11 17:18:18 +01:00
|
|
|
func newAccountWithId(accountId, userId, domain string) *Account {
|
2021-08-01 19:06:01 +02:00
|
|
|
log.Debugf("creating new account")
|
|
|
|
|
|
|
|
setupKeys := make(map[string]*SetupKey)
|
2021-09-07 18:36:46 +02:00
|
|
|
defaultKey := GenerateDefaultSetupKey()
|
2022-09-11 23:16:40 +02:00
|
|
|
oneOffKey := GenerateSetupKey("One-off key", SetupKeyOneOff, DefaultSetupKeyDuration, []string{})
|
2021-09-07 18:36:46 +02:00
|
|
|
setupKeys[defaultKey.Key] = defaultKey
|
|
|
|
setupKeys[oneOffKey.Key] = oneOffKey
|
2022-01-14 14:34:27 +01:00
|
|
|
network := NewNetwork()
|
2021-08-01 19:06:01 +02:00
|
|
|
peers := make(map[string]*Peer)
|
2021-12-27 13:17:15 +01:00
|
|
|
users := make(map[string]*User)
|
2022-08-18 18:22:15 +02:00
|
|
|
routes := make(map[string]*route.Route)
|
2022-09-30 13:47:11 +02:00
|
|
|
nameServersGroups := make(map[string]*nbdns.NameServerGroup)
|
2022-06-09 13:14:34 +02:00
|
|
|
users[userId] = NewAdminUser(userId)
|
2021-09-07 18:36:46 +02:00
|
|
|
log.Debugf("created new account %s with setup key %s", accountId, defaultKey.Key)
|
2021-08-01 19:06:01 +02:00
|
|
|
|
2022-06-09 13:14:34 +02:00
|
|
|
acc := &Account{
|
2022-09-30 13:47:11 +02:00
|
|
|
Id: accountId,
|
|
|
|
SetupKeys: setupKeys,
|
|
|
|
Network: network,
|
|
|
|
Peers: peers,
|
|
|
|
Users: users,
|
|
|
|
CreatedBy: userId,
|
|
|
|
Domain: domain,
|
|
|
|
Routes: routes,
|
|
|
|
NameServerGroups: nameServersGroups,
|
2022-02-11 17:18:18 +01:00
|
|
|
}
|
2022-06-09 13:14:34 +02:00
|
|
|
|
|
|
|
addAllGroup(acc)
|
|
|
|
return acc
|
2021-08-12 12:49:10 +02:00
|
|
|
}
|
2021-08-20 22:33:43 +02:00
|
|
|
|
|
|
|
func getAccountSetupKeyByKey(acc *Account, key string) *SetupKey {
|
|
|
|
for _, k := range acc.SetupKeys {
|
|
|
|
if key == k.Key {
|
|
|
|
return k
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2022-06-14 10:32:54 +02:00
|
|
|
|
|
|
|
func removeFromList(inputList []string, toRemove []string) []string {
|
|
|
|
toRemoveMap := make(map[string]struct{})
|
|
|
|
for _, item := range toRemove {
|
|
|
|
toRemoveMap[item] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
var resultList []string
|
|
|
|
for _, item := range inputList {
|
|
|
|
_, ok := toRemoveMap[item]
|
|
|
|
if !ok {
|
|
|
|
resultList = append(resultList, item)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return resultList
|
|
|
|
}
|