mirror of
https://github.com/netbirdio/netbird.git
synced 2026-09-19 13:19:06 +02:00
Move profile resolution to the authz gate
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
@@ -59,7 +58,7 @@ func TestClaimProfile_RecordsTheOwner(t *testing.T) {
|
||||
srv := claimTestServer(t)
|
||||
|
||||
owner := claimOwner(4242)
|
||||
resp, err := srv.ClaimProfile(rootCtx(), &proto.ClaimProfileRequest{
|
||||
resp, err := srv.ClaimProfile(withTarget(rootCtx(), profilemanager.DefaultConfigPath), &proto.ClaimProfileRequest{
|
||||
Handle: "default",
|
||||
Owner: owner,
|
||||
})
|
||||
@@ -119,10 +118,7 @@ func TestClaimProfile_RequiresBothArguments(t *testing.T) {
|
||||
func TestClaimProfile_RefusesAnUnknownProfile(t *testing.T) {
|
||||
srv := claimTestServer(t)
|
||||
|
||||
_, err := srv.ClaimProfile(rootCtx(), &proto.ClaimProfileRequest{
|
||||
Handle: "no-such-profile",
|
||||
Owner: claimOwner(4242),
|
||||
})
|
||||
_, err := srv.ResolveTarget(privilegedIdentity(), "no-such-profile")
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, codes.NotFound, gstatus.Convert(err).Code())
|
||||
}
|
||||
@@ -130,12 +126,11 @@ func TestClaimProfile_RefusesAnUnknownProfile(t *testing.T) {
|
||||
func TestClaimProfile_NeedsAnIdentifiedCaller(t *testing.T) {
|
||||
srv := claimTestServer(t)
|
||||
|
||||
_, err := srv.ClaimProfile(context.Background(), &proto.ClaimProfileRequest{
|
||||
Handle: "default",
|
||||
Owner: claimOwner(4242),
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.Equal(t, codes.Unauthenticated, gstatus.Convert(err).Code())
|
||||
// A caller the kernel did not vouch for reaches no profile, so the gate has
|
||||
// nothing to authorize and the handler is never entered.
|
||||
target, err := srv.ResolveTarget(ipcauth.Identity{}, "default")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, target.Owned, "an unattested caller must not be able to claim")
|
||||
}
|
||||
|
||||
// A principal is taken as given. The account deliberately does not exist, which
|
||||
@@ -146,7 +141,7 @@ func TestClaimProfile_TakesAPrincipalWithoutResolvingIt(t *testing.T) {
|
||||
t.Run(owner, func(t *testing.T) {
|
||||
srv := claimTestServer(t)
|
||||
|
||||
resp, err := srv.ClaimProfile(rootCtx(), &proto.ClaimProfileRequest{
|
||||
resp, err := srv.ClaimProfile(withTarget(rootCtx(), profilemanager.DefaultConfigPath), &proto.ClaimProfileRequest{
|
||||
Handle: "default",
|
||||
Owner: owner,
|
||||
})
|
||||
@@ -164,7 +159,7 @@ func TestClaimProfile_ResolvesAnAccountName(t *testing.T) {
|
||||
want, ok := profilemanager.PrincipalForUser(u)
|
||||
require.True(t, ok)
|
||||
|
||||
resp, err := srv.ClaimProfile(rootCtx(), &proto.ClaimProfileRequest{
|
||||
resp, err := srv.ClaimProfile(withTarget(rootCtx(), profilemanager.DefaultConfigPath), &proto.ClaimProfileRequest{
|
||||
Handle: "default",
|
||||
Owner: u.Username,
|
||||
})
|
||||
|
||||
@@ -27,15 +27,16 @@ func TestLogin_RefusedChangeLeavesTheProfileAlone(t *testing.T) {
|
||||
// A second profile that runs the SSH server, which is what makes repointing
|
||||
// its management binding a privileged change.
|
||||
target := "ssh-enabled"
|
||||
targetPath := filepath.Join(profilemanager.DefaultConfigPathDir, target+".json")
|
||||
_, err := profilemanager.UpdateOrCreateConfig(profilemanager.ConfigInput{
|
||||
ConfigPath: filepath.Join(profilemanager.DefaultConfigPathDir, target+".json"),
|
||||
ConfigPath: targetPath,
|
||||
ManagementURL: "https://api.netbird.io:443",
|
||||
ServerSSHAllowed: boolPtr(true),
|
||||
Owner: testProfileOwner(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = s.Login(userCtx(), &proto.LoginRequest{
|
||||
_, err = s.Login(withTarget(userCtx(), targetPath), &proto.LoginRequest{
|
||||
ProfileName: &target,
|
||||
Username: &username,
|
||||
ManagementUrl: "https://mgmt.attacker.example:443",
|
||||
@@ -82,7 +83,7 @@ func TestLogin_ChangeThatBecomesPrivilegedMidRequestHasNoSideEffects(t *testing.
|
||||
}
|
||||
t.Cleanup(func() { afterLoginPreCheck = nil })
|
||||
|
||||
_, err = s.Login(userCtx(), &proto.LoginRequest{
|
||||
_, err = s.Login(withTarget(userCtx(), targetPath), &proto.LoginRequest{
|
||||
ProfileName: &target,
|
||||
Username: &username,
|
||||
ManagementUrl: "https://mgmt.attacker.example:443",
|
||||
@@ -108,8 +109,9 @@ func TestLogin_RefusedChangeLeavesAnInProgressLoginAlone(t *testing.T) {
|
||||
s.rootCtx = internal.CtxInitState(context.Background())
|
||||
|
||||
target := "ssh-enabled"
|
||||
targetPath := filepath.Join(profilemanager.DefaultConfigPathDir, target+".json")
|
||||
_, err := profilemanager.UpdateOrCreateConfig(profilemanager.ConfigInput{
|
||||
ConfigPath: filepath.Join(profilemanager.DefaultConfigPathDir, target+".json"),
|
||||
ConfigPath: targetPath,
|
||||
ManagementURL: "https://api.netbird.io:443",
|
||||
ServerSSHAllowed: boolPtr(true),
|
||||
Owner: testProfileOwner(),
|
||||
@@ -119,7 +121,7 @@ func TestLogin_RefusedChangeLeavesAnInProgressLoginAlone(t *testing.T) {
|
||||
cancelled := false
|
||||
s.actCancel = func() { cancelled = true }
|
||||
|
||||
_, err = s.Login(userCtx(), &proto.LoginRequest{
|
||||
_, err = s.Login(withTarget(userCtx(), targetPath), &proto.LoginRequest{
|
||||
ProfileName: &target,
|
||||
Username: &username,
|
||||
ManagementUrl: "https://mgmt.attacker.example:443",
|
||||
|
||||
@@ -48,7 +48,7 @@ func TestLogout_ActiveProfileAllowedWhenProfilesDisabled(t *testing.T) {
|
||||
|
||||
s.profilesDisabled = true
|
||||
|
||||
_, err := s.Logout(userCtx(), &proto.LogoutRequest{
|
||||
_, err := s.Logout(withTarget(userCtx(), cfgPath), &proto.LogoutRequest{
|
||||
ProfileName: &activeProfile,
|
||||
Username: &username,
|
||||
})
|
||||
@@ -67,8 +67,9 @@ func TestLogout_OtherProfileStaysGatedWhenProfilesDisabled(t *testing.T) {
|
||||
s.rootCtx = internal.CtxInitState(context.Background())
|
||||
|
||||
other := "other-profile"
|
||||
otherPath := filepath.Join(profilemanager.DefaultConfigPathDir, other+".json")
|
||||
_, err := profilemanager.UpdateOrCreateConfig(profilemanager.ConfigInput{
|
||||
ConfigPath: filepath.Join(profilemanager.DefaultConfigPathDir, other+".json"),
|
||||
ConfigPath: otherPath,
|
||||
ManagementURL: unreachableManagementURL,
|
||||
Owner: testProfileOwner(),
|
||||
})
|
||||
@@ -76,7 +77,7 @@ func TestLogout_OtherProfileStaysGatedWhenProfilesDisabled(t *testing.T) {
|
||||
|
||||
s.profilesDisabled = true
|
||||
|
||||
_, err = s.Logout(userCtx(), &proto.LogoutRequest{
|
||||
_, err = s.Logout(withTarget(userCtx(), otherPath), &proto.LogoutRequest{
|
||||
ProfileName: &other,
|
||||
Username: &username,
|
||||
})
|
||||
@@ -95,11 +96,11 @@ func TestLogout_ForeignUserProfileStaysGatedWhenProfilesDisabled(t *testing.T) {
|
||||
s.rootCtx = internal.CtxInitState(context.Background())
|
||||
|
||||
shared := "shared-legacy-name"
|
||||
plantNamesakeProfiles(t, s, shared)
|
||||
ownPath := plantNamesakeProfiles(t, s, shared)
|
||||
|
||||
s.profilesDisabled = true
|
||||
|
||||
_, err := s.Logout(userCtx(), &proto.LogoutRequest{
|
||||
_, err := s.Logout(withTarget(userCtx(), ownPath), &proto.LogoutRequest{
|
||||
ProfileName: &shared,
|
||||
Username: &username,
|
||||
})
|
||||
@@ -114,7 +115,7 @@ func TestLogout_ForeignUserProfileStaysGatedWhenProfilesDisabled(t *testing.T) {
|
||||
// which is the one made active. Only the caller's copy carries an owner, so
|
||||
// that is the one a handle resolves to, while the active profile stays the
|
||||
// other file.
|
||||
func plantNamesakeProfiles(t *testing.T, s *Server, id string) {
|
||||
func plantNamesakeProfiles(t *testing.T, s *Server, id string) string {
|
||||
t.Helper()
|
||||
|
||||
foreignDir := filepath.Join(profilemanager.DefaultConfigPathDir, "someone-else")
|
||||
@@ -125,8 +126,9 @@ func plantNamesakeProfiles(t *testing.T, s *Server, id string) {
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
ownPath := filepath.Join(profilemanager.DefaultConfigPathDir, id+".json")
|
||||
_, err = profilemanager.UpdateOrCreateConfig(profilemanager.ConfigInput{
|
||||
ConfigPath: filepath.Join(profilemanager.DefaultConfigPathDir, id+".json"),
|
||||
ConfigPath: ownPath,
|
||||
ManagementURL: unreachableManagementURL,
|
||||
Owner: testProfileOwner(),
|
||||
})
|
||||
@@ -136,6 +138,8 @@ func plantNamesakeProfiles(t *testing.T, s *Server, id string) {
|
||||
ID: profilemanager.ID(id),
|
||||
Username: "someone-else",
|
||||
}))
|
||||
|
||||
return ownPath
|
||||
}
|
||||
|
||||
// Deregistering a namesake profile must not go out with the running config.
|
||||
@@ -156,11 +160,11 @@ func TestLogout_ForeignUserProfileDoesNotUseTheRunningConfig(t *testing.T) {
|
||||
s.connectClient = newDummyConnectClient(context.Background())
|
||||
|
||||
shared := "shared-legacy-name"
|
||||
plantNamesakeProfiles(t, s, shared)
|
||||
ownPath := plantNamesakeProfiles(t, s, shared)
|
||||
|
||||
// Bounded so the deregistration the fixed path attempts fails on the dial
|
||||
// rather than sitting in gRPC backoff for the whole test timeout.
|
||||
ctx, cancel := context.WithTimeout(userCtx(), 2*time.Second)
|
||||
ctx, cancel := context.WithTimeout(withTarget(userCtx(), ownPath), 2*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
|
||||
_, err = s.Logout(ctx, &proto.LogoutRequest{
|
||||
@@ -206,7 +210,7 @@ func TestLogout_ActiveProfileAllowedWhenProfilesEnabled(t *testing.T) {
|
||||
s.rootCtx = internal.CtxInitState(context.Background())
|
||||
enableSSHOnProfile(t, cfgPath)
|
||||
|
||||
_, err := s.Logout(userCtx(), &proto.LogoutRequest{
|
||||
_, err := s.Logout(withTarget(userCtx(), cfgPath), &proto.LogoutRequest{
|
||||
ProfileName: &activeProfile,
|
||||
Username: &username,
|
||||
})
|
||||
|
||||
+112
-68
@@ -533,7 +533,12 @@ func (s *Server) SetConfig(callerCtx context.Context, msg *proto.SetConfigReques
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stored, err := s.storedProfileConfig(msg.ProfileName)
|
||||
resolved, err := s.targetProfile(callerCtx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
stored, err := s.storedProfileConfig(resolved)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -541,7 +546,7 @@ func (s *Server) SetConfig(callerCtx context.Context, msg *proto.SetConfigReques
|
||||
return nil, err
|
||||
}
|
||||
|
||||
config, err := s.setConfigInputFromRequest(msg)
|
||||
config, err := s.setConfigInputFromRequest(msg, resolved)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -571,14 +576,9 @@ func (s *Server) SetConfig(callerCtx context.Context, msg *proto.SetConfigReques
|
||||
// field is its own optional case. Returns the resolved ConfigInput
|
||||
// and a non-nil error only when the active profile file path cannot
|
||||
// be determined.
|
||||
func (s *Server) setConfigInputFromRequest(msg *proto.SetConfigRequest) (profilemanager.ConfigInput, error) {
|
||||
func (s *Server) setConfigInputFromRequest(msg *proto.SetConfigRequest, resolved *profilemanager.Profile) (profilemanager.ConfigInput, error) {
|
||||
var config profilemanager.ConfigInput
|
||||
|
||||
resolved, err := s.resolveProfileHandle(msg.ProfileName)
|
||||
if err != nil {
|
||||
log.Errorf("failed to resolve profile %q: %v", msg.ProfileName, err)
|
||||
return config, err
|
||||
}
|
||||
profPath := resolved.Path
|
||||
if profPath == "" {
|
||||
profPath = profilemanager.DefaultConfigPath
|
||||
@@ -688,7 +688,7 @@ func (s *Server) Login(callerCtx context.Context, msg *proto.LoginRequest) (*pro
|
||||
// refused login neither switches the profile nor cancels a login already in
|
||||
// progress, and it reads the profile the request targets, which is the one the
|
||||
// switch below would activate.
|
||||
stored, err := s.storedLoginConfig(activeProf, msg)
|
||||
stored, err := s.storedLoginConfig(callerCtx, activeProf, msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1090,7 +1090,12 @@ func (s *Server) Up(callerCtx context.Context, msg *proto.UpRequest) (*proto.UpR
|
||||
}
|
||||
|
||||
if msg != nil && msg.ProfileName != nil {
|
||||
if _, err := s.switchProfileIfNeeded(*msg.ProfileName, activeProf); err != nil {
|
||||
resolved, err := s.targetProfile(callerCtx)
|
||||
if err != nil {
|
||||
s.mutex.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.switchProfileIfNeeded(resolved, activeProf); err != nil {
|
||||
s.mutex.Unlock()
|
||||
log.Errorf("failed to switch profile: %v", err)
|
||||
return nil, err
|
||||
@@ -1156,12 +1161,7 @@ func (s *Server) waitForUp(callerCtx context.Context) (*proto.UpResponse, error)
|
||||
// targets, so a privileged-change decision can be made against the values the
|
||||
// profile currently holds. A profile that has no config file yet yields nil,
|
||||
// which every caller must read as "nothing enabled yet".
|
||||
func (s *Server) storedProfileConfig(handle string) (*profilemanager.Config, error) {
|
||||
resolved, err := s.resolveProfileHandle(handle)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (s *Server) storedProfileConfig(resolved *profilemanager.Profile) (*profilemanager.Config, error) {
|
||||
path := resolved.Path
|
||||
if path == "" {
|
||||
path = profilemanager.DefaultConfigPath
|
||||
@@ -1173,7 +1173,7 @@ func (s *Server) storedProfileConfig(handle string) (*profilemanager.Config, err
|
||||
// storedLoginConfig loads the on-disk config of the profile a login request
|
||||
// targets: the one it names, or the active one when it names none. Used to decide
|
||||
// a privileged change before the request is allowed to switch profiles.
|
||||
func (s *Server) storedLoginConfig(activeProf *profilemanager.ActiveProfileState, msg *proto.LoginRequest) (*profilemanager.Config, error) {
|
||||
func (s *Server) storedLoginConfig(ctx context.Context, activeProf *profilemanager.ActiveProfileState, msg *proto.LoginRequest) (*profilemanager.Config, error) {
|
||||
if msg.ProfileName == nil {
|
||||
cfgPath, err := s.profileManager.ActiveProfilePath(activeProf)
|
||||
if err != nil {
|
||||
@@ -1184,7 +1184,11 @@ func (s *Server) storedLoginConfig(activeProf *profilemanager.ActiveProfileState
|
||||
|
||||
// Mirrors switchProfileIfNeeded, so this reads the very profile the switch
|
||||
// would activate.
|
||||
return s.storedProfileConfig(*msg.ProfileName)
|
||||
resolved, err := s.targetProfile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.storedProfileConfig(resolved)
|
||||
}
|
||||
|
||||
// storedConfigAtPath reads a profile config file, yielding nil when it does not
|
||||
@@ -1218,33 +1222,10 @@ func callerIdentity(ctx context.Context) (ipcauth.Identity, error) {
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// resolveProfileHandle resolves a wire-level profile handle (display
|
||||
// name, ID, or unique ID prefix). Returns gRPC status errors so
|
||||
// handlers can return them directly.
|
||||
func (s *Server) resolveProfileHandle(handle string) (*profilemanager.Profile, error) {
|
||||
p, err := s.profileManager.ResolveProfile(handle)
|
||||
if err == nil {
|
||||
return p, nil
|
||||
}
|
||||
var amb *profilemanager.ErrAmbiguousHandle
|
||||
if errors.As(err, &amb) {
|
||||
return nil, gstatus.Errorf(codes.InvalidArgument, "%v", amb)
|
||||
}
|
||||
if errors.Is(err, profilemanager.ErrProfileNotFound) {
|
||||
return nil, gstatus.Errorf(codes.NotFound, "profile %q not found", handle)
|
||||
}
|
||||
return nil, fmt.Errorf("resolve profile: %w", err)
|
||||
}
|
||||
|
||||
// switchProfileIfNeeded resolves the user-supplied handle, updates the
|
||||
// active profile state if it differs from the current one, and returns
|
||||
// the resolved profile so callers can include its ID in RPC responses.
|
||||
func (s *Server) switchProfileIfNeeded(handle string, activeProf *profilemanager.ActiveProfileState) (*profilemanager.Profile, error) {
|
||||
resolved, err := s.resolveProfileHandle(handle)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// switchProfileIfNeeded updates the active profile state when the profile the
|
||||
// gate resolved differs from the current one, and returns it so callers can
|
||||
// include its ID in RPC responses.
|
||||
func (s *Server) switchProfileIfNeeded(resolved *profilemanager.Profile, activeProf *profilemanager.ActiveProfileState) (*profilemanager.Profile, error) {
|
||||
if s.isActiveProfile(activeProf, resolved) {
|
||||
return resolved, nil
|
||||
}
|
||||
@@ -1278,7 +1259,11 @@ func (s *Server) SwitchProfile(callerCtx context.Context, msg *proto.SwitchProfi
|
||||
}
|
||||
|
||||
if msg != nil && msg.ProfileName != nil {
|
||||
if _, err := s.switchProfileIfNeeded(*msg.ProfileName, activeProf); err != nil {
|
||||
resolved, err := s.targetProfile(callerCtx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.switchProfileIfNeeded(resolved, activeProf); err != nil {
|
||||
log.Errorf("failed to switch profile: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
@@ -1431,7 +1416,7 @@ func (s *Server) Logout(ctx context.Context, msg *proto.LogoutRequest) (*proto.L
|
||||
}
|
||||
|
||||
func (s *Server) handleProfileLogout(ctx context.Context, msg *proto.LogoutRequest) (*proto.LogoutResponse, error) {
|
||||
resolved, err := s.resolveProfileHandle(*msg.ProfileName)
|
||||
resolved, err := s.targetProfile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -2243,9 +2228,8 @@ func (s *Server) GetConfig(ctx context.Context, req *proto.GetConfigRequest) (*p
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
resolved, err := s.resolveProfileHandle(req.ProfileName)
|
||||
resolved, err := s.targetProfile(ctx)
|
||||
if err != nil {
|
||||
log.Errorf("failed to resolve profile %q: %v", req.ProfileName, err)
|
||||
return nil, err
|
||||
}
|
||||
cfgPath := resolved.Path
|
||||
@@ -2388,7 +2372,7 @@ func (s *Server) RenameProfile(ctx context.Context, msg *proto.RenameProfileRequ
|
||||
return nil, gstatus.Errorf(codes.InvalidArgument, "profile name and new profile name must be provided")
|
||||
}
|
||||
|
||||
resolved, err := s.resolveProfileHandle(msg.Handle)
|
||||
resolved, err := s.targetProfile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -2417,7 +2401,7 @@ func (s *Server) RemoveProfile(ctx context.Context, msg *proto.RemoveProfileRequ
|
||||
return nil, gstatus.Errorf(codes.InvalidArgument, "profile name must be provided")
|
||||
}
|
||||
|
||||
resolved, err := s.resolveProfileHandle(msg.ProfileName)
|
||||
resolved, err := s.targetProfile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -2464,7 +2448,7 @@ func (s *Server) ClaimProfile(ctx context.Context, msg *proto.ClaimProfileReques
|
||||
return nil, gstatus.Errorf(codes.InvalidArgument, "%v", err)
|
||||
}
|
||||
|
||||
resolved, err := s.resolveProfileHandle(msg.Handle)
|
||||
resolved, err := s.targetProfile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -2831,7 +2815,7 @@ func (s *Server) authorizeAndPrepareLogin(callerCtx context.Context, msg *proto.
|
||||
s.guardedConfigMu.Lock()
|
||||
defer s.guardedConfigMu.Unlock()
|
||||
|
||||
stored, err := s.storedLoginConfig(activeProf, msg)
|
||||
stored, err := s.storedLoginConfig(callerCtx, activeProf, msg)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -2855,7 +2839,11 @@ func (s *Server) authorizeAndPrepareLogin(callerCtx context.Context, msg *proto.
|
||||
}
|
||||
|
||||
if msg.ProfileName != nil {
|
||||
if _, err := s.switchProfileIfNeeded(*msg.ProfileName, activeProf); err != nil {
|
||||
resolved, err := s.targetProfile(callerCtx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if _, err := s.switchProfileIfNeeded(resolved, activeProf); err != nil {
|
||||
return nil, nil, fmt.Errorf("switch profile: %w", err)
|
||||
}
|
||||
}
|
||||
@@ -2896,16 +2884,16 @@ func (s *Server) SessionHolder() (ipcauth.Principal, bool) {
|
||||
return principal, true
|
||||
}
|
||||
|
||||
// OwnsProfile reports whether the profile the handle resolves to answers to
|
||||
// this identity, and what was wrong with the handle when resolution failed.
|
||||
// ResolveTarget resolves the profile a request names to a concrete profile and
|
||||
// reports whether this identity may address it.
|
||||
//
|
||||
// This triggers stamping of legacy profiles, and reloads the active profile's
|
||||
// config so the stamp is visible to SessionHolder.
|
||||
func (s *Server) OwnsProfile(id ipcauth.Identity, handle string) (bool, error) {
|
||||
// This triggers stamping of legacy and default profiles, and reloads the active
|
||||
// profile's config so the stamp is visible to SessionHolder.
|
||||
func (s *Server) ResolveTarget(id ipcauth.Identity, handle string) (ipcauth.Target, error) {
|
||||
s.profileManager.ClaimDefaultProfileIfNeeded(id)
|
||||
s.profileManager.ClaimLegacyProfiles(id)
|
||||
// The daemon's copy of the active profile's config goes stale after a the
|
||||
// possible profile claims above.
|
||||
// The claims above stamp owners on profiles, so the daemon's copy of the
|
||||
// active profile's config might go stale.
|
||||
s.reloadActiveConfig()
|
||||
|
||||
// Without the active profile there is nothing to fall back to and nothing
|
||||
@@ -2914,27 +2902,83 @@ func (s *Server) OwnsProfile(id ipcauth.Identity, handle string) (bool, error) {
|
||||
activeProfile, err := s.profileManager.GetActiveProfileState()
|
||||
if err != nil {
|
||||
log.Warnf("failed to get active profile: %v", err)
|
||||
return false, nil
|
||||
return ipcauth.Target{}, nil
|
||||
}
|
||||
if activeProfile == nil {
|
||||
log.Warn("no active profile to authorize against")
|
||||
return false, nil
|
||||
return ipcauth.Target{}, nil
|
||||
}
|
||||
if handle == "" {
|
||||
handle = activeProfile.ID.String()
|
||||
}
|
||||
|
||||
resolved, resolveErr := s.resolveProfileHandle(handle)
|
||||
match, matchErr := s.profileManager.MatchProfiles(handle)
|
||||
|
||||
if afterProfileResolve != nil {
|
||||
afterProfileResolve()
|
||||
}
|
||||
|
||||
if resolveErr != nil {
|
||||
log.Debugf("failed to resolve profile %q: %v", handle, resolveErr)
|
||||
return false, resolveErr
|
||||
if matchErr != nil {
|
||||
log.Debugf("failed to match profile %q: %v", handle, matchErr)
|
||||
return ipcauth.Target{}, matchHandleError(handle, matchErr)
|
||||
}
|
||||
return resolved.AccessibleBy(id), nil
|
||||
|
||||
return targetFromMatch(id, handle, match)
|
||||
}
|
||||
|
||||
// targetFromMatch picks the profile the caller meant out of everything the
|
||||
// handle matched. Their own profile wins, only a handle matching two of the
|
||||
// caller's own profiles is ambiguous.
|
||||
func targetFromMatch(id ipcauth.Identity, handle string, match profilemanager.HandleMatch) (ipcauth.Target, error) {
|
||||
var owned []profilemanager.Profile
|
||||
for _, p := range match.Profiles {
|
||||
if p.AccessibleBy(id) {
|
||||
owned = append(owned, p)
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case len(owned) == 1:
|
||||
return ipcauth.Target{Path: owned[0].Path, Owned: true}, nil
|
||||
|
||||
case len(owned) > 1:
|
||||
return ipcauth.Target{}, gstatus.Errorf(codes.InvalidArgument, "%v", &profilemanager.ErrAmbiguousHandle{
|
||||
Handle: handle,
|
||||
Candidates: owned,
|
||||
Kind: match.Kind,
|
||||
})
|
||||
|
||||
case len(match.Profiles) > 0:
|
||||
// The handle names a profile that is real but not the caller's.
|
||||
return ipcauth.Target{Path: match.Profiles[0].Path}, nil
|
||||
|
||||
default:
|
||||
return ipcauth.Target{}, gstatus.Errorf(codes.NotFound, "profile %q not found", handle)
|
||||
}
|
||||
}
|
||||
|
||||
// matchHandleError renders a failed match as something the caller can act on.
|
||||
func matchHandleError(handle string, err error) error {
|
||||
if errors.Is(err, profilemanager.ErrProfileNotFound) {
|
||||
return gstatus.Errorf(codes.NotFound, "profile %q not found", handle)
|
||||
}
|
||||
return fmt.Errorf("match profile: %w", err)
|
||||
}
|
||||
|
||||
// targetProfile returns the profile the gate resolved and authorized for this
|
||||
// request.
|
||||
func (s *Server) targetProfile(ctx context.Context) (*profilemanager.Profile, error) {
|
||||
path, ok := ipcauth.TargetFromContext(ctx)
|
||||
if !ok {
|
||||
return nil, gstatus.Error(codes.Internal, "no target profile was resolved for this request")
|
||||
}
|
||||
|
||||
resolved, err := s.profileManager.ProfileByPath(path)
|
||||
if err != nil {
|
||||
log.Debugf("the profile the gate resolved at %q is gone: %v", path, err)
|
||||
return nil, gstatus.Error(codes.NotFound, "the profile this request names is no longer there")
|
||||
}
|
||||
return resolved, nil
|
||||
}
|
||||
|
||||
// afterProfileResolve is a seam for tests to run a concurrent profile switch
|
||||
|
||||
@@ -103,8 +103,9 @@ func TestSwitchProfile_ClearsJWTCache(t *testing.T) {
|
||||
const target = "second"
|
||||
username := "tester"
|
||||
owner := unprivilegedIdentity()
|
||||
targetPath := filepath.Join(profilemanager.DefaultConfigPathDir, target+".json")
|
||||
_, err := profilemanager.UpdateOrCreateConfig(profilemanager.ConfigInput{
|
||||
ConfigPath: filepath.Join(profilemanager.DefaultConfigPathDir, target+".json"),
|
||||
ConfigPath: targetPath,
|
||||
ManagementURL: "https://api.netbird.io:443",
|
||||
Owner: &owner,
|
||||
})
|
||||
@@ -115,7 +116,7 @@ func TestSwitchProfile_ClearsJWTCache(t *testing.T) {
|
||||
name := target
|
||||
// The handler scopes the switch to the caller's identity, which a real
|
||||
// caller gets from the daemon's transport credentials.
|
||||
_, err = s.SwitchProfile(ctxWithIdentity(owner), &proto.SwitchProfileRequest{ProfileName: &name, Username: &username})
|
||||
_, err = s.SwitchProfile(withTarget(ctxWithIdentity(owner), targetPath), &proto.SwitchProfileRequest{ProfileName: &name, Username: &username})
|
||||
require.NoError(t, err)
|
||||
|
||||
active, err := s.profileManager.GetActiveProfileState()
|
||||
|
||||
+77
-21
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -15,10 +16,9 @@ import (
|
||||
|
||||
// Resolving a handle claims every legacy profile the caller can take, the
|
||||
// active one included, whatever profile the handle itself names. SessionHolder
|
||||
// answers from the daemon's in-memory config, so OwnsProfile has to refresh it
|
||||
// for any handle: a copy taken before the claim reports no owner at all, and a
|
||||
// session with no owner is one every identified caller may take over.
|
||||
func TestOwnsProfile_RefreshesActiveConfigForAnyHandle(t *testing.T) {
|
||||
// answers from the daemon's in-memory config, so ResolveTarget has to refresh it
|
||||
// for any handle.
|
||||
func TestResolveTarget_RefreshesActiveConfigForAnyHandle(t *testing.T) {
|
||||
other := "second-profile"
|
||||
|
||||
for _, tc := range []struct {
|
||||
@@ -47,9 +47,9 @@ func TestOwnsProfile_RefreshesActiveConfigForAnyHandle(t *testing.T) {
|
||||
_, running := s.SessionHolder()
|
||||
require.False(t, running, "fixture is wrong: the stale copy already names an owner")
|
||||
|
||||
owns, err := s.OwnsProfile(owner, tc.handle)
|
||||
target, err := s.ResolveTarget(owner, tc.handle)
|
||||
require.NoError(t, err)
|
||||
require.True(t, owns, "the caller owns every profile in this fixture")
|
||||
require.True(t, target.Owned, "the caller owns every profile in this fixture")
|
||||
|
||||
holder, running := s.SessionHolder()
|
||||
require.True(t, running, "the claimed owner never reached the daemon's config, so the live session is unowned")
|
||||
@@ -60,20 +60,18 @@ func TestOwnsProfile_RefreshesActiveConfigForAnyHandle(t *testing.T) {
|
||||
|
||||
// A caller whose profile the daemon cannot read is not the owner of anything.
|
||||
// The answer has to be no rather than a panic in the authorization path.
|
||||
func TestOwnsProfile_UnreadableActiveProfileStateDenies(t *testing.T) {
|
||||
func TestResolveTarget_UnreadableActiveProfileStateDenies(t *testing.T) {
|
||||
s, _, _, _, _ := setupServerWithProfile(t)
|
||||
|
||||
require.NoError(t, os.WriteFile(profilemanager.ActiveProfileStatePath, []byte("{"), 0600))
|
||||
|
||||
owns, err := s.OwnsProfile(unprivilegedIdentity(), "")
|
||||
target, err := s.ResolveTarget(unprivilegedIdentity(), "")
|
||||
require.NoError(t, err, "an unreadable active profile is not the caller's handle to fix")
|
||||
require.False(t, owns)
|
||||
require.False(t, target.Owned)
|
||||
}
|
||||
|
||||
// A config the daemon cannot re-read leaves the one it already has in place.
|
||||
// Dropping a nil in its stead would take down every reader of it, SessionHolder
|
||||
// among them, which is the authorization path itself.
|
||||
func TestOwnsProfile_UnreadableConfigKeepsTheOneInPlace(t *testing.T) {
|
||||
func TestResolveTarget_UnreadableConfigKeepsTheOneInPlace(t *testing.T) {
|
||||
s, _, _, _, _ := setupServerWithProfile(t)
|
||||
|
||||
// An ID no path can be built for, which is what a hand-edited or
|
||||
@@ -84,9 +82,9 @@ func TestOwnsProfile_UnreadableConfigKeepsTheOneInPlace(t *testing.T) {
|
||||
s.config = kept
|
||||
s.clientRunning = true
|
||||
|
||||
owns, err := s.OwnsProfile(unprivilegedIdentity(), "")
|
||||
require.False(t, owns, "a profile that did not resolve is nobody's")
|
||||
require.Equal(t, codes.NotFound, gstatus.Code(err), "resolution failed")
|
||||
target, err := s.ResolveTarget(unprivilegedIdentity(), "")
|
||||
require.NoError(t, err, "an active profile the daemon cannot place is not the caller's handle to fix")
|
||||
require.False(t, target.Owned, "a profile the caller does not own is nobody's to act on")
|
||||
require.Same(t, kept, s.config, "a failed reload replaced the daemon's config")
|
||||
|
||||
holder, running := s.SessionHolder()
|
||||
@@ -98,7 +96,7 @@ func TestOwnsProfile_UnreadableConfigKeepsTheOneInPlace(t *testing.T) {
|
||||
// reads every profile off disk, and SwitchProfile only needs the daemon lock,
|
||||
// which the gate does not hold. The config the reload publishes has to be the
|
||||
// one the daemon is now on, not the one the check started out reading.
|
||||
func TestOwnsProfile_ReloadFollowsASwitchThatLandsMidCheck(t *testing.T) {
|
||||
func TestResolveTarget_ReloadFollowsASwitchThatLandsMidCheck(t *testing.T) {
|
||||
s, _, activeProfile, _, _ := setupServerWithProfile(t)
|
||||
owner := unprivilegedIdentity()
|
||||
|
||||
@@ -123,9 +121,9 @@ func TestOwnsProfile_ReloadFollowsASwitchThatLandsMidCheck(t *testing.T) {
|
||||
}
|
||||
t.Cleanup(func() { afterProfileResolve = nil })
|
||||
|
||||
owns, err := s.OwnsProfile(owner, activeProfile)
|
||||
target, err := s.ResolveTarget(owner, activeProfile)
|
||||
require.NoError(t, err)
|
||||
require.True(t, owns)
|
||||
require.True(t, target.Owned)
|
||||
|
||||
require.NotNil(t, s.config.ManagementURL)
|
||||
require.Equal(t, switchedToURL, s.config.ManagementURL.String(),
|
||||
@@ -133,15 +131,73 @@ func TestOwnsProfile_ReloadFollowsASwitchThatLandsMidCheck(t *testing.T) {
|
||||
}
|
||||
|
||||
// The handlers that start a session read their config off disk themselves.
|
||||
func TestOwnsProfile_IdleDaemonKeepsItsConfig(t *testing.T) {
|
||||
func TestResolveTarget_IdleDaemonKeepsItsConfig(t *testing.T) {
|
||||
s, _, activeProfile, _, _ := setupServerWithProfile(t)
|
||||
|
||||
untouched := &profilemanager.Config{}
|
||||
s.config = untouched
|
||||
s.clientRunning = false
|
||||
|
||||
owns, err := s.OwnsProfile(unprivilegedIdentity(), activeProfile)
|
||||
target, err := s.ResolveTarget(unprivilegedIdentity(), activeProfile)
|
||||
require.NoError(t, err)
|
||||
require.True(t, owns)
|
||||
require.True(t, target.Owned)
|
||||
require.Same(t, untouched, s.config)
|
||||
}
|
||||
|
||||
// foreignIdentity is a caller that is neither this process nor the one the test
|
||||
// fixtures own profiles for, so a profile stamped for either is somebody else.
|
||||
func foreignIdentity() ipcauth.Identity {
|
||||
if runtime.GOOS == "windows" {
|
||||
return ipcauth.KnownForTest(ipcauth.Identity{SID: "S-1-5-21-1-2-3-4242"})
|
||||
}
|
||||
return ipcauth.KnownForTest(ipcauth.Identity{UID: unprivUID + 1, GID: unprivUID + 1})
|
||||
}
|
||||
|
||||
// Two accounts can hold the same legacy profile ID in their own directories,
|
||||
// and a handle is resolved against every profile on the machine.
|
||||
func TestResolveTarget_PrefersTheCallersOwnOverANamesake(t *testing.T) {
|
||||
s, _, _, _, _ := setupServerWithProfile(t)
|
||||
|
||||
shared := "shared-legacy-name"
|
||||
ownPath := plantNamesakeProfiles(t, s, shared)
|
||||
|
||||
target, err := s.ResolveTarget(unprivilegedIdentity(), shared)
|
||||
require.NoError(t, err, "another account's namesake must not make the handle ambiguous")
|
||||
require.True(t, target.Owned)
|
||||
require.Equal(t, ownPath, target.Path, "the handle resolved to the other account's profile")
|
||||
}
|
||||
|
||||
// A profile that exists but belongs to somebody else resolves, so the refusal
|
||||
// is about ownership rather than about the handle.
|
||||
func TestResolveTarget_AnotherUsersProfileIsNotOwned(t *testing.T) {
|
||||
s, _, activeProfile, _, _ := setupServerWithProfile(t)
|
||||
|
||||
target, err := s.ResolveTarget(foreignIdentity(), activeProfile)
|
||||
require.NoError(t, err, "the profile is there, so nothing about the handle is wrong")
|
||||
require.False(t, target.Owned, "a profile the caller does not own is not theirs to act on")
|
||||
}
|
||||
|
||||
// Only a handle matching two of the caller's own profiles is genuinely
|
||||
// ambiguous. Anything else has an answer, and the candidates named are theirs.
|
||||
func TestResolveTarget_AmbiguousOnlyAmongTheCallersOwn(t *testing.T) {
|
||||
s, _, _, _, _ := setupServerWithProfile(t)
|
||||
|
||||
shared := "shared-legacy-name"
|
||||
plantNamesakeProfiles(t, s, shared)
|
||||
|
||||
// A second copy of the same ID in a directory this caller also claims,
|
||||
// which is the case no owner can settle.
|
||||
secondDir := filepath.Join(profilemanager.DefaultConfigPathDir, "second")
|
||||
require.NoError(t, os.MkdirAll(secondDir, 0700))
|
||||
_, err := profilemanager.UpdateOrCreateConfig(profilemanager.ConfigInput{
|
||||
ConfigPath: filepath.Join(secondDir, shared+".json"),
|
||||
ManagementURL: "https://api.netbird.io:443",
|
||||
Owner: testProfileOwner(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = s.ResolveTarget(unprivilegedIdentity(), shared)
|
||||
require.Error(t, err)
|
||||
require.Equal(t, codes.InvalidArgument, gstatus.Code(err),
|
||||
"two profiles of the caller's own under one handle is theirs to disambiguate")
|
||||
}
|
||||
@@ -100,6 +100,12 @@ func setupServerWithProfile(t *testing.T) (s *Server, ctx context.Context, profN
|
||||
// without an identity the gate would (correctly) refuse the SSH fields.
|
||||
ctx = privilegedTestCtx()
|
||||
s = New(ctx, "console", "", false, false, false, false)
|
||||
|
||||
// The gate resolves the request's handle before the handler runs and hands
|
||||
// the profile down in the context. Driving the handler directly skips the
|
||||
// gate, so the fixture stands in for it with the profile these requests
|
||||
// name.
|
||||
ctx = withTarget(ctx, cfgPath)
|
||||
return s, ctx, profName, currUser.Username, cfgPath
|
||||
}
|
||||
|
||||
|
||||
@@ -58,6 +58,10 @@ func TestSetConfig_AllFieldsSaved(t *testing.T) {
|
||||
ctx := privilegedTestCtx()
|
||||
s := New(ctx, "console", "", false, false, false, false)
|
||||
|
||||
// The gate resolves the handle and hands the profile down in the context;
|
||||
// driving the handler directly skips it, so the test stands in for it.
|
||||
ctx = withTarget(ctx, ic.ConfigPath)
|
||||
|
||||
rosenpassEnabled := true
|
||||
rosenpassPermissive := true
|
||||
serverSSHAllowed := true
|
||||
|
||||
@@ -38,6 +38,14 @@ var unprivUID = uint32(os.Geteuid() + 1)
|
||||
|
||||
// The fabricated identities have to be shaped like the platform's: a uid says
|
||||
// nothing on Windows, and a zero uid there would read as root and be privileged.
|
||||
// withTarget is a request context as the gate leaves it: carrying the profile
|
||||
// the gate resolved and authorized out of the request's handle. A test that
|
||||
// calls a target-scoped handler directly supplies it, since the interceptor
|
||||
// that normally would is not in play.
|
||||
func withTarget(ctx context.Context, profilePath string) context.Context {
|
||||
return ipcauth.ContextWithTarget(ctx, profilePath)
|
||||
}
|
||||
|
||||
func rootCtx() context.Context { return ctxWithIdentity(privilegedIdentity()) }
|
||||
func userCtx() context.Context { return ctxWithIdentity(unprivilegedIdentity()) }
|
||||
|
||||
|
||||
Reference in New Issue
Block a user