feat(ui/server): name cross-company environment secret refs instead of calling them missing (#10577)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Environment configs (sandbox providers, SSH) can bind stored company
secrets through `format: "secret-ref"` fields, picked in the environment
editor's secret picker
> - Environments are instance-scoped and shared by every company on an
instance, but the picker lists only the current company's secrets, so a
ref pointing at another company's secret renders as "Missing secret (…)"
in destructive styling
> - That state is indistinguishable from a genuinely deleted secret, so
operators "fix" a healthy binding by creating a duplicate secret in
their own company — the exact sequence that used to corrupt bindings
before #10576
> - This pull request adds an instance-gated metadata endpoint for an
environment's secret refs and teaches the picker to name a cross-company
secret and its owner honestly
> - The benefit is that operators can tell a healthy cross-company
binding from a broken one, and stop creating duplicate secrets

## Linked Issues or Issue Description

**Is your feature request related to a problem? Please describe.**

In the environment editor, a secret-ref field that points at a secret
owned by a different company shows "Missing secret (22095402…)" in red,
with "The previously selected secret is no longer available. Pick
another or remove the binding." The binding is actually healthy — the
current company's picker just cannot list the other company's secrets.
Operators react by creating a duplicate secret and re-pointing the
field.

**Describe the solution you'd like**

The editor should know the referenced secret's name, status, and owning
company (metadata only, never the value) and present a cross-company ref
neutrally, a deleted secret as deleted, and only an unknown id as
missing.

Related: #10576 (fixes the binding corruption this UI state used to
trigger).

## What Changed

- New `GET /environments/:id/secret-refs` returns `{ refs: [{
configPath, secretId, name, status, companyId, companyName }] }` for the
environment's config-derived secret refs. Values are never returned. The
route sits behind `assertCanAccessInstanceEnvironments`, the same gate
as environment editing.
- New `secretService.describeSecretRefs` loads that metadata across
companies; unknown ids are omitted.
- `SecretBindingPicker` reads an optional `SecretRefHintsContext` (keyed
by secret id). With a hint, a ref the company list cannot show renders
as `NAME — Owning Company` with neutral styling and the note "Owned by
the … company. The binding keeps working; selecting a secret from this
list re-points it here." A hint with `status: "deleted"` reports the
secret as deleted. Without hints, behavior is byte-identical to before —
agent editors and other picker users are unaffected.
- `CompanyEnvironments` fetches descriptors for the environment being
edited and provides them through the context.

## Verification

- `cd server && pnpm vitest run src/__tests__/environment-routes.test.ts
src/__tests__/secrets-service.test.ts` — new endpoint happy path, agent
403 (descriptors never computed), and embedded-Postgres coverage proving
cross-company names resolve and unknown ids drop out.
- `cd ui && pnpm vitest run src/components/SecretBindingPicker.test.tsx
src/components/JsonSchemaForm.test.tsx
src/pages/CompanyEnvironments.test.tsx` — hinted cross-company
rendering, hinted deleted secret, and unchanged no-hint fallback.
- `pnpm run typecheck` in `server` and `ui`.
- Manual: edit an environment whose secret-ref field references another
company's secret; the field names the secret and its owning company
instead of "Missing secret".

## Risks

- The endpoint exposes secret names and company names across companies
to instance-level environment editors. Those actors already manage
instance-shared environments (and instance admins are implicit members
of every company), so this reveals no secret material and no new reach;
the service method documents that callers must sit behind an
instance-level gate.
- UI change is additive and context-gated; pickers without a provider
render exactly as before.

## Model Used

Claude Fable 5 (`claude-fable-5`, Anthropic) via Claude Code — extended
thinking, agentic tool use (file edits, vitest/tsc runs). No other
models involved.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Devin Foley authored and GitHub committed 2026-07-31 16:46:26 -07:00
1 parent f51cba33fa
commit 90ead239a8
10 files changed
+443 -3

No files matched your search

@@ -66,6 +66,7 @@ const mockSecretService = vi.hoisted(() => ({
syncEnvBindingsForTarget: vi.fn(),
syncSecretRefsForTarget: vi.fn(),
replaceSecretRefsForInstanceTarget: vi.fn(),
describeSecretRefs: vi.fn(),
remove: vi.fn(),
}));
const mockValidatePluginEnvironmentDriverConfig = vi.hoisted(() => vi.fn());
@@ -269,6 +270,8 @@ describe("environment routes", () => {
mockSecretService.syncEnvBindingsForTarget.mockReset();
mockSecretService.syncSecretRefsForTarget.mockReset();
mockSecretService.replaceSecretRefsForInstanceTarget.mockReset();
mockSecretService.describeSecretRefs.mockReset();
mockSecretService.describeSecretRefs.mockResolvedValue([]);
mockSecretService.remove.mockReset();
mockSecretService.create.mockResolvedValue({
id: "11111111-1111-1111-1111-111111111111",
@@ -1224,6 +1227,76 @@ describe("environment routes", () => {
expect(mockEnvironmentService.removeIfDeletable).not.toHaveBeenCalled();
});
it("describes an environment's secret refs with owner metadata", async () => {
const secretId = "22222222-2222-2222-2222-222222222222";
mockEnvironmentService.getById.mockResolvedValue({
...createEnvironment(),
id: "env-sandbox",
name: "Daytona",
driver: "sandbox" as const,
config: {
provider: "secure-plugin",
template: "base",
apiKey: secretId,
timeoutMs: 450000,
reuseLease: true,
},
});
mockSecretService.describeSecretRefs.mockResolvedValue([
{
configPath: "apiKey",
secretId,
name: "DAYTONA_API_KEY",
status: "active",
companyId: "company-2",
companyName: "Other Team",
},
]);
const app = createApp({
type: "board",
userId: "admin-1",
source: "local_implicit",
});
const res = await request(app).get("/api/environments/env-sandbox/secret-refs");
expect(res.status).toBe(200);
expect(res.body.refs).toEqual([
{
configPath: "apiKey",
secretId,
name: "DAYTONA_API_KEY",
status: "active",
companyId: "company-2",
companyName: "Other Team",
},
]);
expect(mockSecretService.describeSecretRefs).toHaveBeenCalledWith([
{ secretId, configPath: "apiKey", versionSelector: "latest" },
]);
});
it("denies secret-ref descriptors to agents without instance environment access", async () => {
mockAgentService.getById.mockResolvedValue({
id: "agent-1",
companyId: "company-1",
role: "engineer",
permissions: { canCreateAgents: false },
});
mockAccessService.hasPermission.mockResolvedValue(false);
const app = createApp({
type: "agent",
agentId: "agent-1",
companyId: "company-1",
source: "agent_key",
});
const res = await request(app).get("/api/environments/env-1/secret-refs");
expect(res.status).toBe(403);
expect(mockSecretService.describeSecretRefs).not.toHaveBeenCalled();
});
it("clears environment selections and secret bindings across all companies when deleting an environment", async () => {
const environment = {
...createEnvironment(),
@@ -286,6 +286,47 @@ describeEmbeddedPostgres("secretService", () => {
expect(rows[0]?.companyId).toBe(companyA);
});
it("describeSecretRefs names secrets across companies and omits unknown ids", async () => {
const companyA = await seedCompany("Alpha");
const companyB = await seedCompany("Beta");
const svc = secretService(db);
const secretA = await svc.create(companyA, {
name: "PROVIDER_KEY_A",
provider: "local_encrypted",
value: "a",
});
const secretB = await svc.create(companyB, {
name: "PROVIDER_KEY_B",
provider: "local_encrypted",
value: "b",
});
const described = await svc.describeSecretRefs([
{ secretId: secretA.id, configPath: "apiKey" },
{ secretId: secretB.id, configPath: "privateKeySecretRef" },
{ secretId: randomUUID(), configPath: "token" },
]);
expect(described).toEqual([
{
configPath: "apiKey",
secretId: secretA.id,
name: "PROVIDER_KEY_A",
status: "active",
companyId: companyA,
companyName: "Alpha",
},
{
configPath: "privateKeySecretRef",
secretId: secretB.id,
name: "PROVIDER_KEY_B",
status: "active",
companyId: companyB,
companyName: "Beta",
},
]);
});
it("prevents duplicate bindings for a target config path", async () => {
const companyId = await seedCompany();
const svc = secretService(db);
+16
View File
@@ -932,6 +932,22 @@ export function environmentRoutes(
res.json(presentEnvironmentForRead(req, environment));
});
router.get("/environments/:id/secret-refs", async (req, res) => {
assertCanAccessInstanceEnvironments(req);
const environment = await svc.getById(req.params.id as string);
if (!environment) {
res.status(404).json({ error: "Environment not found" });
return;
}
// Metadata only (name / status / owning company) — never secret values.
// Environments are instance-scoped while secrets are company-scoped, so
// the editor needs this to render refs whose secret a given company's
// picker cannot list. Gated by the same instance-level access check as
// environment editing.
const refs = await collectEnvironmentSecretRefs({ db, environment });
res.json({ refs: await secrets.describeSecretRefs(refs) });
});
router.get("/environments/:id/leases", async (req, res) => {
assertCanReadInstanceEnvironments(req);
const environment = await svc.getById(req.params.id as string);
+9
View File
@@ -4576,6 +4576,15 @@ registry.registerPath({
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
});
registry.registerPath({
method: "get",
path: "/api/environments/{id}/secret-refs",
tags: ["environments"],
summary: "Describe an environment's config secret refs (name, status, owning company — never values)",
request: { params: z.object({ id: z.string() }) },
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
});
registry.registerPath({
method: "get",
path: "/api/environments/{id}/leases",
+46
View File
@@ -3,6 +3,7 @@ import { and, desc, eq, inArray, like, ne, notInArray, notLike, or, sql } from "
import type { Db } from "@paperclipai/db";
import {
agents,
companies,
companySecretBindings,
companySecretProviderConfigs,
companySecrets,
@@ -4120,6 +4121,51 @@ export function secretService(db: Db) {
return normalizedRefs;
},
/**
* Describe secret refs (id + config path) with the referenced secret's
* name, status, and owning company. Environments are instance-scoped
* while secrets are company-scoped, so an environment can legitimately
* reference a secret a given company's picker cannot list; this gives
* instance-level readers enough metadata to present such refs honestly.
* Returns names across companies — callers must sit behind an
* instance-level authorization gate. Never returns secret values.
*/
describeSecretRefs: async (
refs: Array<{ secretId: string; configPath: string }>,
): Promise<Array<{
configPath: string;
secretId: string;
name: string;
status: string;
companyId: string;
companyName: string | null;
}>> => {
if (refs.length === 0) return [];
const secretIds = [...new Set(refs.map((ref) => ref.secretId))];
const secretRows = await db
.select()
.from(companySecrets)
.where(inArray(companySecrets.id, secretIds));
const secretsById = new Map(secretRows.map((row) => [row.id, row]));
const companyIds = [...new Set(secretRows.map((row) => row.companyId))];
const companyRows = companyIds.length > 0
? await db.select().from(companies).where(inArray(companies.id, companyIds))
: [];
const companyNamesById = new Map(companyRows.map((row) => [row.id, row.name]));
return refs.flatMap((ref) => {
const secret = secretsById.get(ref.secretId);
if (!secret) return [];
return [{
configPath: ref.configPath,
secretId: secret.id,
name: secret.name,
status: secret.status,
companyId: secret.companyId,
companyName: companyNamesById.get(secret.companyId) ?? null,
}];
});
},
listBindingCompanyIdsForTarget: async (
target: { targetType: SecretBindingTargetType; targetId: string },
): Promise<string[]> =>