fix(security): harden privileged server boundaries (#12776)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server controls secrets, host files, outbound requests, and
workspace commands
> - A red-team review found cases where restricted callers could cross
these trust boundaries
> - These cases could expose credentials or let untrusted input reach
privileged resources
> - This pull request applies least-privilege checks at each affected
server boundary
> - The benefit is safer agent execution without changing the
private-instance bootstrap contract

## Linked Issues or Issue Description

**What happened?**

Several server paths used authorization, redaction, or content-delivery
rules that were too broad. Restricted agent keys could obtain
company-level operational data. Some adapter and instruction paths could
reach server-owned network or file resources without the required owner
approval.

**Expected behavior**

Paperclip must redact credential values, enforce restricted-key scopes,
guard outbound network access, prevent same-origin script execution, and
reserve host-level file and command controls for authorized operators.

**Steps to reproduce**

1. Configure an authenticated development instance at the parent commit.
2. Exercise the affected APIs with a restricted agent key or a
non-instance-admin company user.
3. Observe that the parent commit returns privileged data or accepts a
privileged operation.
4. Repeat on this branch and observe a redacted response, a safe
download, or an HTTP 403 response.

**Paperclip version or commit**

The findings reproduce from commit `39898ab22` and are fixed by this
pull request.

**Deployment mode**

Authenticated self-hosted server and local development modes.

**Installation method**

Built from source with pnpm.

## What Changed

- Redact generic secret `value` and `token` fields recursively in
structured logs.
- Classify exact and separator-suffixed `KEY` environment names as
secrets in company exports.
- Limit restricted self-identity responses and protect company run, log,
and secret catalog APIs.
- Route HTTP adapter requests through DNS-pinned SSRF protection with
exact private-origin allowlisting.
- Download HTML, SVG, and other script-capable assets with `nosniff` and
a sandbox CSP.
- Require instance-admin access for external instruction roots and
exports that read them.
- Block agent-authenticated host command persistence across supported
workspace runtime shapes.
- Apply the central runtime-management decision before workspace command
controls.
- Keep the documented first-user instance-admin claim contract
unchanged.
- Add regression tests and server-owner configuration documentation.

## Verification

- `pnpm -r typecheck` passes.
- The Node 24 remediation suite passes with 365 tests. It skips 25
environment-gated tests.
- `pnpm build` passes under Node 24.
- `git diff --check` passes.
- The full local runner reaches known macOS-only general-server harness
failures before the serialized route lane. The Linux PR matrix is the
authoritative full-suite gate.

## Risks

- Restricted agent keys now receive HTTP 403 responses from company-wide
run, log, and secret catalog endpoints.
- Script-capable assets now download instead of rendering inline.
- External instruction roots now require instance-admin access.
- Private HTTP adapter endpoints now require an exact origin in
`PAPERCLIP_HTTP_ADAPTER_PRIVATE_ENDPOINT_ALLOWLIST`.
- Public HTTP adapter endpoints remain enabled. Redirects and metadata
or link-local targets remain blocked.
- No database migration is required.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex, GPT-5. The exact serving snapshot and context-window size
are not exposed. The model used tool-enabled reasoning, repository
access, code execution, and test execution.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-03 14:15:32 -05:00
1 parent 31a63638ac
commit 9dd6526b47
36 files changed
+1435 -122

No files matched your search

+13
View File
@@ -282,6 +282,19 @@ function deriveBundleState(agent: AgentLike): BundleState {
};
}
/** Classify the configured bundle without touching the filesystem. */
export function agentInstructionsBundleMode(agent: AgentLike): BundleMode | null {
const state = deriveBundleState(agent);
if (state.mode === "external") return "external";
if (
state.rootPath
&& path.resolve(state.rootPath) !== resolveManagedInstructionsRoot(agent)
) {
return "external";
}
return state.mode;
}
async function recoverManagedBundleState(agent: AgentLike, state: BundleState): Promise<BundleState> {
const managedRootPath = resolveManagedInstructionsRoot(agent);
const stat = await statIfExists(managedRootPath);
@@ -0,0 +1,67 @@
import { normalizeAgentUrlKey } from "@paperclipai/shared";
import { readBuiltInAgentMarker } from "./built-in-agent-metadata.js";
interface ExportAgentCandidate {
id: string;
name: string;
status: string;
metadata: unknown;
}
export function resolvePortableExportAgentSelection<T extends ExportAgentCandidate>(
allAgentRows: T[],
selectors: string[] | undefined,
includeAgents: boolean,
): { agents: T[]; warnings: string[] } {
const warnings: string[] = [];
const liveAgentRows = allAgentRows.filter((agent) => agent.status !== "terminated");
const builtInAgentRows = liveAgentRows.filter((agent) => readBuiltInAgentMarker(agent.metadata));
const portableAgentRows = liveAgentRows.filter((agent) => !readBuiltInAgentMarker(agent.metadata));
if (includeAgents) {
const skipped = allAgentRows.length - liveAgentRows.length;
if (skipped > 0) {
warnings.push(`Skipped ${skipped} terminated agent${skipped === 1 ? "" : "s"} from export.`);
}
if (builtInAgentRows.length > 0) {
warnings.push(`Skipped ${builtInAgentRows.length} built-in managed agent${builtInAgentRows.length === 1 ? "" : "s"} from export.`);
}
}
const agentByReference = new Map<string, T>();
const builtInAgentByReference = new Map<string, T>();
const addAgentReferences = (map: Map<string, T>, agent: T) => {
map.set(agent.id, agent);
map.set(agent.name, agent);
const normalizedName = normalizeAgentUrlKey(agent.name);
if (normalizedName) map.set(normalizedName, agent);
};
for (const agent of portableAgentRows) addAgentReferences(agentByReference, agent);
for (const agent of builtInAgentRows) addAgentReferences(builtInAgentByReference, agent);
const selectedAgents = new Map<string, T>();
for (const selector of selectors ?? []) {
const trimmed = selector.trim();
if (!trimmed) continue;
const normalized = normalizeAgentUrlKey(trimmed) ?? trimmed;
const match = agentByReference.get(trimmed) ?? agentByReference.get(normalized);
if (!match) {
const builtInMatch = builtInAgentByReference.get(trimmed) ?? builtInAgentByReference.get(normalized);
if (builtInMatch) {
warnings.push(`Agent selector "${selector}" is a built-in managed agent and was skipped.`);
} else {
warnings.push(`Agent selector "${selector}" was not found and was skipped.`);
}
continue;
}
selectedAgents.set(match.id, match);
}
// Preserve the established compatibility behavior: no effective explicit
// selection falls back to every portable agent when agent export is enabled.
if (includeAgents && selectedAgents.size === 0) {
for (const agent of portableAgentRows) selectedAgents.set(agent.id, agent);
}
return { agents: Array.from(selectedAgents.values()), warnings };
}
+21 -59
View File
@@ -76,7 +76,7 @@ import { ghFetch, gitHubApiBase, resolveRawGitHubUrl } from "./github-fetch.js";
import type { StorageService } from "../storage/types.js";
import { accessService } from "./access.js";
import { agentService } from "./agents.js";
import { agentInstructionsService } from "./agent-instructions.js";
import { agentInstructionsBundleMode, agentInstructionsService } from "./agent-instructions.js";
import { assetService } from "./assets.js";
import { generateReadme } from "./company-export-readme.js";
import { renderOrgChartPng, type OrgNode } from "../routes/org-chart-svg.js";
@@ -96,7 +96,7 @@ import {
readCatalogStringList,
readPortableCatalogProvenance,
} from "./catalog-provenance.js";
import { readBuiltInAgentMarker } from "./built-in-agent-metadata.js";
import { resolvePortableExportAgentSelection } from "./company-portability-agent-selection.js";
import { normalizePortablePath } from "./portable-path.js";
import type {
ImportIssueRow,
@@ -555,6 +555,9 @@ function buildSkillExportDirMap(skills: CompanySkill[], companyIssuePrefix: stri
function isSensitiveEnvKey(key: string) {
const normalized = key.trim().toLowerCase();
return (
normalized === "key" ||
normalized.endsWith("_key") ||
normalized.endsWith("-key") ||
normalized === "token" ||
normalized.endsWith("_token") ||
normalized.endsWith("-token") ||
@@ -3834,7 +3837,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
async function exportBundle(
companyId: string,
input: CompanyPortabilityExport,
options: { preview?: boolean } = {},
options: { preview?: boolean; allowExternalInstructions?: boolean } = {},
): Promise<CompanyPortabilityExportResult> {
const include = normalizeInclude({
...input.include,
@@ -3877,67 +3880,16 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
);
const allAgentRows = include.agents ? await agents.list(companyId, { includeTerminated: true }) : [];
const liveAgentRows = allAgentRows.filter((agent) => agent.status !== "terminated");
const builtInAgentRows = liveAgentRows.filter((agent) => readBuiltInAgentMarker(agent.metadata));
const portableAgentRows = liveAgentRows.filter((agent) => !readBuiltInAgentMarker(agent.metadata));
const agentSelection = resolvePortableExportAgentSelection(allAgentRows, input.agents, include.agents);
const companySkillRowsRaw = include.skills ? await companySkills.listFull(companyId) : [];
const managedSkillRows = companySkillRowsRaw.filter((skill) => managedSkillIds.has(skill.id));
const companySkillRows = companySkillRowsRaw.filter((skill) => !managedSkillIds.has(skill.id));
if (include.agents) {
const skipped = allAgentRows.length - liveAgentRows.length;
if (skipped > 0) {
warnings.push(`Skipped ${skipped} terminated agent${skipped === 1 ? "" : "s"} from export.`);
}
if (builtInAgentRows.length > 0) {
warnings.push(`Skipped ${builtInAgentRows.length} built-in managed agent${builtInAgentRows.length === 1 ? "" : "s"} from export.`);
}
}
warnings.push(...agentSelection.warnings);
if (include.skills && managedSkillRows.length > 0) {
warnings.push(`Skipped ${managedSkillRows.length} built-in managed skill${managedSkillRows.length === 1 ? "" : "s"} from export.`);
}
const agentByReference = new Map<string, typeof liveAgentRows[number]>();
const builtInAgentByReference = new Map<string, typeof liveAgentRows[number]>();
const addAgentReferences = (map: Map<string, typeof liveAgentRows[number]>, agent: typeof liveAgentRows[number]) => {
map.set(agent.id, agent);
map.set(agent.name, agent);
const normalizedName = normalizeAgentUrlKey(agent.name);
if (normalizedName) {
map.set(normalizedName, agent);
}
};
for (const agent of portableAgentRows) {
addAgentReferences(agentByReference, agent);
}
for (const agent of builtInAgentRows) {
addAgentReferences(builtInAgentByReference, agent);
}
const selectedAgents = new Map<string, typeof liveAgentRows[number]>();
for (const selector of input.agents ?? []) {
const trimmed = selector.trim();
if (!trimmed) continue;
const normalized = normalizeAgentUrlKey(trimmed) ?? trimmed;
const match = agentByReference.get(trimmed) ?? agentByReference.get(normalized);
if (!match) {
const builtInMatch = builtInAgentByReference.get(trimmed) ?? builtInAgentByReference.get(normalized);
if (builtInMatch) {
warnings.push(`Agent selector "${selector}" is a built-in managed agent and was skipped.`);
continue;
}
warnings.push(`Agent selector "${selector}" was not found and was skipped.`);
continue;
}
selectedAgents.set(match.id, match);
}
if (include.agents && selectedAgents.size === 0) {
for (const agent of portableAgentRows) {
selectedAgents.set(agent.id, agent);
}
}
const agentRows = Array.from(selectedAgents.values())
const agentRows = agentSelection.agents
.sort((left, right) => left.name.localeCompare(right.name));
const usedSlugs = new Set<string>();
@@ -4118,7 +4070,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
projectSlugById.set(project.id, uniqueSlug(baseSlug, usedProjectSlugs));
}
const sidebarOrder = requestedSidebarOrder ?? stripEmptyValues({
agents: sortAgentsBySidebarOrder(Array.from(selectedAgents.values()))
agents: sortAgentsBySidebarOrder(agentSelection.agents)
.map((agent) => idToSlug.get(agent.id))
.filter((slug): slug is string => Boolean(slug)),
projects: selectedProjectRows
@@ -4227,6 +4179,12 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
}
if (include.agents) {
if (
!options.allowExternalInstructions
&& agentRows.some((agent) => agentInstructionsBundleMode(agent) === "external")
) {
throw forbidden("Instance admin access is required to export external instruction bundles");
}
const agentInstructionsById = new Map(
await mapWithConcurrency(agentRows, EXPORT_READ_CONCURRENCY, async (agent) => (
[agent.id, await instructions.exportFiles(agent)] as const
@@ -4817,6 +4775,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
async function previewExport(
companyId: string,
input: CompanyPortabilityExport,
options: { allowExternalInstructions?: boolean } = {},
): Promise<CompanyPortabilityExportPreviewResult> {
const previewInput: CompanyPortabilityExport = {
...input,
@@ -4831,7 +4790,10 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
if (previewInput.include && previewInput.include.issues === undefined) {
previewInput.include.issues = false;
}
const exported = await exportBundle(companyId, previewInput, { preview: true });
const exported = await exportBundle(companyId, previewInput, {
preview: true,
allowExternalInstructions: options.allowExternalInstructions,
});
return {
...exported,
fileInventory: Object.keys(exported.files)
+22 -9
View File
@@ -38,7 +38,7 @@ import {
} from "@paperclipai/shared";
import { resolveHomeAwarePath, resolvePaperclipInstanceRoot } from "../home-paths.js";
import { notFound, unprocessable } from "../errors.js";
import { agentInstructionsService } from "./agent-instructions.js";
import { agentInstructionsBundleMode, agentInstructionsService } from "./agent-instructions.js";
import {
createFeedbackRedactionState,
finalizeFeedbackRedactionSummary,
@@ -1168,12 +1168,23 @@ async function buildAgentContext(
: [];
const usage = asRecord(run?.usageJson) ?? {};
const externalInstructions = agentInstructionsBundleMode({
id: agent.id,
companyId: agent.companyId,
name: agent.name,
adapterConfig: agent.adapterConfig,
}) === "external";
if (externalInstructions) {
state.omittedFields.add("bundle.agentContext.runtime.configuredInstructionsFilePath");
state.omittedFields.add("bundle.agentContext.runtime.configuredInstructionsRootPath");
state.omittedFields.add("bundle.agentContext.instructions");
}
const runtime = {
configuredModel: asString(adapterConfig.model),
configuredInstructionsBundleMode: asString(adapterConfig.instructionsBundleMode),
configuredInstructionsEntryFile: asString(adapterConfig.instructionsEntryFile),
configuredInstructionsFilePath: asString(adapterConfig.instructionsFilePath),
configuredInstructionsRootPath: asString(adapterConfig.instructionsRootPath),
configuredInstructionsFilePath: externalInstructions ? null : asString(adapterConfig.instructionsFilePath),
configuredInstructionsRootPath: externalInstructions ? null : asString(adapterConfig.instructionsRootPath),
heartbeatPolicy: sanitizeFeedbackValue(runtimeConfig.heartbeat ?? null, state, "bundle.agentContext.runtime.heartbeatPolicy", 400),
provenanceMode: run ? "source_run" : "vote_time_snapshot",
sourceRun: run
@@ -1218,12 +1229,14 @@ async function buildAgentContext(
: null,
};
const instructionsBundle = await instructionsSvc.getBundle({
id: agent.id,
companyId: agent.companyId,
name: agent.name,
adapterConfig: agent.adapterConfig,
}).catch(() => null);
const instructionsBundle = externalInstructions
? null
: await instructionsSvc.getBundle({
id: agent.id,
companyId: agent.companyId,
name: agent.name,
adapterConfig: agent.adapterConfig,
}).catch(() => null);
let entryDigest: string | null = null;
let entryBody: string | null = null;
+4 -1
View File
@@ -16,7 +16,7 @@ import { notFound } from "../errors.js";
import { agentService } from "./agents.js";
import { approvalService } from "./approvals.js";
import { logActivity } from "./activity-log.js";
import { agentInstructionsService } from "./agent-instructions.js";
import { agentInstructionsBundleMode, agentInstructionsService } from "./agent-instructions.js";
const MANAGED_AGENT_ENTITY_TYPE = "managed_agent";
const DEFAULT_MANAGED_AGENT_ADAPTER_TYPE = "process";
@@ -364,6 +364,9 @@ export function pluginManagedAgentService(
const variables = await optionsForInstructionVariables(companyId);
const declared = declaredInstructionFiles(declaration, variables);
if (!declared) return null;
if (agentInstructionsBundleMode(agent) === "external") {
return { entryFile: declared.entryFile, changedFiles: [declared.entryFile] };
}
let exported: Awaited<ReturnType<typeof instructions.exportFiles>>;
try {