1package app
2
3import (
4 "crypto/rand"
5 "encoding/hex"
6 "encoding/json"
7 "fmt"
8 "os"
9 "path/filepath"
10 "time"
11
12 "github.com/bnema/zerowrap"
13)
14
15const (
16 internalRegistryUsername = "gordon-internal"
17 serviceTokenSubject = "gordon-service"
18 serviceTokenDefaultTTL = 30 * 24 * time.Hour
19)
20
21func generateInternalRegistryAuth() (string, string, error) {
22 password, err := randomTokenHex(32)
23 if err != nil {
24 return "", "", err
25 }
26 return internalRegistryUsername, password, nil
27}
28
29func randomTokenHex(size int) (string, error) {
30 buf := make([]byte, size)
31 if _, err := rand.Read(buf); err != nil {
32 return "", err
33 }
34 return hex.EncodeToString(buf), nil
35}
36
37// InternalCredentials holds the internal registry credentials for CLI access.
38type InternalCredentials struct {
39 Username string `json:"username"`
40 Password string `json:"password"`
41}
42
43// getSecureRuntimeDir returns a secure directory for runtime files.
44// Priority: XDG_RUNTIME_DIR > ~/.gordon/run
45func getSecureRuntimeDir() (string, error) {
46 // Try XDG_RUNTIME_DIR first (typically /run/user/<uid> on Linux)
47 if runtimeDir := os.Getenv("XDG_RUNTIME_DIR"); runtimeDir != "" {
48 gordonDir := filepath.Join(runtimeDir, "gordon")
49 if err := os.MkdirAll(gordonDir, 0700); err == nil {
50 return gordonDir, nil
51 }
52 }
53
54 // Fall back to ~/.gordon/run
55 homeDir, err := os.UserHomeDir()
56 if err != nil {
57 return "", fmt.Errorf("failed to get home directory: %w", err)
58 }
59
60 gordonDir := filepath.Join(homeDir, ".gordon", "run")
61 if err := os.MkdirAll(gordonDir, 0700); err != nil {
62 return "", fmt.Errorf("failed to create runtime directory: %w", err)
63 }
64
65 return gordonDir, nil
66}
67
68// getInternalCredentialsFile returns the path to the internal credentials file.
69// SECURITY: Credentials are stored in a secure location with restricted permissions.
70func getInternalCredentialsFile() string {
71 runtimeDir, err := getSecureRuntimeDir()
72 if err != nil {
73 // Fall back to temp dir if we can't get secure dir (shouldn't happen)
74 return filepath.Join(os.TempDir(), "gordon-internal-creds.json")
75 }
76 return filepath.Join(runtimeDir, "internal-creds.json")
77}
78
79// persistInternalCredentials saves the internal registry credentials to a secure file.
80// SECURITY: Credentials are stored in XDG_RUNTIME_DIR or ~/.gordon/run with 0600 permissions.
81// The file is cleaned up on graceful shutdown but may persist if Gordon crashes.
82// These credentials are for internal loopback communication only and are regenerated on each start.
83func persistInternalCredentials(username, password string) error {
84 creds := InternalCredentials{
85 Username: username,
86 Password: password,
87 }
88 data, err := json.Marshal(creds)
89 if err != nil {
90 return fmt.Errorf("failed to marshal credentials: %w", err)
91 }
92
93 credFile := getInternalCredentialsFile()
94
95 // Ensure parent directory exists with secure permissions
96 if err := os.MkdirAll(filepath.Dir(credFile), 0700); err != nil {
97 return fmt.Errorf("failed to create credentials directory: %w", err)
98 }
99
100 // Write file with restrictive permissions (owner read/write only)
101 if err := os.WriteFile(credFile, data, 0600); err != nil {
102 return fmt.Errorf("failed to write credentials file: %w", err)
103 }
104 return nil
105}
106
107// cleanupInternalCredentials removes the internal credentials file.
108func cleanupInternalCredentials() {
109 _ = os.Remove(getInternalCredentialsFile())
110}
111
112// getInternalCredentialsCandidates returns candidate file paths in priority order:
113// 1. XDG_RUNTIME_DIR/gordon/ (set by systemd for the daemon)
114// 2. /run/user/<uid>/gordon/ (well-known systemd default, for CLI in shells without XDG_RUNTIME_DIR)
115// 3. ~/.gordon/run/ (fallback for non-systemd environments)
116// 4. os.TempDir() (last resort, matches getInternalCredentialsFile fallback path)
117func getInternalCredentialsCandidates() []string {
118 var candidates []string
119
120 // 1. XDG_RUNTIME_DIR (set in daemon's environment)
121 if runtimeDir := os.Getenv("XDG_RUNTIME_DIR"); runtimeDir != "" {
122 candidates = append(candidates, filepath.Join(runtimeDir, "gordon", "internal-creds.json"))
123 }
124
125 // 2. /run/user/<uid>/gordon/ (systemd default, may not be in CLI's env)
126 uid := os.Getuid()
127 sysRuntime := filepath.Join("/run/user", fmt.Sprintf("%d", uid), "gordon", "internal-creds.json")
128 // Avoid duplicate if XDG_RUNTIME_DIR already points here
129 if len(candidates) == 0 || candidates[0] != sysRuntime {
130 candidates = append(candidates, sysRuntime)
131 }
132
133 // 3. ~/.gordon/run/ fallback
134 if homeDir, err := os.UserHomeDir(); err == nil {
135 candidates = append(candidates, filepath.Join(homeDir, ".gordon", "run", "internal-creds.json"))
136 }
137
138 // 4. os.TempDir() last resort — matches the fallback path in getInternalCredentialsFile,
139 // ensuring GetInternalCredentials can find credentials even when getSecureRuntimeDir fails.
140 candidates = append(candidates, filepath.Join(os.TempDir(), "gordon-internal-creds.json"))
141
142 return candidates
143}
144
145// GetInternalCredentialsFromCandidates reads credentials from the first candidate file that exists.
146// Exported for testing.
147func GetInternalCredentialsFromCandidates(candidates []string) (*InternalCredentials, error) {
148 var lastErr error
149 for _, path := range candidates {
150 data, err := os.ReadFile(path)
151 if os.IsNotExist(err) {
152 continue
153 }
154 if err != nil {
155 // Non-permission errors (e.g. EACCES) may be transient or path-specific;
156 // record and try the next candidate rather than failing immediately.
157 lastErr = fmt.Errorf("failed to read credentials file %s: %w", path, err)
158 continue
159 }
160 var creds InternalCredentials
161 if err := json.Unmarshal(data, &creds); err != nil {
162 // Corrupt file — record and fall through to lower-priority candidates.
163 lastErr = fmt.Errorf("failed to parse credentials at %s: %w", path, err)
164 continue
165 }
166 return &creds, nil
167 }
168 if lastErr != nil {
169 return nil, lastErr
170 }
171 return nil, fmt.Errorf("no credentials file found (is Gordon running?): checked %v", candidates)
172}
173
174// GetInternalCredentials reads the internal registry credentials from file.
175// Probes all candidate runtime directories so CLI works regardless of whether
176// XDG_RUNTIME_DIR is set in the current shell environment.
177func GetInternalCredentials() (*InternalCredentials, error) {
178 return GetInternalCredentialsFromCandidates(getInternalCredentialsCandidates())
179}
180
181func setupInternalRegistryAuth(svc *services, log zerowrap.Logger) error {
182 var err error
183 svc.internalRegUser, svc.internalRegPass, err = generateInternalRegistryAuth()
184 if err != nil {
185 return log.WrapErr(err, "failed to generate internal registry credentials")
186 }
187
188 // Persist credentials to file for CLI access (gordon auth internal)
189 if err := persistInternalCredentials(svc.internalRegUser, svc.internalRegPass); err != nil {
190 log.Warn().Err(err).Msg("failed to persist internal credentials for CLI access")
191 }
192
193 log.Debug().Msg("internal registry auth generated for loopback pulls")
194 return nil
195}