mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-01 09:24:46 +00:00
Machine API keys: headless teams pull for deploy boxes and CI (#230)
A person's lsk_ key acts as the person, with one identity key per user. Logging a fresh box in with `login --token` uploaded the box's new keypair as the person's identity and replaced the real one. Machine keys fix that: a key made for a box, scoped to one team (and optionally named vaults), read-only unless --read-write, optionally expiring, with its OWN identity key registered on the key row. A vault key reaches it as a grant sealed to that public key (credshare_key_grants), never through the person. Schema (005_machine_keys, SQLite + Postgres): api_keys gains kind, team_id, vault_scope, read_only (default 0, so existing person keys keep writing), expires_at, public_key; new credshare_key_grants; credshare_audit.actor_key_id. Server: each credshare route declares what a machine key may do (read / write / register); the rest are people-only. Machine keys see only their team and scoped vaults, read their grant from credshare_key_grants (audited as vault:read with the key id), are refused every write when read-only, and cannot mint/list/revoke keys, read /api/me or touch the personal vault. Expired and revoked keys are 401. New GET|POST /api/keys, DELETE /api/keys/:id, and GET|POST|DELETE /api/credshare/vaults/:id/key-grants. A re-key re-seals the machine grants it is given and drops the rest. CLI 0.8.0: `logicsrc keys create|list|revoke` (--team, --vault, --read-only / --read-write, --expires, --out 0600); LOGICSRC_API_KEY and `login --api-key` with a per-key identity in keys/<prefix>.json (0600), generated and registered on first use; `login --token` with a machine key takes that path instead of replacing the person's key; `teams grant … --key <name>`; `credentials rotate` re-seals machine keys. PWA: settings creates machine keys (team, vaults, read-only, expiry); a vault page grants or revokes a machine key in the browser after unlock. MCP: list_api_keys / create_api_key / revoke_api_key over /api/keys with a Bearer LOGICSRC_API_KEY. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4df342a064
commit
ade33efd17
35 changed files with 2220 additions and 106 deletions
78
packages/logicsrc-mcp/src/apikeys.test.ts
Normal file
78
packages/logicsrc-mcp/src/apikeys.test.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||
import { createLogicSrcMcpServer } from "./server.js";
|
||||
|
||||
type Call = { url: string; method: string; auth: string | null; body: unknown };
|
||||
|
||||
/** A fake credentials app: records each request and answers like /api/keys does. */
|
||||
function fakeApi(calls: Call[], status = 200, payload: unknown = { keys: [] }): typeof fetch {
|
||||
return (async (input: string | URL | Request, init?: RequestInit) => {
|
||||
const headers = new Headers(init?.headers);
|
||||
calls.push({
|
||||
url: String(input),
|
||||
method: init?.method ?? "GET",
|
||||
auth: headers.get("authorization"),
|
||||
body: init?.body ? JSON.parse(String(init.body)) : undefined
|
||||
});
|
||||
return new Response(JSON.stringify(payload), { status, headers: { "content-type": "application/json" } });
|
||||
}) as typeof fetch;
|
||||
}
|
||||
|
||||
async function connect(env: NodeJS.ProcessEnv, doFetch: typeof fetch) {
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
const server = createLogicSrcMcpServer({ apiKeys: { env, fetch: doFetch } });
|
||||
const client = new Client({ name: "test-client", version: "0.1.0" });
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
return { client, close: async () => { await client.close(); await server.close(); } };
|
||||
}
|
||||
|
||||
function text(result: unknown): string {
|
||||
const content = (result as { content?: Array<{ type: string; text?: string }> }).content ?? [];
|
||||
return content[0]?.text ?? "";
|
||||
}
|
||||
|
||||
describe("API key tools", () => {
|
||||
it("lists keys with the Bearer key against LOGICSRC_API", async () => {
|
||||
const calls: Call[] = [];
|
||||
const { client, close } = await connect({ LOGICSRC_API_KEY: "lsk_person", LOGICSRC_API: "https://example.test/" }, fakeApi(calls));
|
||||
const tools = await client.listTools();
|
||||
expect(tools.tools.map((t) => t.name)).toEqual(expect.arrayContaining(["list_api_keys", "create_api_key", "revoke_api_key"]));
|
||||
const result = await client.callTool({ name: "list_api_keys", arguments: {} });
|
||||
expect(text(result)).toContain('"keys"');
|
||||
expect(calls).toEqual([{ url: "https://example.test/api/keys", method: "GET", auth: "Bearer lsk_person", body: undefined }]);
|
||||
await close();
|
||||
});
|
||||
|
||||
it("creates a read-only machine key by default and revokes by id", async () => {
|
||||
const calls: Call[] = [];
|
||||
const { client, close } = await connect({ LOGICSRC_API_KEY: "lsk_person" }, fakeApi(calls, 201, { key: { name: "dev2" }, secret: "lsk_new" }));
|
||||
await client.callTool({ name: "create_api_key", arguments: { name: "dev2", team: "acme", vaults: ["web--prod"], expires: "30d" } });
|
||||
expect(calls[0]).toMatchObject({
|
||||
url: "https://app.logicsrc.com/api/keys",
|
||||
method: "POST",
|
||||
body: { name: "dev2", kind: "machine", team: "acme", vaults: ["web--prod"], readOnly: true, expiresAt: "30d" }
|
||||
});
|
||||
await client.callTool({ name: "revoke_api_key", arguments: { id: "k/1" } });
|
||||
expect(calls[1]).toMatchObject({ url: "https://app.logicsrc.com/api/keys/k%2F1", method: "DELETE" });
|
||||
await close();
|
||||
});
|
||||
|
||||
it("says what is missing instead of calling out without a key, and passes server refusals through", async () => {
|
||||
const calls: Call[] = [];
|
||||
const noKey = await connect({}, fakeApi(calls));
|
||||
const missing = await noKey.client.callTool({ name: "list_api_keys", arguments: {} });
|
||||
expect((missing as { isError?: boolean }).isError).toBe(true);
|
||||
expect(text(missing)).toContain("LOGICSRC_API_KEY is not set");
|
||||
expect(calls).toHaveLength(0);
|
||||
await noKey.close();
|
||||
|
||||
const machine = await connect({ LOGICSRC_API_KEY: "lsk_machine" }, fakeApi(calls, 403, { error: "A machine API key cannot manage API keys." }));
|
||||
const refused = await machine.client.callTool({ name: "create_api_key", arguments: { name: "x", team: "acme" } });
|
||||
expect((refused as { isError?: boolean }).isError).toBe(true);
|
||||
expect(text(refused)).toContain("403");
|
||||
expect(text(refused)).toContain("machine API key cannot manage");
|
||||
await machine.close();
|
||||
});
|
||||
});
|
||||
115
packages/logicsrc-mcp/src/apikeys.ts
Normal file
115
packages/logicsrc-mcp/src/apikeys.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* API-key tools for the MCP server: list, create and revoke LogicSRC API keys
|
||||
* by calling the credentials app's /api/keys over HTTPS.
|
||||
*
|
||||
* Auth is a Bearer token from LOGICSRC_API_KEY (and LOGICSRC_API for a server
|
||||
* other than https://app.logicsrc.com). It must be a PERSON's key (`logicsrc
|
||||
* keys create <name> --kind user`, or the one `logicsrc login` stored): the
|
||||
* server refuses to let a machine key mint, list or revoke keys, and these
|
||||
* tools pass that refusal through rather than working around it.
|
||||
*
|
||||
* Secrets: `create_api_key` returns the new key's secret exactly once, in its
|
||||
* result. Nothing here stores it.
|
||||
*/
|
||||
|
||||
export const DEFAULT_API_URL = "https://app.logicsrc.com";
|
||||
|
||||
export interface ApiKeyToolsOptions {
|
||||
env?: NodeJS.ProcessEnv;
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
class ToolError extends Error {}
|
||||
|
||||
function client(options: ApiKeyToolsOptions) {
|
||||
const env = options.env ?? process.env;
|
||||
const doFetch = options.fetch ?? fetch;
|
||||
return async function call(method: string, path: string, body?: unknown): Promise<unknown> {
|
||||
const token = env.LOGICSRC_API_KEY?.trim();
|
||||
if (!token) {
|
||||
throw new ToolError(
|
||||
"LOGICSRC_API_KEY is not set. Give this MCP server a person's LogicSRC API key (logicsrc keys create <name> --kind user) in its environment."
|
||||
);
|
||||
}
|
||||
const base = (env.LOGICSRC_API || env.LOGICSRC_API_URL || DEFAULT_API_URL).replace(/\/+$/, "");
|
||||
const headers: Record<string, string> = { accept: "application/json", authorization: `Bearer ${token}` };
|
||||
if (body !== undefined) headers["content-type"] = "application/json";
|
||||
const res = await doFetch(`${base}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
const text = await res.text();
|
||||
let parsed: unknown;
|
||||
try { parsed = text ? JSON.parse(text) : undefined; } catch { parsed = undefined; }
|
||||
if (!res.ok) {
|
||||
const message = parsed && typeof parsed === "object" && "error" in parsed ? String((parsed as { error: unknown }).error) : `${res.status} ${res.statusText}`;
|
||||
throw new ToolError(`${method} ${path} failed (${res.status}): ${message}`);
|
||||
}
|
||||
return parsed;
|
||||
};
|
||||
}
|
||||
|
||||
function textResult(text: string, isError = false) {
|
||||
return { content: [{ type: "text" as const, text }], ...(isError ? { isError: true } : {}) };
|
||||
}
|
||||
|
||||
async function guarded(fn: () => Promise<unknown>) {
|
||||
try {
|
||||
return textResult(JSON.stringify(await fn(), null, 2));
|
||||
} catch (error) {
|
||||
return textResult(error instanceof Error ? error.message : String(error), true);
|
||||
}
|
||||
}
|
||||
|
||||
export function registerApiKeys(server: McpServer, options: ApiKeyToolsOptions = {}): void {
|
||||
const call = client(options);
|
||||
|
||||
server.registerTool(
|
||||
"list_api_keys",
|
||||
{
|
||||
title: "List LogicSRC API Keys",
|
||||
description: "Lists the caller's LogicSRC API keys (person and machine keys): name, prefix, team and vault scope, read-only, expiry, whether a machine key has registered its identity. Never returns secrets. Needs LOGICSRC_API_KEY (a person's key).",
|
||||
annotations: { readOnlyHint: true, openWorldHint: true }
|
||||
},
|
||||
async () => guarded(() => call("GET", "/api/keys"))
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"create_api_key",
|
||||
{
|
||||
title: "Create LogicSRC API Key",
|
||||
description: "Creates a LogicSRC API key. A machine key (the default) is scoped to one team and optionally some vaults (<project>--<env>), read-only unless readOnly is false, and may expire. The secret is in this result only; hand it to the deploy box and do not repeat it. Needs LOGICSRC_API_KEY (a person's key).",
|
||||
inputSchema: {
|
||||
name: z.string().min(1).max(40).describe("A name for the key, e.g. dev2-deploy."),
|
||||
kind: z.enum(["machine", "user"]).optional().describe("machine (default) or user (acts as the person)."),
|
||||
team: z.string().optional().describe("Team slug; required for a machine key."),
|
||||
vaults: z.array(z.string()).optional().describe("Vault names the key may read, e.g. [\"web--prod\"]. Omit for every vault in the team."),
|
||||
readOnly: z.boolean().optional().describe("Machine keys: true (default) pulls only."),
|
||||
expires: z.string().optional().describe("30d, 12h, 1y, or a date such as 2027-01-01. Omit for no expiry.")
|
||||
},
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
|
||||
},
|
||||
async ({ name, kind, team, vaults, readOnly, expires }) =>
|
||||
guarded(async () => {
|
||||
const k = kind ?? "machine";
|
||||
if (k === "machine" && !team) throw new ToolError("A machine key needs a team.");
|
||||
return call("POST", "/api/keys", {
|
||||
name,
|
||||
kind: k,
|
||||
...(k === "machine" ? { team, vaults: vaults ?? [], readOnly: readOnly ?? true } : {}),
|
||||
...(expires ? { expiresAt: expires } : {})
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
server.registerTool(
|
||||
"revoke_api_key",
|
||||
{
|
||||
title: "Revoke LogicSRC API Key",
|
||||
description: "Revokes one of the caller's LogicSRC API keys by id (from list_api_keys). Anything using it gets a 401 from then on, and its vault grants are deleted. Needs LOGICSRC_API_KEY (a person's key).",
|
||||
inputSchema: { id: z.string().min(1).describe("The key id from list_api_keys.") },
|
||||
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true }
|
||||
},
|
||||
async ({ id }) => guarded(() => call("DELETE", `/api/keys/${encodeURIComponent(id)}`))
|
||||
);
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ import { z } from "zod";
|
|||
import { assertSchemaKind, parseDocument, schemas, validate, type SchemaKind } from "@logicsrc/validators";
|
||||
import { registerOpenOntology } from "./openontology.js";
|
||||
import { registerOpenPrd } from "./openprd.js";
|
||||
import { registerApiKeys, type ApiKeyToolsOptions } from "./apikeys.js";
|
||||
|
||||
const docs = {
|
||||
"communication-accounts": `LogicSRC Communication Accounts defines shared contracts for connecting social and email identities, granting scoped human/agent/plugin access, evaluating policy gates, brokering credentials, and auditing every account action without exposing raw secrets.`,
|
||||
|
|
@ -15,7 +16,7 @@ CommandBoard.run is a hosted product by Profullstack, Inc., built on LogicSRC. L
|
|||
|
||||
const schemaKinds = Object.keys(schemas) as SchemaKind[];
|
||||
|
||||
export function createLogicSrcMcpServer() {
|
||||
export function createLogicSrcMcpServer(options: { apiKeys?: ApiKeyToolsOptions } = {}) {
|
||||
const server = new McpServer(
|
||||
{
|
||||
name: "@profullstack/logicsrc-mcp",
|
||||
|
|
@ -27,7 +28,7 @@ export function createLogicSrcMcpServer() {
|
|||
tools: {},
|
||||
prompts: {}
|
||||
},
|
||||
instructions: "Use this server for LogicSRC standards, schema resources, validation, draft object generation, OpenOntology knowledge (entities, claims, provenance, governed change sets), and OpenPRD product requirements documents. Treat CommandBoard.run as a reference implementation, not the standards identity. Ontology and PRD write tools propose; they never apply."
|
||||
instructions: "Use this server for LogicSRC standards, schema resources, validation, draft object generation, OpenOntology knowledge (entities, claims, provenance, governed change sets), and OpenPRD product requirements documents, and LogicSRC API keys (list/create/revoke over the credentials app, with LOGICSRC_API_KEY). Treat CommandBoard.run as a reference implementation, not the standards identity. Ontology and PRD write tools propose; they never apply."
|
||||
}
|
||||
);
|
||||
|
||||
|
|
@ -155,6 +156,7 @@ export function createLogicSrcMcpServer() {
|
|||
|
||||
registerOpenOntology(server);
|
||||
registerOpenPrd(server);
|
||||
registerApiKeys(server, options.apiKeys);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue