-
-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathruntime_identity.go
More file actions
319 lines (267 loc) · 8.94 KB
/
Copy pathruntime_identity.go
File metadata and controls
319 lines (267 loc) · 8.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package startup
import (
"context"
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
pkgutils "github.com/getarcaneapp/arcane/backend/pkg/utils"
)
const (
defaultDataDirectory = "/app/data"
defaultBuildsDirectory = "/builds"
defaultDatabaseURL = "file:data/arcane.db?_pragma=journal_mode(WAL)&_pragma=busy_timeout(2500)&_txlock=immediate"
defaultDockerSocketPath = "/var/run/docker.sock"
defaultRuntimeUID = 65532
defaultRuntimeGID = 65532
mountInfoPath = "/proc/self/mountinfo"
)
type runtimeIdentityRequest struct {
Enabled bool
UID int
GID int
CredentialUID uint32
CredentialGID uint32
}
// ApplyRequestedRuntimeIdentity switches the current process to the configured
// runtime UID/GID before the rest of the app initializes.
func ApplyRequestedRuntimeIdentity(ctx context.Context) error {
req, warning, err := loadRuntimeIdentityRequestInternal(os.Getenv)
if warning != "" {
fmt.Fprintf(os.Stderr, "Runtime identity warning: %s\n", warning)
}
if err != nil || !req.Enabled {
return err
}
runtimeUID := req.UID
runtimeGID := req.GID
// Avoid re-execing forever when the requested runtime identity is already active,
// including explicit root requests such as PUID=0/PGID=0.
if os.Geteuid() == runtimeUID && os.Getegid() == runtimeGID {
return ensureSQLiteFilesExistInternal(os.Getenv("DATABASE_URL"))
}
if os.Geteuid() != 0 {
fmt.Fprintf(os.Stderr, "Runtime identity warning: process is not root (euid=%d), cannot switch to PUID=%d PGID=%d; continuing as current user\n",
os.Geteuid(), runtimeUID, runtimeGID)
return ensureSQLiteFilesExistInternal(os.Getenv("DATABASE_URL"))
}
mountpoints, err := loadMountpointsInternal(mountInfoPath)
if err != nil {
return fmt.Errorf("load mountpoints: %w", err)
}
if err := prepareWritablePathsInternal(runtimeUID, runtimeGID, mountpoints); err != nil {
return err
}
return reexecWithRuntimeIdentityInternal(ctx, req)
}
func loadRuntimeIdentityRequestInternal(getenv func(string) string) (runtimeIdentityRequest, string, error) {
puid := strings.TrimSpace(getenv("PUID"))
pgid := strings.TrimSpace(getenv("PGID"))
if puid == "" && pgid == "" {
if strings.EqualFold(strings.TrimSpace(getenv("ARCANE_DEFAULT_NONROOT")), "true") {
return runtimeIdentityRequest{
Enabled: true,
UID: defaultRuntimeUID,
GID: defaultRuntimeGID,
CredentialUID: uint32(defaultRuntimeUID),
CredentialGID: uint32(defaultRuntimeGID),
}, "", nil
}
return runtimeIdentityRequest{}, "", nil
}
if puid == "" || pgid == "" {
return runtimeIdentityRequest{}, "PUID and PGID must both be set to enable non-root mode; continuing with default runtime user", nil
}
uid, credentialUID, err := parseRuntimeIdentityValueInternal(puid, "PUID")
if err != nil {
return runtimeIdentityRequest{}, "", fmt.Errorf("invalid PUID %q: %w", puid, err)
}
gid, credentialGID, err := parseRuntimeIdentityValueInternal(pgid, "PGID")
if err != nil {
return runtimeIdentityRequest{}, "", fmt.Errorf("invalid PGID %q: %w", pgid, err)
}
return runtimeIdentityRequest{
Enabled: true,
UID: uid,
GID: gid,
CredentialUID: credentialUID,
CredentialGID: credentialGID,
}, "", nil
}
func runtimeIdentitySupplementaryGroupsInternal(getenv func(string) string, resolveSocketGroup func(string) (uint32, bool)) []uint32 {
socketPath, ok := dockerSocketPathInternal(getenv("DOCKER_HOST"))
if !ok {
return nil
}
socketGID, ok := resolveSocketGroup(socketPath)
if !ok {
return nil
}
return []uint32{socketGID}
}
func dockerSocketPathInternal(raw string) (string, bool) {
value := strings.TrimSpace(raw)
if value == "" {
return defaultDockerSocketPath, true
}
parsed, err := url.Parse(value)
if err != nil || parsed.Scheme != "unix" {
return "", false
}
if parsed.Host != "" || parsed.Path != "" {
socketPath := parsed.Host + parsed.Path
if !strings.HasPrefix(socketPath, "/") {
socketPath = "/" + socketPath
}
return filepath.Clean(socketPath), true
}
if parsed.Opaque == "" {
return "", false
}
socketPath := strings.TrimPrefix(parsed.Opaque, "//")
if !strings.HasPrefix(socketPath, "/") {
socketPath = "/" + socketPath
}
return filepath.Clean(socketPath), true
}
func prepareWritablePathsInternal(uid int, gid int, mountpoints map[string]struct{}) error {
if err := os.MkdirAll(defaultDataDirectory, pkgutils.DirPerm); err != nil {
return fmt.Errorf("create data directory: %w", err)
}
if err := os.Chown(defaultDataDirectory, uid, gid); err != nil {
return fmt.Errorf("chown data directory: %w", err)
}
entries, err := os.ReadDir(defaultDataDirectory)
if err != nil {
return fmt.Errorf("read data directory: %w", err)
}
for _, entry := range entries {
entryPath := filepath.Join(defaultDataDirectory, entry.Name())
if _, mounted := mountpoints[entryPath]; mounted {
continue
}
if err := chownRecursiveInternal(entryPath, uid, gid, mountpoints); err != nil {
return fmt.Errorf("chown %s: %w", entryPath, err)
}
}
if _, mounted := mountpoints[defaultBuildsDirectory]; mounted {
return nil
}
if _, err := os.Stat(defaultBuildsDirectory); err != nil {
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("stat builds directory: %w", err)
}
if err := chownRecursiveInternal(defaultBuildsDirectory, uid, gid, mountpoints); err != nil {
return fmt.Errorf("chown builds directory: %w", err)
}
return nil
}
func ensureSQLiteFilesExistInternal(databaseURL string) error {
sqlitePath, ok, err := sqliteDatabasePathInternal(databaseURL)
if err != nil {
return err
}
if !ok {
return nil
}
// Ensure the parent directory exists before creating the file.
// This covers the "already the right user" early-return path where
// prepareWritablePathsInternal is not called.
dir := filepath.Dir(sqlitePath)
if dir != "" && dir != "." {
if err := os.MkdirAll(dir, pkgutils.DirPerm); err != nil { //nolint:gosec // path is derived from the configured SQLite DSN, not user input
return fmt.Errorf("create sqlite directory %s: %w", dir, err)
}
}
file, err := os.OpenFile(sqlitePath, os.O_CREATE|os.O_RDWR, pkgutils.FilePerm) //nolint:gosec // path is derived from the configured SQLite DSN
if err != nil {
return fmt.Errorf("create sqlite file %s: %w", sqlitePath, err)
}
if err := file.Close(); err != nil {
return fmt.Errorf("close sqlite file %s: %w", sqlitePath, err)
}
return nil
}
func sqliteDatabasePathInternal(databaseURL string) (string, bool, error) {
value := strings.TrimSpace(databaseURL)
if value == "" {
value = defaultDatabaseURL
}
if !strings.HasPrefix(value, "file:") {
return "", false, nil
}
parsed, err := url.Parse(value)
if err != nil {
return "", false, fmt.Errorf("parse sqlite database url: %w", err)
}
// For relative URLs like "file:data/arcane.db", url.Parse puts the path in
// Opaque (without a leading slash). For absolute URLs like "file:/app/data/arcane.db",
// Opaque is empty and Path contains the absolute path. Only strip the leading
// slash from the opaque portion to preserve absolute paths.
var pathPart string
if parsed.Opaque != "" {
pathPart = strings.TrimPrefix(parsed.Opaque, "/")
} else {
pathPart = parsed.Path
}
if pathPart == "" || strings.HasPrefix(pathPart, ":memory:") {
return "", false, nil
}
return filepath.Clean(pathPart), true, nil
}
func chownRecursiveInternal(path string, uid int, gid int, mountpoints map[string]struct{}) error {
return filepath.Walk(path, func(currentPath string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip any sub-tree that is a separate mountpoint.
if currentPath != path {
if _, mounted := mountpoints[filepath.Clean(currentPath)]; mounted {
return filepath.SkipDir
}
}
//nolint:gosec // currentPath comes from fixed container paths under /app/data or /builds
return os.Lchown(currentPath, uid, gid)
})
}
func loadMountpointsInternal(path string) (map[string]struct{}, error) {
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return map[string]struct{}{}, nil
}
return nil, err
}
return parseMountpointsInternal(string(data)), nil
}
func parseMountpointsInternal(data string) map[string]struct{} {
mountpoints := make(map[string]struct{})
for line := range strings.SplitSeq(data, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
fields := strings.Fields(line)
if len(fields) < 5 {
continue
}
mountpoint := filepath.Clean(unescapeMountInfoPathInternal(fields[4]))
mountpoints[mountpoint] = struct{}{}
}
return mountpoints
}
// unescapeMountInfoPathInternal decodes the kernel's octal escape sequences
// used in /proc/self/mountinfo. The kernel only uses \040 (space), \011 (tab),
// \012 (newline), and \134 (backslash) — no other escape forms appear.
func unescapeMountInfoPathInternal(path string) string {
replacer := strings.NewReplacer(
`\040`, " ",
`\011`, "\t",
`\012`, "\n",
`\134`, `\`,
)
return replacer.Replace(path)
}