* Scope MCP OAuth tokens to user + workspace
Bind authorization-code grants to the authorizing workspace (via auth codes),
inherit workspace on refresh, resolve MCP/API requests from the token instead
of current_workspace_id, backfill existing grants, and revoke workspace tokens
when a member is removed.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Add multi-workspace MCP OAuth coverage
Cover coexistence of the same client across workspaces, settings
list/disconnect scoped to the current workspace, and API key
controllers excluding workspace-bound MCP grants.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Use constrained foreignUuid for oauth_auth_codes.workspace_id
Match the project's UUID foreign-key convention instead of a separate
foreign() call.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Localize the MCP OAuth authorize consent screen
Wire authorize.blade.php to mcp.* translation keys (including the
workspace scope copy) and cover pt-BR rendering.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Fix invalid Mockery import in bind workspace test
CI treats the non-compound `use Mockery` as an ErrorException and
aborts the whole parallel suite.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline MCP OAuth workspace backfill into the migration
Move the one-shot backfill out of a dedicated Action and wrap it in an
explicit transaction so a failure rolls back partial binds/revokes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest MCP authorize i18n keys and test backfill rollback
Group consent-screen copy under mcp.authorize.*, and assert the
workspace backfill migration rolls back binds when it fails before
commit.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Hardcode TryPost in the MCP authorize page title
Drop the config('app.name') interpolation from the consent screen title.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Add workspace picker to MCP OAuth consent screen
Let users choose which workspace to bind at authorize time instead of
always using current_workspace_id; silent re-consent still falls back.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Tighten MCP authorize workspace select spacing
Match NativeSelect styling and give the label, control, and helper text room to breathe.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Convert MCP OAuth consent screen to Inertia Vue
Reuse AuthCardLayout, Button, and NativeSelect so the authorize page
matches the app UI. Keep native form posts so Passport's external
redirect still works for MCP client popups.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Polish MCP authorize layout with logo and workspace combobox
Drop the shield and AuthCardLayout double-logo, put TryPost branding
at the top, and reuse the app Combobox pattern for workspace search.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Align MCP OAuth workspace backfill with mcpOAuth scope
Reuse AccessToken::mcpOAuth() so the migration only touches mcp:use
grants on non-PAT clients, matching the rest of the codebase.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Tighten MCP OAuth workspace backfill heuristics
Only touch connected MCP sessions, bind a sole membership or a valid
current workspace, and revoke ambiguous multi-workspace grants instead
of guessing the oldest workspace.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Drop Passport connection override from auth code migration
Always use the app default database connection from .env.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Bind MCP OAuth workspace in AccessTokenRepository
Replace the AccessTokenCreated listener with the same Passport repository
override pattern used for auth codes, so workspace_id is set at persist.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Simplify AccessTokenRepository workspace binding
Drop redundant string casts and the oldest-workspace fallback; keep a
small ownedWorkspace/payloadId helper surface instead.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Extract Passport MCP authorization view from AppServiceProvider
Keep configurePassport thin by moving the Inertia consent props into an
invokable App\Passport\AuthorizationView class.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Simplify AuthorizationView and cover it with direct tests
Use collection higher-order mapping for workspaces/scopes and add focused
tests for current-workspace selection and empty-user props.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename BindWorkspaceToAccessTokenTest after listener removal
The suite now covers AuthCodeRepository and AccessTokenRepository
workspace binding, not an AccessTokenCreated listener.
* Fail closed when auth code has no bindable workspace
Authorization-code grants no longer fall back to the user's current
workspace, so a token cannot be minted for a different tenant than consent.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Retrigger CI after GitHub Actions infrastructure failures
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore: retrigger CI
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: harden MCP OAuth workspace binding on refresh and backfill
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: always show MCP OAuth consent to pick a workspace
Disable Passport silent re-consent and require an explicit workspace_id
from the consent form, with Passport wiring moved to its own provider.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: sort MCP connected clients by last used
Show most recently used OAuth connections first on the workspace MCP settings page.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
298 lines
8.7 KiB
PHP
298 lines
8.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
use App\Enums\UserWorkspace\Role;
|
|
use App\Models\AccessToken;
|
|
use App\Models\Account;
|
|
use App\Models\Plan;
|
|
use App\Models\User;
|
|
use App\Models\Workspace;
|
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use Tests\BrowserTestCase;
|
|
use Tests\TestCase;
|
|
|
|
/*
|
|
|--------------------------------------------------------------------------
|
|
| Test Case
|
|
|--------------------------------------------------------------------------
|
|
|
|
|
| The closure you provide to your test functions is always bound to a specific PHPUnit test
|
|
| case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may
|
|
| need to change it using the "pest()" function to bind a different classes or traits.
|
|
|
|
|
*/
|
|
|
|
pest()->extend(TestCase::class)
|
|
->use(RefreshDatabase::class)
|
|
->in('Feature', 'Unit');
|
|
|
|
pest()->extend(BrowserTestCase::class)
|
|
->use(RefreshDatabase::class)
|
|
->in('Browser');
|
|
|
|
/*
|
|
|--------------------------------------------------------------------------
|
|
| Expectations
|
|
|--------------------------------------------------------------------------
|
|
|
|
|
| When you're writing tests, you often need to check that values meet certain conditions. The
|
|
| "expect()" function gives you access to a set of "expectations" methods that you can use
|
|
| to assert different things. Of course, you may extend the Expectation API at any time.
|
|
|
|
|
*/
|
|
|
|
expect()->extend('toBeOne', function () {
|
|
return $this->toBe(1);
|
|
});
|
|
|
|
/*
|
|
|--------------------------------------------------------------------------
|
|
| Functions
|
|
|--------------------------------------------------------------------------
|
|
|
|
|
| While Pest is very powerful out-of-the-box, you may have some testing code specific to your
|
|
| project that you don't want to repeat in every file. Here you can also expose helpers as
|
|
| global functions to help you to reduce the number of lines of code in your test files.
|
|
|
|
|
*/
|
|
|
|
/**
|
|
* Issue a real Passport personal access token bound to a workspace and return
|
|
* the plain JWT string. Use the returned token in `Authorization: Bearer ...`
|
|
* to exercise the auth:api + workspace.token middleware stack.
|
|
*/
|
|
function passportToken(User $user, Workspace $workspace, array $scopes = []): string
|
|
{
|
|
$result = $user->createToken('Test', $scopes);
|
|
|
|
AccessToken::find($result->token->id)
|
|
->forceFill(['workspace_id' => $workspace->id])
|
|
->saveQuietly();
|
|
|
|
return $result->accessToken;
|
|
}
|
|
|
|
/**
|
|
* Create a workspace + owner + Passport token suitable for hitting the public
|
|
* API. Drop-in replacement for the legacy `createXApiToken` helpers.
|
|
*
|
|
* @param array{workspace?: Workspace} $overrides
|
|
* @return array{plain_token: string, workspace: Workspace, user: User}
|
|
*/
|
|
function createApiTestToken(array $overrides = []): array
|
|
{
|
|
$workspace = data_get($overrides, 'workspace');
|
|
|
|
if (! $workspace) {
|
|
$user = User::factory()->create();
|
|
$workspace = Workspace::factory()->create([
|
|
'account_id' => $user->account_id,
|
|
'user_id' => $user->id,
|
|
]);
|
|
$workspace->members()->attach($user->id, [
|
|
'role' => Role::Admin->value,
|
|
]);
|
|
$user->update(['current_workspace_id' => $workspace->id]);
|
|
} else {
|
|
$user = $workspace->owner ?? User::factory()->create([
|
|
'account_id' => $workspace->account_id,
|
|
]);
|
|
|
|
if ($workspace->account && $workspace->account->owner_id !== $user->id) {
|
|
$workspace->account->update(['owner_id' => $user->id]);
|
|
}
|
|
}
|
|
|
|
return [
|
|
'plain_token' => passportToken($user, $workspace),
|
|
'workspace' => $workspace,
|
|
'user' => $user,
|
|
];
|
|
}
|
|
|
|
function feedFixture(string $name): string
|
|
{
|
|
return file_get_contents(base_path("tests/fixtures/feeds/{$name}.xml"));
|
|
}
|
|
|
|
/**
|
|
* Create an account on the Workspace plan with an active subscription on the
|
|
* given Stripe price, plus N workspaces. Used by the billing-cycle tests.
|
|
*
|
|
* @param array<string, mixed> $subscriptionAttributes
|
|
*/
|
|
function billingAccount(string $price, array $subscriptionAttributes = [], int $workspaces = 1): Account
|
|
{
|
|
$plan = Plan::query()->firstOrFail();
|
|
$plan->update([
|
|
'stripe_monthly_price_id' => 'price_month',
|
|
'stripe_yearly_price_id' => 'price_year',
|
|
]);
|
|
|
|
$account = Account::factory()->create([
|
|
'plan_id' => $plan->id,
|
|
'trial_ends_at' => null,
|
|
]);
|
|
|
|
$account->subscriptions()->create(array_merge([
|
|
'type' => Account::SUBSCRIPTION_NAME,
|
|
'stripe_id' => 'sub_'.fake()->uuid(),
|
|
'stripe_status' => 'active',
|
|
'stripe_price' => $price,
|
|
'quantity' => $workspaces,
|
|
], $subscriptionAttributes));
|
|
|
|
Workspace::factory()->count($workspaces)->create(['account_id' => $account->id]);
|
|
|
|
return $account->refresh();
|
|
}
|
|
|
|
/**
|
|
* Attach an active default subscription to the given account.
|
|
*/
|
|
function subscribeAccount(Account $account): void
|
|
{
|
|
$account->subscriptions()->create([
|
|
'type' => Account::SUBSCRIPTION_NAME,
|
|
'stripe_id' => 'sub_'.fake()->uuid(),
|
|
'stripe_status' => 'active',
|
|
'stripe_price' => 'price_123',
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Insert an OAuth client suitable for MCP connection tests.
|
|
*/
|
|
function mcpOauthClient(string $name = 'My Agent'): string
|
|
{
|
|
$id = (string) Str::uuid();
|
|
|
|
DB::table('oauth_clients')->insert([
|
|
'id' => $id,
|
|
'name' => $name,
|
|
'secret' => null,
|
|
'provider' => null,
|
|
'redirect_uris' => '[]',
|
|
'grant_types' => json_encode(['authorization_code', 'refresh_token']),
|
|
'revoked' => false,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
]);
|
|
|
|
return $id;
|
|
}
|
|
|
|
/**
|
|
* Create an active OAuth access token for MCP connection tests.
|
|
*
|
|
* @param list<string> $scopes
|
|
*/
|
|
function mcpAccessToken(
|
|
User $user,
|
|
string $clientId,
|
|
?Workspace $workspace = null,
|
|
array $scopes = ['mcp:use'],
|
|
): AccessToken {
|
|
$token = new AccessToken;
|
|
$token->forceFill([
|
|
'id' => Str::random(80),
|
|
'user_id' => $user->id,
|
|
'client_id' => $clientId,
|
|
'workspace_id' => $workspace?->id,
|
|
'name' => 'MCP',
|
|
'scopes' => $scopes,
|
|
'revoked' => false,
|
|
'expires_at' => now()->addYear(),
|
|
])->save();
|
|
|
|
return $token->refresh();
|
|
}
|
|
|
|
/**
|
|
* Issue a Passport token, attach it to a dedicated MCP OAuth client, and bind
|
|
* it to a workspace — the post-#222 shape used by middleware / MCP endpoint tests.
|
|
*
|
|
* @param list<string> $scopes
|
|
* @return array{token: AccessToken, plain_token: string}
|
|
*/
|
|
function mcpBearerToken(User $user, Workspace $workspace, array $scopes = ['mcp:use']): array
|
|
{
|
|
$result = $user->createToken('MCP', $scopes);
|
|
$token = AccessToken::query()->findOrFail($result->token->id);
|
|
|
|
// Reassign to a dedicated MCP client so we never mutate Passport's shared
|
|
// personal-access client (which would poison PAT fixtures in the same run).
|
|
$token->forceFill([
|
|
'client_id' => mcpOauthClient(),
|
|
'workspace_id' => $workspace->id,
|
|
])->saveQuietly();
|
|
|
|
return [
|
|
'token' => $token->refresh(),
|
|
'plain_token' => $result->accessToken,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Move a member onto a shared account (stranded-member / invitee fixture).
|
|
*
|
|
* @return array{
|
|
* owner: User,
|
|
* member: User,
|
|
* shared_workspaces: list<Workspace>
|
|
* }
|
|
*/
|
|
function strandedMemberOnSharedAccount(
|
|
int $sharedWorkspaces = 0,
|
|
bool $attachMember = true,
|
|
bool $attachMemberToAll = true,
|
|
bool $setMemberCurrent = false,
|
|
?User $owner = null,
|
|
?string $memberEmail = null,
|
|
): array {
|
|
$owner ??= User::factory()->create();
|
|
$member = User::factory()->create(array_filter([
|
|
'email' => $memberEmail,
|
|
]));
|
|
|
|
// Closed-account model: the member's empty signup shell is gone after
|
|
// accepting the invite, so drop it here to match the real state.
|
|
$member->account?->delete();
|
|
|
|
$shared = [];
|
|
|
|
for ($i = 0; $i < $sharedWorkspaces; $i++) {
|
|
$workspace = Workspace::factory()->create([
|
|
'account_id' => $owner->account_id,
|
|
'user_id' => $owner->id,
|
|
]);
|
|
|
|
$workspace->members()->syncWithoutDetaching([
|
|
$owner->id => ['role' => Role::Admin->value],
|
|
]);
|
|
|
|
if ($attachMember && ($attachMemberToAll || $i === 0)) {
|
|
$workspace->members()->attach($member->id, [
|
|
'role' => Role::Member->value,
|
|
]);
|
|
}
|
|
|
|
$shared[] = $workspace;
|
|
}
|
|
|
|
$member->update([
|
|
'account_id' => $owner->account_id,
|
|
'current_workspace_id' => ($setMemberCurrent && $shared !== [])
|
|
? $shared[0]->id
|
|
: null,
|
|
]);
|
|
|
|
return [
|
|
'owner' => $owner->fresh(),
|
|
'member' => $member->fresh(),
|
|
'shared_workspaces' => $shared,
|
|
];
|
|
}
|