@@ -158,20 +158,46 @@ func getMountOptions(context map[string]string) string {
158158 return ""
159159}
160160
161- // chmodIfPermissionMismatch only perform chmod when permission mismatches
162- func chmodIfPermissionMismatch (targetPath string , mode os.FileMode ) error {
161+ // unixModeToFileMode converts a raw Unix mode_t value (e.g. 02770) into Go's
162+ // os.FileMode representation with correct bit positions for setuid, setgid,
163+ // and sticky bits.
164+ func unixModeToFileMode (mode uint32 ) os.FileMode {
165+ goMode := os .FileMode (mode ) & os .ModePerm
166+ if mode & 04000 != 0 {
167+ goMode |= os .ModeSetuid
168+ }
169+ if mode & 02000 != 0 {
170+ goMode |= os .ModeSetgid
171+ }
172+ if mode & 01000 != 0 {
173+ goMode |= os .ModeSticky
174+ }
175+ return goMode
176+ }
177+
178+ // chmodIfPermissionMismatch only performs chmod when permission mismatches.
179+ // The mode parameter is a raw Unix mode_t value (e.g. 02770).
180+ // Compares both regular permission bits (0777) and special bits (setuid/setgid/sticky)
181+ // to avoid unnecessary chmod calls while still detecting special-bit differences.
182+ // Note: on Windows, the chmod fallback (os.Chmod) cannot apply special bits, so
183+ // modes with setuid/setgid/sticky will never fully converge there.
184+ func chmodIfPermissionMismatch (targetPath string , mode uint32 ) error {
163185 info , err := os .Lstat (targetPath )
164186 if err != nil {
165187 return err
166188 }
167- perm := info .Mode () & os .ModePerm
168- if perm != mode {
169- klog .V (2 ).Infof ("chmod targetPath(%s, mode:0%o) with permissions(0%o)" , targetPath , info .Mode (), mode )
170- if err := os .Chmod (targetPath , mode ); err != nil {
189+ // Convert the raw Unix mode to Go's FileMode representation for comparison.
190+ desiredMode := unixModeToFileMode (mode )
191+ // Mask for perm bits + special bits in Go's representation.
192+ mask := os .ModePerm | os .ModeSetuid | os .ModeSetgid | os .ModeSticky
193+ currentMode := info .Mode () & mask
194+ if currentMode != desiredMode {
195+ klog .V (2 ).Infof ("chmod targetPath(%s, currentMode:0%o) with desiredMode(0%o)" , targetPath , mode , mode )
196+ if err := chmod (targetPath , mode ); err != nil {
171197 return err
172198 }
173199 } else {
174- klog .V (2 ).Infof ("skip chmod on targetPath(%s) since mode is already 0%o) " , targetPath , info . Mode () )
200+ klog .V (2 ).Infof ("skip chmod on targetPath(%s) since mode is already 0%o" , targetPath , mode )
175201 }
176202 return nil
177203}
0 commit comments