Skip to content

Caching autoDiscovery result#6

Open
DrNixx wants to merge 1 commit into
maicol07:mainfrom
DrNixx:discover-cache
Open

Caching autoDiscovery result#6
DrNixx wants to merge 1 commit into
maicol07:mainfrom
DrNixx:discover-cache

Conversation

@DrNixx
Copy link
Copy Markdown

@DrNixx DrNixx commented Apr 10, 2026

List of common tasks a pull request require complete

  • Changelog entry is added or the pull request don't alter library's functionality

Summary by CodeRabbit

  • Performance Improvements
    • OIDC discovery documents are now cached to reduce redundant HTTP requests and improve performance. Cache duration is configurable via environment settings.

@what-the-diff
Copy link
Copy Markdown

what-the-diff Bot commented Apr 10, 2026

PR Summary

  • Introducing Cache Import
    An additional resource has been implemented - Illuminate\Support\Facades\Cache, which will be employed to manage and store data smartly and temporarily.

  • Caching Mechanism for Auto-Discovery Responses
    A new mechanism has been introduced to cache responses for auto-discovery. This means that instead of always requesting data from the server every time, we can briefly store and use it repeatedly.

  • Switch to Cached Version for Direct API Call
    The direct network call to the API has been replaced with a cache version. This change ensures that instead of making redundant network requests to $provider_url/$this->DISCOVERY_PATH, we directly employ the cached data.

  • Response Handling Modification
    We have updated our response management system to first verify the cached configuration's validity before stepping forward to process the data.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 10, 2026

📝 Walkthrough

Walkthrough

The autoDiscovery() method now implements caching for discovery documents using a deterministic cache key derived from provider URL and query parameters. Discovery HTTP requests execute within Cache::remember() with configurable TTL from environment variable (default 3600 seconds), and configuration parsing only proceeds when a valid cached or freshly fetched response exists.

Changes

Cohort / File(s) Summary
Discovery Document Caching
src/Traits/AutoDiscovery.php
Added in-memory caching layer with md5-based deterministic cache key (oidc:discovery:...), configurable TTL from OIDC_DISCOVERY_CACHE_TTL env var, HTTP request wrapped in Cache::remember(), and conditional config parsing on successful responses.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant Cache
    participant HTTPClient as HTTP Client
    participant ConfigParser as Config Parser

    Caller->>Cache: Check for cached discovery<br/>(key: oidc:discovery:md5(...))
    alt Cache Hit
        Cache-->>Caller: Return cached config
    else Cache Miss
        Cache->>HTTPClient: Fetch discovery document
        HTTPClient-->>Cache: Response (status, body)
        alt Response OK
            Cache->>ConfigParser: Parse configuration
            ConfigParser-->>Cache: Parsed config
            Cache->>Cache: Store in cache (TTL: 3600s)
        else Response Not OK
            Cache->>Cache: Return null
        end
        Cache-->>Caller: Return config or null
    end
    Caller->>ConfigParser: Process configuration<br/>(if config is truthy)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hops of joy through cache so grand,
Discovery documents, oh so planned!
With TTLs and keys, deterministic and true,
No more requests to fetch what we knew!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding caching to the autoDiscovery result to avoid repeated HTTP requests.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements caching for the OpenID Connect discovery process within the AutoDiscovery trait to improve performance. The feedback highlights two main areas for improvement: ensuring cache key consistency by sorting query parameters before hashing, and replacing the direct use of the env() helper with the config() helper to prevent issues when Laravel's configuration is cached.

if ($provider_url) {
$response = $this->client()
->get("$provider_url/$this->DISCOVERY_PATH", $query_params);
$cacheKey = 'oidc:discovery:' . md5(json_encode([$provider_url, $query_params]));
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The cache key generation is sensitive to the order of keys in the $query_params array. If the same parameters are passed in a different order, it will result in different MD5 hashes and unnecessary cache misses. To ensure consistent cache hits, consider sorting the query parameters (e.g., using ksort()) before encoding them into the cache key.

->get("$provider_url/$this->DISCOVERY_PATH", $query_params);
$cacheKey = 'oidc:discovery:' . md5(json_encode([$provider_url, $query_params]));
/** @noinspection LaravelFunctionsInspection */
$cacheTtl = env('OIDC_DISCOVERY_CACHE_TTL', 3600);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Avoid using the env() helper directly in application logic. In Laravel, env() should ideally only be used within configuration files. When the application configuration is cached (via php artisan config:cache), all env() calls outside of configuration files return null. This causes the code to ignore the actual environment variable and fall back to the default value of 3600. It is recommended to define a configuration key (e.g., in config/openid.php) and use the config() helper instead.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is not a Laravel-specific library, but a generic PHP one, it should be better to get the ttl from a config parameter instead of an env

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/Traits/AutoDiscovery.php (1)

42-42: Canonicalize query params before hashing cache key.

Line 42 currently hashes raw $query_params; equivalent associative arrays with different key order will generate different keys and reduce cache hit rate.

♻️ Suggested change
-            $cacheKey = 'oidc:discovery:' . md5(json_encode([$provider_url, $query_params]));
+            $normalizedQueryParams = $query_params;
+            if (is_array($normalizedQueryParams)) {
+                ksort($normalizedQueryParams);
+            }
+            $cacheKey = 'oidc:discovery:' . md5(json_encode([$provider_url, $normalizedQueryParams]));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/Traits/AutoDiscovery.php` at line 42, The cache key generation is using
raw $query_params which can vary by key order; update the AutoDiscovery trait so
before computing $cacheKey you canonicalize $query_params (e.g., recursively
sort associative arrays by keys) then encode that canonicalized structure (with
$provider_url) for md5; locate the line building $cacheKey and replace the input
to json_encode with a deterministic/canonicalized version of $query_params so
equivalent param sets always produce the same $cacheKey.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/Traits/AutoDiscovery.php`:
- Line 42: The cache key generation is using raw $query_params which can vary by
key order; update the AutoDiscovery trait so before computing $cacheKey you
canonicalize $query_params (e.g., recursively sort associative arrays by keys)
then encode that canonicalized structure (with $provider_url) for md5; locate
the line building $cacheKey and replace the input to json_encode with a
deterministic/canonicalized version of $query_params so equivalent param sets
always produce the same $cacheKey.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 456c6d35-530b-40a5-8488-4656fbea42fb

📥 Commits

Reviewing files that changed from the base of the PR and between 174ae5e and 23e2bc0.

📒 Files selected for processing (1)
  • src/Traits/AutoDiscovery.php

@maicol07
Copy link
Copy Markdown
Owner

Hi @DrNixx, thank you for your PR!
Sorry for the late review, I missed the notification!

The feature is great and useful, but I agree with Gemini comments that should be addressed (also check my comment in the second one).

After this, I'll be happy to merge it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants