generated from thegrind/laravel-dockerized
Compare commits
2 Commits
038ee47fa3
...
1fd6f03a81
Author | SHA1 | Date | |
---|---|---|---|
1fd6f03a81 | |||
8e0abedbbb |
@ -21,6 +21,13 @@ class Register extends Component
|
||||
|
||||
public string $password_confirmation = '';
|
||||
|
||||
public string $code = '';
|
||||
|
||||
public function mount()
|
||||
{
|
||||
dd($this->code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming registration request.
|
||||
*/
|
||||
@ -28,7 +35,7 @@ class Register extends Component
|
||||
{
|
||||
$validated = $this->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
|
||||
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:' . User::class],
|
||||
'password' => ['required', 'string', 'confirmed', Rules\Password::defaults()],
|
||||
]);
|
||||
|
||||
|
38
app/Livewire/ManageUsers.php
Normal file
38
app/Livewire/ManageUsers.php
Normal file
@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Livewire;
|
||||
|
||||
use App\Models\Invitation;
|
||||
use App\Models\User;
|
||||
use Flux\Flux;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Livewire\Component;
|
||||
|
||||
class ManageUsers extends Component
|
||||
{
|
||||
public string $invite_email = '';
|
||||
public Collection $users;
|
||||
public Collection $invitations;
|
||||
|
||||
public function mount()
|
||||
{
|
||||
$this->users = User::all();
|
||||
$this->invitations = Invitation::all();
|
||||
}
|
||||
|
||||
public function inviteUser()
|
||||
{
|
||||
$inv = Invitation::create([
|
||||
'code' => str()->random(50),
|
||||
'email' => $this->invite_email,
|
||||
'invited_by' => auth()->user()->id,
|
||||
'expires_at' => now()->addDays(7),
|
||||
]);
|
||||
Flux::modal('invite-user')->close();
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
return view('livewire.manage-users');
|
||||
}
|
||||
}
|
53
app/Mail/InvitationMail.php
Normal file
53
app/Mail/InvitationMail.php
Normal file
@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class InvitationMail extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
/**
|
||||
* Create a new message instance.
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the message envelope.
|
||||
*/
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Invitation Mail',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the message content definition.
|
||||
*/
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
view: 'view.name',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attachments for the message.
|
||||
*
|
||||
* @return array<int, \Illuminate\Mail\Mailables\Attachment>
|
||||
*/
|
||||
public function attachments(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
24
app/Models/Invitation.php
Normal file
24
app/Models/Invitation.php
Normal file
@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Invitation extends Model
|
||||
{
|
||||
protected $guarded = ['id'];
|
||||
protected $casts = [
|
||||
'expires_at' => 'datetime',
|
||||
'accepted_at' => 'datetime'
|
||||
];
|
||||
|
||||
public function status(): string
|
||||
{
|
||||
return !empty($this->accepted_at) ? 'accepted' : 'pending';
|
||||
}
|
||||
|
||||
public function isPending(): bool
|
||||
{
|
||||
return empty($this->accepted_at);
|
||||
}
|
||||
}
|
60
database/factories/InvitationFactory.php
Normal file
60
database/factories/InvitationFactory.php
Normal file
@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Models\Invitation;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
|
||||
/**
|
||||
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Invitation>
|
||||
*/
|
||||
class InvitationFactory extends Factory
|
||||
{
|
||||
/**
|
||||
* Define the model's default state.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function definition(): array
|
||||
{
|
||||
return [
|
||||
'code' => Invitation::generateCode(),
|
||||
'email' => fake()->unique()->safeEmail(),
|
||||
'invited_by' => User::factory(),
|
||||
'expires_at' => now()->addDays(7),
|
||||
'email_sent' => fake()->boolean(30),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that the invitation is expired.
|
||||
*/
|
||||
public function expired(): static
|
||||
{
|
||||
return $this->state(fn(array $attributes) => [
|
||||
'expires_at' => now()->subDay(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that the invitation has been accepted.
|
||||
*/
|
||||
public function accepted(): static
|
||||
{
|
||||
return $this->state(fn(array $attributes) => [
|
||||
'accepted_at' => now(),
|
||||
'user_id' => User::factory(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that the email was sent.
|
||||
*/
|
||||
public function emailSent(): static
|
||||
{
|
||||
return $this->state(fn(array $attributes) => [
|
||||
'email_sent' => true,
|
||||
]);
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('invitations', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('code')->unique();
|
||||
$table->string('email')->unique();
|
||||
$table->foreignId('invited_by')->constrained('users')->onDelete('cascade');
|
||||
$table->timestamp('expires_at');
|
||||
$table->timestamp('accepted_at')->nullable();
|
||||
$table->foreignId('user_id')->nullable()->constrained('users')->onDelete('cascade');
|
||||
$table->boolean('email_sent')->default(false);
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('invitations');
|
||||
}
|
||||
};
|
@ -1,6 +1,4 @@
|
||||
@props(['class' => ''])
|
||||
|
||||
<div {{ $attributes->merge(['class' => 'bg-white dark:bg-zinc-800 shadow-sm border border-gray-200 dark:border-zinc-700
|
||||
rounded-lg ' . $class]) }}>
|
||||
p-6'] ) }}>
|
||||
{{ $slot }}
|
||||
</div>
|
@ -1,5 +1,8 @@
|
||||
<x-layouts.app :title="__('Dashboard')">
|
||||
<div class="max-w-4xl mx-auto py-12">
|
||||
<div class="mb-4">
|
||||
<livewire:manage-users />
|
||||
</div>
|
||||
<div class="grid grid-cols-2">
|
||||
<livewire:forms.user-profile />
|
||||
</div>
|
||||
|
0
resources/views/emails/invitation.blade.php
Normal file
0
resources/views/emails/invitation.blade.php
Normal file
52
resources/views/livewire/manage-users.blade.php
Normal file
52
resources/views/livewire/manage-users.blade.php
Normal file
@ -0,0 +1,52 @@
|
||||
<div>
|
||||
<div class="flex justify-between items-center">
|
||||
<flux:heading size="xl">Users</flux:heading>
|
||||
</div>
|
||||
<flux:separator class="my-8" />
|
||||
@foreach ($users as $u)
|
||||
<x-card class="flex items-center justify-between p-6">
|
||||
<div class="flex gap-4">
|
||||
<flux:heading>{{$u->name}}</flux:heading>
|
||||
<flux:text>{{$u->email}}</flux:text>
|
||||
</div>
|
||||
</x-card>
|
||||
@endforeach
|
||||
<div class="flex justify-between items-center mt-8">
|
||||
<flux:heading size="xl">Invitations</flux:heading>
|
||||
<div>
|
||||
<flux:modal.trigger name="invite-user">
|
||||
<flux:button variant="primary" icon="plus">Create</flux:button>
|
||||
</flux:modal.trigger>
|
||||
</div>
|
||||
</div>
|
||||
<flux:separator class="my-8" />
|
||||
@foreach ($invitations as $inv)
|
||||
<x-card class="flex items-center justify-between p-6">
|
||||
<div class="flex gap-4 items-center flex-1">
|
||||
<flux:heading>{{$inv->email}}</flux:heading>
|
||||
@switch($inv->status())
|
||||
@case('accepted')
|
||||
<flux:badge color="green">Accepted</flux:badge>
|
||||
@break
|
||||
@case('pending')
|
||||
<flux:badge>Pending</flux:badge>
|
||||
@break
|
||||
@default
|
||||
<flux:badge>{{$inv->status}}</flux:badge>
|
||||
@endswitch
|
||||
</div>
|
||||
<flux:text>Invite link: {{route('register', ['code' => $inv->code])}}</flux:text>
|
||||
<div class="flex gap-4 items-center">
|
||||
<flux:button variant="primary" size="sm">Copy invite link</flux:button>
|
||||
</div>
|
||||
</x-card>
|
||||
@endforeach
|
||||
<flux:modal name="invite-user" class="w-96">
|
||||
<flux:heading>Invite User</flux:heading>
|
||||
<flux:separator class="my-4" />
|
||||
<form wire:submit="inviteUser" class="flex flex-col gap-4">
|
||||
<flux:input label="Email" wire:model="invite_email" />
|
||||
<flux:button type="submit" variant="primary">Create invitation</flux:button>
|
||||
</form>
|
||||
</flux:modal>
|
||||
</div>
|
7
tests/Feature/InvitationSystemTest.php
Normal file
7
tests/Feature/InvitationSystemTest.php
Normal file
@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
test('example', function () {
|
||||
$response = $this->get('/');
|
||||
|
||||
$response->assertStatus(200);
|
||||
});
|
401
tests/Feature/OIDCControllerTest.php
Normal file
401
tests/Feature/OIDCControllerTest.php
Normal file
@ -0,0 +1,401 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Application;
|
||||
use App\Models\AuthenticationToken;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
beforeEach(function () {
|
||||
$this->user = User::factory()->create([
|
||||
'name' => 'Test User',
|
||||
'email' => 'test@example.com',
|
||||
'preferred_username' => 'testuser',
|
||||
]);
|
||||
|
||||
$this->application = Application::factory()->create([
|
||||
'name' => 'Test App',
|
||||
'client_id' => 'test-client-id',
|
||||
'client_secret' => 'test-client-secret',
|
||||
'redirect_uri' => 'https://example.com/callback',
|
||||
]);
|
||||
|
||||
// Create RSA key pair for testing
|
||||
$this->createTestKeys();
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
// Clean up test keys
|
||||
$this->cleanupTestKeys();
|
||||
});
|
||||
|
||||
// Helper function to create test RSA keys
|
||||
function createTestKeys()
|
||||
{
|
||||
$keyDir = storage_path('oauth');
|
||||
if (!file_exists($keyDir)) {
|
||||
mkdir($keyDir, 0755, true);
|
||||
}
|
||||
|
||||
$config = [
|
||||
'digest_alg' => 'sha256',
|
||||
'private_key_bits' => 2048,
|
||||
'private_key_type' => OPENSSL_KEYTYPE_RSA,
|
||||
];
|
||||
|
||||
$privateKey = openssl_pkey_new($config);
|
||||
openssl_pkey_export($privateKey, $privateKeyPem);
|
||||
file_put_contents(storage_path('oauth/private.pem'), $privateKeyPem);
|
||||
|
||||
$publicKey = openssl_pkey_get_details($privateKey);
|
||||
file_put_contents(storage_path('oauth/public.pem'), $publicKey['key']);
|
||||
}
|
||||
|
||||
// Helper function to clean up test keys
|
||||
function cleanupTestKeys()
|
||||
{
|
||||
$privateKeyPath = storage_path('oauth/private.pem');
|
||||
$publicKeyPath = storage_path('oauth/public.pem');
|
||||
|
||||
if (file_exists($privateKeyPath)) {
|
||||
unlink($privateKeyPath);
|
||||
}
|
||||
if (file_exists($publicKeyPath)) {
|
||||
unlink($publicKeyPath);
|
||||
}
|
||||
}
|
||||
|
||||
describe('OIDC Authorization Endpoint', function () {
|
||||
it('redirects to consent screen with valid parameters', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$response = $this->get('/auth/authorize?' . http_build_query([
|
||||
'client_id' => $this->application->client_id,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'response_type' => 'code',
|
||||
'scope' => 'openid email profile',
|
||||
'state' => 'test-state',
|
||||
]));
|
||||
|
||||
$response->assertRedirect(route('auth.confirm'));
|
||||
|
||||
// Verify session data is set
|
||||
$this->assertEquals($this->application->id, session('app_id'));
|
||||
expect(session('redirect_on_confirm'))->toContain($this->application->redirect_uri);
|
||||
expect(session('redirect_on_confirm'))->toContain('code=');
|
||||
expect(session('redirect_on_confirm'))->toContain('state=test-state');
|
||||
});
|
||||
|
||||
it('fails with invalid client_id', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$response = $this->get('/auth/authorize?' . http_build_query([
|
||||
'client_id' => 'invalid-client-id',
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'response_type' => 'code',
|
||||
]));
|
||||
|
||||
$response->assertStatus(404);
|
||||
});
|
||||
|
||||
it('fails with redirect_uri mismatch', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$response = $this->get('/auth/authorize?' . http_build_query([
|
||||
'client_id' => $this->application->client_id,
|
||||
'redirect_uri' => 'https://evil.com/callback',
|
||||
'response_type' => 'code',
|
||||
]));
|
||||
|
||||
$response->assertStatus(403);
|
||||
});
|
||||
|
||||
it('requires authentication', function () {
|
||||
$response = $this->get('/auth/authorize?' . http_build_query([
|
||||
'client_id' => $this->application->client_id,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'response_type' => 'code',
|
||||
]));
|
||||
|
||||
$response->assertRedirect(route('login'));
|
||||
});
|
||||
|
||||
it('supports PKCE parameters', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$codeVerifier = Str::random(128);
|
||||
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
|
||||
|
||||
$response = $this->get('/auth/authorize?' . http_build_query([
|
||||
'client_id' => $this->application->client_id,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'response_type' => 'code',
|
||||
'code_challenge' => $codeChallenge,
|
||||
'code_challenge_method' => 'S256',
|
||||
]));
|
||||
|
||||
$response->assertRedirect(route('auth.confirm'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('OIDC Token Endpoint', function () {
|
||||
beforeEach(function () {
|
||||
// Set up authorization code in cache
|
||||
$this->authCode = Str::random(40);
|
||||
$this->payload = [
|
||||
'user_id' => $this->user->id,
|
||||
'client_id' => $this->application->id,
|
||||
'scope' => 'openid email profile',
|
||||
'nonce' => 'test-nonce',
|
||||
];
|
||||
Cache::put("auth_code:{$this->authCode}", $this->payload, now()->addMinutes(5));
|
||||
});
|
||||
|
||||
it('exchanges authorization code for tokens with client credentials', function () {
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $this->authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'client_id' => $this->application->client_id,
|
||||
'client_secret' => $this->application->client_secret,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json();
|
||||
|
||||
expect($data)->toHaveKeys(['access_token', 'token_type', 'expires_in', 'id_token']);
|
||||
expect($data['token_type'])->toBe('Bearer');
|
||||
expect($data['expires_in'])->toBe(3600);
|
||||
|
||||
// Verify authentication token was created
|
||||
$this->assertDatabaseHas('authentication_tokens', [
|
||||
'user_id' => $this->user->id,
|
||||
'application_id' => $this->application->id,
|
||||
'token' => $data['access_token'],
|
||||
]);
|
||||
|
||||
// Verify auth code was consumed
|
||||
expect(Cache::get("auth_code:{$this->authCode}"))->toBeNull();
|
||||
});
|
||||
|
||||
it('exchanges authorization code for tokens with PKCE', function () {
|
||||
$codeVerifier = Str::random(128);
|
||||
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
|
||||
|
||||
// Update cache with PKCE parameters
|
||||
$this->payload['code_challenge'] = $codeChallenge;
|
||||
$this->payload['code_challenge_method'] = 'S256';
|
||||
Cache::put("auth_code:{$this->authCode}", $this->payload, now()->addMinutes(5));
|
||||
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $this->authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'code_verifier' => $codeVerifier,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json();
|
||||
|
||||
expect($data)->toHaveKeys(['access_token', 'token_type', 'expires_in', 'id_token']);
|
||||
});
|
||||
|
||||
it('fails with invalid authorization code', function () {
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => 'invalid-code',
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'client_id' => $this->application->client_id,
|
||||
'client_secret' => $this->application->client_secret,
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
});
|
||||
|
||||
it('fails with expired authorization code', function () {
|
||||
// Set expired code
|
||||
Cache::put("auth_code:expired", $this->payload, now()->subMinute());
|
||||
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => 'expired',
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'client_id' => $this->application->client_id,
|
||||
'client_secret' => $this->application->client_secret,
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
});
|
||||
|
||||
it('fails with invalid client credentials', function () {
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $this->authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'client_id' => $this->application->client_id,
|
||||
'client_secret' => 'wrong-secret',
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
});
|
||||
|
||||
it('fails with invalid PKCE code_verifier', function () {
|
||||
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', 'correct-verifier', true)), '+/', '-_'), '=');
|
||||
|
||||
$this->payload['code_challenge'] = $codeChallenge;
|
||||
$this->payload['code_challenge_method'] = 'S256';
|
||||
Cache::put("auth_code:{$this->authCode}", $this->payload, now()->addMinutes(5));
|
||||
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $this->authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'code_verifier' => 'wrong-verifier',
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
});
|
||||
|
||||
it('fails with redirect_uri mismatch', function () {
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $this->authCode,
|
||||
'redirect_uri' => 'https://evil.com/callback',
|
||||
'client_id' => $this->application->client_id,
|
||||
'client_secret' => $this->application->client_secret,
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
});
|
||||
|
||||
it('fails with missing authentication', function () {
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $this->authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('OIDC UserInfo Endpoint', function () {
|
||||
beforeEach(function () {
|
||||
$this->token = AuthenticationToken::create([
|
||||
'user_id' => $this->user->id,
|
||||
'application_id' => $this->application->id,
|
||||
'token' => Str::random(64),
|
||||
'issued_at' => now(),
|
||||
'expires_at' => now()->addMonth(),
|
||||
'ip' => '127.0.0.1',
|
||||
'user_agent' => 'Test Agent',
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns user information with valid token', function () {
|
||||
$response = $this->get('/auth/userinfo', [
|
||||
'Authorization' => 'Bearer ' . $this->token->token,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json();
|
||||
|
||||
expect($data)->toBe([
|
||||
'sub' => (string) $this->user->id,
|
||||
'email' => $this->user->email,
|
||||
'name' => $this->user->name,
|
||||
'preferred_username' => $this->user->preferred_username,
|
||||
'picture' => null, // No avatar set in test
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns user information with avatar', function () {
|
||||
$this->user->update(['avatar' => 'test-avatar.jpg']);
|
||||
|
||||
$response = $this->get('/auth/userinfo', [
|
||||
'Authorization' => 'Bearer ' . $this->token->token,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json();
|
||||
|
||||
expect($data['picture'])->toContain('test-avatar.jpg');
|
||||
});
|
||||
|
||||
it('fails with missing authorization header', function () {
|
||||
$response = $this->get('/auth/userinfo');
|
||||
|
||||
$response->assertStatus(400);
|
||||
expect($response->json()['error'])->toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('fails with invalid authorization header format', function () {
|
||||
$response = $this->get('/auth/userinfo', [
|
||||
'Authorization' => 'Basic invalid-format',
|
||||
]);
|
||||
|
||||
$response->assertStatus(400);
|
||||
expect($response->json()['error'])->toBe('invalid_request');
|
||||
});
|
||||
|
||||
it('fails with invalid token', function () {
|
||||
$response = $this->get('/auth/userinfo', [
|
||||
'Authorization' => 'Bearer invalid-token',
|
||||
]);
|
||||
|
||||
$response->assertStatus(401);
|
||||
expect($response->json()['error'])->toBe('invalid_token');
|
||||
});
|
||||
});
|
||||
|
||||
describe('OIDC JWKS Endpoint', function () {
|
||||
it('returns public keys in JWKS format', function () {
|
||||
$response = $this->get('/auth/keys');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json();
|
||||
|
||||
expect($data)->toHaveKey('keys');
|
||||
expect($data['keys'])->toBeArray();
|
||||
expect($data['keys'][0])->toHaveKeys(['kty', 'use', 'alg', 'kid', 'n', 'e']);
|
||||
expect($data['keys'][0]['kty'])->toBe('RSA');
|
||||
expect($data['keys'][0]['use'])->toBe('sig');
|
||||
expect($data['keys'][0]['alg'])->toBe('RS256');
|
||||
});
|
||||
});
|
||||
|
||||
describe('OIDC OpenID Configuration', function () {
|
||||
it('returns openid configuration', function () {
|
||||
$response = $this->get('/.well-known/openid-configuration');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json();
|
||||
|
||||
$expectedKeys = [
|
||||
'issuer',
|
||||
'authorization_endpoint',
|
||||
'token_endpoint',
|
||||
'useringo_endpoint',
|
||||
'scopes_supported',
|
||||
'response_types_supported',
|
||||
'jwks_uri',
|
||||
'id_token_signing_alg_values_supported',
|
||||
'claims_supported'
|
||||
];
|
||||
|
||||
expect($data)->toHaveKeys($expectedKeys);
|
||||
expect($data['issuer'])->toBe(config('app.url'));
|
||||
expect($data['scopes_supported'])->toContain('openid');
|
||||
expect($data['response_types_supported'])->toContain('code');
|
||||
expect($data['id_token_signing_alg_values_supported'])->toContain('RS256');
|
||||
});
|
||||
});
|
||||
|
||||
describe('OIDC Logout Endpoint', function () {
|
||||
it('returns logout view', function () {
|
||||
$response = $this->get('/auth/logout');
|
||||
|
||||
$response->assertStatus(200);
|
||||
$response->assertViewIs('logged-out');
|
||||
});
|
||||
});
|
310
tests/Feature/OIDCJWTTest.php
Normal file
310
tests/Feature/OIDCJWTTest.php
Normal file
@ -0,0 +1,310 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Application;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Str;
|
||||
use Lcobucci\JWT\Configuration;
|
||||
use Lcobucci\JWT\Signer\Key\InMemory;
|
||||
use Lcobucci\JWT\Signer\Rsa\Sha256;
|
||||
|
||||
beforeEach(function () {
|
||||
$this->user = User::factory()->create([
|
||||
'name' => 'JWT Test User',
|
||||
'email' => 'jwt@example.com',
|
||||
]);
|
||||
|
||||
$this->application = Application::factory()->create([
|
||||
'name' => 'JWT Test App',
|
||||
'client_id' => 'jwt-test-client',
|
||||
'client_secret' => 'jwt-test-secret',
|
||||
'redirect_uri' => 'https://jwt.example.com/callback',
|
||||
]);
|
||||
|
||||
// Create test keys
|
||||
$this->createJWTTestKeys();
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
$this->cleanupJWTTestKeys();
|
||||
});
|
||||
|
||||
function createJWTTestKeys()
|
||||
{
|
||||
$keyDir = storage_path('oauth');
|
||||
if (!file_exists($keyDir)) {
|
||||
mkdir($keyDir, 0755, true);
|
||||
}
|
||||
|
||||
$config = [
|
||||
'digest_alg' => 'sha256',
|
||||
'private_key_bits' => 2048,
|
||||
'private_key_type' => OPENSSL_KEYTYPE_RSA,
|
||||
];
|
||||
|
||||
$privateKey = openssl_pkey_new($config);
|
||||
openssl_pkey_export($privateKey, $privateKeyPem);
|
||||
file_put_contents(storage_path('oauth/private.pem'), $privateKeyPem);
|
||||
|
||||
$publicKey = openssl_pkey_get_details($privateKey);
|
||||
file_put_contents(storage_path('oauth/public.pem'), $publicKey['key']);
|
||||
}
|
||||
|
||||
function cleanupJWTTestKeys()
|
||||
{
|
||||
$files = [
|
||||
storage_path('oauth/private.pem'),
|
||||
storage_path('oauth/public.pem')
|
||||
];
|
||||
|
||||
foreach ($files as $file) {
|
||||
if (file_exists($file)) {
|
||||
unlink($file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('JWT ID Token Generation and Validation', function () {
|
||||
it('generates valid JWT ID token', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
// Set up authorization flow
|
||||
$authCode = Str::random(40);
|
||||
Cache::put("auth_code:$authCode", [
|
||||
'user_id' => $this->user->id,
|
||||
'client_id' => $this->application->id,
|
||||
'scope' => 'openid email profile',
|
||||
'nonce' => 'test-nonce-123',
|
||||
], now()->addMinutes(5));
|
||||
|
||||
// Exchange code for tokens
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'client_id' => $this->application->client_id,
|
||||
'client_secret' => $this->application->client_secret,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json();
|
||||
|
||||
// Validate ID token structure and basic properties
|
||||
$idToken = $data['id_token'];
|
||||
expect($idToken)->toBeString();
|
||||
expect(substr_count($idToken, '.'))->toBe(2); // JWT has 3 parts separated by dots
|
||||
|
||||
// Decode JWT payload for basic validation (without signature verification for simplicity)
|
||||
$parts = explode('.', $idToken);
|
||||
$payload = json_decode(base64_decode(str_pad(strtr($parts[1], '-_', '+/'), strlen($parts[1]) % 4, '=', STR_PAD_RIGHT)), true);
|
||||
|
||||
// Validate basic claims structure
|
||||
expect($payload)->toHaveKeys(['iss', 'aud', 'sub', 'email', 'nonce', 'iat', 'exp']);
|
||||
expect($payload['iss'])->toBe(config('app.url'));
|
||||
expect($payload['aud'])->toBe($this->application->client_id);
|
||||
expect($payload['sub'])->toBe((string) $this->user->id);
|
||||
expect($payload['email'])->toBe($this->user->email);
|
||||
expect($payload['nonce'])->toBe('test-nonce-123');
|
||||
|
||||
// Validate timing
|
||||
expect($payload['iat'])->toBeLessThanOrEqual(time());
|
||||
expect($payload['exp'])->toBeGreaterThan(time());
|
||||
});
|
||||
|
||||
it('generates JWT without nonce when not provided', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$authCode = Str::random(40);
|
||||
Cache::put("auth_code:$authCode", [
|
||||
'user_id' => $this->user->id,
|
||||
'client_id' => $this->application->id,
|
||||
'scope' => 'openid email profile',
|
||||
// No nonce provided
|
||||
], now()->addMinutes(5));
|
||||
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'client_id' => $this->application->client_id,
|
||||
'client_secret' => $this->application->client_secret,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json();
|
||||
|
||||
// Parse JWT payload for basic validation
|
||||
$parts = explode('.', $data['id_token']);
|
||||
$payload = json_decode(base64_decode(str_pad(strtr($parts[1], '-_', '+/'), strlen($parts[1]) % 4, '=', STR_PAD_RIGHT)), true);
|
||||
|
||||
// Verify nonce claim is not present
|
||||
expect($payload)->not->toHaveKey('nonce');
|
||||
});
|
||||
|
||||
it('JWT expires in 5 minutes', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$authCode = Str::random(40);
|
||||
Cache::put("auth_code:$authCode", [
|
||||
'user_id' => $this->user->id,
|
||||
'client_id' => $this->application->id,
|
||||
'scope' => 'openid email profile',
|
||||
], now()->addMinutes(5));
|
||||
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'client_id' => $this->application->client_id,
|
||||
'client_secret' => $this->application->client_secret,
|
||||
]);
|
||||
|
||||
$data = $response->json();
|
||||
|
||||
// Parse JWT payload
|
||||
$parts = explode('.', $data['id_token']);
|
||||
$payload = json_decode(base64_decode(str_pad(strtr($parts[1], '-_', '+/'), strlen($parts[1]) % 4, '=', STR_PAD_RIGHT)), true);
|
||||
|
||||
// Should expire in 5 minutes (300 seconds)
|
||||
expect($payload['exp'] - $payload['iat'])->toBe(300);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PKCE Code Challenge Validation', function () {
|
||||
it('validates S256 code challenge correctly', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$codeVerifier = Str::random(128);
|
||||
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
|
||||
|
||||
$authCode = Str::random(40);
|
||||
Cache::put("auth_code:$authCode", [
|
||||
'user_id' => $this->user->id,
|
||||
'client_id' => $this->application->id,
|
||||
'scope' => 'openid',
|
||||
'code_challenge' => $codeChallenge,
|
||||
'code_challenge_method' => 'S256',
|
||||
], now()->addMinutes(5));
|
||||
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'code_verifier' => $codeVerifier,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
});
|
||||
|
||||
it('validates plain code challenge correctly', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$codeVerifier = 'plain-text-verifier';
|
||||
|
||||
$authCode = Str::random(40);
|
||||
Cache::put("auth_code:$authCode", [
|
||||
'user_id' => $this->user->id,
|
||||
'client_id' => $this->application->id,
|
||||
'scope' => 'openid',
|
||||
'code_challenge' => $codeVerifier,
|
||||
'code_challenge_method' => 'plain',
|
||||
], now()->addMinutes(5));
|
||||
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'code_verifier' => $codeVerifier,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
});
|
||||
|
||||
it('rejects invalid code challenge method', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$authCode = Str::random(40);
|
||||
Cache::put("auth_code:$authCode", [
|
||||
'user_id' => $this->user->id,
|
||||
'client_id' => $this->application->id,
|
||||
'scope' => 'openid',
|
||||
'code_challenge' => 'some-challenge',
|
||||
'code_challenge_method' => 'invalid-method',
|
||||
], now()->addMinutes(5));
|
||||
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'code_verifier' => 'some-verifier',
|
||||
]);
|
||||
|
||||
$response->assertStatus(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Access Token Management', function () {
|
||||
it('creates authentication token record with correct metadata', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$authCode = Str::random(40);
|
||||
Cache::put("auth_code:$authCode", [
|
||||
'user_id' => $this->user->id,
|
||||
'client_id' => $this->application->id,
|
||||
'scope' => 'openid email profile',
|
||||
], now()->addMinutes(5));
|
||||
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'client_id' => $this->application->client_id,
|
||||
'client_secret' => $this->application->client_secret,
|
||||
], [
|
||||
'User-Agent' => 'Test Browser/1.0',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
$data = $response->json();
|
||||
|
||||
// Verify token record was created with metadata
|
||||
$tokenRecord = $this->user->tokens()->where('token', $data['access_token'])->first();
|
||||
|
||||
expect($tokenRecord)->not->toBeNull();
|
||||
expect($tokenRecord->application_id)->toBe($this->application->id);
|
||||
expect($tokenRecord->ip)->toBe('127.0.0.1'); // Default test IP
|
||||
expect($tokenRecord->user_agent)->toBe('Test Browser/1.0');
|
||||
expect($tokenRecord->issued_at)->not->toBeNull();
|
||||
expect($tokenRecord->expires_at)->not->toBeNull();
|
||||
});
|
||||
|
||||
it('sets access token expiration to 1 month', function () {
|
||||
$this->actingAs($this->user);
|
||||
|
||||
$authCode = Str::random(40);
|
||||
Cache::put("auth_code:$authCode", [
|
||||
'user_id' => $this->user->id,
|
||||
'client_id' => $this->application->id,
|
||||
'scope' => 'openid',
|
||||
], now()->addMinutes(5));
|
||||
|
||||
$before = now();
|
||||
|
||||
$response = $this->post('/auth/token', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $authCode,
|
||||
'redirect_uri' => $this->application->redirect_uri,
|
||||
'client_id' => $this->application->client_id,
|
||||
'client_secret' => $this->application->client_secret,
|
||||
]);
|
||||
|
||||
$after = now();
|
||||
$data = $response->json();
|
||||
|
||||
$tokenRecord = $this->user->tokens()->where('token', $data['access_token'])->first();
|
||||
|
||||
// Token should expire approximately 1 month from now
|
||||
$expectedExpiry = $before->addMonth();
|
||||
expect($tokenRecord->expires_at)->toBeBetween($expectedExpiry, $after->addMonth());
|
||||
});
|
||||
});
|
@ -2,9 +2,10 @@
|
||||
|
||||
namespace Tests;
|
||||
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
|
||||
|
||||
abstract class TestCase extends BaseTestCase
|
||||
{
|
||||
//
|
||||
use RefreshDatabase;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user