Skip to content

Commit fe57f25

Browse files
refactor: Check current and run as users before changing user
* When current user and run as user are same, there is no need to called SETUID. By verifying this at the beginning we can avoid requiring an additional cap for the app Signed-off-by: Mahendra Paipuri <[email protected]>
1 parent 502bf93 commit fe57f25

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

internal/security/manager.go

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ type acl struct {
4141
type Manager struct {
4242
logger *slog.Logger
4343
runAsUser *user.User
44+
currentUser *user.User
4445
caps []cap.Value
4546
acls []acl
4647
securityContexts map[string]*SecurityContext
@@ -57,7 +58,7 @@ func NewManager(c *Config, logger *slog.Logger) (*Manager, error) {
5758
}
5859

5960
// Get current user
60-
currentUser, err := user.Current()
61+
manager.currentUser, err = user.Current()
6162
if err != nil {
6263
return nil, fmt.Errorf("failed to get current user: %w", err)
6364
}
@@ -107,10 +108,10 @@ func NewManager(c *Config, logger *slog.Logger) (*Manager, error) {
107108
switch mode := fperms.Stat.Mode(); {
108109
case mode.IsDir():
109110
perms = 5
110-
hasPerms = hasReadExecutable(fperms, currentUser, manager.runAsUser)
111+
hasPerms = hasReadExecutable(fperms, manager.currentUser, manager.runAsUser)
111112
case mode.IsRegular():
112113
perms = 4
113-
hasPerms = hasRead(fperms, currentUser, manager.runAsUser)
114+
hasPerms = hasRead(fperms, manager.currentUser, manager.runAsUser)
114115
}
115116

116117
// If the path is readable/executable by runAsUser, nothing to do here. Continue
@@ -144,10 +145,10 @@ func NewManager(c *Config, logger *slog.Logger) (*Manager, error) {
144145
switch mode := fperms.Stat.Mode(); {
145146
case mode.IsDir():
146147
perms = 7
147-
hasPerms = hasReadWriteExecutable(fperms, currentUser, manager.runAsUser)
148+
hasPerms = hasReadWriteExecutable(fperms, manager.currentUser, manager.runAsUser)
148149
case mode.IsRegular():
149150
perms = 6
150-
hasPerms = hasReadWrite(fperms, currentUser, manager.runAsUser)
151+
hasPerms = hasReadWrite(fperms, manager.currentUser, manager.runAsUser)
151152
}
152153

153154
// If the path is readable/executable by runAsUser, nothing to do here. Continue
@@ -292,6 +293,11 @@ func (m *Manager) addACLEntries() error {
292293

293294
// changeUser switches the current user to run as user.
294295
func (m *Manager) changeUser() error {
296+
// If current user and runAsUser is same, return
297+
if m.currentUser.Uid == m.runAsUser.Uid {
298+
return nil
299+
}
300+
295301
localUserUID, err := strconv.Atoi(m.runAsUser.Uid)
296302
if err != nil {
297303
return fmt.Errorf("could not parse UID %s as int: %w", m.runAsUser.Uid, err)

0 commit comments

Comments
 (0)