Skip to content

Commit 9506aa6

Browse files
author
exe.dev user
committed
Preserve saved model API keys when editing integrations
1 parent 33ec09d commit 9506aa6

7 files changed

Lines changed: 69 additions & 17 deletions

File tree

‎packages/api-client/src/schema.d.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,8 @@ export interface paths {
169169
};
170170
get?: never;
171171
/**
172-
* Replace a model account credential
173-
* @description Owner session required. Saves an OpenAI-compatible provider URL and optional API key. Replaces the managed credential without changing the selected account ID; active runs use the replacement on their next request.
172+
* Update a model account credential
173+
* @description Owner session required. An omitted API key preserves the saved key when the provider URL is unchanged. Supply a replacement key or explicit null for keyless access when changing the provider URL. Active runs use the updated credential on their next request.
174174
*
175175
* Requires the integrations:write scope.
176176
*
@@ -4308,7 +4308,7 @@ export interface operations {
43084308
description: string | null;
43094309
/** Format: uri */
43104310
providerUrl: string;
4311-
apiKey?: string;
4311+
apiKey?: string | null;
43124312
/** @default 128000 */
43134313
contextWindow?: number;
43144314
/** @default 8192 */

‎packages/api/src/api-contract.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ export const API_ROUTES: RouteContract[] = [
269269
description: "Requires an interactive owner browser session and the current collection revision. Saves an OpenAI-compatible provider URL, optional API key, and model limits in encrypted storage. Credentials are never returned.",
270270
responses: { "201": { description: "Created model account", content: { "application/json": { schema: jsonSchema(bearerIntegrationWriteResult, "output") } } } },
271271
}, (service, { body }) => service.createModelAccount(body), { body: modelAccountCreate, maxBodyBytes: 70_000, ownerSession: true }),
272-
route("PUT", "/api/v1/model-accounts/{accountId}", "integrations:write", {summary:"Replace a model account credential",description:"Owner session required. Saves an OpenAI-compatible provider URL and optional API key. Replaces the managed credential without changing the selected account ID; active runs use the replacement on their next request.",responses:{"200":{description:"Model account updated",content:{"application/json":{schema:jsonSchema(bearerIntegrationWriteResult,"output")}}}}},(service,{params,body})=>service.updateModelAccount(params.accountId,body),{body:modelAccountCreate.omit({id:true}),maxBodyBytes:70_000,ownerSession:true,parameters:z.object({accountId:z.uuid()})}),
272+
route("PUT", "/api/v1/model-accounts/{accountId}", "integrations:write", {summary:"Update a model account credential",description:"Owner session required. An omitted API key preserves the saved key when the provider URL is unchanged. Supply a replacement key or explicit null for keyless access when changing the provider URL. Active runs use the updated credential on their next request.",responses:{"200":{description:"Model account updated",content:{"application/json":{schema:jsonSchema(bearerIntegrationWriteResult,"output")}}}}},(service,{params,body})=>service.updateModelAccount(params.accountId,body),{body:modelAccountCreate.omit({id:true}).extend({apiKey:modelProviderConfiguration.shape.apiKey.unwrap().nullable().optional().meta({writeOnly:true})}),maxBodyBytes:70_000,ownerSession:true,parameters:z.object({accountId:z.uuid()})}),
273273

