Skip to content

Commit

Permalink
Merge pull request #8 from CreativeCrafts/7-task-add-100-test-coverag…
Browse files Browse the repository at this point in the history
…e-to-openidconnectmanager-service-class

Task:  Added more test coverage
  • Loading branch information
rockblings authored Oct 21, 2024
2 parents e6cf28b + ce1c586 commit 81f3135
Show file tree
Hide file tree
Showing 5 changed files with 131 additions and 94 deletions.
103 changes: 44 additions & 59 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,59 +1,44 @@
# Changelog

All notable changes to `laravel-openid-connect` will be documented in this file.

### 0.0.1 - 2024-10-04

feat: Update OpenID Connect Integration with Enhanced Configurations and Interfaces

- Refactored Service Provider:

- Updated composer.json to reflect proper namespace changes.
- Renamed LaravelOpenidConnectServiceProvider to LaravelOpenIdConnectServiceProvider.

- Enhanced Configuration:

- Added detailed comments in config/openid-connect.php for better documentation.
- Introduced multiple OIDC providers configurations: Google, Okta, and Azure.

- New Interfaces:

- Introduced AuthorizationDataContract for encapsulating authorization data responsibilities.
- Added LaravelOpenIdConnectContract for defining the main OpenID Connect flow.
- Created LaravelOpenIdConnectServiceContract for HTTP interaction responsibilities.

- Data Transfer Object:

- Added AuthorizationData DTO implementing AuthorizationDataContract, providing methods for access token data, refresh token data, issuer URL, and query parameters.

- New Exception:

- Introduced InvalidProviderConfigurationException to handle missing or invalid provider configurations.

- Laravel OpenID Connect Implementation:

- Implemented LaravelOpenIdConnect class providing methods for generation of authorization URL, obtaining access token, user info retrieval, and token refresh functionality.

- Service Implementation:

- Implemented LaravelOpenIdConnectService providing stateless HTTP interactions (GET and POST) with OpenID Connect providers.

- Testing:

- Added comprehensive tests for DTOs, service class, and main OpenID Connect class covering validations, HTTP interactions, and configuration assertions.

- Code Updates:

- Removed obsolete files and updated namespace usages across the project for consistency.
- Added stricter type declarations and improved code comments for better clarity and maintainability.


These changes aim to enhance the flexibility, configurability, and reliability of the OpenID Connect integration within the Laravel package.

## 0.0.2 - 2024-10-07

- feat: Added support for custom configuration in the OpenID Connect integration.
- Updated the configuration file to allow custom provider configurations.
- Divided the configuration into authorization, access_token and refresh_token.
- Added missing pest test
- 100% test coverage and mutation
44fc45c 2024-10-19 (HEAD -> 7-task-add-100-test-coverage-to-openidconnectmanager-service-class) fixed issue with manager process response
35f3287 2024-10-19 fixed static analysis error
e6cf28b 2024-10-19 (origin/main, origin/HEAD, main) Merge pull request #6 from CreativeCrafts/5-task-add-100-test-coverage-to-openidconnectjwtprocessor-service-class
5974bba 2024-10-19 Fix styling
3144b2f 2024-10-19 Fixed #5
ea5aeda 2024-10-19 added an empty test file for OpenIDConnectJWTProcessor
c656d1d 2024-10-18 clean up
44bae18 2024-10-18 Merge pull request #4 from CreativeCrafts/3-task-add-pest-test-to-openidconnecttokenmanager-service-class
ccfbefe 2024-10-18 Fix styling
9987238 2024-10-18 Fixed #3
b3717f7 2024-10-18 Merge pull request #2 from CreativeCrafts/1-task-add-pest-test-to-openidconnecthttpclient-service
b6b15a9 2024-10-18 Fixed #1
a8945f8 2024-10-18 added issue templates
d940b0e 2024-10-18 minor changes to rector github action flow
c34696f 2024-10-18 added test for OpenIDConnectConfig and also added rector github action flow
b1054b4 2024-10-07 (tag: 0.0.2) updated change log
e3b93a0 2024-10-07 fixed broken pest test and added missing test
d6977eb 2024-10-07 ## 0.0.2
a5d09fc 2024-10-04 updated the Readme
e5545cc 2024-10-04 Merge branch 'main' of https://github.com/CreativeCrafts/laravel-openid-connect
23ec020 2024-10-04 updated the Readme
62e154b 2024-10-04 Update CHANGELOG
7457e92 2024-10-04 (tag: 0.0.1) added the change log
026eb7a 2024-10-04 updated the readme with installation instructions
3301d4e 2024-10-04 updated the run test github action workflow
c30e3a6 2024-10-04 Merge branch 'main' of https://github.com/CreativeCrafts/laravel-openid-connect
892bd5c 2024-10-04 updated the run test github action workflow
a2f834f 2024-10-04 Fix styling
4907104 2024-10-04 updated the run test github action workflow
874878d 2024-10-04 updated the run test github action workflow
9081c43 2024-10-04 updated the run test github action workflow
f6326aa 2024-10-04 updated the run test github action workflow
54ca338 2024-10-04 updated the run test github action workflow
c2540c5 2024-10-04 updated the run test github action workflow
3e6d3f9 2024-10-04 Merge remote-tracking branch 'origin/main'
f611dfc 2024-10-04 feat: Refactor OpenID Connect services and enhance tests.
3c7de37 2024-10-04 Fix styling
4a9462b 2024-10-04 Merge remote-tracking branch 'origin/main'
89d7398 2024-10-04 feat: Update OpenID Connect Integration with Enhanced Configurations and Interfaces
a47efa4 2024-10-04 Fix styling
47fc2d9 2024-10-04 Merge branch 'main' of https://github.com/CreativeCrafts/laravel-openid-connect
e019f09 2024-10-04 initial setup
5a3d7ed 2024-10-04 Fix styling
00fbba9 2024-10-04 initial start
4 changes: 2 additions & 2 deletions src/Contracts/OpenIDConnectConfigContract.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,9 @@ public function setProviderURL(string $providerUrl): void;
*
* @param string $key The key of the configuration value.
* @param string|null $default The default value to return if the key is not found.
* @return string The configuration value or the default value if not found.
* @return string|array The configuration value or the default value if not found.
*/
public function getProviderConfigValue(string $key, string $default = null): string;
public function getProviderConfigValue(string $key, string $default = null): string|array;

