todo_service: запись назначенному в любом проекте и без проекта, агентские токены, тест не зависит от реальной даты
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,7 +4,11 @@
|
||||
|
||||
HTTP `127.0.0.1:8094` (контейнер `khb-todo-service`, во внутренней сети - `http://khb-todo-service:8094`). Наружу через nginx на общем хосте сервисов (`https://services.khbuild.freeddns.org/api/todo`, префикс `/api/todo` nginx отрезает) открыты только `/webhooks/jobtread/<secret>`, `/mcp` и `/.well-known/oauth-protected-resource`.
|
||||
|
||||
**Авторизация.** `Authorization: Bearer <todo_service.http.token>`. Права по вызывающему: заголовок `X-Caller-Person: <person id>`. CEO (`construction_manager.chat_kind = 'ceo'`) видит и меняет всё; менеджер - todo своих проектов (`assistant_project`) и назначенные ему. Без заголовка - права администратора (внутренний вызов). Запись возможна только в проекты из `todo_service.allowedJobIds`. Ответы об ошибках: `{ "error": "..." }` (401, 403, 404, 400, 502).
|
||||
**Авторизация.** Два типа токенов (`Authorization: Bearer ...`).
|
||||
- Административный `todo_service.http.token` (для сервисов: слежение, лента событий, служебные вызовы; агентам не выдаётся): без `X-Caller-Person` - права администратора, с заголовком - права этого person.
|
||||
- Агентский `todo_service.http.agentTokens[]` (для агентов менеджеров): с `personId` токен привязан к person, заголовок не нужен (если передан, должен совпасть, иначе 403); без `personId` заголовок `X-Caller-Person` обязателен (без него 403). Администратором агентский токен не становится.
|
||||
|
||||
Права person: CEO (`construction_manager.chat_kind = 'ceo'`) видит и меняет всё; менеджер видит todo своих проектов (`assistant_project`) и назначенные ему. **Запись:** менеджер меняет, закрывает, откладывает и снимает (`keep`) todo своих проектов и любые назначенные ему, в том числе в чужом проекте и без проекта; `allowedJobIds` (глобальный гейт) применяется только к todo с проектом, создание всегда требует `jobId` из `allowedJobIds`. Todo без проекта, не назначенное вызывающему (не CEO и не администратор), недоступно: чтение 404. Ответы об ошибках: `{ "error": "..." }` (401, 403, 404, 400, 502).
|
||||
|
||||
**Запись.** Идемпотентность: заголовок `Idempotency-Key` (повтор возвращает прежний результат). Ответ `200 { status: "done", id, todo }`, либо `202 { status: "queued", requestId }`, если JobTread недоступен (повтор до 5 минут, состояние - `GET /requests/:id`).
|
||||
|
||||
|
||||
@@ -17,18 +17,33 @@ export class Auth {
|
||||
private jwks: ReturnType<typeof createRemoteJWKSet> | null = null;
|
||||
constructor(private readonly pool: Pool, private readonly s: TodoServiceSettings) {}
|
||||
|
||||
/** REST: только внутренний токен; person передаётся заголовком X-Caller-Person. */
|
||||
async internal(authorization: string | undefined, callerPerson: string | undefined): Promise<Caller> {
|
||||
const t = bearer(authorization);
|
||||
if (!t || !safeEqual(t, this.s.http.token)) throw new AccessError("unauthorized", 401);
|
||||
return callerPerson ? resolveCaller(this.pool, callerPerson) : ADMIN;
|
||||
/** Токен -> права: административный (без заголовка - администратор) или агентский (всегда конкретный person). null - токен не наш. */
|
||||
private async byServiceToken(t: string, callerPerson: string | undefined): Promise<Caller | null> {
|
||||
if (safeEqual(t, this.s.http.token)) return callerPerson ? resolveCaller(this.pool, callerPerson) : ADMIN;
|
||||
const at = this.s.http.agentTokens.find((x) => safeEqual(t, x.token));
|
||||
if (!at) return null;
|
||||
if (at.personId) {
|
||||
if (callerPerson && callerPerson.toLowerCase() !== at.personId.toLowerCase()) throw new AccessError("X-Caller-Person не совпадает с person токена", 403);
|
||||
return resolveCaller(this.pool, at.personId);
|
||||
}
|
||||
if (!callerPerson) throw new AccessError("агентскому токену нужен заголовок X-Caller-Person", 403);
|
||||
return resolveCaller(this.pool, callerPerson);
|
||||
}
|
||||
|
||||
/** MCP: внутренний токен, статический токен или JWT Keycloak; JWT без известного person отклоняется. */
|
||||
/** REST: административный или агентский токен; person передаётся заголовком X-Caller-Person. */
|
||||
async internal(authorization: string | undefined, callerPerson: string | undefined): Promise<Caller> {
|
||||
const t = bearer(authorization);
|
||||
const c = t ? await this.byServiceToken(t, callerPerson) : null;
|
||||
if (!c) throw new AccessError("unauthorized", 401);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** MCP: токен сервиса, статический токен или JWT Keycloak; JWT без известного person отклоняется. */
|
||||
async mcp(authorization: string | undefined, callerPerson: string | undefined): Promise<Caller> {
|
||||
const t = bearer(authorization);
|
||||
if (!t) throw new AccessError("unauthorized", 401);
|
||||
if (safeEqual(t, this.s.http.token)) return callerPerson ? resolveCaller(this.pool, callerPerson) : ADMIN;
|
||||
const sc = await this.byServiceToken(t, callerPerson);
|
||||
if (sc) return sc;
|
||||
const st = this.s.mcp.staticTokens.find((x) => safeEqual(t, x.token));
|
||||
if (st) return st.personId ? resolveCaller(this.pool, st.personId) : { ...ADMIN, name: st.name ?? "mcp-token" };
|
||||
if (!this.s.mcp.issuer) throw new AccessError("unauthorized", 401);
|
||||
|
||||
@@ -311,10 +311,16 @@ export class TodoCore {
|
||||
|
||||
// ---------------------------------------------------------------- запись (JobTread - главный; очередь повторов до 5 минут)
|
||||
|
||||
private assertWritable(caller: Caller, jobId: string | null): void {
|
||||
if (!jobId) throw new HttpError(400, "у todo нет проекта: запись не поддерживается");
|
||||
if (!this.d.settings.allowedJobIds.includes(jobId)) throw new AccessError(`запись в проект ${jobId} не разрешена настройками сервиса`);
|
||||
if (!caller.all && !caller.jobIds.has(jobId)) throw new AccessError("нет доступа к проекту");
|
||||
/**
|
||||
* Право записи: CEO/администратор - всё; менеджер - todo своих проектов и назначенные ему (в любом проекте и без проекта).
|
||||
* allowedJobIds (глобальный гейт) действует только для todo с проектом; создание всегда требует проект.
|
||||
*/
|
||||
private assertWritable(caller: Caller, jobId: string | null, assigneeIds: string[] = []): void {
|
||||
if (jobId && !this.d.settings.allowedJobIds.includes(jobId)) throw new AccessError(`запись в проект ${jobId} не разрешена настройками сервиса`);
|
||||
if (caller.all) return;
|
||||
if (jobId && caller.jobIds.has(jobId)) return;
|
||||
if (caller.membershipId && assigneeIds.includes(caller.membershipId)) return;
|
||||
throw new AccessError(jobId ? "нет доступа к проекту" : "todo без проекта: запись только назначенному или CEO");
|
||||
}
|
||||
|
||||
/** Назначение: membership id и/или person id (через person.jt_membership_id). */
|
||||
@@ -468,6 +474,7 @@ export class TodoCore {
|
||||
key?: string,
|
||||
): Promise<WriteResult> {
|
||||
if (!i.name?.trim()) throw new HttpError(400, "нужно name");
|
||||
if (!i.jobId) throw new HttpError(400, "нужен jobId");
|
||||
this.assertWritable(caller, i.jobId);
|
||||
const kind = i.kind ?? guessKind(i.name);
|
||||
const name = kind === "control" ? ensureControlPrefix(i.name) : i.name.trim();
|
||||
@@ -494,6 +501,7 @@ export class TodoCore {
|
||||
key?: string,
|
||||
): Promise<WriteResult> {
|
||||
if (!i.executor?.name?.trim() || !i.control?.name?.trim()) throw new HttpError(400, "нужны executor.name и control.name");
|
||||
if (!i.jobId) throw new HttpError(400, "нужен jobId");
|
||||
this.assertWritable(caller, i.jobId);
|
||||
const ctl = (await this.d.pool.query("select jt_membership_id from person where id = $1 and is_active", [i.controllerPersonId])).rows[0];
|
||||
if (!ctl?.jt_membership_id) throw new HttpError(400, "у контролёра нет person или membership JobTread");
|
||||
@@ -528,7 +536,7 @@ export class TodoCore {
|
||||
if (p.kind !== undefined) ext.kind = p.kind;
|
||||
if (p.reviewDate !== undefined) ext.reviewDate = p.reviewDate;
|
||||
const jtTouched = p.name !== undefined || p.description !== undefined || p.due !== undefined || p.assigneeMembershipIds || p.assigneePersonIds;
|
||||
if (jtTouched || ext.reviewDate !== undefined) this.assertWritable(caller, cur.jobId);
|
||||
if (jtTouched || ext.reviewDate !== undefined) this.assertWritable(caller, cur.jobId, cur.assignees.map((a) => a.id));
|
||||
if (p.name !== undefined) {
|
||||
if (!p.name.trim()) throw new HttpError(400, "пустое name");
|
||||
patch.name = cur.kind === "control" || p.kind === "control" ? desiredName(ensureControlPrefix(p.name), { done: cur.doneFlag, overdue: cur.overdueFlag }) : p.name.trim();
|
||||
@@ -550,19 +558,19 @@ export class TodoCore {
|
||||
|
||||
async close(caller: Caller, id: string, key?: string): Promise<WriteResult> {
|
||||
const cur = await this.get(caller, id);
|
||||
this.assertWritable(caller, cur.jobId);
|
||||
this.assertWritable(caller, cur.jobId, cur.assignees.map((a) => a.id));
|
||||
return this.runWrite("update", { id, patch: { progress: 1 } }, caller, key).then(async (r) => (r.status === "done" ? { ...r, id, todo: await this.get(caller, id) } : r));
|
||||
}
|
||||
|
||||
async reopen(caller: Caller, id: string, key?: string): Promise<WriteResult> {
|
||||
const cur = await this.get(caller, id);
|
||||
this.assertWritable(caller, cur.jobId);
|
||||
this.assertWritable(caller, cur.jobId, cur.assignees.map((a) => a.id));
|
||||
return this.runWrite("update", { id, patch: { progress: 0 } }, caller, key).then(async (r) => (r.status === "done" ? { ...r, id, todo: await this.get(caller, id) } : r));
|
||||
}
|
||||
|
||||
async remove(caller: Caller, id: string, key?: string): Promise<WriteResult> {
|
||||
const cur = await this.get(caller, id);
|
||||
this.assertWritable(caller, cur.jobId);
|
||||
this.assertWritable(caller, cur.jobId, cur.assignees.map((a) => a.id));
|
||||
return this.runWrite("delete", { id }, caller, key);
|
||||
}
|
||||
|
||||
@@ -576,7 +584,7 @@ export class TodoCore {
|
||||
/** "Keep confirmed": флаг в надстройке и строка в описании. */
|
||||
async keep(caller: Caller, id: string): Promise<WriteResult> {
|
||||
const cur = await this.get(caller, id);
|
||||
this.assertWritable(caller, cur.jobId);
|
||||
this.assertWritable(caller, cur.jobId, cur.assignees.map((a) => a.id));
|
||||
await this.ensureExt(id);
|
||||
await this.d.pool.query("update todo_ext set keep_confirmed = true, updated_at = now() where task_id = $1", [id]);
|
||||
const desc = withKeepConfirmed(cur.description, this.today());
|
||||
|
||||
@@ -25,7 +25,10 @@ d("todo_service (временная БД, JobTread подменён)", () => {
|
||||
let watchers: Watchers;
|
||||
let clock = new Date("2026-10-29T15:00:00Z"); // чт 11:00 по Тампе
|
||||
const settings = todoServiceSchema.parse({
|
||||
http: { token: "internal-token", port: 0 },
|
||||
http: {
|
||||
token: "internal-token", port: 0,
|
||||
agentTokens: [{ token: "agent-token-mgr-0001", personId: MGR }, { token: "agent-token-shared-01" }],
|
||||
},
|
||||
allowedJobIds: [JOB],
|
||||
webhook: { secret: "hooksecret123", publicBaseUrl: "https://todo.example.org", autoRegister: true },
|
||||
mcp: { staticTokens: [{ token: "static-mcp-token-0001", personId: MGR }] },
|
||||
@@ -72,6 +75,28 @@ d("todo_service (временная БД, JobTread подменён)", () => {
|
||||
await expect(core.create(ADMIN, { jobId: OTHER_JOB, name: "x" })).rejects.toBeInstanceOf(AccessError);
|
||||
});
|
||||
|
||||
it("запись: назначенному менеджеру можно менять todo без проекта", async () => {
|
||||
await db.pool.query(
|
||||
"insert into todo_item (task_id, job_id, name, assignee_ids) values ('NOP0000001x', null, 'org todo', '{MEMmgr}'), ('NOP0000002x', null, 'org unassigned', '{}')",
|
||||
);
|
||||
jt.tasks.set("NOP0000001x", { id: "NOP0000001x", jobId: null, name: "org todo", description: null, assigneeIds: ["MEMmgr"], startDate: null, endDate: null, progress: null, isToDo: true, createdAt: clock.toISOString() });
|
||||
const mgr = await resolveCaller(db.pool, MGR);
|
||||
expect((await core.close(mgr, "NOP0000001x")).status).toBe("done");
|
||||
expect((await core.get(ADMIN, "NOP0000001x")).status).toBe("done");
|
||||
await expect(core.close(mgr, "NOP0000002x")).rejects.toMatchObject({ status: 404 }); // не назначено и нет проекта: даже не видно
|
||||
});
|
||||
|
||||
it("токены: агентский не даёт прав администратора и не позволяет подменить person", async () => {
|
||||
const auth = new Auth(db.pool, settings);
|
||||
expect((await auth.internal("Bearer internal-token", undefined)).all).toBe(true);
|
||||
expect(await auth.internal("Bearer agent-token-mgr-0001", undefined)).toMatchObject({ personId: MGR, all: false });
|
||||
expect((await auth.internal("Bearer agent-token-mgr-0001", MGR)).personId).toBe(MGR);
|
||||
await expect(auth.internal("Bearer agent-token-mgr-0001", CEO)).rejects.toMatchObject({ status: 403 });
|
||||
await expect(auth.internal("Bearer agent-token-shared-01", undefined)).rejects.toMatchObject({ status: 403 });
|
||||
expect((await auth.internal("Bearer agent-token-shared-01", MGR2)).personId).toBe(MGR2);
|
||||
await expect(auth.internal("Bearer nope", undefined)).rejects.toMatchObject({ status: 401 });
|
||||
});
|
||||
|
||||
it("JobTread недоступен: запрос в очереди, потом выполняется; ключ не дублирует", async () => {
|
||||
jt.failWrites = 1;
|
||||
const r = await core.create(ADMIN, { jobId: JOB, name: "Queued todo" }, "key-q");
|
||||
@@ -89,7 +114,7 @@ d("todo_service (временная БД, JobTread подменён)", () => {
|
||||
jt.failWrites = 100;
|
||||
const r = await core.create(ADMIN, { jobId: JOB, name: "Never" }, "key-never");
|
||||
expect(r.status).toBe("queued");
|
||||
await db.pool.query("update todo_request set next_attempt_at = now() - interval '1 second', deadline = now() - interval '1 second' where id = $1", [(r as { requestId: string }).requestId]);
|
||||
await db.pool.query("update todo_request set next_attempt_at = now() - interval '1 second', deadline = $2 where id = $1", [(r as { requestId: string }).requestId, new Date(clock.getTime() - 1000)]);
|
||||
await core.processRequests();
|
||||
jt.failWrites = 0;
|
||||
expect((await core.request(ADMIN, (r as { requestId: string }).requestId)).status).toBe("failed");
|
||||
|
||||
@@ -1,7 +1,17 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const todoServiceSchema = z.object({
|
||||
http: z.object({ host: z.string().default("127.0.0.1"), port: z.number().default(8094), token: z.string().min(1) }),
|
||||
http: z.object({
|
||||
host: z.string().default("127.0.0.1"),
|
||||
port: z.number().default(8094),
|
||||
/** Административный токен (сервисы: слежение, лента событий, служебные вызовы). Без X-Caller-Person - права администратора. Агентам не выдаётся. */
|
||||
token: z.string().min(1),
|
||||
/**
|
||||
* Агентские токены (для агентов менеджеров). С personId - токен привязан к person, X-Caller-Person не нужен
|
||||
* (если передан, должен совпасть). Без personId - X-Caller-Person обязателен; без него 403. Администратором не станут.
|
||||
*/
|
||||
agentTokens: z.array(z.object({ token: z.string().min(16), personId: z.string().uuid().optional(), name: z.string().optional() })).default([]),
|
||||
}),
|
||||
/** Проекты JobTread, куда сервису разрешено писать (создавать, менять, закрывать). Пусто - запись запрещена. */
|
||||
allowedJobIds: z.array(z.string()).default([]),
|
||||
webhook: z
|
||||
|
||||
@@ -81,7 +81,7 @@
|
||||
},
|
||||
|
||||
todo_service: { // todo поверх JobTread и Supabase (services.khbuild.freeddns.org/api/todo): REST, MCP, вебхуки
|
||||
http: { host: "127.0.0.1", port: 8094, token: "<token для внутренних вызовов и команды khb-todo>" },
|
||||
http: { host: "127.0.0.1", port: 8094, token: "<административный токен сервисов>", agentTokens: [{ token: "<агентский токен, 16+ знаков>", personId: "<person id менеджера>" }] },
|
||||
allowedJobIds: ["<id проекта JobTread, куда сервису разрешено писать>"],
|
||||
webhook: { publicBaseUrl: "https://services.khbuild.freeddns.org/api/todo", secret: "<секрет в адресе вебхука, 8+ знаков>", autoRegister: true },
|
||||
poll: { intervalSeconds: 300, backfillOnStart: true },
|
||||
|
||||
Reference in New Issue
Block a user