@devries-cameron20 / composio Mirror · read-only
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 243 lines 8.94 KB
Raw
1 /**
2 * macOS Keychain store backed by the `/usr/bin/security` CLI.
3 *
4 * This is a structural port of the `apple-native-keyring-store` crate
5 * from keyring-rs. The Rust version calls Security.framework via
6 * `security-framework::os::macos::passwords::{find,set}_generic_password`;
7 * we shell out to `/usr/bin/security`'s `add-generic-password`,
8 * `find-generic-password`, and `delete-generic-password` subcommands
9 * because they are 1:1 wrappers over the same Security.framework APIs,
10 * ship with every macOS, and give us a trivially auditable execution
11 * surface vs. FFI.
12 *
13 * Exit-code mapping is taken from `decode_error` in
14 * `apple-native-keyring-store/src/keychain.rs`:
15 *
16 * errSecItemNotFound (-25300) → NoEntry
17 * errSecNotAvailable (-25291) → NoStorageAccess
18 * errSecReadOnly (-25292) → NoStorageAccess
19 * errSecNoSuchKeychain (-25294) → NoStorageAccess
20 * errSecInvalidKeychain (-25295) → NoStorageAccess
21 * errSecAuthFailed (-25293) → NoStorageAccess
22 * everything else → PlatformFailure
23 *
24 * The `security` CLI translates OSStatus values to its own exit codes
25 * (typically the low byte of the OSStatus), which is why we see exit
26 * 44 for item-not-found instead of -25300.
27 */
28
29 import type { CredentialStore, EntryModifiers } from '../core/store';
30 import { CredentialPersistence } from '../core/persistence';
31 import { KeyringError } from '../core/errors';
32 import { bytesToUtf8, decodeSecret, encodeSecret, runCommand, type SpawnResult } from './shared';
33
34 const SECURITY_BIN = '/usr/bin/security';
35
36 /** `security` CLI exit code for `errSecItemNotFound`. */
37 const EXIT_ITEM_NOT_FOUND = 44;
38 /** `security` CLI exit code for `errSecDuplicateItem`. */
39 const EXIT_DUPLICATE_ITEM = 45;
40 /**
41 * Exit codes that translate to `NoStorageAccess`. These correspond to
42 * the OSStatus values keyring-rs's `decode_error` maps to the same
43 * variant — keychain locked, read-only mount, missing/invalid keychain
44 * domain, or auth failure when the user cancels an unlock prompt.
45 */
46 const EXIT_NO_STORAGE_ACCESS = new Set([36, 37, 50, 51, 45401]);
47
48 /** Map the `keychain` modifier onto the `-A`/-domain flags of `security`. */
49 function domainFlag(domain: EntryModifiers['keychain']): readonly string[] {
50 // The `security` CLI picks the login keychain by default, which is
51 // the `User` domain. The other domains require the -A / --keychain
52 // flag with a specific path; surface them as NotSupportedByStore for
53 // v0 so we don't silently write to the wrong place.
54 if (domain === undefined || domain === 'User') {
55 return [];
56 }
57 throw new KeyringError({
58 kind: 'NotSupportedByStore',
59 operation: `macos keychain domain "${domain}"`,
60 });
61 }
62
63 function validateSpecifier(service: string, user: string): void {
64 // Empty service or user would become wildcards in Keychain Services
65 // — keyring-rs throws `Error::Invalid` here and we match that.
66 if (service.includes('\0')) {
67 throw new KeyringError({
68 kind: 'Invalid',
69 param: 'service',
70 reason: 'service must not contain NUL bytes',
71 });
72 }
73 if (user.includes('\0')) {
74 throw new KeyringError({
75 kind: 'Invalid',
76 param: 'user',
77 reason: 'user must not contain NUL bytes',
78 });
79 }
80 }
81
82 function classifyExitCode(result: SpawnResult, operation: string): KeyringError {
83 const code = result.code;
84 const stderr = bytesToUtf8(result.stderr).trim();
85 if (code === EXIT_ITEM_NOT_FOUND) {
86 return new KeyringError({ kind: 'NoEntry' });
87 }
88 if (code !== null && EXIT_NO_STORAGE_ACCESS.has(code)) {
89 return new KeyringError({
90 kind: 'NoStorageAccess',
91 cause: new Error(stderr || `security ${operation} failed with exit ${code}`),
92 });
93 }
94 return new KeyringError({
95 kind: 'PlatformFailure',
96 cause: new Error(stderr || `security ${operation} failed with exit ${code}`),
97 });
98 }
99
100 export class MacOSSecuritySubprocessStore implements CredentialStore {
101 readonly id = 'macos-security-subprocess';
102 readonly vendor = 'Apple Security.framework (via /usr/bin/security)';
103
104 persistence(): CredentialPersistence {
105 return CredentialPersistence.UntilDelete;
106 }
107
108 async setSecret(
109 service: string,
110 user: string,
111 secret: Uint8Array,
112 modifiers: EntryModifiers
113 ): Promise<void> {
114 validateSpecifier(service, user);
115 const encoded = encodeSecret(secret);
116 const label = modifiers.label ?? defaultLabel(service, user);
117 const domainArgs = domainFlag(modifiers.keychain);
118
119 // Delete-then-add pattern instead of `-U`: the `-U` flag updates
120 // the password of an existing entry but PRESERVES the old ACL.
121 // If a previous composio version wrote this entry with a
122 // per-binary ACL (e.g. the FFI ACL builder in an earlier beta),
123 // `-U` would leave that ACL in place and our `-A` flag would be
124 // silently ignored. Deleting first guarantees a fresh allow-any
125 // ACL on the next add.
126 //
127 // The delete is best-effort — if no entry exists yet (first
128 // login / clean install), `security` exits with 44 (itemNotFound)
129 // and we proceed to the add.
130 try {
131 await runCommand({
132 command: SECURITY_BIN,
133 args: ['delete-generic-password', '-a', user, '-s', service, ...domainArgs],
134 });
135 } catch {
136 // Spawn failure (e.g. /usr/bin/security missing) — the add
137 // below will hit the same failure and surface it properly.
138 }
139
140 // -A: allow ANY application to read this item without prompting
141 // (produces a genuine allow-any ACL — the only configuration
142 // that works reliably for reads from an ad-hoc signed
143 // composio binary via /usr/bin/security).
144 // -l: human-readable label (shown in Keychain Access).
145 //
146 // Password leak risk: `-w <value>` puts the secret on argv, so it
147 // is briefly visible in `ps` output. This matches the behavior of
148 // every OTHER tool that shells out to `security` (git credential
149 // osxkeychain, 1Password CLI, etc.). Callers that can't tolerate
150 // this are expected to fall back to the on-disk `~/.composio/`
151 // user config — the CLI already owns that code path.
152 const args = [
153 'add-generic-password',
154 '-A',
155 '-a',
156 user,
157 '-s',
158 service,
159 '-l',
160 label,
161 '-w',
162 encoded,
163 ...domainArgs,
164 ];
165
166 let result: SpawnResult;
167 try {
168 result = await runCommand({ command: SECURITY_BIN, args });
169 } catch (err) {
170 throw new KeyringError({ kind: 'NoStorageAccess', cause: err });
171 }
172
173 if (result.code === 0) return;
174
175 if (result.code === EXIT_DUPLICATE_ITEM) {
176 throw new KeyringError({
177 kind: 'PlatformFailure',
178 cause: new Error(
179 'security add-generic-password: delete-then-add produced duplicate. ' +
180 'The existing item may have an ACL that blocks deletion — ' +
181 'run `security delete-generic-password -s com.composio.cli -a default` manually.'
182 ),
183 });
184 }
185 throw classifyExitCode(result, 'add-generic-password');
186 }
187
188 async getSecret(service: string, user: string, modifiers: EntryModifiers): Promise<Uint8Array> {
189 validateSpecifier(service, user);
190 const domainArgs = domainFlag(modifiers.keychain);
191
192 // -w prints the password to stdout and nothing else. Without -w,
193 // `security` dumps the item's attributes in a human-readable form
194 // that's painful to parse.
195 const args = ['find-generic-password', '-a', user, '-s', service, '-w', ...domainArgs];
196
197 let result: SpawnResult;
198 try {
199 result = await runCommand({ command: SECURITY_BIN, args });
200 } catch (err) {
201 throw new KeyringError({ kind: 'NoStorageAccess', cause: err });
202 }
203
204 if (result.code !== 0) {
205 throw classifyExitCode(result, 'find-generic-password');
206 }
207
208 // `security -w` prints the value followed by \n. Strip exactly one
209 // trailing newline — the base64 alphabet does not contain \n, so
210 // any remaining whitespace would be a malformed blob.
211 const stdout = bytesToUtf8(result.stdout).replace(/\n$/, '');
212 try {
213 return decodeSecret(stdout);
214 } catch (err) {
215 throw new KeyringError({
216 kind: 'BadDataFormat',
217 bytes: new Uint8Array(result.stdout),
218 cause: err,
219 });
220 }
221 }
222
223 async deleteCredential(service: string, user: string, modifiers: EntryModifiers): Promise<void> {
224 validateSpecifier(service, user);
225 const domainArgs = domainFlag(modifiers.keychain);
226 const args = ['delete-generic-password', '-a', user, '-s', service, ...domainArgs];
227
228 let result: SpawnResult;
229 try {
230 result = await runCommand({ command: SECURITY_BIN, args });
231 } catch (err) {
232 throw new KeyringError({ kind: 'NoStorageAccess', cause: err });
233 }
234
235 if (result.code === 0) return;
236 throw classifyExitCode(result, 'delete-generic-password');
237 }
238 }
239
240 /** Default label matches the format keyring-rs generates on Linux (`keyring:{user}@{service}`). */
241 function defaultLabel(service: string, user: string): string {
242 return `keyring:${user}@${service}`;
243 }