274274
route("DELETE", "/api/v1/model-accounts/{accountId}", "integrations:write", {
275275
summary: "Delete a model account",

‎packages/api/src/flow-service.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1644,11 +1644,15 @@ export class ApiService {
16441644
throw error;
16451645
}
16461646
}
1647-
async updateModelAccount(id: string, input: {expectedRevision: number; idempotencyKey: string; name: string; description: string | null} & ModelProviderConfiguration) {
1647+
async updateModelAccount(id: string, input: {expectedRevision: number; idempotencyKey: string; name: string; description: string | null; apiKey?: string | null} & Omit<ModelProviderConfiguration,"apiKey">) {
16481648
await this.authorizeOwnerSession("integrations:write");
16491649
const repository=this.credentials();
16501650
if (!(await repository.metadata("model")).some(record=>record.id===id)) throw new ServiceError(404,"not_found","Model account not found.");
1651-
try {return await repository.write({...input,id,kind:"model",origin:null,operation:"upsert",managedModelPayload:JSON.stringify(modelProviderConfiguration.parse({providerUrl:input.providerUrl,apiKey:input.apiKey,contextWindow:input.contextWindow,maxTokens:input.maxTokens}))});}
1651+
const existing=configuredPiProvider((await repository.managedCredential(id,"model"))?.payload ?? "");
1652+
if(input.apiKey===undefined && existing?.apiKey && new URL(existing.providerUrl).href.replace(/\/$/,"")!==new URL(input.providerUrl).href.replace(/\/$/,""))
1653+
throw new ServiceError(400,"invalid_request","Enter a replacement API key or select keyless access when changing the provider URL.");
1654+
const apiKey=input.apiKey===undefined?existing?.apiKey:input.apiKey ?? undefined;
1655+
try {return await repository.write({...input,id,kind:"model",origin:null,operation:"upsert",managedModelPayload:JSON.stringify(modelProviderConfiguration.parse({providerUrl:input.providerUrl,apiKey,contextWindow:input.contextWindow,maxTokens:input.maxTokens}))});}
16521656
catch (error) {if(error instanceof StaleIntegrationRevisionError) throw new ServiceError(409,"stale_revision","The model account collection changed. Reload and retry."); if(error instanceof IntegrationIdempotencyConflictError) throw new ServiceError(409,"conflict",error.message); if(error instanceof IntegrationValidationError) throw new ServiceError(400,"invalid_request",error.message); throw error;}
16531657
}
16541658
async deleteModelAccount(id: string, input: { expectedRevision: number; idempotencyKey: string }) {

‎packages/api/test/encrypted-integration-api.postgres.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,31 @@ describe.skipIf(!databaseUrl)("owner-only managed credential API (PostgreSQL)",
9898
} finally { await f.cleanup(); }
9999
});
100100

101+
it("preserves omitted model keys, replaces or explicitly clears them, and prevents forwarding to a changed provider", async () => {
102+
const f = await loadingFixture(databaseUrl!);
103+
try {
104+
const id=crypto.randomUUID(), path=f.env.APP_ORIGIN+"/api/v1/model-accounts";
105+
const request=(url:string,method:string,body:unknown)=>worker.fetch(new Request(url,{method,headers:{Cookie:f.cookie,Origin:f.env.APP_ORIGIN,"Content-Type":"application/json"},body:JSON.stringify(body)}),f.env,{waitUntil(){}} as any);
106+
const metadata={name:"OpenAI",description:null,providerUrl:"https://model.fixture/v1"};
107+
expect((await request(path,"POST",{...metadata,id,expectedRevision:0,idempotencyKey:crypto.randomUUID(),apiKey:"original-fixture-key"})).status).toBe(201);
108+
const repository=new CredentialRepository(f.db,f.tenantId,f.env.CREDENTIAL_ENCRYPTION_KEY);
109+
const saved=async()=>JSON.parse((await repository.managedCredential(id,"model"))!.payload);
110+
const update={...metadata,name:"Renamed",expectedRevision:1,idempotencyKey:crypto.randomUUID()};
111+
expect((await request(path+`/${id}`,"PUT",update)).status).toBe(200);
112+
expect((await saved()).apiKey).toBe("original-fixture-key");
113+
expect(await (await request(path+`/${id}`,"PUT",update)).json()).toEqual({revision:2,duplicate:true});
114+
const redirected=await request(path+`/${id}`,"PUT",{...metadata,providerUrl:"https://other.fixture/v1",expectedRevision:2,idempotencyKey:crypto.randomUUID()});
115+
expect(redirected.status).toBe(400);
116+
expect((await saved()).providerUrl).toBe(metadata.providerUrl);
117+
expect((await request(path+`/${id}`,"PUT",{...metadata,apiKey:"replacement-fixture-key",expectedRevision:2,idempotencyKey:crypto.randomUUID()})).status).toBe(200);
118+
expect((await saved()).apiKey).toBe("replacement-fixture-key");
119+
const publicMetadata=await (await worker.fetch(new Request(path,{headers:{Cookie:f.cookie}}),f.env,{waitUntil(){}} as any)).text();
120+
expect(publicMetadata).not.toContain("fixture-key");
121+
expect((await request(path+`/${id}`,"PUT",{...metadata,apiKey:null,expectedRevision:3,idempotencyKey:crypto.randomUUID()})).status).toBe(200);
122+
expect(await saved()).not.toHaveProperty("apiKey");
123+
} finally {await f.cleanup();}
124+
});
125+
101126
it("requires a browser session and isolates records across tenants", async () => {
102127
const f = await loadingFixture(databaseUrl!);
103128
try {

‎packages/app/src/features/settings/model-accounts.tsx‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@ import {Dialog} from "../../shared/dialog";
1010
import {IntegrationRow,ProviderTile} from "./integration-ui";
1111
type Account={id:string;name:string;description:string|null;providerUrl:string|null;credentialConfigured:boolean};
1212
export function useModelAccounts(){
13-
const cache=useQueryClient(),[open,setOpen]=useState(false),[editId,setEditId]=useState<string|null>(null),[name,setName]=useState(""),[description,setDescription]=useState(""),[providerUrl,setProviderUrl]=useState(""),[key,setKey]=useState(""),[error,setError]=useState(""),[contextWindow,setContextWindow]=useState(128000),[maxTokens,setMaxTokens]=useState(8192);
13+
const cache=useQueryClient(),[open,setOpen]=useState(false),[editId,setEditId]=useState<string|null>(null),[name,setName]=useState(""),[description,setDescription]=useState(""),[providerUrl,setProviderUrl]=useState(""),[key,setKey]=useState(""),[keyless,setKeyless]=useState(false),[error,setError]=useState(""),[contextWindow,setContextWindow]=useState(128000),[maxTokens,setMaxTokens]=useState(8192);
1414
const accounts=useQuery(modelAccountsQuery);
1515
const refresh=()=>cache.invalidateQueries({queryKey:["settings"]});
16-
const reset=()=>{setEditId(null);setName("");setDescription("");setProviderUrl("");setKey("");setContextWindow(128000);setMaxTokens(8192);setError("");};
16+
const reset=()=>{setEditId(null);setName("");setDescription("");setProviderUrl("");setKey("");setKeyless(false);setContextWindow(128000);setMaxTokens(8192);setError("");};
1717
const save=useMutation({retry:false,mutationFn:async()=>{
1818
if(!accounts.data)throw new Error("Model integrations are still loading.");
19-
const body={expectedRevision:accounts.data.revision,idempotencyKey:crypto.randomUUID(),name:name.trim(),description:description.trim()||null,providerUrl:providerUrl.trim(),contextWindow,maxTokens,...(key.trim()?{apiKey:key.trim()}:{} )};
20-
const response=editId?await api.PUT("/api/v1/model-accounts/{accountId}",{params:{path:{accountId:editId}},body}):await api.POST("/api/v1/model-accounts",{body:{...body,id:crypto.randomUUID()}});
19+
const body={expectedRevision:accounts.data.revision,idempotencyKey:crypto.randomUUID(),name:name.trim(),description:description.trim()||null,providerUrl:providerUrl.trim(),contextWindow,maxTokens};
20+
const response=editId?await api.PUT("/api/v1/model-accounts/{accountId}",{params:{path:{accountId:editId}},body:{...body,...(keyless?{apiKey:null}:key.trim()?{apiKey:key.trim()}:{})}}):await api.POST("/api/v1/model-accounts",{body:{...body,id:crypto.randomUUID(),...(key.trim()?{apiKey:key.trim()}:{})}});
2121
if(!response.data||response.error)throw new Error(messageOf(response.error));
2222
},onSuccess:async()=>{reset();setOpen(false);await refresh();},onError:async reason=>{setError(reason.message);await refresh();}});
2323
const remove=useMutation({retry:false,mutationFn:async(account:Account)=>{
@@ -35,7 +35,8 @@ export function useModelAccounts(){
3535
<Label>Name<Input required maxLength={120} value={name} onChange={event=>setName(event.target.value)}/></Label>
3636
<Label>Description (optional)<Input maxLength={500} value={description} onChange={event=>setDescription(event.target.value)}/></Label>
3737
<Label>Provider URL<Input required type="url" placeholder="https://provider.example/v1" maxLength={2048} value={providerUrl} onChange={event=>setProviderUrl(event.target.value)}/></Label>
38-
<Label>API key (optional)<SecretInput name="model-api-key" aria-label="API key (optional)" maxLength={32768} value={key} onChange={event=>setKey(event.target.value)}/><span className="text-xs">Blank saves a keyless integration. Enter the replacement key when editing an authenticated provider.</span></Label>
38+
<Label>API key (optional)<SecretInput disabled={keyless} name="model-api-key" aria-label="API key (optional)" maxLength={32768} value={key} onChange={event=>setKey(event.target.value)}/><span className="text-xs">{editId?"Leave blank to keep the saved API key. Enter a new key to replace it.":"Enter your provider API key, or leave blank for a keyless provider."}</span></Label>
39+
{editId&&<Label><span className="flex items-center gap-2"><input type="checkbox" checked={keyless} onChange={event=>setKeyless(event.target.checked)}/>Use keyless access (remove saved API key)</span></Label>}
3940
<details><summary>Model limits</summary><Label>Context window (tokens)<Input required type="number" min={1024} max={2000000} value={contextWindow} onChange={event=>setContextWindow(event.target.valueAsNumber)}/></Label><Label>Maximum output tokens<Input required type="number" min={1} max={200000} value={maxTokens} onChange={event=>setMaxTokens(event.target.valueAsNumber)}/></Label></details>
4041
<Button variant="primary" disabled={save.isPending||accounts.isPending||Boolean(accounts.error)}>{save.isPending?"Saving…":"Save model integration"}</Button>
4142
</form>{editId&&<ModelPricing integrationId={editId}/ >}{error&&<p role="alert">{error}</p>}</Dialog>};

‎packages/app/test/functional/integrations-presets-code.spec.mjs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,26 @@ const withinViewport = async locator => {
1616
const box = await locator.boundingBox(), viewport = await locator.page().evaluate(() => ({ width: innerWidth, height: innerHeight }));
1717
expect(box.x).toBeGreaterThanOrEqual(0); expect(box.y).toBeGreaterThanOrEqual(0); expect(box.x + box.width).toBeLessThanOrEqual(viewport.width); expect(box.y + box.height).toBeLessThanOrEqual(viewport.height);
1818
};
19+
20+
test("editing model integrations preserves keys unless keyless access is explicitly selected", async ({ page }) => {
21+
await mockApi(page);
22+
const id="4dcfb380-67f6-4db4-bd45-3a0bfedc950d", writes=[];
23+
await page.route("**/api/v1/model-accounts", route=>route.fulfill({json:{revision:3,accounts:[{id,name:"OpenAI",description:null,revision:3,credentialConfigured:true,providerUrl:"https://api.openai.com/v1",contextWindow:128000,maxTokens:8192}]}}));
24+
await page.route(`**/api/v1/model-accounts/${id}`, async route=>{writes.push(route.request().postDataJSON());await route.fulfill({json:{revision:4,duplicate:false}});});
25+
await page.goto(origin+"/integrations");
26+
const edit=async()=>{await page.getByRole("button",{name:"Actions for OpenAI",exact:true}).click();await page.getByRole("menuitem",{name:"Edit model integration"}).click();};
27+
await edit();
28+
let dialog=page.getByRole("dialog");
29+
await expect(dialog.getByLabel("API key (optional)",{exact:true})).toHaveValue("");
30+
await expect(dialog.getByText("Leave blank to keep the saved API key. Enter a new key to replace it.")).toBeVisible();
31+
await dialog.getByRole("button",{name:"Save model integration"}).click();
32+
await expect(dialog).toBeHidden();expect(writes[0]).not.toHaveProperty("apiKey");
33+
await edit();dialog=page.getByRole("dialog");
34+
await dialog.getByLabel("Use keyless access (remove saved API key)").check();
35+
await expect(dialog.getByLabel("API key (optional)",{exact:true})).toBeDisabled();
36+
await dialog.getByRole("button",{name:"Save model integration"}).click();
37+
await expect(dialog).toBeHidden();expect(writes[1].apiKey).toBeNull();
38+
});
1939
test("Phoenix installs through the compact provider list and joins connected integrations", async ({ page }, testInfo) => {
2040
await page.setViewportSize({ width: 390, height: 844 }); await mockApi(page);
2141
let config = { configured: false, endpoint: "", projectName: "factorize", projectId: null, credentialConfigured: false, enabled: false, revision: 0, lastTestAt: null, lastError: null };

‎packages/docs/openapi.yaml‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2702,9 +2702,9 @@ paths:
27022702
additionalProperties: false
27032703
/api/v1/model-accounts/{accountId}:
27042704
put:
2705-
summary: Replace a model account credential
2705+
summary: Update a model account credential
27062706
description: |-
2707-
Owner session required. Saves an OpenAI-compatible provider URL and optional API key. Replaces the managed credential without changing the selected account ID; active runs use the replacement on their next request.
2707+
Owner session required. An omitted API key preserves the saved key when the provider URL is unchanged. Supply a replacement key or explicit null for keyless access when changing the provider URL. Active runs use the updated credential on their next request.
27082708

27092709
Requires the integrations:write scope.
27102710

@@ -2790,10 +2790,12 @@ paths:
27902790
format: uri
27912791
apiKey:
27922792
writeOnly: true
2793-
type: string
2794-
minLength: 1
2795-
maxLength: 32768
2796-
pattern: ^[^\r\n]+$
2793+
anyOf:
2794+
- type: string
2795+
minLength: 1
2796+
maxLength: 32768
2797+
pattern: ^[^\r\n]+$
2798+
- type: "null"
27972799
contextWindow:
27982800
default: 128000
27992801
type: integer

0 commit comments

Comments
 (0)