You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@solr.apache.org by "laminelam (via GitHub)" <gi...@apache.org> on 2023/07/18 18:36:18 UTC

[GitHub] [solr] laminelam opened a new pull request, #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

laminelam opened a new pull request, #1791:
URL: https://github.com/apache/solr/pull/1791

   https://issues.apache.org/jira/browse/SOLR-16896
   
   # Description
   
   Solr’s JWT authentication plugin uses _implicit flow_ to request _Access_ & _ID tokens_ via OIDC/OAuth 2.0.
   
   Due to its inherent security weaknesses, such as potential exposure of access tokens in the browser's history or the risk of leakage at the redirect stage, the _Implicit flow_ has fallen out of favor. Its usage has been deprecated in OAuth 2.1, and many OIDC/OAuth 2.0 providers no longer support it. A decade ago, Implicit flow was the only practical way to retrieve tokens in a single call through browser redirection when cross-origin requests were blocked to shield applications from cross-site scripting attacks.
   
   However, the development of Single Page Applications (SPAs) and advancements in modern browsers' handling of CORS requests have made the _Implicit flow_ obsolete. Current applications and Content Security Policies (CSPs) can be configured to permit CORS requests.
   
   OAuth 2.0 offers various flows (protocols) suited to different use cases. The Authorization Code Flow, recommended for SPAs and native apps, is available in two variants:
   
   - Authorization Code Flow with a secret: This involves server-side communication with the authorization server, necessitating secure secret storage. The retrieved tokens are then shared with the client.
   
   - Authorization Code Flow with PKCE: Given that the source code of native apps and SPAs is accessible to client devices, storing the secret client-side is impractical. The PKCE solution facilitates an exchange of a verifier code between the client and the authorization server, granting access to the tokens. Hence the acronym: Proof Key for Code Exchange (PKCE).
   
   Given that the Solr admin Webapp is an SPA, this contribution employs the PKCE method. However, we can incorporate support for the Authorization Code Flow with a secret, while still reusing the front-end code, to allow these two options to coexist in a configurable manner.
   
   This implementation is expected to enhance security by mitigating the risk of token interception, ensuring tokens are delivered to the intended client, and providing a safer overall user authentication process.
     
   
   More details are available in the below resources:
   
   [OAuth 2.0 RFC (implicit flow)](https://datatracker.ietf.org/doc/html/rfc6749#section-1.3.2)
   
   [PKCE RFC](https://datatracker.ietf.org/doc/html/rfc7636 )
   
   [The State of the Implicit Flow in OAuth2](https://brockallen.com/2019/01/03/the-state-of-the-implicit-flow-in-oauth2/)
   
   [Why the implicit flow is no longer recommended](http://taithienbo.com/why-the-implicit-flow-is-no-longer-recommended-for-protecting-a-public-client/)
   
   ---
   
   This PR represents the "front-end" part of the contribution. See the "back-end" [PR](https://github.pie.apple.com/IPR/apache-solr/pull/50).
   
   
   The PKCE code flow process retrieves tokens in two stages:
   
   1. Acquire the authorization code via browser redirection.
   2. Utilize the received code to invoke the /token endpoint and fetch the tokens.
   
   For the sake of backward compatibility, the 'implicit flow' is maintained and established as the default mode.
   
    
   
   
   # Tests
   
   Test cases added to the back-end PR.
   Front-end app does not support unit testing.
   
   Extensive tests were done on the browser.
   
   Ref guide to be updated.
   
   
   
   
   
   
   
   
    
   
    
   
   # Checklist
   
   Please review the following and check all that apply:
   
   - [x] I have reviewed the guidelines for [How to Contribute](https://wiki.apache.org/solr/HowToContribute) and my code conforms to the standards described there to the best of my ability.
   - [x] I have created a Jira issue and added the issue ID to my pull request title.
   - [x] I have given Solr maintainers [access](https://help.github.com/en/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork) to contribute to my PR branch. (optional but recommended)
   - [x] I have developed this patch against the `main` branch.
   - [x] I have run `./gradlew check`.
   - [x] I have added tests for my changes.
   - [ ] I have added documentation for the [Reference Guide](https://github.com/apache/solr/tree/main/solr/solr-ref-guide)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1296130713


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   > One outstanding question is: how can we incorporate the /token URL into the list of allowed URLs in the CSP connect-src directive? For now, this is manually added in server/etc/jetty.xml.’
   
   Yea, we need backend to be able to generate CSP header dynamically (now it is set statically in `jetty.xml`). Let's explore that.



##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   > One outstanding question is: how can we incorporate the /token URL into the list of allowed URLs in the CSP connect-src directive? For now, this is manually added in server/etc/jetty.xml.’
   
   Yea, we need backend to be able to generate CSP header dynamically (now it is set statically in `jetty.xml`). Let's explore that.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on PR #1791:
URL: https://github.com/apache/solr/pull/1791#issuecomment-1718007335

   @janhoy 
   
   I think it's good for a merge now.
   THANK YOU again for all the time you spent on this, reviewing and contributing.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1322136364


##########
solr/webapp/web/js/angular/services.js:
##########
@@ -286,8 +286,74 @@ solrAdminServices.factory('System',
         })
 }])
 .factory('AuthenticationService',
-    ['base64', function (base64) {
-        var service = {};
+    ['base64', '$resource', function (base64, $resource) {
+      var service = {};
+
+      service.getOAuthTokens = function (url, data) {
+        var serializedData = serialize(data);
+        var resource = $resource(url, {}, {
+          getToken: {
+            method: 'POST',
+            timeout: 10000,
+            headers: {
+              'Content-Type': 'application/x-www-form-urlencoded',
+              'X-Requested-With': undefined // Set this header to undefined to prevent preflight requests
+            },
+            transformResponse: function (data) {
+              return angular.fromJson(data);
+            }
+          }
+        });
+        return resource.getToken({}, serializedData).$promise;
+      };
+
+      var codeChallengeMethod = "S256";
+      service.getCodeChallengeMethod = function getCodeChallengeMethod() {
+        return codeChallengeMethod;
+      }
+
+      service.generateCodeVerifier = function generateCodeVerifier() {
+        var codeVerifier = '';
+        var possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
+        for (var i = 0; i < 96; i++) {
+          codeVerifier += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
+        }
+        return codeVerifier;
+      }
+
+      service.generateCodeChallengeFromVerifier = async function generateCodeChallengeFromVerifier(v) {
+        var hashed = await sha256(v);
+        var base64encoded = base64urlencode(hashed);
+        return base64encoded;
+      }
+
+      function sha256(str) {
+        const encoder = new TextEncoder();
+        return window.crypto.subtle.digest("SHA-256", encoder.encode(str));

Review Comment:
   Hi @janhoy  I have tested jsSHA locally it's working fine. Let me give it another test on a remote cluster before pushing the code.
   PS: Sorry for not getting back sooner as I promised, was pretty sick end of last week.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1298542144


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   I feel your pain as I am facing the same issue to test the code.
   I had it as a one PR but was asked by another committer to split it to facilitate its review by different committers as not everybody is familiar with the front-end part of Solr.
   
   I think if we could merge the back-end one it would make much easier to test the front-end part.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1297041120


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   This part probably belongs in the backend. BTW how would you feel about combining the backend and frontend PRs into one (this)? I had to merge both branches into a new branch locally to be able to test it, and there is no clear benefit in releasing one and not the other.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on PR #1791:
URL: https://github.com/apache/solr/pull/1791#issuecomment-1706104598

   @laminelam Not much left on this now, do you need help with anything?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on PR #1791:
URL: https://github.com/apache/solr/pull/1791#issuecomment-1706859388

   > @laminelam Not much left on this now, do you need help with anything?
   
   Hi @janhoy 
   Yes the only thing left is supporting http (in addition to https) for the code hasher (sha256).
   Give me a couple of days will get back to you, busy with other stuff. I think/hope we can finish everything by the end of the week.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1298542144


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   I feel your pain as I am facing the same issue to test the code.
   I had it as a one PIR by was asked by another committer to split it to facilitate its review by different committers as not everybody is familiar with the front-end part of Solr.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1298542144


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   I feel your pain as I am facing the same issue to test the code.
   I had it as a one PIR by was asked by another committer to split it to facilitate its review by different committers as not everybody is familiar with the front-end part of Solr.
   
   I think if we could merge the back-end one it would make much easier to test the front-end part.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1298538572


##########
solr/webapp/web/js/angular/services.js:
##########
@@ -286,8 +286,74 @@ solrAdminServices.factory('System',
         })
 }])
 .factory('AuthenticationService',
-    ['base64', function (base64) {
-        var service = {};
+    ['base64', '$resource', function (base64, $resource) {
+      var service = {};
+
+      service.getOAuthTokens = function (url, data) {
+        var serializedData = serialize(data);
+        var resource = $resource(url, {}, {
+          getToken: {
+            method: 'POST',
+            timeout: 10000,
+            headers: {
+              'Content-Type': 'application/x-www-form-urlencoded',
+              'X-Requested-With': undefined // Set this header to undefined to prevent preflight requests
+            },
+            transformResponse: function (data) {
+              return angular.fromJson(data);
+            }
+          }
+        });
+        return resource.getToken({}, serializedData).$promise;
+      };
+
+      var codeChallengeMethod = "S256";
+      service.getCodeChallengeMethod = function getCodeChallengeMethod() {
+        return codeChallengeMethod;
+      }
+
+      service.generateCodeVerifier = function generateCodeVerifier() {
+        var codeVerifier = '';
+        var possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
+        for (var i = 0; i < 96; i++) {
+          codeVerifier += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
+        }
+        return codeVerifier;
+      }
+
+      service.generateCodeChallengeFromVerifier = async function generateCodeChallengeFromVerifier(v) {
+        var hashed = await sha256(v);
+        var base64encoded = base64urlencode(hashed);
+        return base64encoded;
+      }
+
+      function sha256(str) {
+        const encoder = new TextEncoder();
+        return window.crypto.subtle.digest("SHA-256", encoder.encode(str));

Review Comment:
   That's a good catch. I only tested on localhost and https hosts. I think you're right, this would't work on http. 
   What do you suggest? Keep it as it is and require https for this plugin, or change the code to support http?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1315570191


##########
solr/webapp/web/js/angular/services.js:
##########
@@ -286,8 +286,74 @@ solrAdminServices.factory('System',
         })
 }])
 .factory('AuthenticationService',
-    ['base64', function (base64) {
-        var service = {};
+    ['base64', '$resource', function (base64, $resource) {
+      var service = {};
+
+      service.getOAuthTokens = function (url, data) {
+        var serializedData = serialize(data);
+        var resource = $resource(url, {}, {
+          getToken: {
+            method: 'POST',
+            timeout: 10000,
+            headers: {
+              'Content-Type': 'application/x-www-form-urlencoded',
+              'X-Requested-With': undefined // Set this header to undefined to prevent preflight requests
+            },
+            transformResponse: function (data) {
+              return angular.fromJson(data);
+            }
+          }
+        });
+        return resource.getToken({}, serializedData).$promise;
+      };
+
+      var codeChallengeMethod = "S256";
+      service.getCodeChallengeMethod = function getCodeChallengeMethod() {
+        return codeChallengeMethod;
+      }
+
+      service.generateCodeVerifier = function generateCodeVerifier() {
+        var codeVerifier = '';
+        var possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
+        for (var i = 0; i < 96; i++) {
+          codeVerifier += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
+        }
+        return codeVerifier;
+      }
+
+      service.generateCodeChallengeFromVerifier = async function generateCodeChallengeFromVerifier(v) {
+        var hashed = await sha256(v);
+        var base64encoded = base64urlencode(hashed);
+        return base64encoded;
+      }
+
+      function sha256(str) {
+        const encoder = new TextEncoder();
+        return window.crypto.subtle.digest("SHA-256", encoder.encode(str));

Review Comment:
   See https://github.com/laminelam/solr/pull/1 for a proposal that I believe will solve this also for http.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1292753402


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";

Review Comment:
   Have you considered to have this "default" happening in backend #1792 instead, meaning the frontend will always receive either `authorization_flow` or `implicit` in this var?



##########
solr/webapp/web/js/angular/services.js:
##########
@@ -286,8 +286,74 @@ solrAdminServices.factory('System',
         })
 }])
 .factory('AuthenticationService',
-    ['base64', function (base64) {
-        var service = {};
+    ['base64', '$resource', function (base64, $resource) {
+      var service = {};
+
+      service.getOAuthTokens = function (url, data) {
+        var serializedData = serialize(data);
+        var resource = $resource(url, {}, {
+          getToken: {
+            method: 'POST',
+            timeout: 10000,
+            headers: {
+              'Content-Type': 'application/x-www-form-urlencoded',
+              'X-Requested-With': undefined // Set this header to undefined to prevent preflight requests
+            },
+            transformResponse: function (data) {
+              return angular.fromJson(data);
+            }
+          }
+        });
+        return resource.getToken({}, serializedData).$promise;
+      };
+
+      var codeChallengeMethod = "S256";
+      service.getCodeChallengeMethod = function getCodeChallengeMethod() {
+        return codeChallengeMethod;
+      }
+
+      service.generateCodeVerifier = function generateCodeVerifier() {
+        var codeVerifier = '';
+        var possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
+        for (var i = 0; i < 96; i++) {
+          codeVerifier += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
+        }
+        return codeVerifier;
+      }
+
+      service.generateCodeChallengeFromVerifier = async function generateCodeChallengeFromVerifier(v) {
+        var hashed = await sha256(v);
+        var base64encoded = base64urlencode(hashed);
+        return base64encoded;
+      }
+
+      function sha256(str) {
+        const encoder = new TextEncoder();
+        return window.crypto.subtle.digest("SHA-256", encoder.encode(str));

Review Comment:
   The [digest](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest) function is only available in secure context (https). I believe we have not required SSL to test JWT before, will this be changing that?
   
   I absolutely think we should require SSL for using auth, just trying to be explicit 



##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");

Review Comment:
   This debug and on line 115 would be redundant as the 'raw' flow is printed in line 73



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on PR #1791:
URL: https://github.com/apache/solr/pull/1791#issuecomment-1648720273

   I’m on vacation so please proceed without my review. I’m thrilled to see this be completed. Ok to support impl flow for 9.x but it should be removed for 10.0


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1298543083


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   BTW, thank you very much for the time you're spending on this contrib, I really appreciate it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1296859919


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   Here's a patch that sets CSP dynamically. Verified the headers get correctly set, but not yet spun it up with true JWT plugin, will be able to do that next week.
   
   ```patch
   Subject: [PATCH] Update io.netty:* to v4.1.96.Final (#1813)
   
   (cherry picked from commit b0d3085b83994b1636e455f95e6858aab7039e29)
   ---
   Index: solr/server/etc/jetty.xml
   IDEA additional info:
   Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
   <+>UTF-8
   ===================================================================
   diff --git a/solr/server/etc/jetty.xml b/solr/server/etc/jetty.xml
   --- a/solr/server/etc/jetty.xml	(revision 2fb8f9e3734eb9572c701a7e1a1a9834a94f4a38)
   +++ b/solr/server/etc/jetty.xml	(date 1692202681699)
   @@ -90,6 +90,7 @@
          <Set name="originalPathAttribute">requestedPath</Set>
    
          <!-- security-related headers -->
   +<!-- TODO: SOLR-16896 - csp is now set from Java backend
          <Call name="addRule">
            <Arg>
              <New class="org.eclipse.jetty.rewrite.handler.HeaderPatternRule">
   @@ -99,6 +100,7 @@
              </New>
            </Arg>
          </Call>
   +-->
          <Call name="addRule">
            <Arg>
              <New class="org.eclipse.jetty.rewrite.handler.HeaderPatternRule">
   Index: solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java
   IDEA additional info:
   Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
   <+>UTF-8
   ===================================================================
   diff --git a/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java b/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java
   --- a/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java	(revision 2fb8f9e3734eb9572c701a7e1a1a9834a94f4a38)
   +++ b/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java	(date 1692260572052)
   @@ -16,11 +16,13 @@
     */
    package org.apache.solr.servlet;
    
   +import com.google.common.net.HttpHeaders;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.nio.charset.StandardCharsets;
   +import java.util.stream.Collectors;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.commons.io.output.CloseShieldOutputStream;
   @@ -37,6 +39,8 @@
      // check system properties for whether or not admin UI is disabled, default is false
      private static final boolean disabled =
          Boolean.parseBoolean(System.getProperty("disableAdminUI", "false"));
   +  // Any system property that starts with this prefix will be added to the CSP connect-src
   +  public static final String SYSPROP_CSP_HOSTS_PREFIX = "solr.ui.csp.hosts";
    
      @Override
      public void doGet(HttpServletRequest _request, HttpServletResponse _response) throws IOException {
   @@ -60,6 +64,12 @@
          if (in != null && cores != null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
   +        String connectSrc = generateCspConnectSrc();
   +        response.setHeader(
   +            HttpHeaders.CONTENT_SECURITY_POLICY,
   +            "default-src 'none'; base-uri 'none'; connect-src "
   +                + connectSrc
   +                + "; form-action 'self'; font-src 'self'; frame-ancestors 'none'; img-src 'self' data:; media-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; worker-src 'self';");
    
            // We have to close this to flush OutputStreamWriter buffer
            try (Writer out =
   @@ -76,4 +86,18 @@
          }
        }
      }
   +
   +  /**
   +   * Iterate all system properties with prefix {@link #SYSPROP_CSP_HOSTS_PREFIX} and concatenate
   +   * them into a space separated string that can be use in CSP
   +   */
   +  private String generateCspConnectSrc() {
   +    var props =
   +        System.getProperties().keySet().stream()
   +            .filter(k -> k instanceof String && ((String) k).startsWith(SYSPROP_CSP_HOSTS_PREFIX))
   +            .map(key -> System.getProperty((String) key))
   +            .collect(Collectors.toList());
   +    props.add("'self'");
   +    return String.join(" ", props);
   +  }
    }
   Index: solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java
   IDEA additional info:
   Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
   <+>UTF-8
   ===================================================================
   diff --git a/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java b/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java
   --- a/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java	(revision 2fb8f9e3734eb9572c701a7e1a1a9834a94f4a38)
   +++ b/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java	(date 1692260035611)
   @@ -19,6 +19,7 @@
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.lang.invoke.MethodHandles;
   +import java.net.URI;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Path;
   @@ -63,6 +64,7 @@
    import org.apache.solr.security.ConfigEditablePlugin;
    import org.apache.solr.security.jwt.JWTAuthPlugin.JWTAuthenticationResponse.AuthCode;
    import org.apache.solr.security.jwt.api.ModifyJWTAuthPluginConfigAPI;
   +import org.apache.solr.servlet.LoadAdminUiServlet;
    import org.apache.solr.util.CryptoKeys;
    import org.eclipse.jetty.client.api.Request;
    import org.jose4j.jwa.AlgorithmConstraints;
   @@ -282,10 +284,25 @@
        }
    
        initConsumer();
   +    registerTokenEndpointForCsp();
    
        lastInitTime = Instant.now();
      }
    
   +  /** Record Issuer URL as a system property so it can be picked up and sent to Admin UI as CSP */
   +  private void registerTokenEndpointForCsp() {
   +    final String syspropName = LoadAdminUiServlet.SYSPROP_CSP_HOSTS_PREFIX + ".jwt";
   +    String url = !issuerConfigs.isEmpty() ? getPrimaryIssuer().getTokenEndpoint() : null;
   +    if (url != null) {
   +      URI uri = URI.create(url);
   +      System.setProperty(
   +          syspropName,
   +          String.format(Locale.ROOT, "%s://%s:%s", uri.getScheme(), uri.getHost(), uri.getPort()));
   +    } else {
   +      System.clearProperty(syspropName);
   +    }
   +  }
   +
      /**
       * Given a configuration object of a file name or list of file names, read X509 certificates from
       * each file
   ```
   
   The only problem with this is that now the CSP header is only set when loading the admin UI, not for all the API endpoints as it used to be. Is there a way to have Jetty add the header only if the servlet has not added it already?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on PR #1791:
URL: https://github.com/apache/solr/pull/1791#issuecomment-1688203926

   I tested in a real KeyCloak idp environment today, with my [custom image](https://hub.docker.com/layers/cominvent/solr/10-codeflow-csp2/images/sha256-a85f101563a03b8dc43e648d800615909570cbaa5c096073f6359c8c00065d81?context=explore) based on [this branch](https://github.com/janhoy/solr/tree/codeflow), which is a merge of backend and frontend PRs plus the patch from the comment above.
   
   This all worked nicely, pulling the token endpoint from `well-known` endpoint and auto configuring the CSP header based on that...


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1296859919


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   Here's a patch that sets CSP dynamically. Verified the headers get correctly set, but not yet spun it up with true JWT plugin, will be able to do that next week.
   
   ```patch
   Index: solr/server/etc/jetty.xml
   IDEA additional info:
   Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
   <+>UTF-8
   ===================================================================
   diff --git a/solr/server/etc/jetty.xml b/solr/server/etc/jetty.xml
   --- a/solr/server/etc/jetty.xml	(revision 2fb8f9e3734eb9572c701a7e1a1a9834a94f4a38)
   +++ b/solr/server/etc/jetty.xml	(date 1692202681699)
   @@ -90,6 +90,7 @@
          <Set name="originalPathAttribute">requestedPath</Set>
    
          <!-- security-related headers -->
   +<!-- TODO: SOLR-16896 - csp is now set from Java backend
          <Call name="addRule">
            <Arg>
              <New class="org.eclipse.jetty.rewrite.handler.HeaderPatternRule">
   @@ -99,6 +100,7 @@
              </New>
            </Arg>
          </Call>
   +-->
          <Call name="addRule">
            <Arg>
              <New class="org.eclipse.jetty.rewrite.handler.HeaderPatternRule">
   Index: solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java
   IDEA additional info:
   Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
   <+>UTF-8
   ===================================================================
   diff --git a/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java b/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java
   --- a/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java	(revision 2fb8f9e3734eb9572c701a7e1a1a9834a94f4a38)
   +++ b/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java	(date 1692260572052)
   @@ -16,11 +16,13 @@
     */
    package org.apache.solr.servlet;
    
   +import com.google.common.net.HttpHeaders;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.nio.charset.StandardCharsets;
   +import java.util.stream.Collectors;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.commons.io.output.CloseShieldOutputStream;
   @@ -37,6 +39,8 @@
      // check system properties for whether or not admin UI is disabled, default is false
      private static final boolean disabled =
          Boolean.parseBoolean(System.getProperty("disableAdminUI", "false"));
   +  // Any system property that starts with this prefix will be added to the CSP connect-src
   +  public static final String SYSPROP_CSP_HOSTS_PREFIX = "solr.ui.csp.hosts";
    
      @Override
      public void doGet(HttpServletRequest _request, HttpServletResponse _response) throws IOException {
   @@ -60,6 +64,12 @@
          if (in != null && cores != null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
   +        String connectSrc = generateCspConnectSrc();
   +        response.setHeader(
   +            HttpHeaders.CONTENT_SECURITY_POLICY,
   +            "default-src 'none'; base-uri 'none'; connect-src "
   +                + connectSrc
   +                + "; form-action 'self'; font-src 'self'; frame-ancestors 'none'; img-src 'self' data:; media-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; worker-src 'self';");
    
            // We have to close this to flush OutputStreamWriter buffer
            try (Writer out =
   @@ -76,4 +86,18 @@
          }
        }
      }
   +
   +  /**
   +   * Iterate all system properties with prefix {@link #SYSPROP_CSP_HOSTS_PREFIX} and concatenate
   +   * them into a space separated string that can be use in CSP
   +   */
   +  private String generateCspConnectSrc() {
   +    var props =
   +        System.getProperties().keySet().stream()
   +            .filter(k -> k instanceof String && ((String) k).startsWith(SYSPROP_CSP_HOSTS_PREFIX))
   +            .map(key -> System.getProperty((String) key))
   +            .collect(Collectors.toList());
   +    props.add("'self'");
   +    return String.join(" ", props);
   +  }
    }
   Index: solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java
   IDEA additional info:
   Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
   <+>UTF-8
   ===================================================================
   diff --git a/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java b/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java
   --- a/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java	(revision 2fb8f9e3734eb9572c701a7e1a1a9834a94f4a38)
   +++ b/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java	(date 1692260035611)
   @@ -19,6 +19,7 @@
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.lang.invoke.MethodHandles;
   +import java.net.URI;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Path;
   @@ -63,6 +64,7 @@
    import org.apache.solr.security.ConfigEditablePlugin;
    import org.apache.solr.security.jwt.JWTAuthPlugin.JWTAuthenticationResponse.AuthCode;
    import org.apache.solr.security.jwt.api.ModifyJWTAuthPluginConfigAPI;
   +import org.apache.solr.servlet.LoadAdminUiServlet;
    import org.apache.solr.util.CryptoKeys;
    import org.eclipse.jetty.client.api.Request;
    import org.jose4j.jwa.AlgorithmConstraints;
   @@ -282,10 +284,25 @@
        }
    
        initConsumer();
   +    registerTokenEndpointForCsp();
    
        lastInitTime = Instant.now();
      }
    
   +  /** Record Issuer URL as a system property so it can be picked up and sent to Admin UI as CSP */
   +  private void registerTokenEndpointForCsp() {
   +    final String syspropName = LoadAdminUiServlet.SYSPROP_CSP_HOSTS_PREFIX + ".jwt";
   +    String url = !issuerConfigs.isEmpty() ? getPrimaryIssuer().getTokenEndpoint() : null;
   +    if (url != null) {
   +      URI uri = URI.create(url);
   +      System.setProperty(
   +          syspropName,
   +          String.format(Locale.ROOT, "%s://%s:*", uri.getScheme(), uri.getHost()));
   +    } else {
   +      System.clearProperty(syspropName);
   +    }
   +  }
   +
      /**
       * Given a configuration object of a file name or list of file names, read X509 certificates from
       * each file
   ```
   
   The only problem with this is that now the CSP header is only set when loading the admin UI, not for all the API endpoints as it used to be. Is there a way to have Jetty add the header only if the servlet has not added it already?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1296859919


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   Here's a patch that sets CSP dynamically. Verified the headers get correctly set, but not yet spun it up with true JWT plugin, will be able to do that next week.
   
   ```patch
   Index: solr/server/etc/jetty.xml
   IDEA additional info:
   Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
   <+>UTF-8
   ===================================================================
   diff --git a/solr/server/etc/jetty.xml b/solr/server/etc/jetty.xml
   --- a/solr/server/etc/jetty.xml	(revision 2fb8f9e3734eb9572c701a7e1a1a9834a94f4a38)
   +++ b/solr/server/etc/jetty.xml	(date 1692202681699)
   @@ -90,6 +90,7 @@
          <Set name="originalPathAttribute">requestedPath</Set>
    
          <!-- security-related headers -->
   +<!-- TODO: SOLR-16896 - csp is now set from Java backend
          <Call name="addRule">
            <Arg>
              <New class="org.eclipse.jetty.rewrite.handler.HeaderPatternRule">
   @@ -99,6 +100,7 @@
              </New>
            </Arg>
          </Call>
   +-->
          <Call name="addRule">
            <Arg>
              <New class="org.eclipse.jetty.rewrite.handler.HeaderPatternRule">
   Index: solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java
   IDEA additional info:
   Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
   <+>UTF-8
   ===================================================================
   diff --git a/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java b/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java
   --- a/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java	(revision 2fb8f9e3734eb9572c701a7e1a1a9834a94f4a38)
   +++ b/solr/core/src/java/org/apache/solr/servlet/LoadAdminUiServlet.java	(date 1692260572052)
   @@ -16,11 +16,13 @@
     */
    package org.apache.solr.servlet;
    
   +import com.google.common.net.HttpHeaders;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.nio.charset.StandardCharsets;
   +import java.util.stream.Collectors;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.commons.io.output.CloseShieldOutputStream;
   @@ -37,6 +39,8 @@
      // check system properties for whether or not admin UI is disabled, default is false
      private static final boolean disabled =
          Boolean.parseBoolean(System.getProperty("disableAdminUI", "false"));
   +  // Any system property that starts with this prefix will be added to the CSP connect-src
   +  public static final String SYSPROP_CSP_HOSTS_PREFIX = "solr.ui.csp.hosts";
    
      @Override
      public void doGet(HttpServletRequest _request, HttpServletResponse _response) throws IOException {
   @@ -60,6 +64,12 @@
          if (in != null && cores != null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
   +        String connectSrc = generateCspConnectSrc();
   +        response.setHeader(
   +            HttpHeaders.CONTENT_SECURITY_POLICY,
   +            "default-src 'none'; base-uri 'none'; connect-src "
   +                + connectSrc
   +                + "; form-action 'self'; font-src 'self'; frame-ancestors 'none'; img-src 'self' data:; media-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'; worker-src 'self';");
    
            // We have to close this to flush OutputStreamWriter buffer
            try (Writer out =
   @@ -76,4 +86,18 @@
          }
        }
      }
   +
   +  /**
   +   * Iterate all system properties with prefix {@link #SYSPROP_CSP_HOSTS_PREFIX} and concatenate
   +   * them into a space separated string that can be use in CSP
   +   */
   +  private String generateCspConnectSrc() {
   +    var props =
   +        System.getProperties().keySet().stream()
   +            .filter(k -> k instanceof String && ((String) k).startsWith(SYSPROP_CSP_HOSTS_PREFIX))
   +            .map(key -> System.getProperty((String) key))
   +            .collect(Collectors.toList());
   +    props.add("'self'");
   +    return String.join(" ", props);
   +  }
    }
   Index: solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java
   IDEA additional info:
   Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
   <+>UTF-8
   ===================================================================
   diff --git a/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java b/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java
   --- a/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java	(revision 2fb8f9e3734eb9572c701a7e1a1a9834a94f4a38)
   +++ b/solr/modules/jwt-auth/src/java/org/apache/solr/security/jwt/JWTAuthPlugin.java	(date 1692260035611)
   @@ -19,6 +19,7 @@
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.lang.invoke.MethodHandles;
   +import java.net.URI;
    import java.nio.charset.StandardCharsets;
    import java.nio.file.Files;
    import java.nio.file.Path;
   @@ -63,6 +64,7 @@
    import org.apache.solr.security.ConfigEditablePlugin;
    import org.apache.solr.security.jwt.JWTAuthPlugin.JWTAuthenticationResponse.AuthCode;
    import org.apache.solr.security.jwt.api.ModifyJWTAuthPluginConfigAPI;
   +import org.apache.solr.servlet.LoadAdminUiServlet;
    import org.apache.solr.util.CryptoKeys;
    import org.eclipse.jetty.client.api.Request;
    import org.jose4j.jwa.AlgorithmConstraints;
   @@ -282,10 +284,25 @@
        }
    
        initConsumer();
   +    registerTokenEndpointForCsp();
    
        lastInitTime = Instant.now();
      }
    
   +  /** Record Issuer URL as a system property so it can be picked up and sent to Admin UI as CSP */
   +  private void registerTokenEndpointForCsp() {
   +    final String syspropName = LoadAdminUiServlet.SYSPROP_CSP_HOSTS_PREFIX + ".jwt";
   +    String url = !issuerConfigs.isEmpty() ? getPrimaryIssuer().getTokenEndpoint() : null;
   +    if (url != null) {
   +      URI uri = URI.create(url);
   +      System.setProperty(
   +          syspropName,
   +          String.format(Locale.ROOT, "%s://%s:%s", uri.getScheme(), uri.getHost(), uri.getPort()));
   +    } else {
   +      System.clearProperty(syspropName);
   +    }
   +  }
   +
      /**
       * Given a configuration object of a file name or list of file names, read X509 certificates from
       * each file
   ```
   
   The only problem with this is that now the CSP header is only set when loading the admin UI, not for all the API endpoints as it used to be. Is there a way to have Jetty add the header only if the servlet has not added it already?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1298542144


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   I feel your pain as I am facing the same issue to test the code.
   I had it as a one PR but was asked by another committer to split it to facilitate its review by different committers as not everybody is familiar with the front-end part of Solr.
   
   I think if we could merge the back-end one it would make it much easier to test the front-end part.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1315545934


##########
solr/webapp/web/js/angular/services.js:
##########
@@ -286,8 +286,74 @@ solrAdminServices.factory('System',
         })
 }])
 .factory('AuthenticationService',
-    ['base64', function (base64) {
-        var service = {};
+    ['base64', '$resource', function (base64, $resource) {
+      var service = {};
+
+      service.getOAuthTokens = function (url, data) {
+        var serializedData = serialize(data);
+        var resource = $resource(url, {}, {
+          getToken: {
+            method: 'POST',
+            timeout: 10000,
+            headers: {
+              'Content-Type': 'application/x-www-form-urlencoded',
+              'X-Requested-With': undefined // Set this header to undefined to prevent preflight requests
+            },
+            transformResponse: function (data) {
+              return angular.fromJson(data);
+            }
+          }
+        });
+        return resource.getToken({}, serializedData).$promise;
+      };
+
+      var codeChallengeMethod = "S256";
+      service.getCodeChallengeMethod = function getCodeChallengeMethod() {
+        return codeChallengeMethod;
+      }
+
+      service.generateCodeVerifier = function generateCodeVerifier() {
+        var codeVerifier = '';
+        var possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
+        for (var i = 0; i < 96; i++) {
+          codeVerifier += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
+        }
+        return codeVerifier;
+      }
+
+      service.generateCodeChallengeFromVerifier = async function generateCodeChallengeFromVerifier(v) {
+        var hashed = await sha256(v);
+        var base64encoded = base64urlencode(hashed);
+        return base64encoded;
+      }
+
+      function sha256(str) {
+        const encoder = new TextEncoder();
+        return window.crypto.subtle.digest("SHA-256", encoder.encode(str));

Review Comment:
   There is https://www.npmjs.com/package/@aws-crypto/sha256-js as an alternative. Will check



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1324818462


##########
solr/webapp/web/js/angular/services.js:
##########
@@ -286,8 +286,74 @@ solrAdminServices.factory('System',
         })
 }])
 .factory('AuthenticationService',
-    ['base64', function (base64) {
-        var service = {};
+    ['base64', '$resource', function (base64, $resource) {
+      var service = {};
+
+      service.getOAuthTokens = function (url, data) {
+        var serializedData = serialize(data);
+        var resource = $resource(url, {}, {
+          getToken: {
+            method: 'POST',
+            timeout: 10000,
+            headers: {
+              'Content-Type': 'application/x-www-form-urlencoded',
+              'X-Requested-With': undefined // Set this header to undefined to prevent preflight requests
+            },
+            transformResponse: function (data) {
+              return angular.fromJson(data);
+            }
+          }
+        });
+        return resource.getToken({}, serializedData).$promise;
+      };
+
+      var codeChallengeMethod = "S256";
+      service.getCodeChallengeMethod = function getCodeChallengeMethod() {
+        return codeChallengeMethod;
+      }
+
+      service.generateCodeVerifier = function generateCodeVerifier() {
+        var codeVerifier = '';
+        var possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
+        for (var i = 0; i < 96; i++) {
+          codeVerifier += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
+        }
+        return codeVerifier;
+      }
+
+      service.generateCodeChallengeFromVerifier = async function generateCodeChallengeFromVerifier(v) {
+        var hashed = await sha256(v);
+        var base64encoded = base64urlencode(hashed);
+        return base64encoded;
+      }
+
+      function sha256(str) {
+        const encoder = new TextEncoder();
+        return window.crypto.subtle.digest("SHA-256", encoder.encode(str));

Review Comment:
   Ddid more testes on a remote cluster worked nicely.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on PR #1791:
URL: https://github.com/apache/solr/pull/1791#issuecomment-1663529357

   Hi @risdenk 
   As @janhoy is on vacation, can you please have another reviewer look at this? Thank you.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1301661134


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";

Review Comment:
   Thanks for fixing



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on PR #1791:
URL: https://github.com/apache/solr/pull/1791#issuecomment-1684023770

   > Read through with some comments.
   > 
   > A pity we don't have unit tests for frontend, cause there are some of this which is hard to test, especially error cases.
   > 
   > I have not spun this up yet. May have a chance to test it with a KeyCloak protected cluster next week, where we currently use Solr with imiplicit flow.
   > 
   > **Using a standard js lib?** I see you implemented PKCE flow with custom JS, which was not as bad/large as I feared it would be. Still, I have a feeling we should delegate all of this to some standard JS lib at some point, which would buy us token background refresh capabilities as well as a more tested and tried impl. [When I had a look at this a few years ago](https://issues.apache.org/jira/browse/SOLR-15434?focusedCommentId=17419625&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-17419625) I found some OpenID js libs, but most of them tendend to be coupled with React or abandoned. I jumped back and found that [oidc-client-ts](https://authts.github.io/oidc-client-ts/) seems to be well maintained.
   
   Couldn't find an easy way to integrate third party libraries without some heavy changes in the front-end code. Given we don't have unit tests and the non maintainability of AngularJS, I thought it'd better, cleaner an easier to maintain/debug if we code it ourselves, especially this is straightforward logic (catch the returned code from the redirection and use it to make a second call to get the tokens.)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on PR #1791:
URL: https://github.com/apache/solr/pull/1791#issuecomment-1704350022

   Backend PR merged, meaning we are unblocked to finalize this too. I'm going to mark the JIRA as blocker for 9.4 since the ref guide already promises the functionality.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1301171535


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   I can manage a few git merge commands. But you'd perhaps get broader review with a combined PR. Have you given my patch a try? Going to test it in a real environment today...



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1298542144


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";
+              console.log("Callback: authorization_flow : " +flow);
+              var isCodePKCE = flow == 'code_pkce';
+              if (isCodePKCE) {
+                // code flow with PKCE
+                console.debug("Callback. Using code flow with PKCE");
+                var code = hp['code'];
+                var tokenEndpoint = $scope.authData['tokenEndpoint'];
+                // concurrent Solr API calls will trigger 401 and erase session's "auth.realm" in app.js
+                // save it before it's erased
+                var authRealm = sessionStorage.getItem("auth.realm");
+
+                var data = {
+                  'grant_type': 'authorization_code',
+                  'code': code,
+                  'redirect_uri': $window.location.href.split('#')[0],
+                  'scope': "openid " + $scope.authData['scope'],
+                  'code_verifier': sessionStorage.getItem('codeVerifier'),
+                  "client_id": $scope.authData['client_id']
+                };
 
-                  if (errorText === "") {
-                    sessionStorage.setItem("auth.username", payload['sub']);
-                    sessionStorage.setItem("auth.header", "Bearer " + hp['access_token']);
-                    sessionStorage.removeItem("auth.statusText");
-                    sessionStorage.removeItem("auth.stateRandom");
-                    sessionStorage.removeItem("auth.wwwAuthHeader");
-                    console.log("User " + payload['sub'] + " is logged in");
-                    var redirectTo = sessionStorage.getItem("auth.location");
-                    console.log("Redirecting to stored location " + redirectTo);
-                    sessionStorage.setItem("auth.state", "authenticated");
-                    sessionStorage.removeItem("http401");
-                    $location.path(redirectTo).hash("");
+                console.debug(`Callback. Got code: ${code} \nCalling token endpoint:: ${tokenEndpoint} `);
+                AuthenticationService.getOAuthTokens(tokenEndpoint, data).then(function(response) {

Review Comment:
   I feel your pain as I am facing the same issue to test the code.
   I had it as a one PIR by was asked by another committer to split it to facilitate its review by different committers as not everybody is familiar with the front-end part of Solr.
   
   I think if we could merge the back-end one it would make much easier to test



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1298538572


##########
solr/webapp/web/js/angular/services.js:
##########
@@ -286,8 +286,74 @@ solrAdminServices.factory('System',
         })
 }])
 .factory('AuthenticationService',
-    ['base64', function (base64) {
-        var service = {};
+    ['base64', '$resource', function (base64, $resource) {
+      var service = {};
+
+      service.getOAuthTokens = function (url, data) {
+        var serializedData = serialize(data);
+        var resource = $resource(url, {}, {
+          getToken: {
+            method: 'POST',
+            timeout: 10000,
+            headers: {
+              'Content-Type': 'application/x-www-form-urlencoded',
+              'X-Requested-With': undefined // Set this header to undefined to prevent preflight requests
+            },
+            transformResponse: function (data) {
+              return angular.fromJson(data);
+            }
+          }
+        });
+        return resource.getToken({}, serializedData).$promise;
+      };
+
+      var codeChallengeMethod = "S256";
+      service.getCodeChallengeMethod = function getCodeChallengeMethod() {
+        return codeChallengeMethod;
+      }
+
+      service.generateCodeVerifier = function generateCodeVerifier() {
+        var codeVerifier = '';
+        var possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
+        for (var i = 0; i < 96; i++) {
+          codeVerifier += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
+        }
+        return codeVerifier;
+      }
+
+      service.generateCodeChallengeFromVerifier = async function generateCodeChallengeFromVerifier(v) {
+        var hashed = await sha256(v);
+        var base64encoded = base64urlencode(hashed);
+        return base64encoded;
+      }
+
+      function sha256(str) {
+        const encoder = new TextEncoder();
+        return window.crypto.subtle.digest("SHA-256", encoder.encode(str));

Review Comment:
   That's a good catch. I only tested on localhost and https hosts. I think you're right, this would't work on http. 
   Why do you suggest? Keep it as it is and require https for this plugin, or change the code to support http?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] epugh commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "epugh (via GitHub)" <gi...@apache.org>.
epugh commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1296072822


##########
solr/webapp/web/js/angular/controllers/login.js:
##########
@@ -60,92 +60,169 @@ solrAdminApp.controller('LoginController',
             var hp = AuthenticationService.decodeHashParams(hash);
             var expectedState = sessionStorage.getItem("auth.stateRandom") + "_" + sessionStorage.getItem("auth.location");
             sessionStorage.setItem("auth.state", "error");
-            if (hp['access_token'] && hp['token_type'] && hp['state']) {
-              // Validate state
-              if (hp['state'] !== expectedState) {
-                $scope.error = "Problem with auth callback";
-                console.log("Expected state param " + expectedState + " but got " + hp['state']);
-                errorText += "Invalid values in state parameter. ";
-              }
-              // Validate token type
-              if (hp['token_type'].toLowerCase() !== "bearer") {
-                console.log("Expected token_type param 'bearer', but got " + hp['token_type']);
-                errorText += "Invalid values in token_type parameter. ";
-              }
-              // Unpack ID token and validate nonce, get username
-              if (hp['id_token']) {
-                var idToken = hp['id_token'].split(".");
-                if (idToken.length === 3) {
-                  var payload = AuthenticationService.decodeJwtPart(idToken[1]);
-                  if (!payload['nonce'] || payload['nonce'] !== sessionStorage.getItem("auth.nonce")) {
-                    errorText += "Invalid 'nonce' value, possible attack detected. Please log in again. ";
-                  }
+            $scope.authData = AuthenticationService.getAuthDataHeader();
+            if (!validateState(hp['state'], expectedState)) {
+              $scope.error = "Problems with OpenID callback";
+              $scope.errorDescription = errorText;
+              $scope.http401 = "true";
+              sessionStorage.setItem("auth.state", "error");
+            }
+            else {
+              // for backward compatibility default flow to 'implicit'
+              var flow = $scope.authData ? $scope.authData['authorization_flow'] : "implicit";

Review Comment:
   would this simplify life too if we got the Solr CLI plugged in?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy commented on a diff in pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy commented on code in PR #1791:
URL: https://github.com/apache/solr/pull/1791#discussion_r1301664112


##########
solr/webapp/web/js/angular/services.js:
##########
@@ -286,8 +286,74 @@ solrAdminServices.factory('System',
         })
 }])
 .factory('AuthenticationService',
-    ['base64', function (base64) {
-        var service = {};
+    ['base64', '$resource', function (base64, $resource) {
+      var service = {};
+
+      service.getOAuthTokens = function (url, data) {
+        var serializedData = serialize(data);
+        var resource = $resource(url, {}, {
+          getToken: {
+            method: 'POST',
+            timeout: 10000,
+            headers: {
+              'Content-Type': 'application/x-www-form-urlencoded',
+              'X-Requested-With': undefined // Set this header to undefined to prevent preflight requests
+            },
+            transformResponse: function (data) {
+              return angular.fromJson(data);
+            }
+          }
+        });
+        return resource.getToken({}, serializedData).$promise;
+      };
+
+      var codeChallengeMethod = "S256";
+      service.getCodeChallengeMethod = function getCodeChallengeMethod() {
+        return codeChallengeMethod;
+      }
+
+      service.generateCodeVerifier = function generateCodeVerifier() {
+        var codeVerifier = '';
+        var possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
+        for (var i = 0; i < 96; i++) {
+          codeVerifier += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
+        }
+        return codeVerifier;
+      }
+
+      service.generateCodeChallengeFromVerifier = async function generateCodeChallengeFromVerifier(v) {
+        var hashed = await sha256(v);
+        var base64encoded = base64urlencode(hashed);
+        return base64encoded;
+      }
+
+      function sha256(str) {
+        const encoder = new TextEncoder();
+        return window.crypto.subtle.digest("SHA-256", encoder.encode(str));

Review Comment:
   I'd prefer if we don't introduce a hard requirement for SSL on Solr when doing JWT, in this PR, as people may be running dev and test envs in this mode. But if it is very hard to avoid we can document our way out of this in upgrade notes...



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] janhoy merged pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "janhoy (via GitHub)" <gi...@apache.org>.
janhoy merged PR #1791:
URL: https://github.com/apache/solr/pull/1791


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org


[GitHub] [solr] laminelam commented on pull request #1791: add support of OAuth 2.0/OIDC 'code with PKCE' flow (front-end)

Posted by "laminelam (via GitHub)" <gi...@apache.org>.
laminelam commented on PR #1791:
URL: https://github.com/apache/solr/pull/1791#issuecomment-1642059052

   > I think there are a bunch of `console.log` that could be `console.error` if its an error or `console.debug` if its just debug logging.
   
   Thanks @risdenk 
   Done (was following the existing logging style)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@solr.apache.org
For additional commands, e-mail: issues-help@solr.apache.org