AiModelResourceTest.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. use App\Models\AiModel;
  3. use Illuminate\Foundation\Testing\RefreshDatabase;
  4. use Illuminate\Support\Str;
  5. uses(RefreshDatabase::class);
  6. const SECRET_KEY = 'sk-super-secret-api-key';
  7. const SECRET_PROMPT = 'you are a very secret assistant';
  8. function modelWithSecrets(string $ownerId): AiModel
  9. {
  10. return AiModel::factory()->ownedBy($ownerId)->create([
  11. 'name' => 'secret-model',
  12. 'key' => SECRET_KEY,
  13. 'system_prompt' => SECRET_PROMPT,
  14. 'privacy' => 'public',
  15. ]);
  16. }
  17. it('never exposes the api key to a stranger listing models', function () {
  18. modelWithSecrets((string) Str::uuid());
  19. $body = $this->getJson('/api/v2/ai-model?view=all', authHeader((string) Str::uuid()))
  20. ->assertOk()
  21. ->getContent();
  22. expect($body)->not->toContain(SECRET_KEY);
  23. expect($body)->not->toContain(SECRET_PROMPT);
  24. // 非敏感字段仍须返回,否则前端列表会空
  25. expect($body)->toContain('secret-model');
  26. });
  27. it('gives the owner back key and system_prompt so the edit form can prefill', function () {
  28. $owner = (string) Str::uuid();
  29. $model = modelWithSecrets($owner);
  30. $this->getJson("/api/v2/ai-model/{$model->uid}", authHeader($owner))
  31. ->assertOk()
  32. ->assertJsonPath('data.key', SECRET_KEY)
  33. ->assertJsonPath('data.system_prompt', SECRET_PROMPT);
  34. });
  35. it('does not leak internal columns', function () {
  36. $owner = (string) Str::uuid();
  37. $model = modelWithSecrets($owner);
  38. $data = $this->getJson("/api/v2/ai-model/{$model->uid}", authHeader($owner))
  39. ->assertOk()
  40. ->json('data');
  41. // real_name 是模型的登录身份标识,id 是自增主键,都不该外露
  42. expect($data)->not->toHaveKey('real_name');
  43. expect($data)->not->toHaveKey('id');
  44. });