Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,11 @@ jobs:
- uses: actions/checkout@v4

- uses: pnpm/action-setup@v4
with:
version: 10
# version is read from package.json packageManager field

- uses: actions/setup-node@v4
with:
node-version: 20
node-version: 22
cache: pnpm

- name: Install
Expand Down
4 changes: 2 additions & 2 deletions apps/api/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@ export async function requireApiToken(req: FastifyRequest, _reply: FastifyReply)
const path = (req.url ?? '').split('?')[0] ?? '';
if (PUBLIC_PREFIXES.some((p) => path === p || path.startsWith(`${p}/`))) return;

// Fail closed in production: mutating control plane must not be open.
// Fail closed in production: EVERY request must be authenticated.
if (keys.length === 0) {
const env = process.env.NODE_ENV ?? 'development';
if (env === 'production' && req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS') {
if (env === 'production') {
throw new ProofloopError(
'unauthorized',
'PROOFLOOP_API_TOKEN (or PROOFLOOP_API_KEYS) must be set in production',
Expand Down
13 changes: 10 additions & 3 deletions apps/api/src/gitlab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import { mapOverallToCheckConclusion } from '@proofloop/core';
import { renderMarkdownReport, type EvidencePack } from '@proofloop/evidence';
import { ensureGitlabCheckout, syncRepoToSha } from '@proofloop/git';
import {
createOrganization,
createRepository,
ensureDefaultOrganization,
findActiveRunForHead,
findClaimedRunForHead,
getRepository,
getRun,
listOrganizations,
listRepositories,
updateRepositoryLocalPath,
updateRunGithubMeta,
Expand Down Expand Up @@ -270,8 +271,14 @@ export async function handleGitlabWebhook(input: {
},
};
}
// Auto-registered GitLab repos belong to the default tenant.
const org = ensureDefaultOrganization();
// Auto-registered GitLab repos scoped to the project namespace (tenant).
// This mimics GitHub's installation-based org isolation.
const org = (() => {
const slug = ownerName.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 60) || 'default';
const existing = listOrganizations().find((o) => o.slug === slug);
if (existing) return existing;
return createOrganization({ name: ownerName, slug });
})();
repo = createRepository({
provider: 'gitlab',
owner: ownerName,
Expand Down
9 changes: 9 additions & 0 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { buildApp } from './app.js';
import { startQueueWorker } from './queue.js';
import { apiAuthEnabled } from './auth.js';

const port = Number(process.env.PORT ?? 8787);
const host = process.env.HOST ?? '0.0.0.0';

// Production guard: refuse to start without API token.
if (process.env.NODE_ENV === 'production' && !apiAuthEnabled()) {
console.error(
'[proofloop] Fatal: PROOFLOOP_API_TOKEN (or PROOFLOOP_API_KEYS) must be set in production.',
);
process.exit(1);
}

const queue = await startQueueWorker();
const app = await buildApp();
await app.listen({ port, host });
Expand Down
28 changes: 28 additions & 0 deletions apps/api/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,16 @@ export async function registerRoutes(app: FastifyInstance) {
if (!Number.isInteger(installationId) || installationId <= 0) {
throw new ProofloopError('bad_request', 'Invalid installation id', 400);
}
// Restrict to global-scoped keys: org-scoped keys must not mint or refresh
// installation tokens that may belong to other tenants.
const scope = scopeForRequest(req as never);
if (scope.organizationId) {
throw new ProofloopError(
'forbidden',
'Only global API keys may mint installation tokens',
403,
);
}
const token = await getInstallationToken(installationId);
if (!token) {
throw new ProofloopError(
Expand Down Expand Up @@ -349,6 +359,24 @@ export async function registerRoutes(app: FastifyInstance) {
const scope = scopeForRequest(req as never);
// Org-bound keys cannot create repositories in another org.
const organizationId = scope.organizationId ?? body.organizationId ?? null;

// Confine localPath to the workspace root so an authenticated caller cannot
// point the pipeline at arbitrary server directories (CVE-like).
if (body.localPath) {
const workspaceRoot = resolve(
process.env.PROOFLOOP_WORKSPACE_ROOT ?? resolve(process.cwd(), '.data', 'workspaces'),
);
const resolved = resolve(body.localPath);
if (!resolved.startsWith(workspaceRoot + '/') && !resolved.startsWith(workspaceRoot + '\\')) {
throw new ProofloopError(
'bad_request',
'localPath must be within PROOFLOOP_WORKSPACE_ROOT',
400,
);
}
body.localPath = resolved;
}

const data = createRepository({ ...body, organizationId });
return { data, requestId: rid(req as { requestId?: string }) };
});
Expand Down
22 changes: 18 additions & 4 deletions apps/web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,27 +47,37 @@ export default function App() {
setRepoId('');
return;
}
let cancelled = false;
api
.repositories(orgId)
.then((r) => {
if (cancelled) return;
setRepos(r.data);
if (r.data[0]) setRepoId(r.data[0].id);
else setRepoId('');
})
.catch((e) => setError(e.message));
return () => { cancelled = true; };
}, [orgId]);

useEffect(() => {
if (!repoId) return;
if (!repoId) {
setRuns([]);
setRunId('');
return;
}
let cancelled = false;
api
.runs(repoId)
.then((r) => {
if (cancelled) return;
setRuns(r.data);
setRunId((prev) =>
prev && r.data.some((x) => x.id === prev) ? prev : (r.data[0]?.id ?? ''),
);
})
.catch((e) => setError(e.message));
return () => { cancelled = true; };
}, [repoId]);

useEffect(() => {
Expand Down Expand Up @@ -122,30 +132,34 @@ export default function App() {
if (!repoId) return;
setLoading(true);
setError(null);
let cancelled = false;
const cancel = () => { cancelled = true; };
try {
const res = await api.createRun(repoId, {
noLlm: true,
base: 'HEAD~1',
head: 'HEAD',
sync: false,
});
if (cancelled) return;
setRuns((prev) => [res.data, ...prev.filter((r) => r.id !== res.data.id)]);
setRunId(res.data.id);
navigate(`/runs/${res.data.id}`);
let current = res.data;
for (let i = 0; i < 180; i++) {
if (['completed', 'failed', 'cancelled'].includes(current.status)) break;
if (cancelled || ['completed', 'failed', 'cancelled'].includes(current.status)) break;
await new Promise((r) => setTimeout(r, 500));
if (cancelled) return;
current = (await api.run(current.id)).data;
setRuns((prev) => [current, ...prev.filter((r) => r.id !== current.id)]);
}
window.dispatchEvent(
new CustomEvent('proofloop:run-updated', { detail: { runId: current.id } }),
);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
if (!cancelled) setError(e instanceof Error ? e.message : String(e));
} finally {
setLoading(false);
if (!cancelled) setLoading(false);
}
}

Expand Down
28 changes: 27 additions & 1 deletion apps/web/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,37 @@ const BASE = '';

function authHeaders(): Record<string, string> {
const token =
(import.meta as { env?: Record<string, string> }).env?.VITE_PROOFLOOP_API_TOKEN ||
(typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('PROOFLOOP_API_TOKEN') : null) ||
(typeof localStorage !== 'undefined' ? localStorage.getItem('PROOFLOOP_API_TOKEN') : null);
return token ? { Authorization: `Bearer ${token}` } : {};
}

/** Allow the UI to set the token from a login dialog. */
export function setApiToken(token: string) {
try {
sessionStorage.setItem('PROOFLOOP_API_TOKEN', token);
} catch {
// sessionStorage may not be available (SSR, privacy mode)
}
}

export function clearApiToken() {
try {
sessionStorage.removeItem('PROOFLOOP_API_TOKEN');
localStorage.removeItem('PROOFLOOP_API_TOKEN');
} catch {
// ignore
}
}

export function getApiToken(): string | null {
try {
return sessionStorage.getItem('PROOFLOOP_API_TOKEN') ?? localStorage.getItem('PROOFLOOP_API_TOKEN');
} catch {
return null;
}
}

async function request<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
...init,
Expand Down
Loading
Loading