From 7d855efb1fe6b97c5d87492f67ed6aefd31b2474 Mon Sep 17 00:00:00 2001
From: Denys Konovalov <kontakt@denyskon.de>
Date: Sat, 3 Jun 2023 05:59:28 +0200
Subject: [PATCH] Allow for PKCE flow without client secret + add docs (#25033)

The PKCE flow according to [RFC
7636](https://datatracker.ietf.org/doc/html/rfc7636) allows for secure
authorization without the requirement to provide a client secret for the
OAuth app.

It is implemented in Gitea since #5378 (v1.8.0), however without being
able to omit client secret.
Since #21316 Gitea supports setting client type at OAuth app
registration.

As public clients are already forced to use PKCE since #21316, in this
PR the client secret check is being skipped if a public client is
detected. As Gitea seems to implement PKCE authorization correctly
according to the spec, this would allow for PKCE flow without providing
a client secret.

Also add some docs for it, please check language as I'm not a native
English speaker.

Closes #17107
Closes #25047
---
 .../doc/development/oauth2-provider.en-us.md  | 78 +++++++++++++++++--
 routers/web/auth/oauth.go                     |  4 +-
 tests/integration/oauth_test.go               | 23 ++++++
 3 files changed, 96 insertions(+), 9 deletions(-)

diff --git a/docs/content/doc/development/oauth2-provider.en-us.md b/docs/content/doc/development/oauth2-provider.en-us.md
index cf045ac2fe..5f9960a477 100644
--- a/docs/content/doc/development/oauth2-provider.en-us.md
+++ b/docs/content/doc/development/oauth2-provider.en-us.md
@@ -1,5 +1,5 @@
 ---
-date: "2019-04-19:44:00+01:00"
+date: "2023-06-01T08:40:00+08:00"
 title: "OAuth2 provider"
 slug: "oauth2-provider"
 weight: 41
@@ -40,7 +40,7 @@ At the moment Gitea only supports the [**Authorization Code Grant**](https://too
 - [Proof Key for Code Exchange (PKCE)](https://tools.ietf.org/html/rfc7636)
 - [OpenID Connect (OIDC)](https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth)
 
-To use the Authorization Code Grant as a third party application it is required to register a new application via the "Settings" (`/user/settings/applications`) section of the settings.
+To use the Authorization Code Grant as a third party application it is required to register a new application via the "Settings" (`/user/settings/applications`) section of the settings. To test or debug you can use the web-tool https://oauthdebugger.com/.
 
 ## Scopes
 
@@ -87,17 +87,19 @@ Gitea supports both confidential and public client types, [as defined by RFC 674
 
 For public clients, a redirect URI of a loopback IP address such as `http://127.0.0.1/` allows any port. Avoid using `localhost`, [as recommended by RFC 8252](https://datatracker.ietf.org/doc/html/rfc8252#section-8.3).
 
-## Example
+## Examples
+
+### Confidential client
 
 **Note:** This example does not use PKCE.
 
-1. Redirect to user to the authorization endpoint in order to get their consent for accessing the resources:
+1. Redirect the user to the authorization endpoint in order to get their consent for accessing the resources:
 
    ```curl
    https://[YOUR-GITEA-URL]/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code&state=STATE
    ```
 
-   The `CLIENT_ID` can be obtained by registering an application in the settings. The `STATE` is a random string that will be send back to your application after the user authorizes. The `state` parameter is optional but should be used to prevent CSRF attacks.
+   The `CLIENT_ID` can be obtained by registering an application in the settings. The `STATE` is a random string that will be sent back to your application after the user authorizes. The `state` parameter is optional, but should be used to prevent CSRF attacks.
 
    ![Authorization Page](/authorize.png)
 
@@ -107,7 +109,7 @@ For public clients, a redirect URI of a loopback IP address such as `http://127.
    https://[REDIRECT_URI]?code=RETURNED_CODE&state=STATE
    ```
 
-2. Using the provided `code` from the redirect, you can request a new application and refresh token. The access token endpoints accepts POST requests with `application/json` and `application/x-www-form-urlencoded` body, for example:
+2. Using the provided `code` from the redirect, you can request a new application and refresh token. The access token endpoint accepts POST requests with `application/json` and `application/x-www-form-urlencoded` body, for example:
 
    ```curl
    POST https://[YOUR-GITEA-URL]/login/oauth/access_token
@@ -134,7 +136,69 @@ For public clients, a redirect URI of a loopback IP address such as `http://127.
    }
    ```
 
-   The `CLIENT_SECRET` is the unique secret code generated for this application. Please note that the secret will only be visible after you created/registered the application with Gitea and cannot be recovered. If you lose the secret you must regenerate the secret via the application's settings.
+   The `CLIENT_SECRET` is the unique secret code generated for this application. Please note that the secret will only be visible after you created/registered the application with Gitea and cannot be recovered. If you lose the secret, you must regenerate the secret via the application's settings.
+
+   The `REDIRECT_URI` in the `access_token` request must match the `REDIRECT_URI` in the `authorize` request.
+
+3. Use the `access_token` to make [API requests](https://docs.gitea.io/en-us/api-usage#oauth2) to access the user's resources.
+
+### Public client (PKCE)
+
+PKCE (Proof Key for Code Exchange) is an extension to the OAuth flow which allows for a secure credential exchange without the requirement to provide a client secret.
+
+**Note**: Please ensure you have registered your OAuth application as a public client.
+
+To achieve this, you have to provide a `code_verifier` for every authorization request. A `code_verifier` has to be a random string with a minimum length of 43 characters and a maximum length of 128 characters. It can contain alphanumeric characters as well as the characters `-`, `.`, `_`  and `~`.
+
+Using this `code_verifier` string, a new one called `code_challenge` is created by using one of two methods:
+
+- If you have the required functionality on your client, set `code_challenge` to be a URL-safe base64-encoded string of the SHA256 hash of `code_verifier`. In that case, your `code_challenge_method` becomes `S256`.
+- If you are unable to do so, you can provide your `code_verifier` as a plain string to `code_challenge`. Then you have to set your `code_challenge_method` as `plain`.
+
+After you have generated this values, you can continue with your request.
+
+1. Redirect the user to the authorization endpoint in order to get their consent for accessing the resources:
+
+   ```curl
+   https://[YOUR-GITEA-URL]/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code&code_challenge_method=CODE_CHALLENGE_METHOD&code_challenge=CODE_CHALLENGE&state=STATE
+   ```
+
+   The `CLIENT_ID` can be obtained by registering an application in the settings. The `STATE` is a random string that will be sent back to your application after the user authorizes. The `state` parameter is optional, but should be used to prevent CSRF attacks.
+
+   ![Authorization Page](/authorize.png)
+
+   The user will now be asked to authorize your application. If they authorize it, the user will be redirected to the `REDIRECT_URL`, for example:
+
+   ```curl
+   https://[REDIRECT_URI]?code=RETURNED_CODE&state=STATE
+   ```
+
+2. Using the provided `code` from the redirect, you can request a new application and refresh token. The access token endpoint accepts POST requests with `application/json` and `application/x-www-form-urlencoded` body, for example:
+
+   ```curl
+   POST https://[YOUR-GITEA-URL]/login/oauth/access_token
+   ```
+
+   ```json
+   {
+     "client_id": "YOUR_CLIENT_ID",
+     "code": "RETURNED_CODE",
+     "grant_type": "authorization_code",
+     "redirect_uri": "REDIRECT_URI",
+     "code_verifier": "CODE_VERIFIER",
+   }
+   ```
+
+   Response:
+
+   ```json
+   {
+     "access_token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJnbnQiOjIsInR0IjowLCJleHAiOjE1NTUxNzk5MTIsImlhdCI6MTU1NTE3NjMxMn0.0-iFsAwBtxuckA0sNZ6QpBQmywVPz129u75vOM7wPJecw5wqGyBkmstfJHAjEOqrAf_V5Z-1QYeCh_Cz4RiKug",
+     "token_type": "bearer",
+     "expires_in": 3600,
+     "refresh_token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJnbnQiOjIsInR0IjoxLCJjbnQiOjEsImV4cCI6MTU1NzgwNDMxMiwiaWF0IjoxNTU1MTc2MzEyfQ.S_HZQBy4q9r5SEzNGNIoFClT43HPNDbUdHH-GYNYYdkRfft6XptJBkUQscZsGxOW975Yk6RbgtGvq1nkEcklOw"
+   }
+   ```
 
    The `REDIRECT_URI` in the `access_token` request must match the `REDIRECT_URI` in the `authorize` request.
 
diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go
index 92a06e7c14..80f149d806 100644
--- a/routers/web/auth/oauth.go
+++ b/routers/web/auth/oauth.go
@@ -695,7 +695,7 @@ func handleRefreshToken(ctx *context.Context, form forms.AccessTokenForm, server
 	}
 	// "The authorization server MUST ... require client authentication for confidential clients"
 	// https://datatracker.ietf.org/doc/html/rfc6749#section-6
-	if !app.ValidateClientSecret([]byte(form.ClientSecret)) {
+	if app.ConfidentialClient && !app.ValidateClientSecret([]byte(form.ClientSecret)) {
 		errorDescription := "invalid client secret"
 		if form.ClientSecret == "" {
 			errorDescription = "invalid empty client secret"
@@ -753,7 +753,7 @@ func handleAuthorizationCode(ctx *context.Context, form forms.AccessTokenForm, s
 		})
 		return
 	}
-	if !app.ValidateClientSecret([]byte(form.ClientSecret)) {
+	if app.ConfidentialClient && !app.ValidateClientSecret([]byte(form.ClientSecret)) {
 		errorDescription := "invalid client secret"
 		if form.ClientSecret == "" {
 			errorDescription = "invalid empty client secret"
diff --git a/tests/integration/oauth_test.go b/tests/integration/oauth_test.go
index 9649b256a9..e9b69f5f14 100644
--- a/tests/integration/oauth_test.go
+++ b/tests/integration/oauth_test.go
@@ -120,6 +120,29 @@ func TestAccessTokenExchange(t *testing.T) {
 	assert.True(t, len(parsed.RefreshToken) > 10)
 }
 
+func TestAccessTokenExchangeWithPublicClient(t *testing.T) {
+	defer tests.PrepareTestEnv(t)()
+	req := NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
+		"grant_type":    "authorization_code",
+		"client_id":     "ce5a1322-42a7-11ed-b878-0242ac120002",
+		"redirect_uri":  "http://127.0.0.1",
+		"code":          "authcodepublic",
+		"code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt",
+	})
+	resp := MakeRequest(t, req, http.StatusOK)
+	type response struct {
+		AccessToken  string `json:"access_token"`
+		TokenType    string `json:"token_type"`
+		ExpiresIn    int64  `json:"expires_in"`
+		RefreshToken string `json:"refresh_token"`
+	}
+	parsed := new(response)
+
+	assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed))
+	assert.True(t, len(parsed.AccessToken) > 10)
+	assert.True(t, len(parsed.RefreshToken) > 10)
+}
+
 func TestAccessTokenExchangeJSON(t *testing.T) {
 	defer tests.PrepareTestEnv(t)()
 	req := NewRequestWithJSON(t, "POST", "/login/oauth/access_token", map[string]string{