Skip to content

Commit 7ad5471

Browse files
fixed incorrect api key usage for debug (#120)
1 parent c44a0bd commit 7ad5471

File tree

3 files changed

+98
-14
lines changed

3 files changed

+98
-14
lines changed

src/commands/executeStepZenRequest.ts

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -59,19 +59,19 @@ export async function executeStepZenRequest(options: {
5959
let customHeaders: Record<string, string> = {};
6060
let adminKey: string | undefined;
6161
if (auth?.type === 'jwt') {
62-
// Always need the admin key for debug header
63-
adminKey = await services.request.getApiKey();
62+
// JWT auth: use JWT for Authorization, admin key for debug
63+
adminKey = await services.request.getAdminKey();
6464
customHeaders = {
6565
'Authorization': `Bearer ${auth.jwt}`,
6666
'StepZen-Debug-Authorization': `apikey ${adminKey}`,
67-
'stepzen-debug-level': String(debugLevel),
67+
'Stepzen-Debug-Level': String(debugLevel),
6868
};
6969
} else {
70-
// Default: admin key in Authorization
71-
adminKey = await services.request.getApiKey();
70+
// Admin auth: use admin key for Authorization
71+
adminKey = await services.request.getAdminKey();
7272
customHeaders = {
7373
'Authorization': `Apikey ${adminKey}`,
74-
'stepzen-debug-level': String(debugLevel),
74+
'Stepzen-Debug-Level': String(debugLevel),
7575
};
7676
}
7777

@@ -98,9 +98,17 @@ export async function executeStepZenRequest(options: {
9898
operationName,
9999
customHeaders
100100
);
101-
// Process results
101+
// Process results and validate debug data
102102
const rawDiags = (result.extensions?.stepzen?.diagnostics ?? []) as StepZenDiagnostic[];
103103
services.logger.info("Processing diagnostics for persisted operation...");
104+
services.logger.debug(`Received ${rawDiags.length} diagnostic entries from StepZen`);
105+
106+
if (debugLevel > 0 && rawDiags.length === 0) {
107+
services.logger.warn(`Expected debug data with debug level ${debugLevel}, but received no diagnostics. Check if headers were sent correctly.`);
108+
} else if (debugLevel > 0) {
109+
services.logger.info(`Successfully received debug data: ${rawDiags.length} diagnostic entries`);
110+
}
111+
104112
const summaries = summariseDiagnostics(rawDiags);
105113
publishDiagnostics(summaries, runtimeDiag);
106114
services.logger.info("Persisted document request completed successfully");
@@ -186,9 +194,17 @@ export async function executeStepZenRequest(options: {
186194
parseErr
187195
);
188196
}
189-
// Process results
197+
// Process results and validate debug data
190198
const rawDiags = (json.extensions?.stepzen?.diagnostics ?? []) as StepZenDiagnostic[];
191199
services.logger.info("Processing diagnostics for file-based request...");
200+
services.logger.debug(`Received ${rawDiags.length} diagnostic entries from StepZen`);
201+
202+
if (debugLevel > 0 && rawDiags.length === 0) {
203+
services.logger.warn(`Expected debug data with debug level ${debugLevel}, but received no diagnostics. Check if Stepzen-Debug-Level header was sent correctly.`);
204+
} else if (debugLevel > 0) {
205+
services.logger.info(`Successfully received debug data: ${rawDiags.length} diagnostic entries`);
206+
}
207+
192208
const summaries = summariseDiagnostics(rawDiags);
193209
publishDiagnostics(summaries, runtimeDiag);
194210
await openResultsPanel(json);

src/services/cli.ts

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -107,18 +107,32 @@ export class StepzenCliService {
107107
}, TIMEOUTS.FILE_CLEANUP_DELAY_MS);
108108
}
109109

110+
// Build headers array - always include debug level, plus any custom headers
111+
const headerArgs: string[] = [];
112+
if (customHeaders && Object.keys(customHeaders).length > 0) {
113+
// Add custom headers
114+
Object.entries(customHeaders).forEach(([k, v]) => {
115+
headerArgs.push('--header', `"${k}: ${v}"`);
116+
});
117+
} else {
118+
// Fallback: just add debug level header
119+
headerArgs.push('--header', `"Stepzen-Debug-Level: ${debugLevel}"`);
120+
}
121+
110122
// Build args array for the request command
111123
const args = [
112124
'request',
113125
'--file', tmpFile,
114126
...(operationName ? ['--operation-name', operationName] : []),
115-
// Add each header as its own --header argument, value wrapped in double quotes
116-
...(customHeaders ? Object.entries(customHeaders).flatMap(([k, v]) => ['--header', `"${k}: ${v}"`]) : ['--header', `"stepzen-debug-level: ${debugLevel}"`]),
127+
...headerArgs,
117128
...varArgs
118129
];
119130

120-
// Execute the request
121-
logger.debug(`Executing StepZen request with args: ${args.join(' ')}${operationName ? ` (operation: ${operationName})` : ''}, debug level: ${debugLevel}`);
131+
// Log the full command for debugging
132+
const fullCommand = `stepzen ${args.join(' ')}`;
133+
logger.info(`Executing StepZen CLI command: ${fullCommand}`);
134+
logger.debug(`Command details: operation=${operationName || 'default'}, debugLevel=${debugLevel}, headers=${JSON.stringify(customHeaders || {})}`);
135+
122136
let stdout;
123137
try {
124138
stdout = await this.spawnProcessWithOutput(args, {
@@ -163,6 +177,34 @@ export class StepzenCliService {
163177
}
164178
}
165179

180+
/**
181+
* Get the admin key from StepZen CLI
182+
*
183+
* @returns Promise resolving to the admin key
184+
* @throws CliError if the operation fails
185+
*/
186+
async getAdminKey(): Promise<string> {
187+
try {
188+
logger.debug('Retrieving admin key from StepZen CLI');
189+
190+
const result = await this.spawnProcessWithOutput(['whoami', '--adminkey']);
191+
const adminKey = result.trim();
192+
193+
if (!adminKey) {
194+
throw new CliError("Empty admin key returned from StepZen CLI", "EMPTY_ADMIN_KEY");
195+
}
196+
197+
logger.debug("Successfully retrieved admin key from CLI");
198+
return adminKey;
199+
} catch (err) {
200+
throw new CliError(
201+
"Failed to retrieve admin key from StepZen CLI",
202+
"ADMIN_KEY_RETRIEVAL_FAILED",
203+
err
204+
);
205+
}
206+
}
207+
166208
/**
167209
* Get the API key from StepZen CLI
168210
*

src/services/request.ts

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,32 @@ export class RequestService {
112112
return { variables };
113113
}
114114

115+
/**
116+
* Get the admin key from StepZen CLI
117+
*
118+
* @returns Promise resolving to the admin key
119+
*/
120+
public async getAdminKey(): Promise<string> {
121+
try {
122+
this.logger.debug("Retrieving admin key from StepZen CLI");
123+
124+
// Import services here to avoid circular dependency
125+
const { services } = await import('./index.js');
126+
127+
// Use the CLI service's getAdminKey method
128+
const adminKey = await services.cli.getAdminKey();
129+
130+
this.logger.debug("Successfully retrieved admin key from CLI service");
131+
return adminKey;
132+
} catch (err) {
133+
throw new ValidationError(
134+
"Failed to retrieve admin key from StepZen CLI",
135+
"ADMIN_KEY_RETRIEVAL_FAILED",
136+
err
137+
);
138+
}
139+
}
140+
115141
/**
116142
* Get the API key from StepZen CLI
117143
*
@@ -191,11 +217,11 @@ export class RequestService {
191217
// Import services here to avoid circular dependency
192218
const { services } = await import('./index.js');
193219

194-
// Get account, domain, and API key from the CLI
220+
// Get account, domain, and admin key from the CLI
195221
const [account, domain, apiKey] = await Promise.all([
196222
services.cli.getAccount(),
197223
services.cli.getDomain(),
198-
this.getApiKey()
224+
this.getAdminKey()
199225
]);
200226

201227
// Construct the GraphQL endpoint URL using the correct pattern

0 commit comments

Comments
 (0)