/**
* Sets the encoding type for the OpenID Connect provider.
Expand Down
4 changes: 2 additions & 2 deletions src/Services/OpenIDConnectConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -291,10 +291,10 @@ public function addAuthParam(string $key, string $value): void
*
* @param string $key The key of the configuration value.
* @param string|null $default The default value to return if the key is not found.
* @return string The configuration value or the default value if not found.
* @return string|array The configuration value or the default value if not found.
* @throws OpenIDConnectClientException
*/
public function getProviderConfigValue(string $key, string $default = null): string
public function getProviderConfigValue(string $key, string $default = null): string|array
{
if (! isset($this->providerConfig[$key])) {
$this->providerConfig[$key] = $this->getWellKnownConfigValue($key, $default);
Expand Down
65 changes: 34 additions & 31 deletions src/Services/OpenIDConnectManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
use CreativeCrafts\LaravelOpenidConnect\Helpers\Base64Helper;
use Exception;
use Illuminate\Http\Client\ConnectionException;
use Jose\Component\Core\JWK;
use Jose\Component\Encryption\JWELoader;

final class OpenIDConnectManager implements OpenIdConnectManagerContract
{
Expand All @@ -22,19 +20,38 @@ final class OpenIDConnectManager implements OpenIdConnectManagerContract

protected OpenIDConnectConfig $config;

private JWELoader $jweLoader;

/**
* @throws OpenIDConnectClientException
*/
public function __construct(array $config)
{
$this->tokenManager = new OpenIDConnectTokenManager();
$this->httpClient = new OpenIDConnectHttpClient();
$this->jwtProcessor = new OpenIDConnectJWTProcessor();
$this->setTokenManager(new OpenIDConnectTokenManager());
$this->setHttpClient(new OpenIDConnectHttpClient());
$this->setJwtProcessor(new OpenIDConnectJWTProcessor());
$this->setConfig($config);
}

/**
* @throws OpenIDConnectClientException
*/
public function setConfig(array $config): void
{
$this->config = new OpenIDConnectConfig($config);
// Initialize JWE Loader
// $this->initializeJWELoader();
}

public function setHttpClient(OpenIDConnectHttpClient $httpClient): void
{
$this->httpClient = $httpClient;
}

public function setTokenManager(OpenIDConnectTokenManager $tokenManager): void
{
$this->tokenManager = $tokenManager;
}

public function setJwtProcessor(OpenIDConnectJWTProcessor $jwtProcessor): void
{
$this->jwtProcessor = $jwtProcessor;
}

/**
Expand Down Expand Up @@ -123,6 +140,7 @@ public function requestUserInfo(string $attribute = null, ?bool $addOpenIdSchema
*
* @throws ConnectionException
* @throws OpenIDConnectClientException
* @throws Exception
*/
protected function handleAuthorizationCodeFlow(): bool
{
Expand Down Expand Up @@ -221,6 +239,7 @@ protected function handleImplicitFlow(): bool
*/
protected function requestTokens(string $code): array
{
/** @var string $tokenEndpoint */
$tokenEndpoint = $this->config->getProviderConfigValue('token_endpoint');
$tokenParams = [
'grant_type' => 'authorization_code',
Expand Down Expand Up @@ -248,6 +267,7 @@ protected function requestTokens(string $code): array
*/
protected function requestAuthorization(): void
{
/** @var string $authEndpoint */
$authEndpoint = $this->config->getProviderConfigValue('authorization_endpoint');
$this->tokenManager->setNonce($this->tokenManager->generateRandString());
$nonce = $this->tokenManager->getNonce();
Expand Down Expand Up @@ -355,6 +375,7 @@ protected function prepareAuthHeaders(): array
*/
protected function getJwks(): array
{
/** @var string $jwksUri */
$jwksUri = $this->config->getProviderConfigValue('jwks_uri');
$response = $this->httpClient->fetchURL($jwksUri);
/** @var array $fetchedJwks */
Expand Down Expand Up @@ -459,28 +480,10 @@ protected function validateAccessTokenHash(string $atHash, string $accessToken):
protected function handleJweResponse(string $jwe): string
{
// Create a JWK (JSON Web Key) for decryption
$key = new JWK([
'kty' => 'RSA',
'n' => '...', // Base64url encoded modulus
'e' => '...', // Base64url encoded public exponent
'd' => '...', // Base64url encoded private exponent
'p' => '...', // Base64url encoded first prime factor
'q' => '...', // Base64url encoded second prime factor
'dp' => '...', // Base64url encoded first factor CRT exponent
'dq' => '...', // Base64url encoded second factor CRT exponent
'qi' => '...', // Base64url encoded first CRT coefficient
]);

// Load and decrypt the JWE
$jweObject = $this->jweLoader->loadAndDecryptWithKey($jwe, $key, $recipientIndex);

// Get the decrypted payload
$decryptedPayload = $jweObject->getPayload();

if (! is_string($decryptedPayload)) {
throw new OpenIDConnectClientException('Unable to decrypt JWE payload');
/*$key = new JWK([
}
return $decryptedPayload;
return $decryptedPayload;*/
throw new OpenIDConnectClientException('JWE response is not supported at the moment.');
}

/**
Expand Down Expand Up @@ -508,7 +511,7 @@ private function processResponse(string $response): object
}

/** @var object $responseObject */
$responseObject = json_decode($response, true);
$responseObject = json_decode($response, false);

return $responseObject;
}
Expand Down
49 changes: 49 additions & 0 deletions tests/Services/OpenIDConnectManagerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

use CreativeCrafts\LaravelOpenidConnect\Exceptions\OpenIDConnectClientException;
use CreativeCrafts\LaravelOpenidConnect\Services\OpenIDConnectManager;

it('throws an exception if there is an error in the request', function () {
$config = ['allow_implicit_flow' => true]; // Example config
$manager = new OpenIDConnectManager($config);

$_REQUEST['error'] = 'access_denied';

$manager->authenticate();
})->throws(OpenIDConnectClientException::class, 'The provider URL has not been set');

/* it('handles authorization code flow', function () {
// Step 1: Create a configuration array
$configArray = [
'provider_url' => 'https://example.com',
'issuer' => 'https://example.com',
'client_id' => 'example_client_id',
'client_secret' => 'example_client_secret',
'scopes' => ['openid', 'email', 'profile'],
'response_type' => 'code',
'redirect_url' => 'https://example.com/callback',
];
// Step 2: Create real instances of the final classes
$config = new OpenIDConnectConfig($configArray);
$httpClient = new OpenIDConnectHttpClient();
$tokenManager = new OpenIDConnectTokenManager();
$jwtProcessor = new OpenIDConnectJWTProcessor();
// Simulate request parameters
$_REQUEST['code'] = 'mock_code';
$_REQUEST['state'] = 'mock_state';
// Step 3: Initialize the OpenIDConnectManager
$manager = new OpenIDConnectManager($configArray);
// Set dependencies using the setter methods
$manager->setHttpClient($httpClient);
$manager->setTokenManager($tokenManager);
$manager->setJwtProcessor($jwtProcessor);
// Step 4: Assert the result of authentication
expect($manager->authenticate())->toBeTrue();
});*/

0 comments on commit 81f3135

Please sign in to comment.