feat: 接入真实登录与成员权限

- auth/members/messages: 新增超级管理员登录、成员权限和密码消息流程
- agent-config/agent: 支持服务端保存 Agent 配置并取消未配置 mock 成功结果
- projects/deploy-runs/settings: 按当前用户权限保护真实接口
- prisma: 新增用户、项目权限和平台消息表结构
This commit is contained in:
湛兮
2026-06-12 00:38:23 +08:00
parent cf1bebf625
commit bc3aa31289
83 changed files with 3844 additions and 378 deletions
+11 -5
View File
@@ -1,4 +1,4 @@
import { Body, Controller, Get, Post } from '@nestjs/common';
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import {
ApiBody,
ApiCreatedResponse,
@@ -6,6 +6,10 @@ import {
ApiTags,
} from '@nestjs/swagger';
import { ZodValidationPipe } from '../common/pipes/zod-validation.pipe';
import { AuthGuard } from '../auth/auth.guard';
import { AuthenticatedUser } from '../auth/auth.types';
import { CurrentUser } from '../auth/current-user.decorator';
import { PasswordChangeGuard } from '../auth/password-change.guard';
import { AgentInvocation } from './agent.types';
import { AgentService } from './agent.service';
import {
@@ -14,24 +18,26 @@ import {
createAgentInvocationSchema,
} from './create-agent-invocation.dto';
@ApiTags('agent')
@ApiTags('Agent 调用')
@Controller('agent/invocations')
@UseGuards(AuthGuard, PasswordChangeGuard)
export class AgentController {
constructor(private readonly agentService: AgentService) {}
@Get()
@ApiOkResponse({ description: 'Agent invocation audit list.' })
@ApiOkResponse({ description: '查询 Agent 调用记录。' })
listInvocations(): AgentInvocation[] {
return this.agentService.listInvocations();
}
@Post()
@ApiBody({ type: CreateAgentInvocationDto })
@ApiCreatedResponse({ description: 'Create a DevOps-scoped agent invocation.' })
@ApiCreatedResponse({ description: '创建 DevOps 工作流范围内的 Agent 调用。' })
async createInvocation(
@CurrentUser() user: AuthenticatedUser,
@Body(new ZodValidationPipe(createAgentInvocationSchema))
body: CreateAgentInvocationInput,
): Promise<AgentInvocation> {
return this.agentService.createInvocation(body);
return this.agentService.createInvocation(body, user);
}
}
+3 -1
View File
@@ -1,11 +1,13 @@
import { Module } from '@nestjs/common';
import { AgentConfigModule } from '../agent-config/agent-config.module';
import { AuditModule } from '../audit/audit.module';
import { AuthModule } from '../auth/auth.module';
import { AgentController } from './agent.controller';
import { AgentService } from './agent.service';
import { LlmClient } from './llm.client';
@Module({
imports: [AuditModule],
imports: [AgentConfigModule, AuditModule, AuthModule],
controllers: [AgentController],
providers: [AgentService, LlmClient],
exports: [AgentService, LlmClient],
+56 -22
View File
@@ -1,4 +1,6 @@
import { AuditService } from '../audit/audit.service';
import { AuthService } from '../auth/auth.service';
import { AuthenticatedUser } from '../auth/auth.types';
import { AppError } from '../common/errors/app-error';
import { AgentService } from './agent.service';
import { CreateAgentInvocationInput } from './create-agent-invocation.dto';
@@ -8,6 +10,16 @@ import { LlmClient } from './llm.client';
* 锁定 Agent 入口只服务 DevOps 场景,避免后续误扩成泛聊天接口。
*/
describe('AgentService', () => {
const operator: AuthenticatedUser = {
id: 'user_admin',
account: 'zhanxi',
displayName: '超级管理员',
role: 'super_admin',
status: 'active',
mustChangePassword: false,
passwordVersion: 1,
};
function createService(options?: {
llmConfigured?: boolean;
llmText?: string;
@@ -17,9 +29,14 @@ describe('AgentService', () => {
} satisfies Pick<AuditService, 'record'>;
const llm = {
healthSummary: jest.fn(() =>
options?.llmConfigured
? { status: 'ok' as const }
: { status: 'not_configured' as const, message: 'Missing LLM_API_KEY' },
Promise.resolve(
options?.llmConfigured
? { status: 'ok' as const }
: {
status: 'not_configured' as const,
message: 'Agent 配置不完整',
},
),
),
complete: jest.fn(() =>
Promise.resolve({
@@ -28,34 +45,45 @@ describe('AgentService', () => {
}),
),
} satisfies Pick<LlmClient, 'healthSummary' | 'complete'>;
const auth = {
requireProjectPermission: jest.fn(() => Promise.resolve()),
} satisfies Pick<AuthService, 'requireProjectPermission'>;
return {
audit,
auth,
llm,
service: new AgentService(
audit as unknown as AuditService,
llm as unknown as LlmClient,
auth as unknown as AuthService,
),
};
}
it('creates a DevOps-scoped mock invocation when LLM is not configured', async () => {
it('returns a failed invocation when LLM is not configured', async () => {
const { audit, llm, service } = createService();
const invocation = await service.createInvocation({
type: 'failure-diagnosis',
runId: 'run_001',
projectKey: 'role-user',
promptSummary: 'Analyze latest failed Jenkins log excerpt.',
});
const invocation = await service.createInvocation(
{
type: 'failure-diagnosis',
runId: 'run_001',
projectKey: 'role-user',
promptSummary: 'Analyze latest failed Jenkins log excerpt.',
},
operator,
);
expect(invocation.status).toBe('success');
expect(invocation.resultMarkdown).toContain('失败诊断摘要');
expect(invocation.status).toBe('failed');
expect(invocation.resultMarkdown).toContain('Agent 配置不完整');
expect(llm.complete).not.toHaveBeenCalled();
expect(audit.record).toHaveBeenCalledWith(
expect.objectContaining({
action: 'AGENT_INVOCATION_CREATED',
action: 'AGENT_INVOCATION_FAILED',
resourceType: 'agent_invocation',
after: expect.objectContaining({
mode: 'not_configured',
}),
}),
);
});
@@ -66,11 +94,14 @@ describe('AgentService', () => {
llmText: '真实 LLM 运维分析结果',
});
const invocation = await service.createInvocation({
type: 'release-risk',
projectKey: 'access-manage',
promptSummary: 'Analyze production tag risk.',
});
const invocation = await service.createInvocation(
{
type: 'release-risk',
projectKey: 'access-manage',
promptSummary: 'Analyze production tag risk.',
},
operator,
);
expect(invocation.status).toBe('success');
expect(invocation.resultMarkdown).toBe('真实 LLM 运维分析结果');
@@ -94,10 +125,13 @@ describe('AgentService', () => {
const { service } = createService();
await expect(
service.createInvocation({
type: 'general-chat',
promptSummary: 'Tell me anything.',
} as unknown as CreateAgentInvocationInput),
service.createInvocation(
{
type: 'general-chat',
promptSummary: 'Tell me anything.',
} as unknown as CreateAgentInvocationInput,
operator,
),
).rejects.toBeInstanceOf(AppError);
});
});
+48 -23
View File
@@ -1,4 +1,6 @@
import { Injectable } from '@nestjs/common';
import { AuthService } from '../auth/auth.service';
import { AuthenticatedUser } from '../auth/auth.types';
import { AppError } from '../common/errors/app-error';
import { AuditService } from '../audit/audit.service';
import { redactSensitive } from '../common/security/redact-sensitive';
@@ -14,19 +16,6 @@ const allowedTypes: AgentPurpose[] = [
'incident-review',
];
const mockResults: Record<AgentPurpose, string> = {
'release-risk':
'发布风险摘要:当前为第一阶段 mock 分析。真实接入后会读取 Gitea ref diff、历史失败记录和项目部署策略。',
'failure-diagnosis':
'失败诊断摘要:当前为第一阶段 mock 分析。真实接入后会基于 Jenkins progressiveText 日志和 run steps 生成建议。',
'runbook-qa':
'Runbook 回答:当前仅允许围绕 DevOps 平台文档、项目 README 和白名单运维资料回答。',
'release-note':
'发布说明草稿:当前为 mock 草稿。真实接入后会根据 commit、PR 和 tag 信息生成。',
'incident-review':
'事故复盘草稿:当前为 mock 草稿。真实接入后会汇总失败 run、耗时、日志摘要和人工处理记录。',
};
@Injectable()
export class AgentService {
private readonly invocations: AgentInvocation[] = [];
@@ -34,6 +23,7 @@ export class AgentService {
constructor(
private readonly auditService: AuditService,
private readonly llmClient: LlmClient,
private readonly authService: AuthService,
) {}
listInvocations(): AgentInvocation[] {
@@ -44,11 +34,12 @@ export class AgentService {
async createInvocation(
input: CreateAgentInvocationInput,
operator: AuthenticatedUser,
): Promise<AgentInvocation> {
if (!allowedTypes.includes(input.type)) {
throw new AppError(
'VALIDATION_FAILED',
'Unsupported agent invocation type',
'不支持的 Agent 调用类型',
400,
{
type: input.type,
@@ -56,7 +47,8 @@ export class AgentService {
);
}
const llmHealth = this.llmClient.healthSummary();
await this.validateAgentScope(input, operator);
const llmHealth = await this.llmClient.healthSummary();
const baseInvocation = {
id: `agent_${Date.now()}_${this.invocations.length + 1}`,
runId: input.runId,
@@ -79,9 +71,14 @@ export class AgentService {
invocation = {
...baseInvocation,
status: 'success',
resultMarkdown: completion.text || mockResults[input.type],
resultMarkdown: completion.text || 'Agent 返回了空结果,请检查模型配置。',
};
await this.recordInvocationAudit(invocation, 'llm', completion.model);
await this.recordInvocationAudit(
invocation,
operator,
'llm',
completion.model,
);
} catch (error) {
invocation = {
...baseInvocation,
@@ -89,19 +86,21 @@ export class AgentService {
resultMarkdown:
error instanceof Error
? redactSensitive({ message: error.message }).message
: 'LLM invocation failed',
: 'Agent 调用失败',
};
await this.recordInvocationAudit(invocation, 'llm_failed');
await this.recordInvocationAudit(invocation, operator, 'llm_failed');
}
} else {
invocation = {
...baseInvocation,
status: 'success',
resultMarkdown: mockResults[input.type],
status: 'failed',
resultMarkdown:
llmHealth.message ?? 'Agent 配置不完整,请先配置 key、baseURL 和 model。',
};
await this.recordInvocationAudit(
invocation,
'mock',
operator,
'not_configured',
undefined,
llmHealth.message,
);
@@ -111,9 +110,33 @@ export class AgentService {
return invocation;
}
private async validateAgentScope(
input: CreateAgentInvocationInput,
operator: AuthenticatedUser,
): Promise<void> {
if (operator.role === 'super_admin') {
return;
}
if (!input.projectKey) {
throw new AppError(
'FORBIDDEN',
'普通成员只能在已授权项目内使用 Agent',
403,
);
}
await this.authService.requireProjectPermission(
operator,
input.projectKey,
'read',
);
}
private async recordInvocationAudit(
invocation: AgentInvocation,
mode: 'mock' | 'llm' | 'llm_failed',
operator: AuthenticatedUser,
mode: 'llm' | 'llm_failed' | 'not_configured',
model?: string,
reason?: string,
): Promise<void> {
@@ -126,6 +149,8 @@ export class AgentService {
action,
resourceType: 'agent_invocation',
resourceId: invocation.id,
actorId: operator.id,
actorName: operator.account,
after: {
type: invocation.type,
runId: invocation.runId,
+2 -1
View File
@@ -52,7 +52,8 @@ export class CreateAgentInvocationDto {
projectKey?: string;
@ApiProperty({
example: 'Analyze latest failed Jenkins log excerpt for access-manage test.',
description: '本次 Agent 调用的中文问题或任务摘要',
example: '分析 access-manage 测试环境最近一次 Jenkins 失败日志。',
})
promptSummary!: string;
}
+29 -31
View File
@@ -1,34 +1,38 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { IntegrationRequestError, IntegrationUnavailableError } from '../common/errors/integration-error';
import { AgentConfigService } from '../agent-config/agent-config.service';
import { AppError } from '../common/errors/app-error';
import { IntegrationRequestError } from '../common/errors/integration-error';
import { redactSensitive } from '../common/security/redact-sensitive';
import { EnvConfig } from '../config/env.schema';
import { LlmCompletionInput, LlmCompletionResult } from './agent.types';
@Injectable()
export class LlmClient {
constructor(private readonly config: ConfigService<EnvConfig, true>) {}
constructor(private readonly agentConfigService: AgentConfigService) {}
healthSummary(): { status: 'ok' | 'not_configured'; message?: string } {
const missing = this.missingConfig();
return missing.length === 0
async healthSummary(): Promise<{
status: 'ok' | 'not_configured';
message?: string;
}> {
const config = await this.agentConfigService.resolveRuntimeConfig();
return config
? { status: 'ok' }
: { status: 'not_configured', message: `Missing ${missing.join(', ')}` };
: {
status: 'not_configured',
message: 'Agent 配置不完整,请配置 key、baseURL 和 model',
};
}
async complete(input: LlmCompletionInput): Promise<LlmCompletionResult> {
this.assertConfigured();
const baseUrl = this.config.get('LLM_BASE_URL', { infer: true }) ?? '';
const apiKey = this.config.get('LLM_API_KEY', { infer: true }) ?? '';
const model = this.config.get('LLM_MODEL', { infer: true }) ?? '';
const response = await fetch(`${baseUrl}/chat/completions`, {
const config = await this.agentConfigService.requireRuntimeConfig();
const response = await fetch(`${this.trimSlash(config.baseURL)}/chat/completions`, {
method: 'POST',
headers: {
authorization: `Bearer ${apiKey}`,
authorization: `Bearer ${config.key}`,
'content-type': 'application/json',
},
body: JSON.stringify({
model,
model: config.model,
messages: [
{ role: 'system', content: input.systemPrompt },
{ role: 'user', content: input.userPrompt },
@@ -37,7 +41,7 @@ export class LlmClient {
});
if (!response.ok) {
throw new IntegrationRequestError('llm', 'LLM request failed', {
throw new IntegrationRequestError('llm', 'Agent 请求失败', {
status: response.status,
purpose: input.purpose,
request: redactSensitive(input),
@@ -51,25 +55,19 @@ export class LlmClient {
return {
text: payload.choices?.[0]?.message?.content ?? '',
model: payload.model ?? model,
model: payload.model ?? config.model,
};
}
private assertConfigured(): void {
const missing = this.missingConfig();
if (missing.length > 0) {
throw new IntegrationUnavailableError('llm', missing);
private trimSlash(value: string): string {
if (!value) {
throw new AppError(
'CONFIG_MISSING',
'Agent baseURL 未配置,请联系超级管理员',
500,
);
}
}
private missingConfig(): string[] {
const entries: Array<[string, string | undefined]> = [
['LLM_BASE_URL', this.config.get('LLM_BASE_URL', { infer: true })],
['LLM_API_KEY', this.config.get('LLM_API_KEY', { infer: true })],
['LLM_MODEL', this.config.get('LLM_MODEL', { infer: true })],
];
return entries.filter(([, value]) => !value).map(([key]) => key);
return value.replace(/\/+$/, '');
}
}