* Shared FD-or-well-known-file credential reader. * * Priority order: * 1. File descriptor (legacy path) — env var points at a pipe FD passed by * the Go env-manager via cmd.ExtraFiles. Pipe is drained on first read * and doesn't cross exec/tmux boundaries. * 2. Well-known file — wri
({
envVar,
wellKnownPath,
label,
getCached,
setCached,
}: {
envVar: string
wellKnownPath: string
label: string
getCached: () => string | null | undefined
setCached: (value: string | null) => void
})
| 95 | * Returns null if neither source has a credential. Cached in global state. |
| 96 | */ |
| 97 | function getCredentialFromFd({ |
| 98 | envVar, |
| 99 | wellKnownPath, |
| 100 | label, |
| 101 | getCached, |
| 102 | setCached, |
| 103 | }: { |
| 104 | envVar: string |
| 105 | wellKnownPath: string |
| 106 | label: string |
| 107 | getCached: () => string | null | undefined |
| 108 | setCached: (value: string | null) => void |
| 109 | }): string | null { |
| 110 | const cached = getCached() |
| 111 | if (cached !== undefined) { |
| 112 | return cached |
| 113 | } |
| 114 | |
| 115 | const fdEnv = process.env[envVar] |
| 116 | if (!fdEnv) { |
| 117 | // No FD env var — either we're not in CCR, or we're a subprocess whose |
| 118 | // parent stripped the (useless) FD env var. Try the well-known file. |
| 119 | const fromFile = readTokenFromWellKnownFile(wellKnownPath, label) |
| 120 | setCached(fromFile) |
| 121 | return fromFile |
| 122 | } |
| 123 | |
| 124 | const fd = parseInt(fdEnv, 10) |
| 125 | if (Number.isNaN(fd)) { |
| 126 | logForDebugging( |
| 127 | `${envVar} must be a valid file descriptor number, got: ${fdEnv}`, |
| 128 | { level: 'error' }, |
| 129 | ) |
| 130 | setCached(null) |
| 131 | return null |
| 132 | } |
| 133 | |
| 134 | try { |
| 135 | // Use /dev/fd on macOS/BSD, /proc/self/fd on Linux |
| 136 | const fsOps = getFsImplementation() |
| 137 | const fdPath = |
| 138 | process.platform === 'darwin' || process.platform === 'freebsd' |
| 139 | ? `/dev/fd/${fd}` |
| 140 | : `/proc/self/fd/${fd}` |
| 141 | |
| 142 | // eslint-disable-next-line custom-rules/no-sync-fs -- legacy FD path, read once at startup, caller is sync |
| 143 | const token = fsOps.readFileSync(fdPath, { encoding: 'utf8' }).trim() |
| 144 | if (!token) { |
| 145 | logForDebugging(`File descriptor contained empty ${label}`, { |
| 146 | level: 'error', |
| 147 | }) |
| 148 | setCached(null) |
| 149 | return null |
| 150 | } |
| 151 | logForDebugging(`Successfully read ${label} from file descriptor ${fd}`) |
| 152 | setCached(token) |
| 153 | maybePersistTokenForSubprocesses(wellKnownPath, token, label) |
| 154 | return token |
no test coverage detected