Skip to content

The Unified and Autonomous Development Platform

feat: add OAuth2 and OpenID Connect provider

Robin Shenc772f41b990c
diff --git a/AGENTS.md b/AGENTS.md
index 3e8c4dd621..885fcbd5f7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,19 +13,43 @@ files are generated automatically.
Do not add tests for trivial or minor changes unless the user explicitly asks
for them.
+Do not run Maven after changing files unless the user explicitly asks for it.
+
Prefer field injection over constructor injection wherever possible for
`@Singleton` services and Wicket components/pages.
+**Service Permission Contract:** Public service methods that check a user's
+permissions must accept the user's `Subject` instead of a `User` for those
+checks. A `Subject` parameter signals permission checks; without one, the
+method runs without permission checks. Internal methods may accept `User`
+and leave authorization to their callers. Document any exception explicitly
+on the method.
+
+**Open Session in View:** A single Wicket request cycle is normally handled
+within a single Hibernate session. OneDev opens the session at the start of
+the request cycle and closes it afterwards.
+
+**Hibernate Session Isolation:** Do not share Hibernate-loaded entity objects
+across Hibernate sessions. For example, a project loaded by ID during Wicket
+page initialization must not be reused in a link's `onClick` listener, which
+runs in another request cycle and Hibernate session. Store the project ID
+instead, and load the project again using that ID in the listener's session.
+
+**Wicket Serialization Safety:** Wicket pages, behaviors, and components are
+serialized to disk after a request is processed. Their serialized state must
+not contain any Hibernate entities. Store Hibernate entities either in
+`transient` fields or in detachable Wicket models, and detach those models
+in the `onDetach()` method of the relevant page, behavior, or component.
+
+Use the bean editor for settings UI whenever possible. Style UI appropriately
+to look polished and consistent with other pages. Prefer existing CSS classes
+from Bootstrap or `base.css` whenever possible.
+
Users may continue privileged work in an existing session after their
privileges are revoked. Revoked privileges must be denied in a new session.
Do not report continued access within the existing session as a security bug
or require immediate revocation within that session.
-For local development, start the OneDev server with `./dev.sh run` from the
-repository root. The server can hot-load changed classes. Use `./dev.sh build`
-to compile them; the first run performs a full compile, while subsequent runs
-compile only the changes. Watch the server console for reload errors and
-restart the server if one occurs.
-
-If you start the development server for a task, stop it with `./dev.sh stop`
-when the task is finished.
+Run `./dev.sh prod` from repository root to start dev server if you want to
+do some tasks with the live instance. Make sure to stop it by running
+`./dev.sh stop` after tasks are finished.
diff --git a/doc/oauth-provider.md b/doc/oauth-provider.md
new file mode 100644
index 0000000000..b2a396c8fc
--- /dev/null
+++ b/doc/oauth-provider.md
@@ -0,0 +1,194 @@
+# OAuth 2.0 and OpenID Connect provider
+
+OneDev uses the bundled Nimbus OAuth 2.0 / OpenID Connect SDK for request parsing,
+responses, PKCE, discovery, token generation and JWT signing. Applications use the
+authorization code flow with S256 PKCE. Implicit, password, client credentials,
+device authorization and dynamic client registration are not supported.
+
+## Provider signing key
+
+A signing key is generated automatically when the provider setting is first
+initialized, enabling the provider by default. Administrators can manage the key
+under **Administration → Keys → OAuth Signing Key**. When the key is deleted, the
+provider endpoints and application pages are unavailable, and the **OAuth
+Applications** and **Authorized Applications** account menu items are hidden.
+
+The same page can regenerate or delete the key. Both actions revoke existing
+authorizations while preserving registered applications. Regeneration replaces
+the public signing key; clients must reload the JWKS and obtain fresh consent.
+Deleting the key disables the provider until a new key is generated. The private
+key is stored in the database and is never displayed. Restarting the server
+preserves existing keys and does not regenerate deleted keys.
+
+## Register an application
+
+Use **OAuth Applications** in your account menu to register and manage applications.
+Administrators can register shared integrations under their own accounts. The owner
+manages the registration; any user can sign in through the application and authorize
+access to their own projects. Every user must give consent, and access is limited
+to that user's permissions.
+
+Click **Add New** to open the registration page. After saving, the application
+opens on its own settings page, where you can copy its client ID and newly generated
+secret. Click an application name in the list to return to its settings.
+
+Register a name, homepage and exact redirect URIs. HTTPS is required except for
+loopback HTTP callbacks (`localhost`, `127.0.0.1`, `[::1]`) and reverse-domain native
+application schemes such as `com.example.app:/callback`. Native schemes are only
+allowed for public clients. Wildcards, fragments and embedded credentials are
+rejected. Public clients using HTTP callbacks to `127.0.0.1` or `[::1]` may choose
+an available port at runtime, as required by
+[RFC 8252](https://www.rfc-editor.org/rfc/rfc8252.html#section-7.3). All other URI components
+must match exactly. Confidential clients and `localhost` callbacks require an
+exact port match. Code exchange must use the complete URI, including the port,
+from the authorization request.
+
+Use a confidential client for a server application that can keep a secret; use a
+public client for a desktop, mobile or browser application. Client secrets are
+shown when generated and stored as hashes. Rotating a secret revokes the
+application's existing authorizations. Both client types must use PKCE.
+
+## Endpoints
+
+Endpoints are relative to the configured OneDev server URL, which is the issuer.
+Use HTTPS in production.
+
+| Purpose | Endpoint | Method |
+| --- | --- | --- |
+| OAuth discovery | `/.well-known/oauth-authorization-server` | GET |
+| OIDC discovery | `/.well-known/openid-configuration` | GET |
+| Authorization and consent | `/~oauth/authorize` | GET |
+| Code exchange and refresh | `/~oauth/token` | POST |
+| Revocation | `/~oauth/revoke` | POST |
+| User information | `/~oauth/userinfo` | GET or POST |
+| Public signing keys | `/~oauth/jwks` | GET |
+
+Token and revocation requests use `application/x-www-form-urlencoded` bodies.
+Confidential clients use `client_secret_basic` or `client_secret_post`; public
+clients send `client_id` without a secret. Send one authentication method per
+request. API and userinfo calls use `Authorization: Bearer <access_token>`.
+Browser clients should perform these calls through their own backend; cross-origin
+token requests are not enabled.
+
+## Scopes and project permissions
+
+Discovery and the registration screen list supported scopes and role descriptions.
+
+| Scope | Access |
+| --- | --- |
+| `openid` | An RS256-signed ID token identifying the OneDev user |
+| `profile` | Name and username through userinfo |
+| `email` | Primary email address and its verification status through userinfo |
+| `offline_access` | Explicitly requests continued access while the user is away |
+| `role:<normalized-name>` | The named role's permissions on projects selected during consent |
+
+At least one supported scope is required. Role scopes use lowercase role names
+with spaces replaced by underscores. Special and non-ASCII characters are UTF-8
+percent-encoded to remain within one scope token. For example, Code Reader has
+scope `role:code_reader`. Use the exact scope values listed in discovery. Pass
+`openid profile role:code_reader` as the scope value to your OAuth client library;
+normal request encoding still applies.
+
+Renaming a role changes its scope if the normalized name changes. Clients must
+request the new scope and obtain fresh consent. Existing grants lose that role's
+project authorizations on their next token exchange or refresh. ID-based scopes
+from earlier versions must also be replaced with name-based scopes and fresh
+consent.
+
+The user selects projects they have permission to manage for the requested roles,
+matching manual access-token authorization. The server checks this permission
+again when consent is submitted. Every requested role applies to
+each selected project and its children that inherit settings. The consent page
+shows the role's detailed permissions. Each project-role authorization applies
+only while the token owner has permission to manage the authorized project,
+matching manual access-token authorization. Losing that permission removes access
+through that authorization, even if the owner retains read access. OAuth tokens
+also receive default project permissions available to logged-in users, just like
+regular access tokens, including for projects not selected during consent.
+Role edits affect existing authorizations, as with personal access tokens.
+
+OAuth grants reuse OneDev's project-role access-token authorizations. They appear
+under **Authorized Applications** and cannot be expanded through the personal
+access-token editor or REST API. System administration and account administration
+permissions are never delegated through role scopes.
+
+## Authorization and token lifecycle
+
+1. Generate a fresh PKCE verifier and its S256 challenge. Redirect to the
+ authorization endpoint with `response_type=code`, `client_id`, the exact
+ `redirect_uri`, `scope`, `state`, `code_challenge` and
+ `code_challenge_method=S256`. Include `nonce` for OIDC.
+2. OneDev signs the user in and asks for consent. Validate the returned `state`.
+3. Exchange the code with `grant_type=authorization_code`, the same `redirect_uri`
+ and `code_verifier`, authenticating the client as above. Codes expire after two
+ minutes and may be exchanged once.
+4. Use the access token for the OneDev API. OIDC clients validate the ID token's
+ signature using JWKS, issuer, audience, expiry and nonce. Its `sub` is the user's
+ stable OneDev ID. Fetch requested profile/email claims from userinfo.
+5. Refresh with `grant_type=refresh_token` and the current `refresh_token`.
+ Persist the returned token pair atomically and serialize refresh requests.
+
+Access tokens last at most one hour. Every explicit consent grants renewable
+access for up to 30 days, including OAuth-only requests; the consent screen states
+this duration. Refresh tokens rotate on every exchange. Refreshing replaces the
+previous access token. Refresh requests may reduce scopes but cannot expand them;
+removed role scopes also remove the corresponding project authorizations.
+Refresh does not extend the original 30-day authorization.
+
+Reusing an exchanged code or an old refresh token revokes the authorization and
+its active token. Under **Authorized Applications**, each user sees one entry per
+application. Opening the application shows all of that user's tokens, including
+their scopes, project-role permissions, redirect URI, authorization date, last
+token exchange, access-token expiry and authorization expiry. Token values and
+refresh-token secrets are not displayed. Users can revoke a token separately or
+revoke an application from its list row or use **Revoke All** on its details
+page to revoke all their tokens for that application. **Revoke All** at the top
+of the list revokes access for every application. Other users' authorizations
+are unaffected.
+
+Revocation immediately removes the authorization, its access tokens and its
+project-role permissions. The application disappears from the user's list when
+no authorizations remain; its registration is kept. There is no separate delete
+action or persisted revoked/expired status. If the revocation transaction fails,
+the authorization remains unchanged and the operation reports failure.
+Expired authorizations and unused codes older than two minutes are rejected
+and hidden immediately based on their expiration dates, then deleted by cleanup
+daily at 00:00 in the server's time zone. Cleanup is rescheduled on startup;
+records that expired during downtime are removed at the next scheduled run.
+An expired access token with a valid refresh
+authorization is retained so the client can refresh it; the whole authorization
+is removed when its 30-day lifetime ends. Existing client application sessions
+are not signed out by token revocation.
+
+Application owners and administrators can revoke all users' authorizations from
+the application's registration settings. Clients can revoke their own access or
+refresh token through the revocation endpoint. Disabled users and disabled
+personal application owners cannot use grants.
+
+OIDC supports the authorization code flow, public subject identifiers, RS256,
+query responses and explicit consent. `prompt=consent` is supported;
+`prompt=none` returns `login_required` or `consent_required`. Request objects,
+`request_uri`, `max_age`, `claims`, `acr_values`, `id_token_hint`, other prompt
+values and alternative response modes are rejected. Signing keys are persisted
+with server settings, survive restarts and are shared by cluster members.
+
+## Client interoperability checks
+
+The [Playwright test spec](../e2e-test/tests/oauth-provider.spec.js) uses
+openid-client for OAuth2 and OIDC, with automated application registration and
+browser consent. It covers public-client, client-secret Basic and client-secret
+POST flows, including PKCE, project isolation, refresh, replay rejection and
+revocation. OIDC checks verify ID-token signatures and claims. See the
+[E2E README](../e2e-test/README.md#oauth2-and-openid-connect-provider) for setup
+and the exact checks performed.
+
+Git over HTTP is also supported through
+[git-credential-oauth](https://github.com/hickford/git-credential-oauth). Register
+a public client with redirect URI `http://127.0.0.1` (no trailing slash), then
+configure the helper's `oauthClientId`, `oauthAuthURL` (`/~oauth/authorize`),
+`oauthTokenURL` (`/~oauth/token`) and `oauthScopes` for your OneDev host. Request
+the Code Reader role for clone/fetch or Code Writer for push, using the actual
+role scope from discovery. Select the allowed projects during consent. Pair the
+helper with a credential store that supports refresh tokens. The JavaScript spec
+tests Git clone/fetch/push, permissions, refresh and revocation using issued
+tokens directly; it does not test the helper executable or its credential cache.
diff --git a/e2e-test/README.md b/e2e-test/README.md
index 1b6a85f955..d60e0410d2 100644
--- a/e2e-test/README.md
+++ b/e2e-test/README.md
@@ -5,7 +5,7 @@ the OneDev web interface in Chromium.
## Setup
-Node.js 20 or newer is required. The service desk tests also require Java and
+Node.js 20.19 or newer is required. The service desk tests also require Java and
Maven to install and run the local GreenMail server.
```bash
@@ -21,7 +21,7 @@ npm run install:mail-server
npm test
```
-By default Playwright starts `./dev.sh run` from the repository root and waits
+By default Playwright starts `./dev.sh prod` from the repository root and waits
up to ten minutes for `http://127.0.0.1:6610`. If a server is already listening
there, Playwright reuses it.
@@ -230,3 +230,48 @@ Use a dedicated server and one worker, as with the new-issue form tests. Test
settings are restored, and test projects and users are removed. No external
mailbox, SMTP credentials or real Jev key is
required. Both Jev suites run as part of the normal test run.
+
+## OAuth2 and OpenID Connect provider
+
+`tests/oauth-provider.spec.js` replaces the standalone Python/Node callback apps
+and manual Git runner. It uses pinned `openid-client` for both OAuth2 and OIDC
+and automates browser registration and consent with Playwright.
+
+```bash
+npm test -- tests/oauth-provider.spec.js
+```
+
+Use a dedicated test server with its OAuth signing key enabled and the default
+Project Owner, Code Reader, and Code Writer roles. The signing key is created
+on initialization; if it has been deleted, generate one under **Administration
+→ Keys → OAuth Signing Key** before running the suite. The server's advertised
+URL must be reachable by both Chromium and the Node test runner. HTTP is allowed
+for explicitly configured development servers. Git must be installed for the
+Git HTTP case.
+
+The suite creates disposable users, projects, and applications. Fixture teardown
+removes them and any remaining grants/tokens, including after failed tests.
+No separate client configuration, client secrets, Python environment, or manual
+consent is required. Only the application's callback landing page is intercepted;
+all provider endpoints and Git operations use the real OneDev server.
+
+Coverage includes:
+
+- OAuth2 and OIDC with public clients, client-secret Basic, and client-secret POST.
+- Discovery, state validation, S256 PKCE rejection/success, and public-client
+ callbacks with an ephemeral loopback port.
+- OIDC ID-token signature/claim validation using JWKS, userinfo, and refreshed
+ ID-token validation.
+- Role-scoped REST access and exclusion of unselected projects.
+- Access/refresh-token rotation, rejection of preceding access tokens, revocation,
+ refresh-token replay detection, and denied consent.
+- Git ls-remote, clone, fetch, Code Reader push denial, Code Writer push/read-back,
+ project isolation, refresh, and rejection after revocation.
+- Secret rotation and rotate-link visibility on application details and list pages.
+
+The Git case passes issued tokens directly to Git via an isolated environment;
+it does not exercise `git-credential-oauth`'s browser launch or credential cache.
+Requests-OAuthlib interoperability is also no longer part of this JavaScript suite.
+Traces and screenshots are disabled for these tests because the pages contain
+one-time client secrets and authorization codes. Assertions do not print token
+values. Stop a locally started server with `./dev.sh stop` after testing.
diff --git a/e2e-test/package-lock.json b/e2e-test/package-lock.json
index ec23c819bd..8d1ef09082 100644
--- a/e2e-test/package-lock.json
+++ b/e2e-test/package-lock.json
@@ -9,10 +9,11 @@
"version": "1.0.0",
"devDependencies": {
"@playwright/test": "1.62.1",
- "nodemailer": "10.0.10"
+ "nodemailer": "10.0.10",
+ "openid-client": "6.8.8"
},
"engines": {
- "node": ">=20"
+ "node": ">=20.19"
}
},
"node_modules/@playwright/test": {
@@ -46,6 +47,16 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
+ "node_modules/jose": {
+ "version": "6.2.14",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.14.tgz",
+ "integrity": "sha512-3JasLuki1NRLQvY4wCoC37KZk4qxoBx2k2aFqLxT84IezqW0bkJKnNtxnZj/Fu1xsQivoc/lytxaRHJoGLjJ1A==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
"node_modules/nodemailer": {
"version": "10.0.10",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.0.10.tgz",
@@ -56,6 +67,30 @@
"node": ">=20.0.0"
}
},
+ "node_modules/oauth4webapi": {
+ "version": "3.8.8",
+ "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.8.tgz",
+ "integrity": "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
+ "node_modules/openid-client": {
+ "version": "6.8.8",
+ "resolved": "https://registry.npmjs.org/openid-client/-/openid-client-6.8.8.tgz",
+ "integrity": "sha512-ZsucJA5Ad04Uv7YN4ql+s4GXNmb9uAYQwyJTsJx7CH/MX3JZioLE2pVKi1SC+YrbSLA4Px3Gi30dMjgOZtb6pA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "jose": "^6.2.12",
+ "oauth4webapi": "^3.8.8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
"node_modules/playwright": {
"version": "1.62.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz",
diff --git a/e2e-test/package.json b/e2e-test/package.json
index 72abf76677..809bbcdc64 100644
--- a/e2e-test/package.json
+++ b/e2e-test/package.json
@@ -4,7 +4,7 @@
"private": true,
"type": "module",
"engines": {
- "node": ">=20"
+ "node": ">=20.19"
},
"scripts": {
"test": "playwright test",
@@ -16,6 +16,7 @@
},
"devDependencies": {
"@playwright/test": "1.62.1",
- "nodemailer": "10.0.10"
+ "nodemailer": "10.0.10",
+ "openid-client": "6.8.8"
}
}
diff --git a/e2e-test/tests/oauth-provider.spec.js b/e2e-test/tests/oauth-provider.spec.js
new file mode 100644
index 0000000000..ad87a1ffe1
--- /dev/null
+++ b/e2e-test/tests/oauth-provider.spec.js
@@ -0,0 +1,307 @@
+import assert from 'node:assert/strict';
+import { execFile } from 'node:child_process';
+import { randomInt, randomUUID } from 'node:crypto';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import * as client from 'openid-client';
+import { expect, test as base } from './fixtures.js';
+
+const exec = promisify(execFile);
+
+const test = base.extend({
+ clientAuth: ['none', { option: true }],
+ protocol: ['oauth2', { option: true }],
+ oauth: async ({ api, page, clientAuth, protocol }, use) => {
+ const metadata = await api.json('get', '.well-known/openid-configuration');
+ const issuer = new URL(metadata.issuer);
+ const serverURL = `${issuer.href.replace(/\/$/, '')}/`;
+ const user = await api.createUser();
+ const selected = await api.createProject();
+ const unselected = await api.createProject();
+ await api.authorizeUser(selected, user, 'Project Owner');
+ await api.authorizeUser(unselected, user, 'Project Owner');
+
+ // Use the advertised issuer for browser sessions as well as token requests.
+ // It may use a different hostname from E2E_BASE_URL.
+ await page.goto(`${serverURL}~login`);
+ await page.getByRole('textbox', { name: 'Login name or email address' }).fill(user.userName);
+ await page.locator('form input[type=password]').fill(user.password);
+ await page.getByRole('button', { name: 'Sign in', exact: true }).click();
+ await page.waitForURL(url => !url.pathname.includes('~login'));
+
+ const callback = new URL(`http://127.0.0.1:${randomInt(49152, 65536)}/callback`);
+ // Only the application's landing page is intercepted. Discovery, consent,
+ // token exchange, JWKS, userinfo, REST and Git all use the real server.
+ await page.route(url => url.origin === callback.origin && url.pathname === callback.pathname,
+ route => route.fulfill({ contentType: 'text/html', body: '<p>Authorization callback received.</p>' }));
+ await page.goto(`${serverURL}~my/oauth-applications/new`);
+ const applicationName = `oauth-e2e-${randomUUID()}`;
+ await page.locator('.property-name input').fill(applicationName);
+ await page.locator('.property-homepage input').fill('https://example.com');
+ const confidential = page.locator('.property-confidential input[type=checkbox]');
+ if (await confidential.isChecked() !== (clientAuth !== 'none'))
+ await confidential.locator('..').click();
+ await expect(confidential).toBeChecked({ checked: clientAuth !== 'none' });
+ // Exercise RFC 8252's variable loopback port for public applications.
+ await page.locator('.property-redirectUris textarea').fill(clientAuth === 'none'
+ ? 'http://127.0.0.1/callback' : callback.href);
+ await page.getByRole('button', { name: 'Save', exact: true }).click();
+ const clientIdLink = page.locator('[aria-label="Copy client ID"]');
+ await expect(clientIdLink).toBeVisible();
+ const clientId = (await clientIdLink.locator('..').locator('span').innerText()).trim();
+ const applicationURL = page.url();
+ let secret;
+ if (clientAuth !== 'none') {
+ const copy = page.locator('[aria-label="Copy client secret"]');
+ await expect(copy).toBeVisible();
+ secret = (await copy.locator('..').locator('span').innerText()).trim();
+ expect(Boolean(secret) && !/^\*+$/.test(secret)).toBe(true);
+ }
+ await expect(page.getByRole('link', { name: 'Rotate Secret', exact: true })).toHaveCount(0);
+
+ const authentication = clientAuth === 'none' ? client.None()
+ : clientAuth === 'basic' ? client.ClientSecretBasic(secret) : client.ClientSecretPost(secret);
+ const execute = [client.enableNonRepudiationChecks];
+ // The E2E runner supports explicitly configured HTTP development servers.
+ if (issuer.protocol === 'http:') execute.push(client.allowInsecureRequests);
+ const config = await client.discovery(issuer, clientId, undefined, authentication, {
+ algorithm: protocol, execute,
+ });
+ expect(config.serverMetadata().supportsPKCE('S256')).toBe(true);
+ const roleScope = name => {
+ const scope = Object.entries(config.serverMetadata().onedev_scope_descriptions)
+ .find(([, description]) => description === `Role: ${name}`)?.[0];
+ expect(scope, `Discovery must advertise the ${name} role`).toBeTruthy();
+ return scope;
+ };
+
+ await use({
+ page, config, user, selected, unselected, callback, clientId, applicationName, applicationURL, serverURL,
+ roleScope,
+ async authorize({ scope, deny = false } = {}) {
+ const verifier = client.randomPKCECodeVerifier();
+ const state = client.randomState();
+ const nonce = protocol === 'oidc' ? client.randomNonce() : undefined;
+ scope ??= protocol === 'oidc' ? 'openid profile email offline_access'
+ : `profile ${roleScope('Code Reader')}`;
+ const url = client.buildAuthorizationUrl(config, {
+ redirect_uri: callback.href, scope, state,
+ code_challenge: await client.calculatePKCECodeChallenge(verifier), code_challenge_method: 'S256',
+ ...(nonce ? { nonce } : {}),
+ });
+ await page.goto(url.href);
+ await expect(page.getByText(applicationName, { exact: true })).toBeVisible();
+ if (scope.split(' ').some(value => value.startsWith('role:'))) {
+ await page.locator('.select2-search--inline textarea').fill(selected.name);
+ await page.getByRole('option', { name: selected.name, exact: true }).click();
+ await expect(page.locator('.select2-selection__choice')).toContainText(selected.name);
+ } else {
+ await expect(page.locator('select[multiple]')).toHaveCount(0);
+ }
+ await page.getByRole('button', { name: deny ? 'Deny' : 'Authorize', exact: true }).click();
+ await page.waitForURL(url => url.origin === callback.origin && url.pathname === callback.pathname);
+ return {
+ url: new URL(page.url()),
+ checks: { pkceCodeVerifier: verifier, expectedState: state,
+ ...(nonce ? { expectedNonce: nonce, idTokenExpected: true } : {}) },
+ };
+ },
+ async get(token, resource) {
+ // No browser cookies or admin fixture credentials can mask a token failure.
+ return fetch(new URL(resource, serverURL), {
+ headers: { Authorization: `Bearer ${token}` }, redirect: 'manual', signal: AbortSignal.timeout(10000),
+ });
+ },
+ });
+ // FixturesApi deletes the dedicated user, cascading to its applications,
+ // grants and tokens, even when a test fails before explicit revocation.
+ },
+});
+
+// These flows display a one-time secret and navigate with authorization codes.
+// Do not save those credentials in Playwright traces or failure screenshots.
+test.use({ trace: 'off', screenshot: 'off' });
+
+for (const protocol of ['oauth2', 'oidc']) {
+ for (const clientAuth of ['none', 'basic', 'post']) {
+ test.describe(`${protocol} with ${clientAuth} client authentication`, () => {
+ test.use({ protocol, clientAuth });
+
+ test('validates consent, PKCE, access, refresh rotation and revocation', async ({ oauth }) => {
+ const { config, selected, unselected, user } = oauth;
+ const transaction = await oauth.authorize();
+ const wrongState = new URL(transaction.url);
+ wrongState.searchParams.set('state', 'incorrect-state');
+ await assert.rejects(client.authorizationCodeGrant(config, wrongState, transaction.checks),
+ error => error.code === 'OAUTH_INVALID_RESPONSE' && /state/.test(error.cause?.message));
+ await assert.rejects(client.authorizationCodeGrant(config, transaction.url, {
+ ...transaction.checks, pkceCodeVerifier: client.randomPKCECodeVerifier(),
+ }), error => error.error === 'invalid_grant');
+ const first = await client.authorizationCodeGrant(config, transaction.url, transaction.checks);
+ expect(first.token_type.toLowerCase()).toBe('bearer');
+ expect(first.expires_in).toBeGreaterThan(0);
+ expect(first.expires_in).toBeLessThanOrEqual(3600);
+ expect(typeof first.refresh_token).toBe('string');
+
+ if (protocol === 'oidc') {
+ expect(first.claims()).toMatchObject({
+ sub: String(user.id), iss: config.serverMetadata().issuer, nonce: transaction.checks.expectedNonce,
+ });
+ const info = await client.fetchUserInfo(config, first.access_token, first.claims().sub);
+ expect(info).toMatchObject({ preferred_username: user.userName,
+ email: `${user.userName}@example.com`, email_verified: expect.any(Boolean) });
+ } else {
+ expect(first.id_token).toBeUndefined();
+ expect((await oauth.get(first.access_token, `~api/projects/${selected.id}`)).status).toBe(200);
+ expect((await oauth.get(first.access_token, `~api/projects/${unselected.id}`)).status).toBe(403);
+ const projects = await (await oauth.get(first.access_token, '~api/projects?offset=0&count=100')).json();
+ expect(projects.map(project => project.id)).toEqual([selected.id]);
+ }
+
+ const second = await client.refreshTokenGrant(config, first.refresh_token);
+ // Boolean assertions avoid printing token values on a regression.
+ expect(first.access_token !== second.access_token).toBe(true);
+ expect(first.refresh_token !== second.refresh_token).toBe(true);
+ if (protocol === 'oidc') {
+ expect(second.claims()?.sub).toBe(first.claims().sub);
+ await client.fetchUserInfo(config, second.access_token, first.claims().sub);
+ } else {
+ expect((await oauth.get(second.access_token, `~api/projects/${selected.id}`)).status).toBe(200);
+ }
+ const protectedPath = protocol === 'oidc' ? '~oauth/userinfo' : `~api/projects/${selected.id}`;
+ expect((await oauth.get(first.access_token, protectedPath)).status).toBe(401);
+ await client.tokenRevocation(config, second.refresh_token);
+ expect((await oauth.get(second.access_token, protectedPath)).status).toBe(401);
+ await assert.rejects(client.refreshTokenGrant(config, second.refresh_token),
+ error => error.error === 'invalid_grant');
+ await oauth.page.goto(`${oauth.serverURL}~my/authorized-applications`);
+ await expect(oauth.page.getByRole('link', { name: oauth.applicationName, exact: true })).toHaveCount(0);
+ });
+ });
+ }
+}
+
+test('denied consent returns access_denied and creates no authorization', async ({ oauth }) => {
+ const transaction = await oauth.authorize({ deny: true });
+ expect(transaction.url.searchParams.get('error')).toBe('access_denied');
+ expect(transaction.url.searchParams.get('state')).toBe(transaction.checks.expectedState);
+ expect(transaction.url.searchParams.has('code')).toBe(false);
+ await oauth.page.goto(`${oauth.serverURL}~my/authorized-applications`);
+ await expect(oauth.page.getByRole('link', { name: oauth.applicationName, exact: true })).toHaveCount(0);
+});
+
+test('replaying a rotated refresh token deletes the entire authorization', async ({ oauth }) => {
+ const transaction = await oauth.authorize();
+ const first = await client.authorizationCodeGrant(oauth.config, transaction.url, transaction.checks);
+ const second = await client.refreshTokenGrant(oauth.config, first.refresh_token);
+ await assert.rejects(client.refreshTokenGrant(oauth.config, first.refresh_token),
+ error => error.error === 'invalid_grant');
+ expect((await oauth.get(second.access_token, `~api/projects/${oauth.selected.id}`)).status).toBe(401);
+ await assert.rejects(client.refreshTokenGrant(oauth.config, second.refresh_token),
+ error => error.error === 'invalid_grant');
+});
+
+// Exercise Git itself with the issued credentials, without Python or an external
+// credential helper. Authentication is isolated from local Git configuration.
+test('Git HTTP enforces reader/writer roles, project isolation, refresh and revocation', async ({ oauth, api }) => {
+ const { selected, unselected, config } = oauth;
+ const content = '# OAuth Git fixture\n';
+ await api.putFile(selected, 'README.md', content);
+ await api.putFile(unselected, 'README.md', content);
+ const selectedURL = new URL(selected.name, oauth.serverURL).href;
+ const unselectedURL = new URL(unselected.name, oauth.serverURL).href;
+ const directory = await mkdtemp(path.join(os.tmpdir(), 'onedev-oauth-git-'));
+ const checkout = path.join(directory, 'checkout');
+ const git = async (token, args) => {
+ try {
+ return { code: 0, ...await exec('git', ['-c', 'credential.helper=', ...args], {
+ timeout: 30000,
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1',
+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_COUNT: '1',
+ GIT_CONFIG_KEY_0: 'http.extraHeader',
+ GIT_CONFIG_VALUE_0: `Authorization: Basic ${Buffer.from(`oauth2:${token}`).toString('base64')}` },
+ }) };
+ } catch (error) {
+ if (typeof error.code !== 'number') throw error;
+ return { code: error.code, stdout: error.stdout, stderr: error.stderr };
+ }
+ };
+ const success = async (token, args) => {
+ const result = await git(token, args);
+ expect(result.code, result.stderr).toBe(0);
+ return result.stdout;
+ };
+ try {
+ const transaction = await oauth.authorize();
+ const reader = await client.authorizationCodeGrant(config, transaction.url, transaction.checks);
+ await success(reader.access_token, ['ls-remote', selectedURL]);
+ await success(reader.access_token, ['clone', '--branch', 'main', selectedURL, checkout]);
+ expect(await readFile(path.join(checkout, 'README.md'), 'utf8')).toBe(content);
+ await success(reader.access_token, ['-C', checkout, 'fetch', 'origin']);
+ expect((await git(reader.access_token, ['ls-remote', unselectedURL])).stderr)
+ .toContain('Project not found or inaccessible');
+ await writeFile(path.join(checkout, 'oauth-test.txt'), 'OAuth write permission fixture\n');
+ await success(reader.access_token, ['-C', checkout, 'add', 'oauth-test.txt']);
+ await success(reader.access_token, ['-C', checkout, '-c', 'user.name=OAuth Test',
+ '-c', '[email protected]', '-c', 'commit.gpgsign=false',
+ 'commit', '-m', 'Test OAuth Git write permission']);
+ const push = ['-C', checkout, 'push', 'origin', 'HEAD:refs/heads/oauth-check'];
+ const denied = await git(reader.access_token, push);
+ expect(denied.code).not.toBe(0);
+ expect(denied.stderr).toContain('403');
+
+ const refreshed = await client.refreshTokenGrant(config, reader.refresh_token);
+ expect(reader.access_token !== refreshed.access_token).toBe(true);
+ expect(reader.refresh_token !== refreshed.refresh_token).toBe(true);
+ await success(refreshed.access_token, ['-C', checkout, 'fetch', 'origin']);
+ expect((await oauth.get(reader.access_token, `~api/projects/${selected.id}`)).status).toBe(401);
+ await client.tokenRevocation(config, refreshed.refresh_token);
+
+ const writeTransaction = await oauth.authorize({ scope: `profile ${oauth.roleScope('Code Writer')}` });
+ const writer = await client.authorizationCodeGrant(config, writeTransaction.url, writeTransaction.checks);
+ await success(writer.access_token, push);
+ const head = (await success(writer.access_token, ['-C', checkout, 'rev-parse', 'HEAD'])).trim();
+ const refs = await success(writer.access_token, ['ls-remote', selectedURL, 'refs/heads/oauth-check']);
+ expect(refs.startsWith(`${head}\t`)).toBe(true);
+ expect((await git(writer.access_token, ['ls-remote', unselectedURL])).stderr)
+ .toContain('Project not found or inaccessible');
+ await client.tokenRevocation(config, writer.refresh_token);
+ const revoked = await git(writer.access_token, ['ls-remote', selectedURL]);
+ expect(revoked.code).not.toBe(0);
+ expect(revoked.stderr).toMatch(/401|Authentication failed|terminal prompts disabled/);
+ await assert.rejects(client.refreshTokenGrant(config, writer.refresh_token),
+ error => error.error === 'invalid_grant');
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+});
+
+test.describe('confidential application secrets', () => {
+ test.use({ clientAuth: 'post' });
+
+ test('rotation hides its link while displaying the new secret on details and list pages', async ({ oauth }) => {
+ const { page } = oauth;
+ const rotate = page.getByRole('link', { name: 'Rotate Secret', exact: true });
+ const copy = page.locator('[aria-label="Copy client secret"]');
+ const transaction = await oauth.authorize();
+ const tokens = await client.authorizationCodeGrant(oauth.config, transaction.url, transaction.checks);
+ await page.goto(oauth.applicationURL);
+ await expect(copy).toHaveCount(0);
+ await expect(rotate).toBeVisible();
+ page.once('dialog', dialog => dialog.accept());
+ await rotate.click();
+ await expect(copy).toBeVisible();
+ await expect(rotate).toHaveCount(0);
+ expect((await oauth.get(tokens.access_token, `~api/projects/${oauth.selected.id}`)).status).toBe(401);
+
+ await page.goto(`${oauth.serverURL}~my/oauth-applications`);
+ const row = page.getByRole('row').filter({ has: page.getByRole('link', { name: oauth.applicationName, exact: true }) });
+ await expect(row.locator('[aria-label="Copy client secret"]')).toHaveCount(0);
+ page.once('dialog', dialog => dialog.accept());
+ await row.getByRole('link', { name: 'Rotate Secret', exact: true }).click();
+ await expect(row.locator('[aria-label="Copy client secret"]')).toBeVisible();
+ await expect(row.getByRole('link', { name: 'Rotate Secret', exact: true })).toHaveCount(0);
+ });
+});
diff --git a/server-core/src/main/java/io/onedev/server/CoreModule.java b/server-core/src/main/java/io/onedev/server/CoreModule.java
index 938bb9808b..91fd93c820 100644
--- a/server-core/src/main/java/io/onedev/server/CoreModule.java
+++ b/server-core/src/main/java/io/onedev/server/CoreModule.java
@@ -190,6 +190,9 @@ import io.onedev.server.security.FilterChainConfigurator;
import io.onedev.server.security.SecurityUtils;
import io.onedev.server.service.AccessTokenAuthorizationService;
import io.onedev.server.service.AccessTokenService;
+import io.onedev.server.oauth.OAuthProviderService;
+import io.onedev.server.oauth.DefaultOAuthProviderService;
+import io.onedev.server.oauth.OAuthEndpointServlet;
import io.onedev.server.service.AgentAttributeService;
import io.onedev.server.service.AgentService;
import io.onedev.server.service.AgentTokenService;
@@ -554,6 +557,8 @@ public class CoreModule extends AbstractPluginModule {
bind(CodeCommentNotificationManager.class);
bind(CodeCommentService.class).to(DefaultCodeCommentService.class);
bind(AccessTokenService.class).to(DefaultAccessTokenService.class);
+ bind(OAuthProviderService.class).to(DefaultOAuthProviderService.class);
+ bind(OAuthEndpointServlet.class);
bind(UserService.class).to(DefaultUserService.class);
bind(IssueWatchService.class).to(DefaultIssueWatchService.class);
bind(IssueChangeService.class).to(DefaultIssueChangeService.class);
@@ -684,6 +689,9 @@ public class CoreModule extends AbstractPluginModule {
bind(ShiroFilter.class).to(DefaultShiroFilter.class);
install(new ShiroAopModule());
contribute(FilterChainConfigurator.class, filterChainManager -> {
+ for (String path: List.of("/~oauth/token", "/~oauth/revoke", "/~oauth/userinfo", "/~oauth/jwks",
+ "/.well-known/oauth-authorization-server", "/.well-known/openid-configuration"))
+ filterChainManager.createChain(path, "noSessionCreation");
filterChainManager.createChain("/**/info/refs", "noSessionCreation, authcBasic, authcBearer");
filterChainManager.createChain("/**/git-upload-pack", "noSessionCreation, authcBasic, authcBearer");
filterChainManager.createChain("/**/git-receive-pack", "noSessionCreation, authcBasic, authcBearer");
diff --git a/server-core/src/main/java/io/onedev/server/buildspec/step/SyncRepository.java b/server-core/src/main/java/io/onedev/server/buildspec/step/SyncRepository.java
index 888488e3f1..fd6faa3a38 100644
--- a/server-core/src/main/java/io/onedev/server/buildspec/step/SyncRepository.java
+++ b/server-core/src/main/java/io/onedev/server/buildspec/step/SyncRepository.java
@@ -65,6 +65,7 @@ public abstract class SyncRepository extends ServerSideStep {
@Editable(order=300, description="Optionally specify user name to access remote repository")
@Interpolative(variableSuggester="suggestVariables")
+ @NotEmpty
public String getUserName() {
return userName;
}
diff --git a/server-core/src/main/java/io/onedev/server/data/DefaultDataService.java b/server-core/src/main/java/io/onedev/server/data/DefaultDataService.java
index 82931b980b..5428ba55be 100644
--- a/server-core/src/main/java/io/onedev/server/data/DefaultDataService.java
+++ b/server-core/src/main/java/io/onedev/server/data/DefaultDataService.java
@@ -47,6 +47,7 @@ import jakarta.persistence.criteria.Root;
import jakarta.validation.Validator;
import org.apache.shiro.authc.credential.PasswordService;
+import org.bouncycastle.openpgp.PGPException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.hibernate.Session;
@@ -72,6 +73,9 @@ import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
+import com.nimbusds.jose.JOSEException;
+import com.nimbusds.jose.jwk.KeyUse;
+import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
import io.onedev.commons.bootstrap.Bootstrap;
import io.onedev.commons.loader.ManagedSerializedForm;
@@ -141,6 +145,7 @@ import io.onedev.server.ssh.SshKeyUtils;
import io.onedev.server.taskschedule.SchedulableTask;
import io.onedev.server.taskschedule.TaskScheduler;
import io.onedev.server.util.BeanUtils;
+import io.onedev.server.util.GpgUtils;
import io.onedev.server.util.init.ManualConfig;
import io.onedev.server.web.util.editbean.NewUserBean;
@@ -831,8 +836,28 @@ public class DefaultDataService implements DataService, Serializable {
setting = settingService.findSetting(Key.GPG);
if (setting == null || setting.getValue() == null) {
GpgSetting gpgSetting = new GpgSetting();
- settingService.saveGpgSetting(gpgSetting);
- }
+ var noreplyEmailDomain = systemSetting != null ? systemSetting.getNoreplyEmailDomain()
+ : settingService.getSystemSetting().getNoreplyEmailDomain();
+ try {
+ var generator = GpgUtils.generateKeyRingGenerator(User.SYSTEM_NAME + "<"
+ + User.SYSTEM_NAME.toLowerCase() + "@" + noreplyEmailDomain + ">");
+ gpgSetting.setEncodedSigningKey(generator.generateSecretKeyRing().getEncoded());
+ } catch (PGPException | IOException e) {
+ throw new RuntimeException("Unable to generate GPG signing key", e);
+ }
+ settingService.saveGpgSetting(gpgSetting);
+ }
+
+ setting = settingService.findSetting(Key.OAUTH_SIGNING_KEY);
+ // A setting with a null value means the administrator explicitly deleted the key.
+ if (setting == null) {
+ try {
+ var key = new RSAKeyGenerator(2048).keyUse(KeyUse.SIGNATURE).keyIDFromThumbprint(true).generate();
+ settingService.saveOAuthSigningKey(key.toJSONString());
+ } catch (JOSEException e) {
+ throw new RuntimeException("Unable to generate OAuth signing key", e);
+ }
+ }
setting = settingService.findSetting(Key.ISSUE);
if (setting == null) {
diff --git a/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java b/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java
index bf5764c824..66ef6e79a3 100644
--- a/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java
+++ b/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java
@@ -9643,4 +9643,8 @@ public class DataMigrator {
}
}
+ private void migrate255(File dataDir, Stack<Integer> versions) {
+ // OAuth applications and grants add new tables and an optional AccessToken.oauthGrant association.
+ }
+
}
diff --git a/server-core/src/main/java/io/onedev/server/model/AccessToken.java b/server-core/src/main/java/io/onedev/server/model/AccessToken.java
index cd80bb9e5c..e26827da09 100644
--- a/server-core/src/main/java/io/onedev/server/model/AccessToken.java
+++ b/server-core/src/main/java/io/onedev/server/model/AccessToken.java
@@ -1,5 +1,6 @@
package io.onedev.server.model;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.onedev.server.rest.annotation.Immutable;
import io.onedev.server.security.SecurityUtils;
@@ -24,7 +25,7 @@ import static io.onedev.server.security.SecurityUtils.asPrincipals;
@Entity
@Table(
- indexes={@Index(columnList="owner_id"), @Index(columnList = "value")},
+ indexes={@Index(columnList="owner_id"), @Index(columnList = "value"), @Index(columnList="oauthGrant_id")},
uniqueConstraints={@UniqueConstraint(columnNames={"owner_id", "name"})})
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class AccessToken extends AbstractEntity implements AuthenticationInfo {
@@ -51,6 +52,18 @@ public class AccessToken extends AbstractEntity implements AuthenticationInfo {
private Date expireDate;
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JsonIgnore
+ private OAuthGrant oauthGrant;
+
+ public OAuthGrant getOauthGrant() {
+ return oauthGrant;
+ }
+
+ public void setOauthGrant(OAuthGrant oauthGrant) {
+ this.oauthGrant = oauthGrant;
+ }
+
@OneToMany(mappedBy="token", cascade=CascadeType.REMOVE)
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
private Collection<AccessTokenAuthorization> authorizations = new ArrayList<>();
@@ -117,8 +130,8 @@ public class AccessToken extends AbstractEntity implements AuthenticationInfo {
}
public Subject asSubject() {
- // Temporal access token, check AccessTokenService.createTemporal
- if (isNew() || isHasOwnerPermissions())
+ // isNew() checks temporal access token, check AccessTokenService.createTemporal
+ if (oauthGrant == null && (isNew() || isHasOwnerPermissions()))
return getOwner().asSubject();
else
return SecurityUtils.asSubject(getPrincipals());
diff --git a/server-core/src/main/java/io/onedev/server/model/OAuthApplication.java b/server-core/src/main/java/io/onedev/server/model/OAuthApplication.java
new file mode 100644
index 0000000000..eea339c114
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/model/OAuthApplication.java
@@ -0,0 +1,108 @@
+package io.onedev.server.model;
+
+import java.io.Serial;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import jakarta.persistence.*;
+
+@Entity
+@Table(indexes=@Index(columnList="owner_id"))
+public class OAuthApplication extends AbstractEntity {
+
+ @Serial
+ private static final long serialVersionUID = 1L;
+
+ @Column(nullable=false)
+ private String name;
+
+ @Column(nullable=false, length=2048)
+ private String homepage;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private User owner;
+
+ @Column(nullable=false, unique=true)
+ private String clientId;
+
+ private String secretHash;
+
+ private boolean confidential;
+
+ @Column(nullable=false, length=65535)
+ private String redirectUris;
+
+ @OneToMany(mappedBy="application", cascade=CascadeType.REMOVE)
+ private Collection<OAuthGrant> grants = new ArrayList<>();
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getHomepage() {
+ return homepage;
+ }
+
+ public void setHomepage(String homepage) {
+ this.homepage = homepage;
+ }
+
+ public User getOwner() {
+ return owner;
+ }
+
+ public void setOwner(User owner) {
+ this.owner = owner;
+ }
+
+ public String getClientId() {
+ return clientId;
+ }
+
+ public void setClientId(String clientId) {
+ this.clientId = clientId;
+ }
+
+ public String getSecretHash() {
+ return secretHash;
+ }
+
+ public void setSecretHash(String secretHash) {
+ this.secretHash = secretHash;
+ }
+
+ public boolean isConfidential() {
+ return confidential;
+ }
+
+ public void setConfidential(boolean confidential) {
+ this.confidential = confidential;
+ }
+
+ public String getRedirectUris() {
+ return redirectUris;
+ }
+
+ public void setRedirectUris(String redirectUris) {
+ this.redirectUris = redirectUris;
+ }
+
+ public Collection<OAuthGrant> getGrants() {
+ return grants;
+ }
+
+ public void setGrants(Collection<OAuthGrant> grants) {
+ this.grants = grants;
+ }
+
+ public List<String> getRedirectUriList() {
+ return redirectUris.lines().map(String::trim).filter(it -> !it.isEmpty()).toList();
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/model/OAuthGrant.java b/server-core/src/main/java/io/onedev/server/model/OAuthGrant.java
new file mode 100644
index 0000000000..c3565dd248
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/model/OAuthGrant.java
@@ -0,0 +1,178 @@
+package io.onedev.server.model;
+
+import java.io.Serial;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+
+import jakarta.persistence.*;
+
+@Entity
+@Table(indexes={@Index(columnList="application_id"), @Index(columnList="owner_id"),
+ @Index(columnList="expireDate"), @Index(columnList="lastUsedDate,codeExpireDate")})
+public class OAuthGrant extends AbstractEntity {
+
+ @Serial
+ private static final long serialVersionUID = 1L;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private OAuthApplication application;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private User owner;
+
+ @Column(nullable=false, length=4096)
+ private String scopes;
+
+ @Column(nullable=false, length=2048)
+ private String redirectUri;
+
+ private String codeHash;
+
+ private String codeChallenge;
+
+ private Date codeExpireDate;
+
+ private String nonce;
+
+ private String refreshTokenHash;
+
+ @Lob
+ @Column(length=1048576)
+ private ArrayList<String> usedRefreshTokenHashes = new ArrayList<>();
+
+ @Column(nullable=false)
+ private Date createDate = new Date();
+
+ @Column(nullable=false)
+ private Date expireDate;
+
+ private Date lastUsedDate;
+
+ @OneToMany(mappedBy="oauthGrant", cascade=CascadeType.REMOVE)
+ private Collection<AccessToken> accessTokens = new ArrayList<>();
+
+ public OAuthApplication getApplication() {
+ return application;
+ }
+
+ public void setApplication(OAuthApplication application) {
+ this.application = application;
+ }
+
+ public User getOwner() {
+ return owner;
+ }
+
+ public void setOwner(User owner) {
+ this.owner = owner;
+ }
+
+ public String getScopes() {
+ return scopes;
+ }
+
+ public void setScopes(String scopes) {
+ this.scopes = scopes;
+ }
+
+ public String getRedirectUri() {
+ return redirectUri;
+ }
+
+ public void setRedirectUri(String redirectUri) {
+ this.redirectUri = redirectUri;
+ }
+
+ public String getCodeHash() {
+ return codeHash;
+ }
+
+ public void setCodeHash(String codeHash) {
+ this.codeHash = codeHash;
+ }
+
+ public String getCodeChallenge() {
+ return codeChallenge;
+ }
+
+ public void setCodeChallenge(String codeChallenge) {
+ this.codeChallenge = codeChallenge;
+ }
+
+ public Date getCodeExpireDate() {
+ return codeExpireDate;
+ }
+
+ public void setCodeExpireDate(Date codeExpireDate) {
+ this.codeExpireDate = codeExpireDate;
+ }
+
+ public String getNonce() {
+ return nonce;
+ }
+
+ public void setNonce(String nonce) {
+ this.nonce = nonce;
+ }
+
+ public String getRefreshTokenHash() {
+ return refreshTokenHash;
+ }
+
+ public void setRefreshTokenHash(String refreshTokenHash) {
+ this.refreshTokenHash = refreshTokenHash;
+ }
+
+ public ArrayList<String> getUsedRefreshTokenHashes() {
+ return usedRefreshTokenHashes;
+ }
+
+ public void setUsedRefreshTokenHashes(ArrayList<String> usedRefreshTokenHashes) {
+ this.usedRefreshTokenHashes = usedRefreshTokenHashes;
+ }
+
+ public Date getCreateDate() {
+ return createDate;
+ }
+
+ public void setCreateDate(Date createDate) {
+ this.createDate = createDate;
+ }
+
+ public Date getExpireDate() {
+ return expireDate;
+ }
+
+ public void setExpireDate(Date expireDate) {
+ this.expireDate = expireDate;
+ }
+
+ public Date getLastUsedDate() {
+ return lastUsedDate;
+ }
+
+ public void setLastUsedDate(Date lastUsedDate) {
+ this.lastUsedDate = lastUsedDate;
+ }
+
+ public Collection<AccessToken> getAccessTokens() {
+ return accessTokens;
+ }
+
+ public void setAccessTokens(Collection<AccessToken> accessTokens) {
+ this.accessTokens = accessTokens;
+ }
+
+ public boolean isActive() {
+ return !isExpired() && !owner.isDisabled() && !application.getOwner().isDisabled();
+ }
+
+ public boolean isExpired() {
+ var now = new Date();
+ return !expireDate.after(now) || lastUsedDate == null && !codeExpireDate.after(now);
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/model/Setting.java b/server-core/src/main/java/io/onedev/server/model/Setting.java
index 40164039b4..ae8d387edc 100644
--- a/server-core/src/main/java/io/onedev/server/model/Setting.java
+++ b/server-core/src/main/java/io/onedev/server/model/Setting.java
@@ -23,7 +23,7 @@ public class Setting extends AbstractEntity {
GROOVY_SCRIPTS, PULL_REQUEST, BUILD, PACK, PROJECT, SSH, GPG,
EMAIL_TEMPLATES, CONTRIBUTED_SETTINGS, SERVICE_DESK_SETTING,
AGENT, PERFORMANCE, BRANDING, CLUSTER_SETTING, SUBSCRIPTION_DATA, ALERT,
- SYSTEM_UUID, AUDIT, AI, WORKSPACE_PROVISIONERS, WORKSPACE
+ SYSTEM_UUID, AUDIT, AI, WORKSPACE_PROVISIONERS, WORKSPACE, OAUTH_SIGNING_KEY
};
@Column(nullable=false, unique=true)
diff --git a/server-core/src/main/java/io/onedev/server/model/User.java b/server-core/src/main/java/io/onedev/server/model/User.java
index f7385bbbbc..aa5e16fa08 100644
--- a/server-core/src/main/java/io/onedev/server/model/User.java
+++ b/server-core/src/main/java/io/onedev/server/model/User.java
@@ -146,6 +146,12 @@ public class User extends AbstractEntity implements AuthenticationInfo {
@OneToMany(mappedBy="owner", cascade=CascadeType.REMOVE)
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
private Collection<AccessToken> accessTokens = new ArrayList<>();
+
+ @OneToMany(mappedBy="owner", cascade=CascadeType.REMOVE)
+ private Collection<OAuthGrant> oauthGrants = new ArrayList<>();
+
+ @OneToMany(mappedBy="owner", cascade=CascadeType.REMOVE)
+ private Collection<OAuthApplication> oauthApplications = new ArrayList<>();
@OneToMany(mappedBy="user", cascade=CascadeType.REMOVE)
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
diff --git a/server-core/src/main/java/io/onedev/server/oauth/DefaultOAuthProviderService.java b/server-core/src/main/java/io/onedev/server/oauth/DefaultOAuthProviderService.java
new file mode 100644
index 0000000000..bfc4fd014f
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/oauth/DefaultOAuthProviderService.java
@@ -0,0 +1,617 @@
+package io.onedev.server.oauth;
+
+import static io.onedev.server.persistence.dao.Restrictions.eq;
+import static io.onedev.server.oauth.OAuthProtocol.*;
+
+import java.net.URI;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import jakarta.inject.Inject;
+import jakarta.inject.Singleton;
+import jakarta.persistence.LockModeType;
+
+import org.apache.shiro.subject.Subject;
+import org.apache.shiro.authz.UnauthorizedException;
+import org.apache.shiro.authc.DisabledAccountException;
+import org.quartz.CronScheduleBuilder;
+import org.quartz.ScheduleBuilder;
+
+import com.nimbusds.jose.JWSAlgorithm;
+import com.nimbusds.jose.JWSHeader;
+import com.nimbusds.jose.crypto.RSASSASigner;
+import com.nimbusds.jose.jwk.JWKSet;
+import com.nimbusds.jose.jwk.KeyUse;
+import com.nimbusds.jose.jwk.RSAKey;
+import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
+import com.nimbusds.jwt.JWTClaimsSet;
+import com.nimbusds.jwt.SignedJWT;
+import com.nimbusds.oauth2.sdk.*;
+import com.nimbusds.oauth2.sdk.auth.*;
+import com.nimbusds.oauth2.sdk.http.HTTPResponse;
+import com.nimbusds.oauth2.sdk.id.ClientID;
+import com.nimbusds.oauth2.sdk.id.Issuer;
+import com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod;
+import com.nimbusds.oauth2.sdk.token.BearerAccessToken;
+import com.nimbusds.oauth2.sdk.token.RefreshToken;
+import com.nimbusds.oauth2.sdk.token.Tokens;
+import com.nimbusds.openid.connect.sdk.OIDCTokenResponse;
+import com.nimbusds.openid.connect.sdk.SubjectType;
+import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
+import com.nimbusds.openid.connect.sdk.token.OIDCTokens;
+
+import io.onedev.commons.utils.ExplicitException;
+import io.onedev.server.cluster.ClusterService;
+import io.onedev.server.event.Listen;
+import io.onedev.server.event.system.SystemStarted;
+import io.onedev.server.event.system.SystemStopping;
+import io.onedev.server.model.AccessToken;
+import io.onedev.server.model.AccessTokenAuthorization;
+import io.onedev.server.model.OAuthApplication;
+import io.onedev.server.model.OAuthGrant;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.Role;
+import io.onedev.server.model.Setting;
+import io.onedev.server.model.User;
+import io.onedev.server.persistence.annotation.Sessional;
+import io.onedev.server.persistence.annotation.Transactional;
+import io.onedev.server.persistence.SessionService;
+import io.onedev.server.persistence.TransactionService;
+import io.onedev.server.persistence.dao.Dao;
+import io.onedev.server.persistence.dao.EntityCriteria;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.service.AccessTokenService;
+import io.onedev.server.service.AuditService;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.service.RoleService;
+import io.onedev.server.service.SettingService;
+import io.onedev.server.taskschedule.SchedulableTask;
+import io.onedev.server.taskschedule.TaskScheduler;
+
+@Singleton
+public class DefaultOAuthProviderService implements OAuthProviderService, SchedulableTask {
+
+ @Inject
+ private Dao dao;
+ @Inject
+ private AccessTokenService accessTokenService;
+ @Inject
+ private AuditService auditService;
+ @Inject
+ private ProjectService projectService;
+ @Inject
+ private RoleService roleService;
+ @Inject
+ private SettingService settingService;
+ @Inject
+ private TaskScheduler taskScheduler;
+ @Inject
+ private ClusterService clusterService;
+ @Inject
+ private SessionService sessionService;
+ @Inject
+ private TransactionService transactionService;
+
+ private volatile String cleanupTaskId;
+
+ @Override
+ public boolean isEnabled() {
+ return settingService.getOAuthSigningKey() != null;
+ }
+
+ private void checkEnabled() {
+ if (!isEnabled())
+ throw new ExplicitException("OAuth2/OIDC provider is disabled");
+ }
+
+ @Override
+ public RSAKey getPublicSigningKey() {
+ return isEnabled() ? signingKey().toPublicJWK() : null;
+ }
+
+ private void lockSigningKey() {
+ // The provider setting may not exist yet. Serialize key changes using an existing singleton row.
+ dao.getSession().lock(settingService.findSetting(Setting.Key.SYSTEM), LockModeType.PESSIMISTIC_WRITE);
+ }
+
+ private void revokeAllGrants() {
+ for (var grant: dao.query(EntityCriteria.of(OAuthGrant.class)))
+ revoke(grant);
+ }
+
+ @Transactional
+ @Override
+ public void generateSigningKey() {
+ lockSigningKey();
+ try {
+ var key = new RSAKeyGenerator(2048).keyUse(KeyUse.SIGNATURE).keyIDFromThumbprint(true).generate();
+ if (isEnabled())
+ revokeAllGrants();
+ settingService.saveOAuthSigningKey(key.toJSONString());
+ auditService.audit(null, "generated OAuth signing key", null, null);
+ } catch (com.nimbusds.jose.JOSEException e) {
+ throw new IllegalStateException("Unable to generate OAuth signing key", e);
+ }
+ }
+
+ @Transactional
+ @Override
+ public void deleteSigningKey() {
+ lockSigningKey();
+ revokeAllGrants();
+ settingService.saveOAuthSigningKey(null);
+ auditService.audit(null, "deleted OAuth signing key", null, null);
+ }
+
+ @Override
+ public OAuthApplication getApplication(Long id) {
+ return dao.load(OAuthApplication.class, id);
+ }
+
+ @Override
+ public OAuthApplication findApplication(String clientId) {
+ return dao.find(EntityCriteria.of(OAuthApplication.class).add(eq("clientId", clientId)));
+ }
+
+ @Override
+ public List<OAuthApplication> getApplications(User owner) {
+ return dao.query(EntityCriteria.of(OAuthApplication.class).add(eq("owner", owner)));
+ }
+
+ @Transactional
+ @Override
+ public String saveApplication(OAuthApplication application) {
+ checkEnabled();
+ if (application.getOwner() == null)
+ throw new ExplicitException("Application owner is required");
+ if (application.getName() == null || application.getName().isBlank() || application.getName().length() > 255)
+ throw new ExplicitException("Application name is required (up to 255 characters)");
+ try {
+ var homepage = URI.create(application.getHomepage());
+ if (!List.of("http", "https").contains(homepage.getScheme()) || homepage.getHost() == null
+ || homepage.getUserInfo() != null || application.getHomepage().length() > 2048)
+ throw new IllegalArgumentException();
+ } catch (IllegalArgumentException | NullPointerException e) {
+ throw new ExplicitException("Specify a valid HTTP or HTTPS homepage");
+ }
+ if (application.getRedirectUris() == null || application.getRedirectUris().length() > 16000
+ || application.getRedirectUriList().isEmpty() || application.getRedirectUriList().size() > 20
+ || application.getRedirectUriList().stream().anyMatch(it -> it.length() > 2048
+ || !isValidRedirectUri(it, application.isConfidential())))
+ throw new ExplicitException("Specify up to 20 exact redirect URIs, using HTTPS, loopback HTTP, or a native app scheme");
+ boolean creating = application.isNew();
+ String secret = null;
+ if (creating) {
+ application.setClientId(new ClientID().getValue());
+ if (application.isConfidential()) {
+ secret = new Secret(32).getValue();
+ application.setSecretHash(hash(secret));
+ }
+ }
+ dao.persist(application);
+ auditService.audit(null, (creating ? "registered" : "updated") + " OAuth application \"" + application.getName() + "\"", null, null);
+ return secret;
+ }
+
+ @Transactional
+ @Override
+ public String rotateSecret(Long id) {
+ var application = getApplication(id);
+ if (!application.isConfidential())
+ throw new ExplicitException("Public applications do not have a client secret");
+ String secret = new Secret(32).getValue();
+ application.setSecretHash(hash(secret));
+ dao.persist(application);
+ revokeApplication(id);
+ auditService.audit(null, "rotated secret of OAuth application \"" + application.getName() + "\"", null, null);
+ return secret;
+ }
+
+ @Transactional
+ @Override
+ public void deleteApplication(Long id) {
+ var application = getApplication(id);
+ revokeApplication(id);
+ auditService.audit(null, "deleted OAuth application \"" + application.getName() + "\"", null, null);
+ dao.remove(application);
+ }
+
+ @Transactional
+ @Override
+ public void revokeApplication(Long id) {
+ var application = getApplication(id);
+ for (var grant: new ArrayList<>(application.getGrants()))
+ revoke(grant);
+ }
+
+ @Override
+ public List<OAuthGrant> getGrants(User owner) {
+ return dao.query(EntityCriteria.of(OAuthGrant.class).add(eq("owner", owner))).stream()
+ .filter(it -> !it.isExpired()).toList();
+ }
+
+ @Transactional
+ @Override
+ public void revokeGrant(Long id) {
+ var grant = dao.getSession().find(OAuthGrant.class, id, LockModeType.PESSIMISTIC_WRITE);
+ if (grant == null)
+ return;
+ revoke(grant);
+ }
+
+ @Transactional
+ @Override
+ public void revokeGrants(User owner, Long applicationId) {
+ var grants = dao.query(EntityCriteria.of(OAuthGrant.class)
+ .add(eq("owner", owner)).add(eq("application.id", applicationId)));
+ for (var grant: grants)
+ revoke(grant);
+ }
+
+ @Transactional
+ @Override
+ public void revokeGrants(User owner) {
+ for (var grant: dao.query(EntityCriteria.of(OAuthGrant.class).add(eq("owner", owner))))
+ revoke(grant);
+ }
+
+ private void removeGrant(OAuthGrant grant) {
+ // Delete tokens explicitly so their removal also invalidates the access-token cache.
+ for (var token: new ArrayList<>(grant.getAccessTokens()))
+ accessTokenService.delete(token);
+ grant.getAccessTokens().clear();
+ dao.remove(grant);
+ }
+
+ private void revoke(OAuthGrant grant) {
+ grant = dao.getSession().find(OAuthGrant.class, grant.getId(), LockModeType.PESSIMISTIC_WRITE);
+ if (grant != null) {
+ auditService.audit(null, "revoked OAuth grant " + grant.getId() + " for application \""
+ + grant.getApplication().getName() + "\" and user \"" + grant.getOwner().getName() + "\"", null, null);
+ removeGrant(grant);
+ }
+ }
+
+ @Listen
+ public void on(SystemStarted event) {
+ cleanupTaskId = taskScheduler.schedule(this);
+ }
+
+ @Listen
+ public void on(SystemStopping event) {
+ if (cleanupTaskId != null)
+ taskScheduler.unschedule(cleanupTaskId);
+ }
+
+ @Override
+ public ScheduleBuilder<?> getScheduleBuilder() {
+ return CronScheduleBuilder.dailyAtHourAndMinute(0, 0);
+ }
+
+ @Override
+ public void execute() {
+ if (!clusterService.isLeaderServer())
+ return;
+ while (true) {
+ var ids = sessionService.call(() -> dao.getSession().createQuery("select id from OAuthGrant "
+ + "where expireDate <= :now "
+ + "or (lastUsedDate is null and codeExpireDate <= :now) order by id", Long.class)
+ .setParameter("now", new Date()).setMaxResults(100).getResultList());
+ if (ids.isEmpty())
+ break;
+ for (var id: ids) {
+ transactionService.run(() -> {
+ var grant = dao.getSession().find(OAuthGrant.class, id, LockModeType.PESSIMISTIC_WRITE);
+ if (grant != null && grant.isExpired())
+ removeGrant(grant);
+ });
+ }
+ }
+ }
+
+ @Override
+ public Map<String, String> getScopes() {
+ Map<String, String> scopes = new LinkedHashMap<>();
+ scopes.put("openid", "Sign in with your OneDev identity");
+ scopes.put("profile", "Read your name and username");
+ scopes.put("email", "Read your primary email address and verification status");
+ scopes.put("offline_access", "Keep access while you are away (up to 30 days)");
+ roleService.query().stream().sorted(java.util.Comparator.comparing(Role::getName))
+ .forEach(it -> scopes.put(getRoleScope(it), "Role: " + it.getName()));
+ return scopes;
+ }
+
+ private String getRoleScope(Role role) {
+ var name = role.getName().toLowerCase(Locale.ROOT).replace(' ', '_');
+ // Keep special and non-ASCII characters in a single scope token.
+ return "role:" + URLEncoder.encode(name, StandardCharsets.UTF_8);
+ }
+
+ @Override
+ public List<Role> getRoles(Scope scope) throws ParseException {
+ if (scope == null || scope.isEmpty() || scope.toString().length() > 4096)
+ throw new ParseException("Specify at least one supported scope", OAuth2Error.INVALID_SCOPE);
+ Map<String, Role> rolesByScope = new LinkedHashMap<>();
+ roleService.query().forEach(it -> rolesByScope.put(getRoleScope(it), it));
+ List<Role> roles = new ArrayList<>();
+ for (var value: scope) {
+ String name = value.getValue();
+ if (List.of("openid", "profile", "email", "offline_access").contains(name))
+ continue;
+ var role = rolesByScope.get(name);
+ if (role == null)
+ throw new ParseException("Unknown scope", OAuth2Error.INVALID_SCOPE);
+ roles.add(role);
+ }
+ return roles;
+ }
+
+ @Transactional
+ @Override
+ public String authorize(Subject subject, AuthorizationRequest request, Collection<Long> projectIds) throws ParseException {
+ checkEnabled();
+ var owner = SecurityUtils.getAuthUser(subject);
+ var application = findApplication(request.getClientID().getValue());
+ if (application == null || !hasRegisteredRedirect(application, request)
+ || application.getOwner().isDisabled())
+ throw new ParseException("Invalid application or redirect URI", OAuth2Error.INVALID_REQUEST);
+ validateAuthorization(request);
+ var roles = getRoles(request.getScope());
+ if (roles.isEmpty() != projectIds.isEmpty())
+ throw new ExplicitException("Select at least one project for the requested roles");
+ List<Project> projects = new ArrayList<>();
+ for (Long projectId: new java.util.HashSet<>(projectIds)) {
+ var project = projectService.load(projectId);
+ if (Project.DEFAULT_ID.equals(projectId) || !SecurityUtils.canManageProject(subject, project))
+ throw new UnauthorizedException("OAuth authorization owner should have permission to manage authorized project");
+ projects.add(project);
+ }
+ var grant = new OAuthGrant();
+ grant.setOwner(owner);
+ grant.setApplication(application);
+ grant.setScopes(request.getScope().toString());
+ grant.setRedirectUri(request.getRedirectionURI().toString());
+ grant.setCodeChallenge(request.getCodeChallenge().getValue());
+ grant.setCodeExpireDate(new Date(System.currentTimeMillis() + 120_000));
+ grant.setExpireDate(new Date(System.currentTimeMillis() + REFRESH_TOKEN_SECONDS * 1000));
+ var nonce = request.getCustomParameter("nonce");
+ if (nonce != null)
+ grant.setNonce(nonce.get(0));
+ dao.persist(grant);
+ String code = grant.getId() + "." + new AuthorizationCode(32).getValue();
+ grant.setCodeHash(hash(code));
+ var token = new AccessToken();
+ token.setOwner(owner);
+ token.setName("OAuth grant " + grant.getId() + " (" + new ClientID().getValue() + ")");
+ token.setOauthGrant(grant);
+ // Not usable until the code is exchanged.
+ token.setExpireDate(new Date(0));
+ accessTokenService.createOrUpdate(token);
+ grant.getAccessTokens().add(token);
+ for (var project: projects) {
+ for (var role: roles) {
+ var authorization = new AccessTokenAuthorization();
+ authorization.setProject(project);
+ authorization.setRole(role);
+ authorization.setToken(token);
+ dao.persist(authorization);
+ token.getAuthorizations().add(authorization);
+ }
+ }
+ auditService.audit(null, "authorized OAuth application \"" + application.getName() + "\" (grant "
+ + grant.getId() + ", scopes: " + grant.getScopes() + ")", null, null);
+ return code;
+ }
+
+ private OAuthApplication authenticate(ClientID clientId, ClientAuthentication authentication) {
+ if (authentication != null)
+ clientId = authentication.getClientID();
+ if (clientId == null)
+ return null;
+ var application = findApplication(clientId.getValue());
+ if (application == null || application.getOwner().isDisabled())
+ return null;
+ if (application.isConfidential()) {
+ if (!(authentication instanceof ClientSecretBasic || authentication instanceof ClientSecretPost)
+ || !matches(((PlainClientSecret) authentication).getClientSecret().getValue(), application.getSecretHash()))
+ return null;
+ } else if (authentication != null) {
+ return null;
+ }
+ return application;
+ }
+
+ private OAuthGrant lockGrant(String credential) {
+ var id = grantId(credential);
+ if (id == null)
+ return null;
+ return dao.getSession().find(OAuthGrant.class, id, LockModeType.PESSIMISTIC_WRITE);
+ }
+
+ @Transactional
+ @Override
+ public TokenResponse exchange(TokenRequest request) {
+ if (!isEnabled())
+ return new TokenErrorResponse(OAuth2Error.TEMPORARILY_UNAVAILABLE);
+ var application = authenticate(request.getClientID(), request.getClientAuthentication());
+ if (application == null)
+ return new TokenErrorResponse(OAuth2Error.INVALID_CLIENT);
+ if (request.getResources() != null || request.getAuthorizationDetails() != null)
+ return new TokenErrorResponse(OAuth2Error.INVALID_REQUEST);
+ OAuthGrant grant;
+ if (request.getAuthorizationGrant() instanceof AuthorizationCodeGrant code) {
+ grant = lockGrant(code.getAuthorizationCode().getValue());
+ if (grant == null || !application.equals(grant.getApplication()) || !grant.isActive()
+ || !matches(code.getAuthorizationCode().getValue(), grant.getCodeHash())
+ || code.getRedirectionURI() == null || !grant.getRedirectUri().equals(code.getRedirectionURI().toString())
+ || !verifyPkce(grant.getCodeChallenge(), code.getCodeVerifier()))
+ return new TokenErrorResponse(OAuth2Error.INVALID_GRANT);
+ if (grant.getLastUsedDate() != null) {
+ revoke(grant);
+ return new TokenErrorResponse(OAuth2Error.INVALID_GRANT);
+ }
+ if (grant.getCodeExpireDate().before(new Date()))
+ return new TokenErrorResponse(OAuth2Error.INVALID_GRANT);
+ } else if (request.getAuthorizationGrant() instanceof RefreshTokenGrant refresh) {
+ String value = refresh.getRefreshToken().getValue();
+ grant = lockGrant(value);
+ if (grant == null || !application.equals(grant.getApplication()) || !grant.isActive())
+ return new TokenErrorResponse(OAuth2Error.INVALID_GRANT);
+ if (grant.getUsedRefreshTokenHashes().contains(hash(value))) {
+ revoke(grant);
+ return new TokenErrorResponse(OAuth2Error.INVALID_GRANT);
+ }
+ if (!matches(value, grant.getRefreshTokenHash()))
+ return new TokenErrorResponse(OAuth2Error.INVALID_GRANT);
+ if (request.getScope() != null && !Scope.parse(grant.getScopes()).containsAll(request.getScope()))
+ return new TokenErrorResponse(OAuth2Error.INVALID_SCOPE);
+ if (request.getScope() != null)
+ grant.setScopes(request.getScope().toString());
+ grant.getUsedRefreshTokenHashes().add(grant.getRefreshTokenHash());
+ } else {
+ return new TokenErrorResponse(OAuth2Error.UNSUPPORTED_GRANT_TYPE);
+ }
+ var scope = Scope.parse(grant.getScopes());
+ var token = grant.getAccessTokens().stream().findFirst().orElse(null);
+ if (token == null)
+ return new TokenErrorResponse(OAuth2Error.INVALID_GRANT);
+ // Narrowing a refresh scope also removes the corresponding project authorizations.
+ for (var authorization: new ArrayList<>(token.getAuthorizations())) {
+ if (!scope.contains(getRoleScope(authorization.getRole()))) {
+ dao.remove(authorization);
+ token.getAuthorizations().remove(authorization);
+ }
+ }
+ long lifetime = Math.min(ACCESS_TOKEN_SECONDS, (grant.getExpireDate().getTime() - System.currentTimeMillis()) / 1000);
+ token.setValue(new BearerAccessToken(32).getValue());
+ token.setExpireDate(new Date(System.currentTimeMillis() + lifetime * 1000));
+ accessTokenService.createOrUpdate(token);
+ RefreshToken refresh = new RefreshToken(grant.getId() + "." + new RefreshToken(32).getValue());
+ grant.setRefreshTokenHash(hash(refresh.getValue()));
+ grant.setLastUsedDate(new Date());
+ dao.persist(grant);
+ var bearer = new BearerAccessToken(token.getValue(), lifetime, scope);
+ if (scope.contains("openid"))
+ return new OIDCTokenResponse(new OIDCTokens(idToken(grant), bearer, refresh));
+ return new AccessTokenResponse(new Tokens(bearer, refresh));
+ }
+
+ @Transactional
+ @Override
+ public HTTPResponse revoke(TokenRevocationRequest request) {
+ if (!isEnabled())
+ return new TokenErrorResponse(OAuth2Error.TEMPORARILY_UNAVAILABLE).toHTTPResponse();
+ var application = authenticate(request.getClientID(), request.getClientAuthentication());
+ if (application == null)
+ return new TokenErrorResponse(OAuth2Error.INVALID_CLIENT).toHTTPResponse();
+ String value = request.getToken().getValue();
+ var grant = lockGrant(value);
+ if (grant != null && application.equals(grant.getApplication())
+ && (matches(value, grant.getRefreshTokenHash()) || grant.getUsedRefreshTokenHashes().contains(hash(value)))) {
+ revoke(grant);
+ } else {
+ var token = findAccessToken(value);
+ if (token != null && token.getOauthGrant() != null && application.equals(token.getOauthGrant().getApplication()))
+ revoke(token.getOauthGrant());
+ }
+ return new HTTPResponse(200);
+ }
+
+ private String issuer() {
+ return settingService.getSystemSetting().getServerUrl().replaceAll("/+$", "");
+ }
+
+ @Transactional
+ @Override
+ public Map<String, Object> getMetadata() {
+ checkEnabled();
+ var metadata = new OIDCProviderMetadata(new Issuer(issuer()), List.of(SubjectType.PUBLIC), URI.create(issuer() + "/~oauth/jwks"));
+ metadata.setAuthorizationEndpointURI(URI.create(issuer() + "/~oauth/authorize"));
+ metadata.setTokenEndpointURI(URI.create(issuer() + "/~oauth/token"));
+ metadata.setRevocationEndpointURI(URI.create(issuer() + "/~oauth/revoke"));
+ metadata.setUserInfoEndpointURI(URI.create(issuer() + "/~oauth/userinfo"));
+ metadata.setResponseTypes(List.of(new ResponseType(ResponseType.Value.CODE)));
+ metadata.setResponseModes(List.of(ResponseMode.QUERY));
+ metadata.setGrantTypes(List.of(GrantType.AUTHORIZATION_CODE, GrantType.REFRESH_TOKEN));
+ metadata.setCodeChallengeMethods(List.of(CodeChallengeMethod.S256));
+ var methods = List.of(ClientAuthenticationMethod.CLIENT_SECRET_BASIC, ClientAuthenticationMethod.CLIENT_SECRET_POST, ClientAuthenticationMethod.NONE);
+ metadata.setTokenEndpointAuthMethods(methods);
+ metadata.setRevocationEndpointAuthMethods(methods);
+ metadata.setIDTokenJWSAlgs(List.of(JWSAlgorithm.RS256));
+ metadata.setScopes(new Scope(getScopes().keySet().toArray(String[]::new)));
+ metadata.setClaims(List.of("sub", "name", "preferred_username", "email", "email_verified"));
+ metadata.setSupportsRequestParam(false);
+ metadata.setSupportsRequestURIParam(false);
+ metadata.setCustomParameter("onedev_scope_descriptions", getScopes());
+ return metadata.toJSONObject();
+ }
+
+ private RSAKey signingKey() {
+ checkEnabled();
+ try {
+ return RSAKey.parse(settingService.getOAuthSigningKey());
+ } catch (java.text.ParseException e) {
+ throw new IllegalStateException("Unable to load OAuth signing key", e);
+ }
+ }
+
+ @Transactional
+ @Override
+ public Map<String, Object> getJwks() {
+ return new JWKSet(signingKey().toPublicJWK()).toJSONObject();
+ }
+
+ private SignedJWT idToken(OAuthGrant grant) {
+ try {
+ var key = signingKey();
+ var claims = new JWTClaimsSet.Builder().issuer(issuer()).subject(grant.getOwner().getId().toString())
+ .audience(grant.getApplication().getClientId()).issueTime(new Date())
+ .expirationTime(new Date(System.currentTimeMillis() + ACCESS_TOKEN_SECONDS * 1000));
+ if (grant.getNonce() != null)
+ claims.claim("nonce", grant.getNonce());
+ var jwt = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(key.getKeyID()).build(), claims.build());
+ jwt.sign(new RSASSASigner(key));
+ return jwt;
+ } catch (Exception e) {
+ throw new IllegalStateException("Unable to sign ID token", e);
+ }
+ }
+
+ @Sessional
+ @Override
+ public Map<String, Object> getUserInfo(String value) {
+ if (!isEnabled())
+ return null;
+ var token = findAccessToken(value);
+ if (token == null || token.getOauthGrant() == null)
+ return null;
+ var scope = Scope.parse(token.getOauthGrant().getScopes());
+ var owner = token.getOwner();
+ Map<String, Object> claims = new LinkedHashMap<>();
+ claims.put("sub", owner.getId().toString());
+ if (scope.contains("profile")) {
+ claims.put("name", owner.getDisplayName());
+ claims.put("preferred_username", owner.getName());
+ }
+ if (scope.contains("email") && owner.getPrimaryEmailAddress() != null) {
+ claims.put("email", owner.getPrimaryEmailAddress().getValue());
+ claims.put("email_verified", owner.getPrimaryEmailAddress().isVerified());
+ }
+ return claims;
+ }
+
+ private AccessToken findAccessToken(String value) {
+ try {
+ return accessTokenService.findByValue(value);
+ } catch (DisabledAccountException e) {
+ return null;
+ }
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/oauth/OAuthEndpointServlet.java b/server-core/src/main/java/io/onedev/server/oauth/OAuthEndpointServlet.java
new file mode 100644
index 0000000000..3da8abc153
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/oauth/OAuthEndpointServlet.java
@@ -0,0 +1,116 @@
+package io.onedev.server.oauth;
+
+import java.io.IOException;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.Map;
+
+import jakarta.inject.Inject;
+import jakarta.inject.Singleton;
+import jakarta.servlet.http.HttpServlet;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import com.nimbusds.oauth2.sdk.OAuth2Error;
+import com.nimbusds.oauth2.sdk.ParseException;
+import com.nimbusds.oauth2.sdk.TokenErrorResponse;
+import com.nimbusds.oauth2.sdk.TokenRequest;
+import com.nimbusds.oauth2.sdk.TokenRevocationRequest;
+import com.nimbusds.oauth2.sdk.http.HTTPRequest;
+import com.nimbusds.oauth2.sdk.http.HTTPResponse;
+import com.nimbusds.oauth2.sdk.token.BearerAccessToken;
+
+import io.onedev.server.persistence.SessionService;
+import net.minidev.json.JSONObject;
+
+@Singleton
+public class OAuthEndpointServlet extends HttpServlet {
+
+ @Inject
+ private OAuthProviderService providerService;
+ @Inject
+ private SessionService sessionService;
+
+ @Override
+ protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ response.setHeader("Cache-Control", "no-store");
+ response.setHeader("Pragma", "no-cache");
+ response.setHeader("X-Content-Type-Options", "nosniff");
+ response.setCharacterEncoding(StandardCharsets.UTF_8.name());
+ response.setContentType("application/json");
+ var result = sessionService.call(() -> handle(request));
+ response.setStatus(result.getStatusCode());
+ if (result.getStatusCode() == 401)
+ response.setHeader("WWW-Authenticate", request.getServletPath().endsWith("userinfo") ? "Bearer" : "Basic realm=\"OAuth\"");
+ if (result.getStatusCode() == 405) {
+ String path = request.getServletPath();
+ response.setHeader("Allow", path.endsWith("userinfo") ? "GET, POST"
+ : path.endsWith("token") || path.endsWith("revoke") ? "POST" : "GET");
+ }
+ if (result.getContent() != null)
+ response.getWriter().write(result.getContent());
+ }
+
+ private HTTPResponse json(Map<String, ?> value) {
+ var response = new HTTPResponse(200);
+ response.setContent(JSONObject.toJSONString(value));
+ return response;
+ }
+
+ private HTTPResponse handle(HttpServletRequest request) throws IOException {
+ if (!providerService.isEnabled())
+ return new HTTPResponse(404);
+ String path = request.getServletPath();
+ try {
+ if (path.endsWith("/token") || path.endsWith("/revoke")) {
+ if (!"POST".equals(request.getMethod()))
+ return new HTTPResponse(405);
+ if (request.getQueryString() != null || request.getContentType() == null
+ || !request.getContentType().split(";", 2)[0].equalsIgnoreCase("application/x-www-form-urlencoded"))
+ return new TokenErrorResponse(OAuth2Error.INVALID_REQUEST).toHTTPResponse();
+ if (request.getContentLengthLong() > 16384)
+ return new TokenErrorResponse(OAuth2Error.INVALID_REQUEST).toHTTPResponse();
+ // Filters may already have asked the servlet container to parse the form body.
+ // Use that parsed form instead of reading the (possibly consumed) input stream.
+ var parameters = new java.util.LinkedHashMap<String, java.util.List<String>>();
+ request.getParameterMap().forEach((key, values) -> parameters.put(key, java.util.Arrays.asList(values)));
+ OAuthProtocol.checkSingleParameters(parameters);
+ var body = com.nimbusds.oauth2.sdk.util.URLUtils.serializeParameters(parameters);
+ if (body.length() > 16384)
+ return new TokenErrorResponse(OAuth2Error.INVALID_REQUEST).toHTTPResponse();
+ var http = new HTTPRequest(HTTPRequest.Method.POST, URI.create(request.getRequestURL().toString()));
+ http.setContentType("application/x-www-form-urlencoded");
+ http.setBody(body);
+ var headers = Collections.list(request.getHeaders("Authorization"));
+ if (headers.size() > 1)
+ throw new ParseException("Repeated Authorization header", OAuth2Error.INVALID_REQUEST);
+ if (!headers.isEmpty())
+ http.setAuthorization(headers.get(0));
+ if (!headers.isEmpty() && (parameters.containsKey("client_secret") || parameters.containsKey("client_id")))
+ throw new ParseException("Use one client authentication method", OAuth2Error.INVALID_REQUEST);
+ return path.endsWith("/token") ? providerService.exchange(TokenRequest.parse(http)).toHTTPResponse()
+ : providerService.revoke(TokenRevocationRequest.parse(http));
+ }
+ if (!"GET".equals(request.getMethod()) && !(path.endsWith("/userinfo") && "POST".equals(request.getMethod())))
+ return new HTTPResponse(405);
+ if (path.startsWith("/.well-known/"))
+ return json(providerService.getMetadata());
+ if (path.endsWith("/jwks"))
+ return json(providerService.getJwks());
+ if (path.endsWith("/userinfo")) {
+ var headers = Collections.list(request.getHeaders("Authorization"));
+ if (headers.size() != 1)
+ return new HTTPResponse(401);
+ var token = BearerAccessToken.parse(headers.get(0));
+ var claims = providerService.getUserInfo(token.getValue());
+ return claims != null ? json(claims) : new HTTPResponse(401);
+ }
+ return new HTTPResponse(404);
+ } catch (ParseException e) {
+ if (path.endsWith("/userinfo"))
+ return new HTTPResponse(401);
+ return new TokenErrorResponse(e.getErrorObject() != null ? e.getErrorObject() : OAuth2Error.INVALID_REQUEST).toHTTPResponse();
+ }
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/oauth/OAuthProtocol.java b/server-core/src/main/java/io/onedev/server/oauth/OAuthProtocol.java
new file mode 100644
index 0000000000..7771b78316
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/oauth/OAuthProtocol.java
@@ -0,0 +1,121 @@
+package io.onedev.server.oauth;
+
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+import org.apache.commons.codec.digest.DigestUtils;
+
+import com.nimbusds.oauth2.sdk.AuthorizationRequest;
+import com.nimbusds.oauth2.sdk.OAuth2Error;
+import com.nimbusds.oauth2.sdk.ParseException;
+import com.nimbusds.oauth2.sdk.ResponseMode;
+import com.nimbusds.oauth2.sdk.ResponseType;
+import com.nimbusds.oauth2.sdk.pkce.CodeChallenge;
+import com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod;
+import com.nimbusds.oauth2.sdk.pkce.CodeVerifier;
+
+import io.onedev.server.model.OAuthApplication;
+
+public class OAuthProtocol {
+
+ public static final long ACCESS_TOKEN_SECONDS = 3600;
+ public static final long REFRESH_TOKEN_SECONDS = 30 * 24 * 3600;
+
+ public static String hash(String value) {
+ return DigestUtils.sha256Hex(value);
+ }
+
+ public static boolean matches(String value, String hash) {
+ return hash != null && MessageDigest.isEqual(hash(value).getBytes(StandardCharsets.US_ASCII),
+ hash.getBytes(StandardCharsets.US_ASCII));
+ }
+
+ public static void checkSingleParameters(Map<String, List<String>> parameters) throws ParseException {
+ for (var entry: parameters.entrySet()) {
+ if (entry.getValue().size() != 1)
+ throw new ParseException("Repeated request parameter", OAuth2Error.INVALID_REQUEST);
+ }
+ }
+
+ public static boolean isValidRedirectUri(String value, boolean confidential) {
+ try {
+ URI uri = URI.create(value);
+ if (!uri.isAbsolute() || uri.getFragment() != null || uri.getUserInfo() != null || value.contains("*"))
+ return false;
+ if ("https".equals(uri.getScheme()))
+ return uri.getHost() != null;
+ if ("http".equals(uri.getScheme()))
+ return uri.getHost() != null && List.of("localhost", "127.0.0.1", "[::1]").contains(uri.getHost());
+ // Private-use schemes are limited to public native applications (RFC 8252).
+ return !confidential && uri.getScheme().contains(".") && !uri.isOpaque();
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ }
+
+ public static boolean hasRegisteredRedirect(OAuthApplication application, AuthorizationRequest request) {
+ var redirect = request.getRedirectionURI();
+ if (redirect == null)
+ return false;
+ if (application.getRedirectUriList().contains(redirect.toString()))
+ return true;
+ // Native clients bind an available loopback port at runtime (RFC 8252, section 7.3).
+ // All other URI components still have to match the registered value exactly.
+ if (!application.isConfidential() && isLoopbackHttp(redirect)
+ && redirect.getPort() > 0 && redirect.getPort() <= 65535) {
+ for (var registeredValue: application.getRedirectUriList()) {
+ var registered = URI.create(registeredValue);
+ if (isLoopbackHttp(registered) && registered.getHost().equals(redirect.getHost())
+ && Objects.equals(registered.getRawPath(), redirect.getRawPath())
+ && Objects.equals(registered.getRawQuery(), redirect.getRawQuery()))
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean isLoopbackHttp(URI uri) {
+ return "http".equals(uri.getScheme()) && uri.getRawUserInfo() == null && uri.getRawFragment() == null
+ && ("127.0.0.1".equals(uri.getHost()) || "[::1]".equals(uri.getHost()));
+ }
+
+ public static void validateAuthorization(AuthorizationRequest request) throws ParseException {
+ if (!new ResponseType(ResponseType.Value.CODE).equals(request.getResponseType()))
+ throw new ParseException("Only the authorization code flow is supported", OAuth2Error.UNSUPPORTED_RESPONSE_TYPE);
+ if (request.getResponseMode() != null && !ResponseMode.QUERY.equals(request.getResponseMode()))
+ throw new ParseException("Only query responses are supported", OAuth2Error.INVALID_REQUEST);
+ if (request.specifiesRequestObject() || request.getResources() != null
+ || request.getAuthorizationDetails() != null || request.getDPoPJWKThumbprintConfirmation() != null)
+ throw new ParseException("Unsupported authorization request extension", OAuth2Error.INVALID_REQUEST);
+ if (!CodeChallengeMethod.S256.equals(request.getCodeChallengeMethod())
+ || request.getCodeChallenge() == null
+ || !request.getCodeChallenge().getValue().matches("[A-Za-z0-9_-]{43}"))
+ throw new ParseException("PKCE with S256 is required", OAuth2Error.INVALID_REQUEST);
+ for (String parameter: List.of("max_age", "claims", "acr_values", "id_token_hint")) {
+ if (request.getCustomParameter(parameter) != null)
+ throw new ParseException("Unsupported authentication parameter: " + parameter, OAuth2Error.INVALID_REQUEST);
+ }
+ var nonce = request.getCustomParameter("nonce");
+ if (nonce != null && (nonce.size() != 1 || nonce.get(0).length() > 255))
+ throw new ParseException("Invalid nonce", OAuth2Error.INVALID_REQUEST);
+ }
+
+ public static boolean verifyPkce(String challenge, CodeVerifier verifier) {
+ return verifier != null && challenge != null
+ && verifier.getValue().matches("[A-Za-z0-9._~-]{43,128}")
+ && CodeChallenge.compute(CodeChallengeMethod.S256, verifier).getValue().equals(challenge);
+ }
+
+ public static Long grantId(String token) {
+ try {
+ int separator = token.indexOf('.');
+ return separator > 0 ? Long.valueOf(token.substring(0, separator)) : null;
+ } catch (NumberFormatException e) {
+ return null;
+ }
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/oauth/OAuthProviderService.java b/server-core/src/main/java/io/onedev/server/oauth/OAuthProviderService.java
new file mode 100644
index 0000000000..ba54f0f8f7
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/oauth/OAuthProviderService.java
@@ -0,0 +1,96 @@
+package io.onedev.server.oauth;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.shiro.subject.Subject;
+import org.jspecify.annotations.Nullable;
+
+import com.nimbusds.jose.jwk.RSAKey;
+import com.nimbusds.oauth2.sdk.AuthorizationRequest;
+import com.nimbusds.oauth2.sdk.ParseException;
+import com.nimbusds.oauth2.sdk.Scope;
+import com.nimbusds.oauth2.sdk.TokenRequest;
+import com.nimbusds.oauth2.sdk.TokenResponse;
+import com.nimbusds.oauth2.sdk.TokenRevocationRequest;
+import com.nimbusds.oauth2.sdk.http.HTTPResponse;
+
+import io.onedev.server.model.OAuthApplication;
+import io.onedev.server.model.OAuthGrant;
+import io.onedev.server.model.Role;
+import io.onedev.server.model.User;
+
+/**
+ * Methods accepting a Subject check that subject's permissions. Owner parameters
+ * identify the target account, not the acting user. Methods without a Subject
+ * leave authorization to callers unless explicitly documented otherwise.
+ */
+public interface OAuthProviderService {
+
+ boolean isEnabled();
+
+ @Nullable
+ RSAKey getPublicSigningKey();
+
+ void generateSigningKey();
+
+ void deleteSigningKey();
+
+ OAuthApplication getApplication(Long id);
+
+ OAuthApplication findApplication(String clientId);
+
+ List<OAuthApplication> getApplications(User owner);
+
+ String saveApplication(OAuthApplication application);
+
+ String rotateSecret(Long id);
+
+ void deleteApplication(Long id);
+
+ void revokeApplication(Long id);
+
+ List<OAuthGrant> getGrants(User owner);
+
+ void revokeGrant(Long id);
+
+ void revokeGrants(User owner, Long applicationId);
+
+ /**
+ * Internal operation without permission checks; callers are responsible for authorization.
+ */
+ void revokeGrants(User owner);
+
+ Map<String, String> getScopes();
+
+ List<Role> getRoles(Scope scope) throws ParseException;
+
+ /**
+ * Checks the subject's permission to manage each selected project. The caller
+ * must supply the subject of an enabled, signed-in user who approved consent.
+ */
+ String authorize(Subject subject, AuthorizationRequest request, Collection<Long> projectIds) throws ParseException;
+
+ /**
+ * Permission contract exception: validates OAuth client and grant credentials
+ * from the request instead of accepting a Subject.
+ */
+ TokenResponse exchange(TokenRequest request);
+
+ /**
+ * Permission contract exception: validates OAuth client credentials and token
+ * ownership from the request instead of accepting a Subject.
+ */
+ HTTPResponse revoke(TokenRevocationRequest request);
+
+ Map<String, Object> getMetadata();
+
+ Map<String, Object> getJwks();
+
+ /**
+ * Permission contract exception: validates the bearer token and limits claims
+ * to its granted scopes instead of accepting a Subject.
+ */
+ Map<String, Object> getUserInfo(String accessToken);
+}
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenAuthorizationResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenAuthorizationResource.java
index 6a0a1b56af..25a3a09790 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenAuthorizationResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenAuthorizationResource.java
@@ -4,6 +4,7 @@ import static io.onedev.server.security.SecurityUtils.canManageProject;
import static io.onedev.server.security.SecurityUtils.getAuthUser;
import static io.onedev.server.security.SecurityUtils.isAdministrator;
+import java.util.Objects;
import java.util.function.Function;
import org.apache.shiro.authz.UnauthorizedException;
@@ -24,6 +25,7 @@ import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
+import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
@@ -55,6 +57,8 @@ public class AccessTokenAuthorizationResource {
@GET
public AccessTokenAuthorization getAuthorization(@PathParam("authorizationId") Long authorizationId) {
var authorization = accessTokenAuthorizationService.load(authorizationId);
+ if (authorization.getToken().getOauthGrant() != null)
+ throw new NotFoundException("Access token authorization not found");
var owner = authorization.getToken().getOwner();
if (!isAdministrator() && !owner.equals(getAuthUser()))
throw new UnauthorizedException();
@@ -64,11 +68,13 @@ public class AccessTokenAuthorizationResource {
@Api(order=200, description="Create access token authorization. Access token owner should have permission to manage authorized project")
@POST
public Long createAuthorization(@NotNull AccessTokenAuthorization authorization) {
+ if (authorization.getToken().getOauthGrant() != null)
+ throw new NotFoundException("Access token not found");
var owner = authorization.getToken().getOwner();
checkAuthorization(owner, authorization.getProject(), BadRequestException::new);
accessTokenAuthorizationService.createOrUpdate(authorization);
- if (!getAuthUser().equals(owner)) {
+ if (!Objects.equals(getAuthUser(), owner)) {
var newAuditContent = VersionedXmlDoc.fromBean(authorization).toXML();
auditService.audit(null, "created access token authorization in account \"" + owner.getName() + "\" via RESTful API", null, newAuditContent);
}
@@ -79,11 +85,13 @@ public class AccessTokenAuthorizationResource {
@Path("/{authorizationId}")
@POST
public Response updateAuthorization(@PathParam("authorizationId") Long authorizationId, @NotNull AccessTokenAuthorization authorization) {
+ if (authorization.getToken().getOauthGrant() != null)
+ throw new NotFoundException("Access token authorization not found");
var owner = authorization.getToken().getOwner();
checkAuthorization(owner, authorization.getProject(), NotAcceptableException::new);
accessTokenAuthorizationService.createOrUpdate(authorization);
- if (!getAuthUser().equals(owner)) {
+ if (!Objects.equals(getAuthUser(), owner)) {
var oldAuditContent = authorization.getOldVersion().toXML();
var newAuditContent = VersionedXmlDoc.fromBean(authorization).toXML();
auditService.audit(null, "changed access token authorization in account \"" + owner.getName() + "\" via RESTful API", oldAuditContent, newAuditContent);
@@ -111,11 +119,13 @@ public class AccessTokenAuthorizationResource {
@DELETE
public Response deleteAuthorization(@PathParam("authorizationId") Long authorizationId) {
var authorization = accessTokenAuthorizationService.load(authorizationId);
+ if (authorization.getToken().getOauthGrant() != null)
+ throw new NotFoundException("Access token authorization not found");
var owner = authorization.getToken().getOwner();
if (!isAdministrator() && !owner.equals(getAuthUser()))
throw new UnauthorizedException();
accessTokenAuthorizationService.delete(authorization);
- if (!getAuthUser().equals(owner)) {
+ if (!Objects.equals(getAuthUser(), owner)) {
var oldAuditContent = VersionedXmlDoc.fromBean(authorization).toXML();
auditService.audit(null, "deleted access token authorization from account \"" + owner.getName() + "\" via RESTful API", oldAuditContent, null);
}
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenResource.java
index 63ed41f7f2..9f71430a8e 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/AccessTokenResource.java
@@ -4,19 +4,13 @@ import static io.onedev.server.security.SecurityUtils.getAuthUser;
import static io.onedev.server.security.SecurityUtils.isAdministrator;
import java.util.Collection;
+import java.util.Objects;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
-import jakarta.ws.rs.BadRequestException;
-import jakarta.ws.rs.Consumes;
-import jakarta.ws.rs.DELETE;
-import jakarta.ws.rs.GET;
-import jakarta.ws.rs.POST;
-import jakarta.ws.rs.Path;
-import jakarta.ws.rs.PathParam;
-import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@@ -35,22 +29,20 @@ import io.onedev.server.rest.annotation.Api;
@Produces(MediaType.APPLICATION_JSON)
@Singleton
public class AccessTokenResource {
-
- private final AccessTokenService accessTokenService;
- private final AuditService auditService;
-
@Inject
- public AccessTokenResource(AccessTokenService accessTokenService, AuditService auditService) {
- this.accessTokenService = accessTokenService;
- this.auditService = auditService;
- }
+ private AccessTokenService accessTokenService;
+
+ @Inject
+ private AuditService auditService;
@Api(order=100)
@Path("/{accessTokenId}")
@GET
public AccessToken getToken(@PathParam("accessTokenId") Long accessTokenId) {
var accessToken = accessTokenService.load(accessTokenId);
+ if (accessToken.getOauthGrant() != null)
+ throw new NotFoundException("Access token not found");
if (!isAdministrator() && !accessToken.getOwner().equals(getAuthUser()))
throw new UnauthorizedException();
return accessToken;
@@ -61,6 +53,8 @@ public class AccessTokenResource {
@GET
public Collection<AccessTokenAuthorization> getAuthorizations(@PathParam("accessTokenId") Long accessTokenId) {
var accessToken = accessTokenService.load(accessTokenId);
+ if (accessToken.getOauthGrant() != null)
+ throw new NotFoundException("Access token not found");
if (!isAdministrator() && !accessToken.getOwner().equals(getAuthUser()))
throw new UnauthorizedException();
return accessToken.getAuthorizations();
@@ -69,6 +63,7 @@ public class AccessTokenResource {
@Api(order=200, description="Create access token")
@POST
public Long createToken(@NotNull @Valid AccessToken accessToken) {
+ // REST creation deserializes a new token, and @JsonIgnore keeps oauthGrant null.
var owner = accessToken.getOwner();
if (!isAdministrator() && !owner.equals(getAuthUser()))
throw new UnauthorizedException();
@@ -80,7 +75,7 @@ public class AccessTokenResource {
accessTokenService.createOrUpdate(accessToken);
- if (!getAuthUser().equals(owner)) {
+ if (!Objects.equals(getAuthUser(), owner)) {
var newAuditContent = VersionedXmlDoc.fromBean(accessToken.getFacade()).toXML();
auditService.audit(null, "created access token \"" + accessToken.getName() + "\" in account \"" + owner.getName() + "\" via RESTful API",
null, newAuditContent);
@@ -93,6 +88,8 @@ public class AccessTokenResource {
@Path("/{accessTokenId}")
@POST
public Response updateToken(@PathParam("accessTokenId") Long accessTokenId, @NotNull @Valid AccessToken accessToken) {
+ if (accessToken.getOauthGrant() != null)
+ throw new NotFoundException("Access token not found");
var owner = accessToken.getOwner();
if (!isAdministrator() && !owner.equals(getAuthUser()))
throw new UnauthorizedException();
@@ -103,7 +100,7 @@ public class AccessTokenResource {
accessTokenService.createOrUpdate(accessToken);
- if (!getAuthUser().equals(owner)) {
+ if (!Objects.equals(getAuthUser(), owner)) {
var oldAuditContent = accessToken.getOldVersion().toXML();
var newAuditContent = VersionedXmlDoc.fromBean(accessToken).toXML();
auditService.audit(null, "changed access token \"" + accessToken.getName() + "\" in account \"" + owner.getName() + "\" via RESTful API",
@@ -117,11 +114,13 @@ public class AccessTokenResource {
@DELETE
public Response deleteToken(@PathParam("accessTokenId") Long accessTokenId) {
var accessToken = accessTokenService.load(accessTokenId);
- if (!isAdministrator() && !accessToken.getOwner().equals(getAuthUser()))
+ if (accessToken.getOauthGrant() != null)
+ throw new NotFoundException("Access token not found");
+ if (!isAdministrator() && !accessToken.getOwner().equals(getAuthUser()))
throw new UnauthorizedException();
accessTokenService.delete(accessToken);
- if (!getAuthUser().equals(accessToken.getOwner())) {
+ if (!Objects.equals(getAuthUser(), accessToken.getOwner())) {
var oldAuditContent = VersionedXmlDoc.fromBean(accessToken.getFacade()).toXML();
auditService.audit(null, "deleted access token \"" + accessToken.getName() + "\" from account \"" + accessToken.getOwner().getName() + "\" via RESTful API",
oldAuditContent, null);
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/UserResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/UserResource.java
index a3f44dfb81..847da59cd1 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/UserResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/UserResource.java
@@ -83,29 +83,23 @@ import io.onedev.server.service.UserService;
@Singleton
public class UserResource {
- private final UserService userService;
-
- private final SshKeyService sshKeyService;
-
- private final PasswordService passwordService;
-
- private final EmailAddressService emailAddressService;
+ @Inject
+ private UserService userService;
- private final SubscriptionService subscriptionService;
+ @Inject
+ private SshKeyService sshKeyService;
- private final AuditService auditService;
-
@Inject
- public UserResource(UserService userService, SshKeyService sshKeyService,
- PasswordService passwordService, EmailAddressService emailAddressService,
- SubscriptionService subscriptionService, AuditService auditService) {
- this.userService = userService;
- this.sshKeyService = sshKeyService;
- this.passwordService = passwordService;
- this.emailAddressService = emailAddressService;
- this.subscriptionService = subscriptionService;
- this.auditService = auditService;
- }
+ private PasswordService passwordService;
+
+ @Inject
+ private EmailAddressService emailAddressService;
+
+ @Inject
+ private SubscriptionService subscriptionService;
+
+ @Inject
+ private AuditService auditService;
private UserData getData(User user) {
var data = new UserData();
@@ -148,7 +142,9 @@ public class UserResource {
User user = userService.load(userId);
if (!SecurityUtils.isAdministrator() && !user.equals(getAuthUser()))
throw new UnauthorizedException();
- return user.getAccessTokens();
+ return user.getAccessTokens().stream()
+ .filter(token -> token.getOauthGrant() == null)
+ .collect(toList());
}
@Api(order=275)
diff --git a/server-core/src/main/java/io/onedev/server/security/DefaultAuthorizingService.java b/server-core/src/main/java/io/onedev/server/security/DefaultAuthorizingService.java
index 8a9d812f56..d21af4d57b 100644
--- a/server-core/src/main/java/io/onedev/server/security/DefaultAuthorizingService.java
+++ b/server-core/src/main/java/io/onedev/server/security/DefaultAuthorizingService.java
@@ -1,15 +1,12 @@
package io.onedev.server.security;
import static io.onedev.server.security.SecurityUtils.getUser;
+import static java.util.Objects.requireNonNull;
import java.io.ObjectStreamException;
import java.io.Serial;
import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
+import java.util.*;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
@@ -107,9 +104,8 @@ public class DefaultAuthorizingService extends AuthorizingRealm implements Autho
if (!SecurityUtils.isAnonymous(principal) || settingService.getSecuritySetting().isEnableAnonymousAccess()) {
permissions.add(p -> {
- if (p instanceof ProjectPermission) {
- ProjectPermission projectPermission = (ProjectPermission) p;
- Project project = projectPermission.getProject();
+ if (p instanceof ProjectPermission projectPermission) {
+ Project project = projectPermission.getProject();
Permission privilege = projectPermission.getPrivilege();
do {
if (project.isPermittedByLoginUser(privilege))
@@ -141,9 +137,8 @@ public class DefaultAuthorizingService extends AuthorizingRealm implements Autho
@Override
public Collection<Permission> getObjectPermissions() {
return Lists.newArrayList(permission -> {
- if (permission instanceof BasePermission) {
- BasePermission basePermission = (BasePermission) permission;
- if (!basePermission.isApplicable(result.getLeft()))
+ if (permission instanceof BasePermission basePermission) {
+ if (!basePermission.isApplicable(result.getLeft()))
return false;
}
if (permission instanceof ProjectPermission projectPermission
@@ -151,10 +146,10 @@ public class DefaultAuthorizingService extends AuthorizingRealm implements Autho
&& subscriptionService.isSubscriptionActive()
&& projectPermission.isWrite()) {
var maintenance = new ProjectPermission(projectPermission.getProject(), new MaintainProject());
- if (result.getRight().stream().noneMatch(it -> it.implies(maintenance)))
+ if (requireNonNull(result.getRight()).stream().noneMatch(it -> it.implies(maintenance)))
return false;
}
- return result.getRight().stream().anyMatch(it -> it.implies(permission));
+ return requireNonNull(result.getRight()).stream().anyMatch(it -> it.implies(permission));
});
}
@@ -198,7 +193,8 @@ public class DefaultAuthorizingService extends AuthorizingRealm implements Autho
throw new UnsupportedOperationException();
}
- public Object writeReplace() throws ObjectStreamException {
+ @Serial
+ public Object writeReplace() throws ObjectStreamException {
return new ManagedSerializedForm(AuthorizingService.class);
}
diff --git a/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java b/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
index ad5738d182..63a962008f 100644
--- a/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
+++ b/server-core/src/main/java/io/onedev/server/security/SecurityUtils.java
@@ -195,7 +195,7 @@ public class SecurityUtils extends org.apache.shiro.SecurityUtils {
}
@Nullable
- private static User getAuthUser(Subject subject) {
+ public static User getAuthUser(Subject subject) {
return getAuthUser((String) subject.getPrincipal());
}
@@ -422,10 +422,6 @@ public class SecurityUtils extends org.apache.shiro.SecurityUtils {
return subject.isPermitted(new ProjectPermission(project, new ScheduleIssues()));
}
- public static boolean isAssignedRole(Project project, Role role) {
- return isAssignedRole(getSubject(), project, role);
- }
-
public static boolean isAssignedRole(Subject subject, Project project, Role role) {
try (var ignored = AuthorizationInfoCache.open()) {
String principal = (String) subject.getPrincipal();
diff --git a/server-core/src/main/java/io/onedev/server/service/SettingService.java b/server-core/src/main/java/io/onedev/server/service/SettingService.java
index 3ce3624dc9..bc738a8d64 100644
--- a/server-core/src/main/java/io/onedev/server/service/SettingService.java
+++ b/server-core/src/main/java/io/onedev/server/service/SettingService.java
@@ -44,6 +44,12 @@ public interface SettingService extends EntityService<Setting> {
@Nullable
Setting findSetting(Key key);
+
+ @NoDBAccess
+ @Nullable
+ String getOAuthSigningKey();
+
+ void saveOAuthSigningKey(@Nullable String signingKey);
/**
* Get system setting.
diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultAccessTokenService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultAccessTokenService.java
index 7b65b81a9a..74930016e7 100644
--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultAccessTokenService.java
+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultAccessTokenService.java
@@ -1,5 +1,6 @@
package io.onedev.server.service.impl;
+import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
@@ -25,6 +26,7 @@ import io.onedev.server.persistence.TransactionService;
import io.onedev.server.persistence.annotation.Sessional;
import io.onedev.server.persistence.annotation.Transactional;
import io.onedev.server.service.AccessTokenService;
+import io.onedev.server.service.SettingService;
import io.onedev.server.service.UserService;
import io.onedev.server.util.facade.AccessTokenCache;
@@ -42,6 +44,9 @@ public class DefaultAccessTokenService extends BaseEntityService<AccessToken> im
@Inject
private SessionService sessionService;
+
+ @Inject
+ private SettingService settingService;
private volatile AccessTokenCache cache;
@@ -67,39 +72,40 @@ public class DefaultAccessTokenService extends BaseEntityService<AccessToken> im
}
}
- private AccessToken checkDisabled(AccessToken accessToken) {
- if (accessToken.getOwner().isDisabled())
- throw new DisabledAccountException("Account is disabled");
- return accessToken;
- }
-
@Override
public final AccessToken findByValue(String value) {
- return sessionService.call(new Callable<AccessToken>() {
-
- @Override
- public AccessToken call() throws Exception {
- if (cache != null) {
- var facade = cache.findByValue(value);
- if (facade != null) {
- return checkDisabled(load(facade.getId()));
- } else {
- Long userId = temporalAccessTokens.get(value);
- if (userId != null) {
- var accessToken = new AccessToken();
- accessToken.setOwner(userService.load(userId));
- accessToken.setHasOwnerPermissions(true);
- accessToken.setValue(value);
- return checkDisabled(accessToken);
- } else {
- return null;
- }
+ return sessionService.call(() -> {
+ if (cache != null) {
+ var facade = cache.findByValue(value);
+ if (facade != null) {
+ var token = load(facade.getId());
+ if (token.getOwner().isDisabled())
+ throw new DisabledAccountException("Account is disabled");
+ if (!value.equals(token.getValue())
+ || token.isExpired()
+ || token.getOauthGrant() != null && (settingService.getOAuthSigningKey() == null || !token.getOauthGrant().isActive())) {
+ return null;
}
- } else {
- throw new ServerNotReadyException();
- }
- }
- });
+ return token;
+ } else {
+ Long userId = temporalAccessTokens.get(value);
+ if (userId != null) {
+ var token = new AccessToken();
+ var user = userService.load(userId);
+ if (user.isDisabled())
+ throw new DisabledAccountException("Account is disabled");
+ token.setOwner(user);
+ token.setHasOwnerPermissions(true);
+ token.setValue(value);
+ return token;
+ } else {
+ return null;
+ }
+ }
+ } else {
+ throw new ServerNotReadyException();
+ }
+ });
}
@Sessional
@@ -107,7 +113,7 @@ public class DefaultAccessTokenService extends BaseEntityService<AccessToken> im
public void on(SystemStarting event) {
HazelcastInstance hazelcastInstance = clusterService.getHazelcastInstance();
- temporalAccessTokens = hazelcastInstance.getMap("temporalAccessTokens");
+ temporalAccessTokens = Objects.requireNonNull(hazelcastInstance).getMap("temporalAccessTokens");
cache = new AccessTokenCache(hazelcastInstance.getReplicatedMap("accessTokenCache"));
for (var token: query())
@@ -139,4 +145,4 @@ public class DefaultAccessTokenService extends BaseEntityService<AccessToken> im
}
}
-}
\ No newline at end of file
+}
diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultRoleService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultRoleService.java
index 119d6c56c9..76b85161a2 100644
--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultRoleService.java
+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultRoleService.java
@@ -267,10 +267,6 @@ public class DefaultRoleService extends BaseEntityService<Role> implements RoleS
issueReporter.setEditableIssueFields(allfieldsExcept);
}
issueReporter.setEditableIssueLinks(Lists.newArrayList("Related"));
-
- jobPrivilege = new JobPrivilege();
- jobPrivilege.setJobNames("*");
- issueReporter.getJobPrivileges().add(jobPrivilege);
create(issueReporter, new ArrayList<>());
}
diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultSettingService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultSettingService.java
index 658ac30500..e8e2af0f4f 100644
--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultSettingService.java
+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultSettingService.java
@@ -123,6 +123,17 @@ public class DefaultSettingService extends BaseEntityService<Setting> implements
var settingValue = cache.get(key);
return settingValue != null? settingValue.orElse(null): null;
}
+
+ @Override
+ public String getOAuthSigningKey() {
+ return (String) getSettingValue(Key.OAUTH_SIGNING_KEY);
+ }
+
+ @Transactional
+ @Override
+ public void saveOAuthSigningKey(@Nullable String signingKey) {
+ saveSetting(Key.OAUTH_SIGNING_KEY, signingKey);
+ }
@Override
public SystemSetting getSystemSetting() {
diff --git a/server-core/src/main/java/io/onedev/server/web/asset/icon/application.svg b/server-core/src/main/java/io/onedev/server/web/asset/icon/application.svg
new file mode 100644
index 0000000000..87f7b3893e
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/asset/icon/application.svg
@@ -0,0 +1 @@
+<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1793404331256" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="11750" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M662.528 144.2816a76.8 76.8 0 0 1 108.544 0l108.6464 108.5952a76.8 76.8 0 0 1 0 108.6464l-108.5952 108.5952a76.8 76.8 0 0 1-108.6464 0l-108.5952-108.5952a76.8 76.8 0 0 1 0-108.6464l108.5952-108.5952z m72.3968 36.1984a25.6 25.6 0 0 0-36.2496 0l-108.544 108.5952a25.6 25.6 0 0 0 0 36.2496l108.544 108.544a25.6 25.6 0 0 0 36.2496 0l108.544-108.544a25.6 25.6 0 0 0 0-36.2496l-108.544-108.544zM153.6 230.4A76.8 76.8 0 0 1 230.4 153.6h153.6A76.8 76.8 0 0 1 460.8 230.4v153.6A76.8 76.8 0 0 1 384 460.8h-153.6A76.8 76.8 0 0 1 153.6 384v-153.6zM230.4 204.8a25.6 25.6 0 0 0-25.6 25.6v153.6a25.6 25.6 0 0 0 25.6 25.6h153.6a25.6 25.6 0 0 0 25.6-25.6v-153.6a25.6 25.6 0 0 0-25.6-25.6h-153.6zM153.6 640A76.8 76.8 0 0 1 230.4 563.2h153.6A76.8 76.8 0 0 1 460.8 640v153.6A76.8 76.8 0 0 1 384 870.4h-153.6A76.8 76.8 0 0 1 153.6 793.6v-153.6z m76.8-25.6a25.6 25.6 0 0 0-25.6 25.6v153.6a25.6 25.6 0 0 0 25.6 25.6h153.6a25.6 25.6 0 0 0 25.6-25.6v-153.6a25.6 25.6 0 0 0-25.6-25.6h-153.6z m332.8 25.6a76.8 76.8 0 0 1 76.8-76.8h153.6a76.8 76.8 0 0 1 76.8 76.8v153.6a76.8 76.8 0 0 1-76.8 76.8h-153.6a76.8 76.8 0 0 1-76.8-76.8v-153.6z m76.8-25.6a25.6 25.6 0 0 0-25.6 25.6v153.6a25.6 25.6 0 0 0 25.6 25.6h153.6a25.6 25.6 0 0 0 25.6-25.6v-153.6a25.6 25.6 0 0 0-25.6-25.6h-153.6z" p-id="11751"></path></svg>
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/web/asset/icon/application2.svg b/server-core/src/main/java/io/onedev/server/web/asset/icon/application2.svg
new file mode 100644
index 0000000000..1015f97518
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/asset/icon/application2.svg
@@ -0,0 +1 @@
+<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1793404331256" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="11750" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M588.8 307.2 L678.4 396.8 L844.8 217.6" fill="none" stroke="currentColor" stroke-width="51.2" stroke-linecap="round" stroke-linejoin="round"/><path d="M153.6 230.4A76.8 76.8 0 0 1 230.4 153.6h153.6A76.8 76.8 0 0 1 460.8 230.4v153.6A76.8 76.8 0 0 1 384 460.8h-153.6A76.8 76.8 0 0 1 153.6 384v-153.6zM230.4 204.8a25.6 25.6 0 0 0-25.6 25.6v153.6a25.6 25.6 0 0 0 25.6 25.6h153.6a25.6 25.6 0 0 0 25.6-25.6v-153.6a25.6 25.6 0 0 0-25.6-25.6h-153.6zM153.6 640A76.8 76.8 0 0 1 230.4 563.2h153.6A76.8 76.8 0 0 1 460.8 640v153.6A76.8 76.8 0 0 1 384 870.4h-153.6A76.8 76.8 0 0 1 153.6 793.6v-153.6z m76.8-25.6a25.6 25.6 0 0 0-25.6 25.6v153.6a25.6 25.6 0 0 0 25.6 25.6h153.6a25.6 25.6 0 0 0 25.6-25.6v-153.6a25.6 25.6 0 0 0-25.6-25.6h-153.6z m332.8 25.6a76.8 76.8 0 0 1 76.8-76.8h153.6a76.8 76.8 0 0 1 76.8 76.8v153.6a76.8 76.8 0 0 1-76.8 76.8h-153.6a76.8 76.8 0 0 1-76.8-76.8v-153.6z m76.8-25.6a25.6 25.6 0 0 0-25.6 25.6v153.6a25.6 25.6 0 0 0 25.6 25.6h153.6a25.6 25.6 0 0 0 25.6-25.6v-153.6a25.6 25.6 0 0 0-25.6-25.6h-153.6z" p-id="11751"></path></svg>
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/web/asset/icon/group2.svg b/server-core/src/main/java/io/onedev/server/web/asset/icon/group2.svg
deleted file mode 100644
index 3c820a2e7d..0000000000
--- a/server-core/src/main/java/io/onedev/server/web/asset/icon/group2.svg
+++ /dev/null
@@ -1 +0,0 @@
-<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1720753036132" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="18350" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M390.4 448H147.2c-32 0-51.2-25.6-51.2-57.6V147.2c0-32 25.6-51.2 51.2-51.2h249.6c25.6 0 51.2 19.2 51.2 51.2v249.6c0 25.6-25.6 51.2-57.6 51.2zM876.8 448H633.6c-32 0-57.6-25.6-57.6-57.6V147.2c0-32 25.6-51.2 51.2-51.2h249.6c32 0 51.2 25.6 51.2 51.2v249.6c0 25.6-19.2 51.2-51.2 51.2zM390.4 928H147.2c-32 0-51.2-25.6-51.2-51.2V633.6c0-32 19.2-57.6 51.2-57.6h249.6c25.6 0 51.2 25.6 51.2 57.6v249.6c0 25.6-25.6 44.8-57.6 44.8zM876.8 928H633.6c-32 0-51.2-25.6-51.2-51.2V633.6c-6.4-32 19.2-57.6 51.2-57.6h249.6c32 0 51.2 25.6 51.2 51.2v249.6c-6.4 32-25.6 51.2-57.6 51.2z" fill="" p-id="18351"></path></svg>
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/web/component/link/copytoclipboard/CopyToClipboardResourceReference.java b/server-core/src/main/java/io/onedev/server/web/component/link/copytoclipboard/CopyToClipboardResourceReference.java
index c7732fa111..f7f90b9e67 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/link/copytoclipboard/CopyToClipboardResourceReference.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/link/copytoclipboard/CopyToClipboardResourceReference.java
@@ -3,10 +3,12 @@ package io.onedev.server.web.component.link.copytoclipboard;
import java.io.Serial;
import java.util.List;
+import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.HeaderItem;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import io.onedev.server.web.asset.clipboard.ClipboardResourceReference;
+import io.onedev.server.web.page.base.BaseDependentCssResourceReference;
import io.onedev.server.web.page.base.BaseDependentResourceReference;
public class CopyToClipboardResourceReference extends BaseDependentResourceReference {
@@ -22,6 +24,8 @@ public class CopyToClipboardResourceReference extends BaseDependentResourceRefer
public List<HeaderItem> getDependencies() {
List<HeaderItem> dependencies = super.getDependencies();
dependencies.add(JavaScriptHeaderItem.forReference(new ClipboardResourceReference()));
+ dependencies.add(CssHeaderItem.forReference(new BaseDependentCssResourceReference(
+ CopyToClipboardResourceReference.class, "copy-to-clipboard.css")));
return dependencies;
}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/link/copytoclipboard/copy-to-clipboard.css b/server-core/src/main/java/io/onedev/server/web/component/link/copytoclipboard/copy-to-clipboard.css
new file mode 100644
index 0000000000..ec5146c358
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/component/link/copytoclipboard/copy-to-clipboard.css
@@ -0,0 +1,8 @@
+code.code-span {
+ cursor: pointer;
+}
+code.code-span.copied,
+.dark-mode code.code-span.copied {
+ background-color: var(--primary);
+ color: white;
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/markdown/markdown.css b/server-core/src/main/java/io/onedev/server/web/component/markdown/markdown.css
index 569c27b32c..5f613b58b9 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/markdown/markdown.css
+++ b/server-core/src/main/java/io/onedev/server/web/component/markdown/markdown.css
@@ -306,17 +306,6 @@ body.markdown-editor-expanded {
word-break: break-word !important;
overflow-wrap: break-word !important;
}
-.markdown-rendered code.code-span {
- cursor: pointer;
-}
-.markdown-rendered code.code-span.copied {
- background-color: var(--primary);
- color: white;
-}
-.dark-mode .markdown-rendered code.code-span.copied {
- background-color: var(--primary);
- color: white;
-}
.markdown-rendered pre.code.suggestion {
white-space: normal;
}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenListPanel.java b/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenListPanel.java
index 84db7cfa03..f9a55127f8 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenListPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/user/accesstoken/AccessTokenListPanel.java
@@ -42,6 +42,7 @@ public abstract class AccessTokenListPanel extends Panel {
@Override
public List<AccessToken> getObject() {
var tokens = new ArrayList<>(getUser().getAccessTokens());
+ tokens.removeIf(it -> it.getOauthGrant() != null);
Collections.sort(tokens);
return tokens;
}
diff --git a/server-core/src/main/java/io/onedev/server/web/editable/editable.css b/server-core/src/main/java/io/onedev/server/web/editable/editable.css
index b190522200..8fbb154d0a 100644
--- a/server-core/src/main/java/io/onedev/server/web/editable/editable.css
+++ b/server-core/src/main/java/io/onedev/server/web/editable/editable.css
@@ -160,14 +160,6 @@
margin: 0.8rem 0;
}
-.editable-description code.code-span {
- cursor: pointer;
-}
-.editable-description code.code-span.copied {
- background-color: var(--primary);
- color: white;
-}
-
.property-editor .select2-container {
width: 100%;
}
diff --git a/server-core/src/main/java/io/onedev/server/web/editable/jobprivilege/JobPrivilegeListEditSupport.java b/server-core/src/main/java/io/onedev/server/web/editable/jobprivilege/JobPrivilegeListEditSupport.java
index 21e36a5f5a..27e41a4d85 100644
--- a/server-core/src/main/java/io/onedev/server/web/editable/jobprivilege/JobPrivilegeListEditSupport.java
+++ b/server-core/src/main/java/io/onedev/server/web/editable/jobprivilege/JobPrivilegeListEditSupport.java
@@ -1,46 +1,53 @@
-package io.onedev.server.web.editable.jobprivilege;
-
-import java.io.Serializable;
-import java.util.List;
-
-import org.apache.wicket.model.IModel;
-
-import io.onedev.server.model.support.role.JobPrivilege;
-import io.onedev.server.util.ReflectionUtils;
-import io.onedev.server.web.editable.EditSupport;
-import io.onedev.server.web.editable.PropertyContext;
-import io.onedev.server.web.editable.PropertyDescriptor;
-import io.onedev.server.web.editable.PropertyEditor;
-import io.onedev.server.web.editable.PropertyViewer;
-
-public class JobPrivilegeListEditSupport implements EditSupport {
-
- @Override
- public PropertyContext<?> getEditContext(PropertyDescriptor descriptor) {
- if (List.class.isAssignableFrom(descriptor.getPropertyClass())) {
- Class<?> elementClass = ReflectionUtils.getCollectionElementClass(descriptor.getPropertyGetter().getGenericReturnType());
- if (elementClass == JobPrivilege.class) {
- return new PropertyContext<List<Serializable>>(descriptor) {
-
- @Override
- public PropertyViewer renderForView(String componentId, final IModel<List<Serializable>> model) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public PropertyEditor<List<Serializable>> renderForEdit(String componentId, IModel<List<Serializable>> model) {
- return new JobPrivilegeListEditPanel(componentId, descriptor, model);
- }
-
- };
- }
- }
- return null;
- }
-
- @Override
- public int getPriority() {
- return 0;
- }
-
-}
+package io.onedev.server.web.editable.jobprivilege;
+
+import java.io.Serializable;
+import java.util.List;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.model.IModel;
+
+import io.onedev.server.model.support.role.JobPrivilege;
+import io.onedev.server.util.ReflectionUtils;
+import io.onedev.server.web.editable.EditSupport;
+import io.onedev.server.web.editable.PropertyContext;
+import io.onedev.server.web.editable.PropertyDescriptor;
+import io.onedev.server.web.editable.PropertyEditor;
+import io.onedev.server.web.editable.PropertyViewer;
+import io.onedev.server.web.editable.beanlist.BeanListPropertyViewer;
+
+public class JobPrivilegeListEditSupport implements EditSupport {
+
+ @Override
+ public PropertyContext<?> getEditContext(PropertyDescriptor descriptor) {
+ if (List.class.isAssignableFrom(descriptor.getPropertyClass())) {
+ Class<?> elementClass = ReflectionUtils.getCollectionElementClass(descriptor.getPropertyGetter().getGenericReturnType());
+ if (elementClass == JobPrivilege.class) {
+ return new PropertyContext<List<Serializable>>(descriptor) {
+
+ @Override
+ public PropertyViewer renderForView(String componentId, final IModel<List<Serializable>> model) {
+ return new PropertyViewer(componentId, descriptor) {
+ @Override
+ protected Component newContent(String id, PropertyDescriptor property) {
+ return new BeanListPropertyViewer(id, property, model.getObject());
+ }
+ };
+ }
+
+ @Override
+ public PropertyEditor<List<Serializable>> renderForEdit(String componentId, IModel<List<Serializable>> model) {
+ return new JobPrivilegeListEditPanel(componentId, descriptor, model);
+ }
+
+ };
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public int getPriority() {
+ return 0;
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.java b/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.java
index e432df6d29..6d400f199b 100644
--- a/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.java
+++ b/server-core/src/main/java/io/onedev/server/web/mapper/BaseUrlMapper.java
@@ -38,6 +38,7 @@ import io.onedev.server.web.page.admin.emailtemplates.StopwatchOverdueTemplatePa
import io.onedev.server.web.page.admin.emailtemplates.UserInvitationTemplatePage;
import io.onedev.server.web.page.admin.emailtemplates.WorkspaceNotificationTemplatePage;
import io.onedev.server.web.page.admin.gpgsigningkey.GpgSigningKeyPage;
+import io.onedev.server.web.page.admin.oauthsigningkey.OAuthSigningKeyPage;
import io.onedev.server.web.page.admin.gpgtrustedkeys.GpgTrustedKeysPage;
import io.onedev.server.web.page.admin.groovyscript.GroovyScriptListPage;
import io.onedev.server.web.page.admin.groupmanagement.GroupListPage;
@@ -175,6 +176,12 @@ import io.onedev.server.web.page.security.EmailAddressVerificationPage;
import io.onedev.server.web.page.security.LoginPage;
import io.onedev.server.web.page.security.LogoutPage;
import io.onedev.server.web.page.security.OAuthCallbackPage;
+import io.onedev.server.web.page.oauth.OAuthAuthorizePage;
+import io.onedev.server.web.page.oauth.MyOAuthApplicationsPage;
+import io.onedev.server.web.page.oauth.MyOAuthApplicationPage;
+import io.onedev.server.web.page.oauth.NewMyOAuthApplicationPage;
+import io.onedev.server.web.page.oauth.MyAuthorizedApplicationPage;
+import io.onedev.server.web.page.oauth.MyAuthorizedApplicationsPage;
import io.onedev.server.web.page.security.PasswordResetPage;
import io.onedev.server.web.page.security.SignUpPage;
import io.onedev.server.web.page.security.SsoProcessPage;
@@ -257,6 +264,12 @@ public class BaseUrlMapper extends CompoundRequestMapper {
add(new BasePageMapper("~my/ssh-keys", MySshKeysPage.class));
add(new BasePageMapper("~my/gpg-keys", MyGpgKeysPage.class));
add(new BasePageMapper("~my/access-tokens", MyAccessTokensPage.class));
+ add(new BasePageMapper("~my/oauth-applications", MyOAuthApplicationsPage.class));
+ add(new BasePageMapper("~my/oauth-applications/new", NewMyOAuthApplicationPage.class));
+ add(new BasePageMapper("~my/oauth-applications/${application}", MyOAuthApplicationPage.class));
+ add(new BasePageMapper("~my/authorized-applications", MyAuthorizedApplicationsPage.class));
+ add(new BasePageMapper("~my/authorized-applications/${application}", MyAuthorizedApplicationPage.class));
+ add(new BasePageMapper("~oauth/authorize", OAuthAuthorizePage.class));
add(new BasePageMapper("~my/two-factor-authentication", MyTwoFactorAuthenticationPage.class));
add(new BasePageMapper("~my/sso-accounts", MySsoAccountsPage.class));
add(new BasePageMapper("~my/query-watches/#{tab}", MyQueryWatchesPage.class));
@@ -412,6 +425,7 @@ public class BaseUrlMapper extends CompoundRequestMapper {
add(new BasePageMapper("~administration/settings/sso-providers/${provider}", SsoProviderDetailPage.class));
add(new BasePageMapper("~administration/settings/ssh-server-key", SshServerKeyPage.class));
add(new BasePageMapper("~administration/settings/gpg-signing-key", GpgSigningKeyPage.class));
+ add(new BasePageMapper("~administration/settings/oauth-signing-key", OAuthSigningKeyPage.class));
add(new BasePageMapper("~administration/settings/gpg-trusted-keys", GpgTrustedKeysPage.class));
add(new BasePageMapper("~administration/agents", AgentListPage.class));
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/gpgsigningkey/GpgSigningKeyPage.html b/server-core/src/main/java/io/onedev/server/web/page/admin/gpgsigningkey/GpgSigningKeyPage.html
index a811d9e615..90861fdc43 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/gpgsigningkey/GpgSigningKeyPage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/gpgsigningkey/GpgSigningKeyPage.html
@@ -23,6 +23,7 @@
<pre wicket:id="publicKey" class="font-size-sm bg-light p-3 rounded"></pre>
</dd>
</dl>
+ <a wicket:id="regenerate" class="btn btn-light-primary mr-2"><wicket:t>Regenerate</wicket:t></a>
<a wicket:id="delete" class="btn btn-light-danger"><wicket:t>Delete</wicket:t></a>
</wicket:fragment>
-</wicket:extend>
\ No newline at end of file
+</wicket:extend>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/gpgsigningkey/GpgSigningKeyPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/gpgsigningkey/GpgSigningKeyPage.java
index a67eb2a1f6..c4569fd92a 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/gpgsigningkey/GpgSigningKeyPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/gpgsigningkey/GpgSigningKeyPage.java
@@ -54,6 +54,35 @@ public class GpgSigningKeyPage extends AdministrationPage {
String publicKey = new String(baos.toByteArray());
fragment.add(new Label("publicKey", publicKey));
fragment.add(new CopyToClipboardLink("copyPublicKey", Model.of(publicKey)));
+
+ fragment.add(new AjaxLink<Void>("regenerate") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ new ConfirmModalPanel(target) {
+
+ @Override
+ protected void onConfirm(AjaxRequestTarget target) {
+ generateSigningKey();
+ auditService.audit(null, "regenerated GPG signing key", null, null);
+ setResponsePage(GpgSigningKeyPage.class);
+ }
+
+ @Override
+ protected String getConfirmMessage() {
+ return _T("Commits generated by ${productName} previously will be shown as unverified if this key is regenerated. "
+ + "Type <code>yes</code> below if you want to continue.");
+ }
+
+ @Override
+ protected String getConfirmInput() {
+ return "yes";
+ }
+
+ };
+ }
+
+ });
fragment.add(new AjaxLink<Void>("delete") {
@@ -93,21 +122,7 @@ public class GpgSigningKeyPage extends AdministrationPage {
@Override
public void onClick(AjaxRequestTarget target) {
- ByteArrayOutputStream baos;
- try {
- PGPKeyRingGenerator generator = GpgUtils.generateKeyRingGenerator(
- User.SYSTEM_NAME + "<" + User.getSystemNoreplyEmailAddress() + ">");
-
- PGPSecretKeyRing secretKeyRing = generator.generateSecretKeyRing();
- baos = new ByteArrayOutputStream();
- secretKeyRing.encode(baos);
- } catch (PGPException | IOException e) {
- throw new RuntimeException(e);
- }
-
- GpgSetting setting = getSettingService().getGpgSetting();
- setting.setEncodedSigningKey(baos.toByteArray());
- getSettingService().saveGpgSetting(setting);
+ generateSigningKey();
auditService.audit(null, "generated GPG signing key", null, null);
setResponsePage(GpgSigningKeyPage.class);
}
@@ -116,6 +131,19 @@ public class GpgSigningKeyPage extends AdministrationPage {
add(fragment);
}
}
+
+ private void generateSigningKey() {
+ try {
+ PGPKeyRingGenerator generator = GpgUtils.generateKeyRingGenerator(
+ User.SYSTEM_NAME + "<" + User.getSystemNoreplyEmailAddress() + ">");
+ byte[] encodedSigningKey = generator.generateSecretKeyRing().getEncoded();
+ GpgSetting setting = getSettingService().getGpgSetting();
+ setting.setEncodedSigningKey(encodedSigningKey);
+ getSettingService().saveGpgSetting(setting);
+ } catch (PGPException | IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
private SettingService getSettingService() {
return OneDev.getInstance(SettingService.class);
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/oauthsigningkey/OAuthSigningKeyPage.html b/server-core/src/main/java/io/onedev/server/web/page/admin/oauthsigningkey/OAuthSigningKeyPage.html
new file mode 100644
index 0000000000..47995b84fd
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/oauthsigningkey/OAuthSigningKeyPage.html
@@ -0,0 +1,25 @@
+<wicket:extend>
+ <div class="card">
+ <div class="card-body">
+ <div class="alert alert-light alert-notice mb-4">
+ <wicket:t>This key signs OpenID Connect ID tokens. Generating a key enables the OAuth2/OIDC provider, allowing users to register applications and authorize access to their account and projects.</wicket:t>
+ </div>
+ <div wicket:id="content"></div>
+ </div>
+ </div>
+ <wicket:fragment wicket:id="undefinedFrag">
+ <p class="text-muted"><wicket:t>The OAuth2/OIDC provider is disabled because no signing key is configured.</wicket:t></p>
+ <a wicket:id="generate" class="btn btn-primary"><wicket:t>Generate</wicket:t></a>
+ </wicket:fragment>
+ <wicket:fragment wicket:id="definedFrag">
+ <p class="text-success font-weight-bold"><wicket:t>The OAuth2/OIDC provider is enabled.</wicket:t></p>
+ <dl>
+ <dt><wicket:t>Key ID</wicket:t></dt>
+ <dd wicket:id="keyID" class="text-break"></dd>
+ <dt class="mb-2"><wicket:t>Public Key</wicket:t> <a wicket:id="copyPublicKey" t:data-tippy-content="Copy public key"><wicket:svg href="copy" class="icon"/></a></dt>
+ <dd><pre wicket:id="publicKey" class="font-size-sm bg-light p-3 rounded text-wrap text-break"></pre></dd>
+ </dl>
+ <a wicket:id="regenerate" class="btn btn-light-primary mr-2"><wicket:t>Regenerate</wicket:t></a>
+ <a wicket:id="delete" class="btn btn-light-danger"><wicket:t>Delete</wicket:t></a>
+ </wicket:fragment>
+</wicket:extend>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/oauthsigningkey/OAuthSigningKeyPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/oauthsigningkey/OAuthSigningKeyPage.java
new file mode 100644
index 0000000000..a95f039b52
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/oauthsigningkey/OAuthSigningKeyPage.java
@@ -0,0 +1,87 @@
+package io.onedev.server.web.page.admin.oauthsigningkey;
+
+import static io.onedev.server.web.translation.Translation._T;
+
+import jakarta.inject.Inject;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+
+import io.onedev.server.oauth.OAuthProviderService;
+import io.onedev.server.web.component.link.copytoclipboard.CopyToClipboardLink;
+import io.onedev.server.web.component.modal.confirm.ConfirmModalPanel;
+import io.onedev.server.web.page.admin.AdministrationPage;
+
+public class OAuthSigningKeyPage extends AdministrationPage {
+
+ @Inject
+ private OAuthProviderService providerService;
+
+ public OAuthSigningKeyPage(PageParameters parameters) {
+ super(parameters);
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+ var key = providerService.getPublicSigningKey();
+ if (key == null) {
+ var fragment = new Fragment("content", "undefinedFrag", this);
+ fragment.add(new AjaxLink<Void>("generate") {
+ @Override public void onClick(AjaxRequestTarget target) {
+ providerService.generateSigningKey();
+ setResponsePage(OAuthSigningKeyPage.class);
+ }
+ });
+ add(fragment);
+ } else {
+ var fragment = new Fragment("content", "definedFrag", this);
+ fragment.add(new Label("keyID", key.getKeyID()));
+ var publicKey = key.toJSONString();
+ fragment.add(new Label("publicKey", publicKey));
+ fragment.add(new CopyToClipboardLink("copyPublicKey", Model.of(publicKey)));
+ fragment.add(newKeyAction("regenerate", false));
+ fragment.add(newKeyAction("delete", true));
+ add(fragment);
+ }
+ }
+
+ private AjaxLink<Void> newKeyAction(String id, boolean delete) {
+ return new AjaxLink<>(id) {
+ @Override public void onClick(AjaxRequestTarget target) {
+ new ConfirmModalPanel(target) {
+ @Override protected void onConfirm(AjaxRequestTarget target) {
+ if (delete)
+ providerService.deleteSigningKey();
+ else
+ providerService.generateSigningKey();
+ setResponsePage(OAuthSigningKeyPage.class);
+ }
+
+ @Override protected String getConfirmMessage() {
+ return delete
+ ? _T("Deleting this key disables the OAuth2/OIDC provider and revokes all existing authorizations. "
+ + "Registered applications are preserved. Type <code>yes</code> below to continue.")
+ : _T("Regenerating this key revokes all existing authorizations and replaces the public signing key. "
+ + "Applications need to sign in again and refresh their cached signing key. "
+ + "Type <code>yes</code> below to continue.");
+ }
+
+ @Override protected String getConfirmInput() {
+ return "yes";
+ }
+ };
+ }
+ };
+ }
+
+ @Override
+ protected Component newTopbarTitle(String id) {
+ return new Label(id, _T("OAuth Signing Key"));
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.html b/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.html
index 8ad0cc8968..c6cac3bac0 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.html
@@ -48,11 +48,11 @@
<a wicket:id="alerts" t:data-tippy-content="Alerts" class="text-warning topbar-link d-none d-lg-inline"><wicket:svg href="exclamation-circle-o" class="icon fade-in-out"></wicket:svg></a>
<a wicket:id="newVersionStatus" t:data-tippy-content="New version available. Red for security/critical update, yellow for bug fix, blue for feature update. Click to show changes. Disable in system setting" class="new-version-status topbar-link d-none"><img wicket:id="icon"/></a>
<a wicket:id="showChat" t:data-tippy-content="Chat with AI" class="topbar-link"><wicket:svg href="ai" class="icon"/></a>
- <a wicket:id="colorMode" t:data-tippy-content="Color mode" class="topbar-link">
+ <a wicket:id="colorMode" t:data-tippy-content="Color mode" class="topbar-link d-none d-sm-inline">
<svg wicket:id="icon" class="icon"/>
</a>
<a wicket:id="showCommandPalette" class="topbar-link command-palette d-none d-md-inline"></a>
- <a wicket:id="languageSelector" t:data-tippy-content="Language" class="topbar-link language-selector"><wicket:svg href="globe" class="icon"></wicket:svg></a>
+ <a wicket:id="languageSelector" t:data-tippy-content="Language" class="topbar-link language-selector d-none d-sm-inline"><wicket:svg href="globe" class="icon"></wicket:svg></a>
<a wicket:id="signIn" class="topbar-link sign-in"><wicket:svg href="login" class="icon"/> <span class="d-none d-sm-inline"><wicket:t>Sign In</wicket:t></span></a>
<a wicket:id="userInfo" class="user-info topbar-link">
<img wicket:id="avatar">
diff --git a/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java b/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java
index 1ecadbf063..312eb4c1d7 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java
@@ -130,6 +130,7 @@ import io.onedev.server.web.page.admin.emailtemplates.ServiceDeskIssueOpenedTemp
import io.onedev.server.web.page.admin.emailtemplates.StopwatchOverdueTemplatePage;
import io.onedev.server.web.page.admin.emailtemplates.UserInvitationTemplatePage;
import io.onedev.server.web.page.admin.gpgsigningkey.GpgSigningKeyPage;
+import io.onedev.server.web.page.admin.oauthsigningkey.OAuthSigningKeyPage;
import io.onedev.server.web.page.admin.gpgtrustedkeys.GpgTrustedKeysPage;
import io.onedev.server.web.page.admin.groovyscript.GroovyScriptListPage;
import io.onedev.server.web.page.admin.groupmanagement.GroupListPage;
@@ -168,6 +169,10 @@ import io.onedev.server.web.page.base.BasePage;
import io.onedev.server.web.page.help.IncompatibilitiesPage;
import io.onedev.server.web.page.my.MyPage;
import io.onedev.server.web.page.my.accesstoken.MyAccessTokensPage;
+import io.onedev.server.web.page.oauth.MyOAuthApplicationsPage;
+import io.onedev.server.web.page.oauth.MyOAuthApplicationPage;
+import io.onedev.server.web.page.oauth.MyAuthorizedApplicationPage;
+import io.onedev.server.web.page.oauth.MyAuthorizedApplicationsPage;
import io.onedev.server.web.page.my.aisetting.MyEntitlementSettingPage;
import io.onedev.server.web.page.my.aisetting.MyModelSettingPage;
import io.onedev.server.web.page.my.aisetting.MyBehaviorPage;
@@ -275,9 +280,10 @@ public abstract class LayoutPage extends BasePage {
GpgSigningKeyPage.class, new PageParameters()));
keyManagementMenuItems.add(new SidebarMenuItem.Page(null, _T("GPG Trusted Keys"),
GpgTrustedKeysPage.class, new PageParameters()));
+ keyManagementMenuItems.add(new SidebarMenuItem.Page(null, _T("OAuth Signing Key"),
+ OAuthSigningKeyPage.class, new PageParameters()));
- var keysTitle = sshPort!=0? _T("SSH & GPG Keys"): _T("GPG Keys");
- administrationMenuItems.add(new SidebarMenuItem.SubMenu(null, keysTitle, keyManagementMenuItems));
+ administrationMenuItems.add(new SidebarMenuItem.SubMenu(null, _T("Keys"), keyManagementMenuItems));
List<SidebarMenuItem> issueSettingMenuItems = new ArrayList<>();
issueSettingMenuItems.add(new SidebarMenuItem.Page(null, _T("Fields"), IssueFieldListPage.class, new PageParameters()));
@@ -1278,6 +1284,12 @@ public abstract class LayoutPage extends BasePage {
getPage() instanceof MyGpgKeysPage));
menuItems.add(newPageMenuItem(_T("Access Tokens"), "token", MyAccessTokensPage.class,
getPage() instanceof MyAccessTokensPage));
+ if (getSettingService().getOAuthSigningKey() != null) {
+ menuItems.add(newPageMenuItem(_T("OAuth Applications"), "application", MyOAuthApplicationsPage.class,
+ getPage() instanceof MyOAuthApplicationsPage || getPage() instanceof MyOAuthApplicationPage));
+ menuItems.add(newPageMenuItem(_T("Authorized Applications"), "application2", MyAuthorizedApplicationsPage.class,
+ getPage() instanceof MyAuthorizedApplicationsPage || getPage() instanceof MyAuthorizedApplicationPage));
+ }
}
if (user.getType() == ORDINARY && !user.isDisabled() && user.isEnforce2FA()) {
menuItems.add(newPageMenuItem(_T("Two-factor Authentication"), "shield",
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationPage.html b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationPage.html
new file mode 100644
index 0000000000..fa6ddb9d7f
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationPage.html
@@ -0,0 +1,41 @@
+<wicket:extend xmlns:wicket="http://www.w3.org/1999/xhtml">
+ <form wicket:id="form" method="post">
+ <input wicket:id="csrf" type="hidden">
+ <h5 wicket:id="name" class="text-break mb-4"></h5>
+ <dl class="row mb-4">
+ <dt class="col-sm-3 font-weight-normal mb-sm-3"><wicket:t>Homepage</wicket:t></dt>
+ <dd class="col-sm-9 mb-3"><a wicket:id="homepage" class="text-break" target="_blank" rel="noopener noreferrer"></a></dd>
+ <dt class="col-sm-3 font-weight-normal mb-sm-3"><wicket:t>Owner</wicket:t></dt>
+ <dd wicket:id="owner" class="col-sm-9 mb-3"></dd>
+ <dt class="col-sm-3 font-weight-normal"><wicket:t>Client ID</wicket:t></dt>
+ <dd class="col-sm-9 mb-0"><code wicket:id="clientId" class="text-break"></code></dd>
+ </dl>
+ <div class="mb-5">
+ <button wicket:id="revokeAll" type="submit" class="btn btn-sm btn-light-danger"><wicket:t>Revoke All</wicket:t></button>
+ </div>
+ <h5 class="border-top pt-5 mb-4"><wicket:t>Authorized Tokens</wicket:t> <span class="text-muted font-size-base ml-2">(<span wicket:id="count"></span>)</span></h5>
+ <p class="text-muted mb-4"><wicket:t>Each token has its own permissions and expiration. Revoking a token also revokes its refresh token. Revoke all to remove this application's access to your account.</wicket:t></p>
+ <div wicket:id="tokens" class="border rounded p-4 mb-4">
+ <dl class="row mb-0">
+ <dt class="col-sm-3 font-weight-normal mb-sm-3"><wicket:t>Authorized</wicket:t></dt>
+ <dd wicket:id="created" class="col-sm-9 mb-3"></dd>
+ <dt class="col-sm-3 font-weight-normal mb-sm-3"><wicket:t>Last token exchange</wicket:t></dt>
+ <dd wicket:id="used" class="col-sm-9 mb-3"></dd>
+ <dt class="col-sm-3 font-weight-normal mb-sm-3"><wicket:t>Access token expires</wicket:t></dt>
+ <dd wicket:id="accessExpires" class="col-sm-9 mb-3"></dd>
+ <dt class="col-sm-3 font-weight-normal mb-sm-3"><wicket:t>Authorization expires</wicket:t></dt>
+ <dd wicket:id="expires" class="col-sm-9 mb-3"></dd>
+ <dt class="col-sm-3 font-weight-normal mb-sm-3"><wicket:t>Redirect URI</wicket:t></dt>
+ <dd class="col-sm-9 mb-3"><code wicket:id="redirectUri" class="text-break"></code></dd>
+ <dt class="col-sm-3 font-weight-normal mb-sm-3"><wicket:t>Scopes</wicket:t></dt>
+ <dd class="col-sm-9 mb-3"><span wicket:id="scopes" class="d-inline-block mr-2"><code wicket:id="scope" class="text-break"></code></span></dd>
+ <dt class="col-sm-3 font-weight-normal"><wicket:t>Projects and roles</wicket:t></dt>
+ <dd wicket:id="projects" class="col-sm-9 text-break mb-0"></dd>
+ </dl>
+ <button wicket:id="revoke" type="submit" class="btn btn-sm btn-light-danger mt-4"><wicket:t>Revoke</wicket:t></button>
+ </div>
+ </form>
+ <wicket:fragment wicket:id="topbarTitleFrag">
+ <a wicket:id="applications"><wicket:t>Authorized Applications</wicket:t></a> <span class="dot"></span> <span wicket:id="name" class="text-truncate"></span>
+ </wicket:fragment>
+</wicket:extend>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationPage.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationPage.java
new file mode 100644
index 0000000000..d680efde33
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationPage.java
@@ -0,0 +1,167 @@
+package io.onedev.server.web.page.oauth;
+
+import static io.onedev.server.web.translation.Translation._T;
+
+import java.text.MessageFormat;
+import java.util.Comparator;
+import java.util.List;
+
+import jakarta.inject.Inject;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.RestartResponseException;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.markup.html.form.AjaxButton;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.head.JavaScriptHeaderItem;
+import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.link.ExternalLink;
+import org.apache.wicket.markup.html.list.ListItem;
+import org.apache.wicket.markup.html.list.ListView;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.unbescape.javascript.JavaScriptEscape;
+
+import io.onedev.server.model.OAuthApplication;
+import io.onedev.server.model.OAuthGrant;
+import io.onedev.server.oauth.OAuthProviderService;
+import io.onedev.server.util.DateUtils;
+import io.onedev.server.web.ajaxlistener.ConfirmClickListener;
+import io.onedev.server.web.component.link.copytoclipboard.CopyToClipboardResourceReference;
+import io.onedev.server.web.page.my.MyPage;
+
+public class MyAuthorizedApplicationPage extends MyPage {
+
+ public static final String PARAM_APPLICATION = "application";
+
+ @Inject
+ private OAuthProviderService providerService;
+
+ private final Long applicationId;
+
+ private final LoadableDetachableModel<List<OAuthGrant>> grants;
+
+ @Override protected boolean isPermitted() {
+ return super.isPermitted() && providerService.isEnabled();
+ }
+
+ public MyAuthorizedApplicationPage(PageParameters parameters) {
+ super(parameters);
+ applicationId = parameters.get(PARAM_APPLICATION).toOptionalLong();
+ if (applicationId == null)
+ throw new RestartResponseException(MyAuthorizedApplicationsPage.class);
+ grants = new LoadableDetachableModel<>() {
+ @Override protected List<OAuthGrant> load() {
+ return providerService.getGrants(getUser()).stream()
+ .filter(it -> it.getApplication().getId().equals(applicationId))
+ .sorted(Comparator.comparing(OAuthGrant::getCreateDate).reversed()).toList();
+ }
+ };
+ }
+
+ private OAuthApplication getAuthorizedApplication() {
+ if (grants.getObject().isEmpty())
+ throw new RestartResponseException(MyAuthorizedApplicationsPage.class);
+ return grants.getObject().get(0).getApplication();
+ }
+
+ @Override protected void onInitialize() {
+ super.onInitialize();
+ var application = getAuthorizedApplication();
+ var form = new OAuthForm("form") {
+ @Override public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(JavaScriptHeaderItem.forReference(new CopyToClipboardResourceReference()));
+ response.render(OnDomReadyHeaderItem.forScript(String.format(
+ "onedev.server.copyToClipboard.initCodeSpans($('#%s'), '%s', '%s');", getMarkupId(),
+ JavaScriptEscape.escapeJavaScript(_T("Click to copy")), JavaScriptEscape.escapeJavaScript(_T("Copied")))));
+ }
+ };
+ form.setOutputMarkupId(true);
+ add(form);
+ form.add(new Label("name", application.getName()));
+ form.add(new ExternalLink("homepage", application.getHomepage(), application.getHomepage()));
+ form.add(new Label("owner", application.getOwner().getDisplayName()));
+ form.add(new Label("clientId", application.getClientId()));
+ form.add(new Label("count", (IModel<Integer>) () -> grants.getObject().stream().mapToInt(it -> it.getAccessTokens().size()).sum()));
+ var applicationName = application.getName();
+ form.add(new AjaxButton("revokeAll") {
+ @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmClickListener(
+ MessageFormat.format(_T("Revoke all tokens for \"{0}\"?"), applicationName)));
+ }
+
+ @Override protected void onSubmit(AjaxRequestTarget target) {
+ providerService.revokeGrants(getUser(), applicationId);
+ getSession().success(_T("All authorizations for this application have been revoked"));
+ setResponsePage(MyAuthorizedApplicationsPage.class);
+ }
+ });
+ form.add(new ListView<>("tokens", grants) {
+ @Override protected void populateItem(ListItem<OAuthGrant> item) {
+ var grant = item.getModelObject();
+ var token = grant.getAccessTokens().stream().findFirst().orElse(null);
+ item.add(new Label("created", DateUtils.formatDateTime(grant.getCreateDate())));
+ item.add(new Label("used", grant.getLastUsedDate() != null ? DateUtils.formatDateTime(grant.getLastUsedDate()) : _T("Not used")));
+ item.add(new Label("accessExpires", grant.getLastUsedDate() != null && token != null
+ ? DateUtils.formatDateTime(token.getExpireDate()) : _T("Not issued")));
+ item.add(new Label("expires", DateUtils.formatDateTime(grant.getLastUsedDate() != null
+ ? grant.getExpireDate() : grant.getCodeExpireDate())));
+ item.add(new Label("redirectUri", grant.getRedirectUri()));
+ item.add(new ListView<>("scopes", List.of(grant.getScopes().split(" "))) {
+ @Override protected void populateItem(ListItem<String> scopeItem) {
+ scopeItem.add(new Label("scope", scopeItem.getModelObject()));
+ }
+ });
+ var projects = String.join(", ", grant.getAccessTokens().stream().flatMap(it -> it.getAuthorizations().stream())
+ .map(it -> it.getProject().getPath() + " (" + it.getRole().getName() + ")").distinct().sorted().toList());
+ item.add(new Label("projects", !projects.isEmpty() ? projects : _T("None")));
+ var grantId = grant.getId();
+ item.add(new AjaxButton("revoke") {
+ @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmClickListener(
+ _T("Revoke this token and its refresh token?")));
+ }
+
+ @Override protected void onSubmit(AjaxRequestTarget target) {
+ providerService.revokeGrant(grantId);
+ grants.detach();
+ getSession().success(_T("Authorization revoked"));
+ if (grants.getObject().isEmpty())
+ setResponsePage(MyAuthorizedApplicationsPage.class);
+ else
+ target.add(form);
+ }
+ });
+ }
+ });
+ }
+
+ @Override protected void onConfigure() {
+ super.onConfigure();
+ getAuthorizedApplication();
+ }
+
+ @Override protected void onDetach() {
+ grants.detach();
+ super.onDetach();
+ }
+
+ @Override protected Component newTopbarTitle(String id) {
+ var fragment = new Fragment(id, "topbarTitleFrag", this);
+ fragment.add(new BookmarkablePageLink<>("applications", MyAuthorizedApplicationsPage.class));
+ fragment.add(new Label("name", getAuthorizedApplication().getName()));
+ return fragment;
+ }
+
+ public static PageParameters paramsOf(OAuthApplication application) {
+ return new PageParameters().add(PARAM_APPLICATION, application.getId());
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationsPage.html b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationsPage.html
new file mode 100644
index 0000000000..3162362d76
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationsPage.html
@@ -0,0 +1,33 @@
+<wicket:extend>
+ <div class="alert alert-notice alert-light mb-5">
+ <wicket:t>Applications with access to your account and selected projects. Open an application to review its tokens and permissions, or revoke its access.</wicket:t>
+ </div>
+ <form wicket:id="applications" method="post">
+ <input wicket:id="csrf" type="hidden">
+ <div wicket:id="empty" class="norecords" role="img" t:aria-label="No authorized applications yet"></div>
+ <div wicket:id="table" class="table-responsive">
+ <table class="table table-hover">
+ <thead>
+ <tr>
+ <th><wicket:t>Application</wicket:t></th>
+ <th><wicket:t>Owner</wicket:t></th>
+ <th class="text-center"><wicket:t>Tokens</wicket:t></th>
+ <th class="d-none d-md-table-cell"><wicket:t>Last Used</wicket:t></th>
+ <th class="minimum d-none d-sm-table-cell"></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr wicket:id="rows">
+ <td class="align-middle"><a wicket:id="detail" class="font-weight-bold text-break"><span wicket:id="name"></span></a></td>
+ <td wicket:id="owner" class="align-middle text-break"></td>
+ <td wicket:id="tokens" class="align-middle text-center"></td>
+ <td wicket:id="used" class="d-none d-md-table-cell align-middle"></td>
+ <td class="minimum align-middle d-none d-sm-table-cell">
+ <button wicket:id="revoke" type="submit" class="btn btn-xs btn-icon btn-light btn-hover-danger" t:data-tippy-content="Revoke" t:aria-label="Revoke"><wicket:svg href="trash" class="icon align-middle"></wicket:svg></button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </form>
+</wicket:extend>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationsPage.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationsPage.java
new file mode 100644
index 0000000000..767fa85d31
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyAuthorizedApplicationsPage.java
@@ -0,0 +1,115 @@
+package io.onedev.server.web.page.oauth;
+
+import static io.onedev.server.web.translation.Translation._T;
+
+import java.text.MessageFormat;
+import java.util.Comparator;
+import java.util.List;
+
+import jakarta.inject.Inject;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.markup.html.form.AjaxButton;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.list.ListItem;
+import org.apache.wicket.markup.html.list.ListView;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+
+import io.onedev.server.model.OAuthApplication;
+import io.onedev.server.model.OAuthGrant;
+import io.onedev.server.oauth.OAuthProviderService;
+import io.onedev.server.util.DateUtils;
+import io.onedev.server.web.ajaxlistener.ConfirmClickListener;
+import io.onedev.server.web.page.my.MyPage;
+
+public class MyAuthorizedApplicationsPage extends MyPage {
+
+ @Inject
+ private OAuthProviderService providerService;
+
+ public MyAuthorizedApplicationsPage(PageParameters parameters) {
+ super(parameters);
+ }
+
+ @Override protected boolean isPermitted() {
+ return super.isPermitted() && providerService.isEnabled();
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+ var grants = new LoadableDetachableModel<List<OAuthGrant>>() {
+ @Override protected List<OAuthGrant> load() {
+ return providerService.getGrants(getUser());
+ }
+ };
+ var applications = new LoadableDetachableModel<List<OAuthApplication>>() {
+ @Override protected List<OAuthApplication> load() {
+ return grants.getObject().stream().map(OAuthGrant::getApplication).distinct()
+ .sorted(Comparator.comparing(OAuthApplication::getName, String.CASE_INSENSITIVE_ORDER)).toList();
+ }
+
+ @Override protected void onDetach() {
+ grants.detach();
+ super.onDetach();
+ }
+ };
+ var form = new OAuthForm("applications");
+ form.setOutputMarkupId(true);
+ add(form);
+ form.add(new WebMarkupContainer("empty") {
+ @Override protected void onConfigure() {
+ super.onConfigure();
+ setVisible(applications.getObject().isEmpty());
+ }
+ });
+ var table = new WebMarkupContainer("table") {
+ @Override protected void onConfigure() {
+ super.onConfigure();
+ setVisible(!applications.getObject().isEmpty());
+ }
+ };
+ form.add(table);
+ table.add(new ListView<>("rows", applications) {
+ @Override protected void populateItem(ListItem<OAuthApplication> item) {
+ var application = item.getModelObject();
+ var applicationGrants = grants.getObject().stream()
+ .filter(it -> it.getApplication().equals(application)).toList();
+ var link = new BookmarkablePageLink<>("detail", MyAuthorizedApplicationPage.class,
+ MyAuthorizedApplicationPage.paramsOf(application));
+ link.add(new Label("name", application.getName()));
+ item.add(link);
+ item.add(new Label("owner", application.getOwner().getDisplayName()));
+ item.add(new Label("tokens", applicationGrants.stream().mapToInt(it -> it.getAccessTokens().size()).sum()));
+ var used = applicationGrants.stream().map(OAuthGrant::getLastUsedDate)
+ .filter(it -> it != null).max(Comparator.naturalOrder()).orElse(null);
+ item.add(new Label("used", used != null ? DateUtils.formatDateTime(used) : _T("Not used")));
+ var applicationId = application.getId();
+ var applicationName = application.getName();
+ item.add(new AjaxButton("revoke") {
+ @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmClickListener(
+ MessageFormat.format(_T("Revoke all tokens for \"{0}\"?"), applicationName)));
+ }
+
+ @Override protected void onSubmit(AjaxRequestTarget target) {
+ providerService.revokeGrants(getUser(), applicationId);
+ applications.detach();
+ getSession().success(_T("All authorizations for this application have been revoked"));
+ target.add(form);
+ }
+ });
+ }
+ });
+ }
+
+ @Override protected Component newTopbarTitle(String id) {
+ return new Label(id, _T("Authorized Applications"));
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/MyOAuthApplicationPage.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyOAuthApplicationPage.java
new file mode 100644
index 0000000000..ebafe7bbd9
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyOAuthApplicationPage.java
@@ -0,0 +1,15 @@
+package io.onedev.server.web.page.oauth;
+
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+
+public class MyOAuthApplicationPage extends OAuthApplicationPage {
+
+ public MyOAuthApplicationPage(PageParameters parameters) {
+ this(parameters, false);
+ }
+
+ protected MyOAuthApplicationPage(PageParameters parameters, boolean creating) {
+ super(parameters, creating);
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/MyOAuthApplicationsPage.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyOAuthApplicationsPage.java
new file mode 100644
index 0000000000..7c087a4404
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/MyOAuthApplicationsPage.java
@@ -0,0 +1,7 @@
+package io.onedev.server.web.page.oauth;
+
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+
+public class MyOAuthApplicationsPage extends OAuthApplicationsPage {
+ public MyOAuthApplicationsPage(PageParameters parameters) { super(parameters); }
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/NewMyOAuthApplicationPage.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/NewMyOAuthApplicationPage.java
new file mode 100644
index 0000000000..a6b54846ca
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/NewMyOAuthApplicationPage.java
@@ -0,0 +1,10 @@
+package io.onedev.server.web.page.oauth;
+
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+
+public class NewMyOAuthApplicationPage extends MyOAuthApplicationPage {
+
+ public NewMyOAuthApplicationPage(PageParameters parameters) {
+ super(parameters, true);
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationBean.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationBean.java
new file mode 100644
index 0000000000..8bc6c12b60
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationBean.java
@@ -0,0 +1,64 @@
+package io.onedev.server.web.page.oauth;
+
+import java.io.Serializable;
+
+import jakarta.validation.constraints.NotEmpty;
+import jakarta.validation.constraints.Size;
+
+import io.onedev.server.annotation.Editable;
+import io.onedev.server.annotation.Multiline;
+
+@Editable
+public class OAuthApplicationBean implements Serializable {
+
+ private String name;
+ private String homepage;
+ private boolean confidential = true;
+ private String redirectUris;
+
+ @Editable(order=100)
+ @NotEmpty
+ @Size(max=255)
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Editable(order=200)
+ @NotEmpty
+ @Size(max=2048)
+ public String getHomepage() {
+ return homepage;
+ }
+
+ public void setHomepage(String homepage) {
+ this.homepage = homepage;
+ }
+
+ @Editable(order=300, name="Confidential Client", description="Check if the application can securely store a secret. "
+ + "Leave unchecked for desktop, mobile, and browser applications. S256 PKCE is required for all applications.")
+ public boolean isConfidential() {
+ return confidential;
+ }
+
+ public void setConfidential(boolean confidential) {
+ this.confidential = confidential;
+ }
+
+ @Editable(order=400, name="Redirect URIs", description="Specify one URI per line. "
+ + "Use HTTPS, loopback HTTP, or a native application scheme for public clients. "
+ + "URIs must match exactly, except public clients may choose any port for HTTP callbacks to 127.0.0.1 or [::1].")
+ @Multiline(monospace=true)
+ @NotEmpty
+ @Size(max=16000)
+ public String getRedirectUris() {
+ return redirectUris;
+ }
+
+ public void setRedirectUris(String redirectUris) {
+ this.redirectUris = redirectUris;
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationPage.html b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationPage.html
new file mode 100644
index 0000000000..12e83ae3e2
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationPage.html
@@ -0,0 +1,42 @@
+<wicket:extend>
+ <div class="m-2 m-sm-5">
+ <div class="card mb-5">
+ <div class="card-header"><div class="card-title"><h5 wicket:id="heading" class="mb-0"></h5></div></div>
+ <div class="card-body">
+ <form wicket:id="form" method="post" class="leave-confirm">
+ <input wicket:id="csrf" type="hidden">
+ <div wicket:id="feedback"></div>
+ <div wicket:id="editor"></div>
+ <div class="d-flex mt-5">
+ <button wicket:id="save" type="submit" class="btn btn-primary dirty-aware mr-2"><wicket:t>Save</wicket:t></button>
+ <a wicket:id="cancel" class="btn btn-light"><wicket:t>Cancel</wicket:t></a>
+ </div>
+ </form>
+ </div>
+ </div>
+ <form wicket:id="manage" method="post" class="card mb-5">
+ <input wicket:id="csrf" type="hidden">
+ <div class="card-header"><div class="card-title"><h5 class="mb-0"><wicket:t>Application Access</wicket:t></h5></div></div>
+ <div class="card-body">
+ <div wicket:id="feedback"></div>
+ <div class="font-weight-bold mb-2"><wicket:t>Client Type</wicket:t></div>
+ <div wicket:id="type" class="mb-4"></div>
+ <div class="font-weight-bold mb-2"><wicket:t>Client ID</wicket:t></div>
+ <div class="d-flex align-items-center mb-4">
+ <span wicket:id="clientId" class="text-monospace text-break font-size-sm mr-2"></span>
+ <a wicket:id="copyClientId" class="flex-shrink-0" t:aria-label="Copy client ID"><wicket:svg href="copy" class="icon"></wicket:svg></a>
+ </div>
+ <div class="font-weight-bold mb-2"><wicket:t>Client Secret</wicket:t></div>
+ <div wicket:id="secret" class="mb-4"></div>
+ <div class="d-flex flex-wrap">
+ <button wicket:id="revoke" type="submit" class="btn btn-light-danger mr-3 mb-2" onclick="return confirm('Revoke all authorizations for this application?')"><wicket:t>Revoke All Authorizations</wicket:t></button>
+ <button wicket:id="delete" type="submit" class="btn btn-light-danger mb-2" onclick="return confirm('Delete this application and all its authorizations?')"><wicket:t>Delete Application</wicket:t></button>
+ </div>
+ </div>
+ </form>
+ <div wicket:id="integration"></div>
+ </div>
+ <wicket:fragment wicket:id="topbarTitleFrag">
+ <a wicket:id="applications"><wicket:t>OAuth Applications</wicket:t></a> <span class="dot"></span> <span wicket:id="applicationName" class="text-truncate"></span>
+ </wicket:fragment>
+</wicket:extend>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationPage.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationPage.java
new file mode 100644
index 0000000000..8a855eafe6
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationPage.java
@@ -0,0 +1,150 @@
+package io.onedev.server.web.page.oauth;
+
+import static io.onedev.server.web.translation.Translation._T;
+
+import java.util.List;
+
+import jakarta.inject.Inject;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.RestartResponseAtInterceptPageException;
+import org.apache.wicket.RestartResponseException;
+import org.apache.wicket.Session;
+import org.apache.wicket.feedback.FencedFeedbackPanel;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.form.Button;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.request.http.WebResponse;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+
+import io.onedev.commons.utils.ExplicitException;
+import io.onedev.server.model.OAuthApplication;
+import io.onedev.server.oauth.OAuthProviderService;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.web.component.link.copytoclipboard.CopyToClipboardLink;
+import io.onedev.server.web.editable.BeanContext;
+import io.onedev.server.web.page.layout.LayoutPage;
+import io.onedev.server.web.page.security.LoginPage;
+
+public abstract class OAuthApplicationPage extends LayoutPage {
+
+ public static final String PARAM_APPLICATION = "application";
+
+ @Inject
+ private OAuthProviderService providerService;
+
+ private final Long applicationId;
+ private transient String secret;
+ private final OAuthApplicationBean bean = new OAuthApplicationBean();
+
+ protected OAuthApplicationPage(PageParameters parameters, boolean creating) {
+ super(parameters);
+ if (SecurityUtils.getAuthUser() == null)
+ throw new RestartResponseAtInterceptPageException(LoginPage.class);
+ applicationId = creating ? null : parameters.get(PARAM_APPLICATION).toOptionalLong();
+ if (!creating && applicationId == null)
+ throw new RestartResponseException(getApplicationsPageClass());
+ }
+
+ @Override protected boolean isPermitted() {
+ return providerService.isEnabled() && SecurityUtils.getAuthUser() != null;
+ }
+
+ private OAuthApplication application() {
+ var application = providerService.getApplication(applicationId);
+ if (!SecurityUtils.isAdministrator() && !SecurityUtils.getAuthUser().equals(application.getOwner()))
+ throw new org.apache.shiro.authz.UnauthorizedException();
+ return application;
+ }
+
+ @Override protected void onInitialize() {
+ super.onInitialize();
+ if (applicationId != null) {
+ var application = application();
+ bean.setName(application.getName());
+ bean.setHomepage(application.getHomepage());
+ bean.setRedirectUris(application.getRedirectUris());
+ bean.setConfidential(application.isConfidential());
+ }
+ var form = new OAuthForm("form") {
+ @Override protected void onSubmit() {
+ var app = applicationId != null ? application() : new OAuthApplication();
+ if (app.isNew()) {
+ app.setOwner(SecurityUtils.getAuthUser());
+ app.setConfidential(bean.isConfidential());
+ }
+ app.setName(bean.getName());
+ app.setHomepage(bean.getHomepage());
+ app.setRedirectUris(bean.getRedirectUris());
+ try {
+ var newSecret = providerService.saveApplication(app);
+ var parameters = paramsOf(app);
+ OAuthApplicationPage page = new MyOAuthApplicationPage(parameters);
+ page.secret = newSecret;
+ Session.get().success(applicationId == null ? _T("Application registered") : _T("Basic settings updated"));
+ setResponsePage(page);
+ } catch (ExplicitException e) {
+ error(e.getMessage());
+ }
+ }
+ };
+ add(form);
+ form.add(new FencedFeedbackPanel("feedback", form));
+ add(new Label("heading", applicationId != null ? _T("Basic Settings") : _T("Register Application")));
+ form.add(BeanContext.edit("editor", bean, applicationId != null ? List.of("confidential") : List.of(), true));
+ form.add(new Button("save"));
+ form.add(new BookmarkablePageLink<>("cancel", getApplicationsPageClass()));
+ var manage = new OAuthForm("manage");
+ manage.setVisible(applicationId != null);
+ add(manage);
+ manage.add(new OAuthClientSecretPanel("secret", applicationId, bean.isConfidential(), secret));
+ secret = null;
+ manage.add(new FencedFeedbackPanel("feedback", manage));
+ manage.add(new Label("type", bean.isConfidential() ? _T("Confidential") : _T("Public")));
+ var clientId = applicationId != null ? application().getClientId() : "";
+ manage.add(new Label("clientId", clientId));
+ manage.add(new CopyToClipboardLink("copyClientId", Model.of(clientId)));
+ manage.add(new Button("revoke") {
+ @Override public void onSubmit() {
+ providerService.revokeApplication(applicationId);
+ success(_T("All authorizations for this application have been revoked"));
+ }
+ });
+ manage.add(new Button("delete") {
+ @Override public void onSubmit() {
+ providerService.deleteApplication(applicationId);
+ Session.get().success(_T("Application deleted"));
+ setResponsePage(getApplicationsPageClass());
+ }
+ });
+ add(new OAuthIntegrationPanel("integration").setVisible(applicationId != null));
+ }
+
+ @Override protected void onConfigure() {
+ super.onConfigure();
+ ((WebResponse) getResponse()).setHeader("Cache-Control", "no-store");
+ }
+
+ @Override protected void onDetach() {
+ secret = null;
+ super.onDetach();
+ }
+
+ private Class<? extends OAuthApplicationsPage> getApplicationsPageClass() {
+ return MyOAuthApplicationsPage.class;
+ }
+
+ public static PageParameters paramsOf(OAuthApplication application) {
+ return new PageParameters().add(PARAM_APPLICATION, application.getId());
+ }
+
+ @Override protected Component newTopbarTitle(String id) {
+ var fragment = new Fragment(id, "topbarTitleFrag", this);
+ fragment.add(new BookmarkablePageLink<>("applications", getApplicationsPageClass()));
+ fragment.add(new Label("applicationName", applicationId != null ? application().getName() : _T("Create New")));
+ return fragment;
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationsPage.html b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationsPage.html
new file mode 100644
index 0000000000..53c54176c6
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationsPage.html
@@ -0,0 +1,37 @@
+<wicket:extend>
+ <div class="m-2 m-sm-5">
+ <div class="card mb-5">
+ <div class="card-body">
+ <div class="mb-4">
+ <a wicket:id="newApplication" class="btn btn-primary"><wicket:svg href="plus" class="icon mr-1"></wicket:svg> <wicket:t>Add New</wicket:t></a>
+ </div>
+ <form wicket:id="applicationList" method="post">
+ <input wicket:id="csrf" type="hidden">
+ <div wicket:id="empty" class="norecords" role="img" t:aria-label="No applications registered yet"></div>
+ <div wicket:id="table" class="table-responsive">
+ <table class="table table-hover">
+ <thead><tr><th><wicket:t>Application</wicket:t></th><th class="d-none d-lg-table-cell"><wicket:t>Client ID</wicket:t></th><th class="d-none d-lg-table-cell"><wicket:t>Client Secret</wicket:t></th><th class="minimum"></th></tr></thead>
+ <tbody>
+ <tr wicket:id="applications">
+ <td class="align-top"><a wicket:id="application" class="font-weight-bold text-break"><span wicket:id="name"></span></a></td>
+ <td class="d-none d-lg-table-cell align-top">
+ <div class="d-flex align-items-center">
+ <span wicket:id="clientId" class="text-monospace text-break font-size-sm mr-2"></span>
+ <a wicket:id="copyClientId" class="flex-shrink-0" t:aria-label="Copy client ID"><wicket:svg href="copy" class="icon"></wicket:svg></a>
+ </div>
+ </td>
+ <td class="d-none d-lg-table-cell align-top"><div wicket:id="secret"></div></td>
+ <td class="minimum align-top text-nowrap">
+ <a wicket:id="edit" class="btn btn-xs btn-icon btn-light btn-hover-primary mr-1" t:data-tippy-content="Edit" t:aria-label="Edit"><wicket:svg href="edit" class="icon"></wicket:svg></a>
+ <button wicket:id="delete" type="submit" class="btn btn-xs btn-icon btn-light btn-hover-danger" t:data-tippy-content="Delete" t:aria-label="Delete"><wicket:svg href="trash" class="icon align-middle"></wicket:svg></button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ </form>
+ </div>
+ </div>
+ <div wicket:id="integration"></div>
+ </div>
+</wicket:extend>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationsPage.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationsPage.java
new file mode 100644
index 0000000000..a506e5e21f
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthApplicationsPage.java
@@ -0,0 +1,115 @@
+package io.onedev.server.web.page.oauth;
+
+import static io.onedev.server.web.translation.Translation._T;
+
+import java.text.MessageFormat;
+import java.util.List;
+
+import jakarta.inject.Inject;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.RestartResponseAtInterceptPageException;
+import org.apache.wicket.RestartResponseException;
+import org.apache.wicket.Session;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.markup.html.form.AjaxButton;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.list.ListItem;
+import org.apache.wicket.markup.html.list.ListView;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.request.http.WebResponse;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+
+import io.onedev.server.oauth.OAuthProviderService;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.web.ajaxlistener.ConfirmClickListener;
+import io.onedev.server.web.component.link.copytoclipboard.CopyToClipboardLink;
+import io.onedev.server.web.page.layout.LayoutPage;
+import io.onedev.server.web.page.security.LoginPage;
+
+public abstract class OAuthApplicationsPage extends LayoutPage {
+
+ @Inject
+ private OAuthProviderService providerService;
+
+ public OAuthApplicationsPage(PageParameters parameters) {
+ super(parameters);
+ if (SecurityUtils.getAuthUser() == null)
+ throw new RestartResponseAtInterceptPageException(LoginPage.class);
+ if (!parameters.get(OAuthApplicationPage.PARAM_APPLICATION).isEmpty())
+ throw new RestartResponseException(getApplicationPageClass(), parameters);
+ }
+
+ @Override protected boolean isPermitted() {
+ return providerService.isEnabled() && SecurityUtils.getAuthUser() != null;
+ }
+
+ private Class<? extends OAuthApplicationPage> getApplicationPageClass() {
+ return MyOAuthApplicationPage.class;
+ }
+
+ @Override protected void onInitialize() {
+ super.onInitialize();
+ add(new BookmarkablePageLink<>("newApplication", NewMyOAuthApplicationPage.class));
+ add(new OAuthIntegrationPanel("integration"));
+ var applications = new LoadableDetachableModel<List<Long>>() {
+ @Override protected List<Long> load() {
+ return providerService.getApplications(SecurityUtils.getAuthUser()).stream().map(it -> it.getId()).toList();
+ }
+ };
+ var applicationList = new OAuthForm("applicationList");
+ applicationList.setOutputMarkupId(true);
+ add(applicationList);
+ applicationList.add(new WebMarkupContainer("empty") {
+ @Override protected void onConfigure() {
+ super.onConfigure();
+ setVisible(applications.getObject().isEmpty());
+ }
+ });
+ var table = new WebMarkupContainer("table") {
+ @Override protected void onConfigure() {
+ super.onConfigure();
+ setVisible(!applications.getObject().isEmpty());
+ }
+ };
+ applicationList.add(table);
+ table.add(new ListView<>("applications", applications) {
+ @Override protected void populateItem(ListItem<Long> item) {
+ var app = providerService.getApplication(item.getModelObject());
+ var link = new BookmarkablePageLink<>("application", getApplicationPageClass(), OAuthApplicationPage.paramsOf(app));
+ link.add(new Label("name", app.getName()));
+ item.add(link);
+ item.add(new Label("clientId", app.getClientId()));
+ item.add(new CopyToClipboardLink("copyClientId", Model.of(app.getClientId())));
+ item.add(new OAuthClientSecretPanel("secret", app.getId(), app.isConfidential(), null));
+ item.add(new BookmarkablePageLink<>("edit", getApplicationPageClass(), OAuthApplicationPage.paramsOf(app)));
+ var applicationName = app.getName();
+ item.add(new AjaxButton("delete") {
+ @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ var message = MessageFormat.format(_T("Delete application \"{0}\" and all its authorizations?"), applicationName);
+ attributes.getAjaxCallListeners().add(new ConfirmClickListener(message));
+ }
+
+ @Override protected void onSubmit(AjaxRequestTarget target) {
+ providerService.deleteApplication(item.getModelObject());
+ applications.detach();
+ Session.get().success(_T("Application deleted"));
+ target.add(applicationList);
+ }
+ });
+ }
+ });
+ }
+
+ @Override protected void onConfigure() {
+ super.onConfigure();
+ ((WebResponse) getResponse()).setHeader("Cache-Control", "no-store");
+ }
+
+ @Override protected Component newTopbarTitle(String id) { return new Label(id, _T("OAuth Applications")); }
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthAuthorizePage.html b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthAuthorizePage.html
new file mode 100644
index 0000000000..ea91c389ef
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthAuthorizePage.html
@@ -0,0 +1,35 @@
+<wicket:extend>
+ <div class="text-left">
+ <p class="mb-4"><strong wicket:id="application" class="text-break"></strong> <wicket:t>wants access to your OneDev account.</wicket:t></p>
+ <dl class="row border-bottom pb-3 mb-4">
+ <dt class="col-sm-4 text-muted font-weight-normal"><wicket:t>Homepage</wicket:t></dt>
+ <dd class="col-sm-8 text-break"><a wicket:id="homepage" rel="noopener noreferrer" target="_blank"></a></dd>
+ <dt class="col-sm-4 text-muted font-weight-normal"><wicket:t>Owner</wicket:t></dt>
+ <dd wicket:id="owner" class="col-sm-8 text-break"></dd>
+ <dt class="col-sm-4 text-muted font-weight-normal"><wicket:t>Signed in as</wicket:t></dt>
+ <dd class="col-sm-8 text-break"><strong wicket:id="user"></strong></dd>
+ </dl>
+ <h6 class="mb-3"><wicket:t>Requested Access</wicket:t></h6>
+ <ul class="pl-4 mb-4"><li wicket:id="scopes" class="mb-2"><span wicket:id="description"></span></li></ul>
+ <form wicket:id="form" method="post" class="mt-4">
+ <input wicket:id="csrf" type="hidden">
+ <div wicket:id="feedback"></div>
+ <wicket:enclosure child="projects">
+ <div class="form-group">
+ <label wicket:for="projects"><wicket:t>Authorize these roles on selected projects and their children</wicket:t></label>
+ <select wicket:id="projects"></select>
+ <div class="text-muted form-text"><wicket:t>Only projects you have permission to manage can be authorized. The application can only exercise permissions you have. Changes to these roles also affect this authorization.</wicket:t></div>
+ </div>
+ </wicket:enclosure>
+ <p class="text-muted mb-0"><wicket:t>Access expires after 30 days. You can revoke access at any time under Authorized Applications.</wicket:t></p>
+ <div class="simple-actions">
+ <button wicket:id="authorize" type="submit" class="btn btn-primary"><wicket:t>Authorize</wicket:t></button>
+ <button wicket:id="deny" type="submit" class="btn btn-light simple-cancel"><wicket:t>Deny</wicket:t></button>
+ </div>
+ </form>
+ <div class="border-top pt-4 mt-4 text-muted font-size-sm">
+ <wicket:t>You will return to:</wicket:t>
+ <div wicket:id="redirect" class="text-break mt-1"></div>
+ </div>
+ </div>
+</wicket:extend>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthAuthorizePage.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthAuthorizePage.java
new file mode 100644
index 0000000000..61d3b23c11
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthAuthorizePage.java
@@ -0,0 +1,178 @@
+package io.onedev.server.web.page.oauth;
+
+import static io.onedev.server.web.translation.Translation._T;
+
+import java.util.Collection;
+import java.util.List;
+
+import jakarta.inject.Inject;
+import jakarta.servlet.http.HttpServletRequest;
+
+import org.apache.wicket.RestartResponseAtInterceptPageException;
+import org.apache.wicket.feedback.FencedFeedbackPanel;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.form.Button;
+import org.apache.wicket.markup.html.link.ExternalLink;
+import org.apache.wicket.markup.html.list.ListItem;
+import org.apache.wicket.markup.html.list.ListView;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.request.http.WebResponse;
+import org.apache.wicket.request.flow.RedirectToUrlException;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+
+import com.nimbusds.oauth2.sdk.*;
+import com.nimbusds.openid.connect.sdk.OIDCError;
+import com.nimbusds.openid.connect.sdk.Prompt;
+
+import io.onedev.commons.utils.ExplicitException;
+import io.onedev.server.model.Project;
+import io.onedev.server.oauth.OAuthProtocol;
+import io.onedev.server.oauth.OAuthProviderService;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.security.permission.ManageProject;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.web.component.project.choice.ProjectMultiChoice;
+import io.onedev.server.web.page.security.LoginPage;
+import io.onedev.server.web.page.simple.SimplePage;
+
+public class OAuthAuthorizePage extends SimplePage {
+
+ @Inject
+ private OAuthProviderService providerService;
+ @Inject
+ private ProjectService projectService;
+
+ private String authorizationQuery;
+ private Long ownerId;
+ private List<Long> selectedProjectIds = List.of();
+
+ public OAuthAuthorizePage(PageParameters parameters) {
+ super(parameters);
+ if (!providerService.isEnabled())
+ throw new ExplicitException("OAuth2/OIDC provider is disabled");
+ var http = (HttpServletRequest) getRequest().getContainerRequest();
+ authorizationQuery = http.getQueryString();
+ if (authorizationQuery == null || authorizationQuery.length() > 16000)
+ throw new ExplicitException("Invalid authorization request");
+ var request = request();
+ var application = providerService.findApplication(request.getClientID().getValue());
+ // Never redirect errors before both client and exact callback have been validated.
+ if (application == null || !OAuthProtocol.hasRegisteredRedirect(application, request)
+ || application.getOwner().isDisabled())
+ throw new ExplicitException("Unknown OAuth application or unregistered redirect URI");
+ try {
+ OAuthProtocol.validateAuthorization(request);
+ providerService.getRoles(request.getScope());
+ } catch (ParseException e) {
+ redirectError(request, e.getErrorObject());
+ }
+ if (request.getPrompt() != null) {
+ if (request.getPrompt().contains(Prompt.Type.NONE))
+ redirectError(request, SecurityUtils.getAuthUser() == null ? OIDCError.LOGIN_REQUIRED : OIDCError.CONSENT_REQUIRED);
+ if (!request.getPrompt().equals(new Prompt(Prompt.Type.CONSENT)))
+ redirectError(request, OAuth2Error.INVALID_REQUEST.setDescription("Only prompt=consent and prompt=none are supported"));
+ }
+ if (SecurityUtils.getAuthUser() == null)
+ throw new RestartResponseAtInterceptPageException(LoginPage.class);
+ ownerId = SecurityUtils.getAuthUser().getId();
+ }
+
+ private AuthorizationRequest request() {
+ try {
+ var request = AuthorizationRequest.parse(authorizationQuery);
+ OAuthProtocol.checkSingleParameters(com.nimbusds.oauth2.sdk.util.URLUtils.parseParameters(authorizationQuery));
+ return request;
+ } catch (ParseException e) {
+ throw new ExplicitException("Invalid authorization request");
+ }
+ }
+
+ private void redirectError(AuthorizationRequest request, ErrorObject error) {
+ throw new RedirectToUrlException(new AuthorizationErrorResponse(request.getRedirectionURI(), error,
+ request.getState(), ResponseMode.QUERY).toURI().toString());
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+ var request = request();
+ var application = providerService.findApplication(request.getClientID().getValue());
+ add(new Label("application", application.getName()));
+ add(new ExternalLink("homepage", application.getHomepage(), application.getHomepage()));
+ add(new Label("owner", application.getOwner().getDisplayName()));
+ add(new Label("user", SecurityUtils.getAuthUser().getDisplayName()));
+ add(new Label("redirect", request.getRedirectionURI().toString()));
+ var descriptions = providerService.getScopes();
+ add(new ListView<>("scopes", request.getScope().toStringList()) {
+ @Override protected void populateItem(ListItem<String> item) {
+ item.add(new Label("description", descriptions.get(item.getModelObject())));
+ }
+ });
+ List<Long> roleIds;
+ try {
+ roleIds = providerService.getRoles(request.getScope()).stream().map(it -> it.getId()).toList();
+ } catch (ParseException e) {
+ throw new ExplicitException("Requested role no longer exists");
+ }
+ var projects = new LoadableDetachableModel<List<Project>>() {
+ @Override protected List<Project> load() {
+ return SecurityUtils.getAuthorizedProjects(SecurityUtils.getAuthUser().asSubject(), new ManageProject()).stream()
+ .sorted(java.util.Comparator.comparing(Project::getPath)).toList();
+ }
+ };
+ var selected = new IModel<Collection<Project>>() {
+ @Override public Collection<Project> getObject() {
+ return selectedProjectIds.stream().map(projectService::load).toList();
+ }
+
+ @Override public void setObject(Collection<Project> projects) {
+ selectedProjectIds = projects.stream().map(Project::getId).toList();
+ }
+ };
+ var form = new OAuthForm("form");
+ add(form);
+ form.add(new FencedFeedbackPanel("feedback", form));
+ var choices = new ProjectMultiChoice("projects", selected, projects) {
+ @Override protected void onInitialize() {
+ super.onInitialize();
+ getSettings().setPlaceholder(_T("Choose projects..."));
+ getSettings().setWidth("100%");
+ }
+ };
+ choices.setVisible(!roleIds.isEmpty());
+ form.add(choices);
+ form.add(new Button("authorize") {
+ @Override public void onSubmit() {
+ var request = request();
+ var user = SecurityUtils.getAuthUser();
+ if (user == null || !user.getId().equals(ownerId))
+ throw new ExplicitException("Your signed-in account changed. Start authorization again");
+ try {
+ String code = providerService.authorize(SecurityUtils.getSubject(), request, selectedProjectIds);
+ throw new RedirectToUrlException(new AuthorizationSuccessResponse(request.getRedirectionURI(),
+ new AuthorizationCode(code), null, request.getState(), ResponseMode.QUERY).toURI().toString());
+ } catch (ParseException e) {
+ redirectError(request, e.getErrorObject());
+ } catch (ExplicitException e) {
+ form.error(e.getMessage());
+ }
+ }
+ });
+ form.add(new Button("deny") {
+ @Override public void onSubmit() { redirectError(request(), OAuth2Error.ACCESS_DENIED); }
+ });
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ var response = (WebResponse) getResponse();
+ response.setHeader("Cache-Control", "no-store");
+ response.setHeader("Referrer-Policy", "no-referrer");
+ response.setHeader("Content-Security-Policy", "frame-ancestors 'none'");
+ }
+
+ @Override protected String getTitle() { return _T("Authorize Application"); }
+ @Override protected String getSubTitle() { return null; }
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthClientSecretPanel.html b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthClientSecretPanel.html
new file mode 100644
index 0000000000..085ca91ed1
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthClientSecretPanel.html
@@ -0,0 +1,8 @@
+<wicket:panel>
+ <div class="d-flex align-items-center">
+ <span wicket:id="value" class="text-monospace text-break font-size-sm mr-2"></span>
+ <a wicket:id="copy" class="flex-shrink-0 mr-1" t:aria-label="Copy client secret"><wicket:svg href="copy" class="icon"></wicket:svg></a>
+ <a wicket:id="rotate" class="flex-shrink-0" t:data-tippy-content="Rotate Secret" t:aria-label="Rotate Secret"><wicket:svg href="refresh2" class="icon"></wicket:svg></a>
+ </div>
+ <div wicket:id="notice" class="text-muted font-size-sm mt-1"><wicket:t>Copy the client secret now. It will not be shown again.</wicket:t></div>
+</wicket:panel>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthClientSecretPanel.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthClientSecretPanel.java
new file mode 100644
index 0000000000..c650b98fe9
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthClientSecretPanel.java
@@ -0,0 +1,86 @@
+package io.onedev.server.web.page.oauth;
+
+import static io.onedev.server.web.translation.Translation._T;
+
+import jakarta.inject.Inject;
+
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
+import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.panel.Panel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.request.http.WebResponse;
+
+import io.onedev.server.oauth.OAuthProviderService;
+import io.onedev.server.web.ajaxlistener.ConfirmClickListener;
+import io.onedev.server.web.component.link.copytoclipboard.CopyToClipboardLink;
+
+public class OAuthClientSecretPanel extends Panel {
+
+ @Inject
+ private OAuthProviderService providerService;
+
+ private final Long applicationId;
+ private final boolean confidential;
+ private transient String secret;
+
+ public OAuthClientSecretPanel(String id, Long applicationId, boolean confidential, String secret) {
+ super(id);
+ this.applicationId = applicationId;
+ this.confidential = confidential;
+ this.secret = secret;
+ setOutputMarkupId(true);
+ }
+
+ @Override protected void onInitialize() {
+ super.onInitialize();
+ add(new Label("value", (IModel<String>) () -> {
+ if (!confidential)
+ return _T("Not applicable");
+ return secret != null ? secret : "*".repeat(30);
+ }));
+ add(new CopyToClipboardLink("copy", (IModel<String>) () -> secret) {
+ @Override protected void onConfigure() {
+ super.onConfigure();
+ setVisible(confidential && secret != null);
+ }
+ });
+ add(new AjaxSubmitLink("rotate") {
+ @Override protected void onConfigure() {
+ super.onConfigure();
+ setVisible(confidential && secret == null);
+ }
+
+ @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
+ super.updateAjaxAttributes(attributes);
+ attributes.getAjaxCallListeners().add(new ConfirmClickListener(
+ _T("Rotate the client secret and revoke all authorizations?")));
+ }
+
+ @Override protected void onSubmit(AjaxRequestTarget target) {
+ secret = providerService.rotateSecret(applicationId);
+ setVisible(false);
+ target.add(OAuthClientSecretPanel.this);
+ }
+ });
+ add(new WebMarkupContainer("notice") {
+ @Override protected void onConfigure() {
+ super.onConfigure();
+ setVisible(confidential && secret != null);
+ }
+ });
+ }
+
+ @Override protected void onConfigure() {
+ super.onConfigure();
+ ((WebResponse) getResponse()).setHeader("Cache-Control", "no-store");
+ }
+
+ @Override protected void onDetach() {
+ // Keep the clear-text secret only for its initial response, never in the saved page.
+ secret = null;
+ super.onDetach();
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthForm.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthForm.java
new file mode 100644
index 0000000000..436ce56154
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthForm.java
@@ -0,0 +1,24 @@
+package io.onedev.server.web.page.oauth;
+
+import org.apache.wicket.markup.html.form.Form;
+import org.apache.wicket.markup.html.form.HiddenField;
+import org.apache.wicket.model.Model;
+
+import com.nimbusds.oauth2.sdk.id.State;
+
+/** Explicit anti-CSRF token for consent and application management POSTs. */
+public class OAuthForm extends Form<Void> {
+
+ private final String csrfToken = new State(32).getValue();
+
+ public OAuthForm(String id) {
+ super(id);
+ var csrf = new HiddenField<>("csrf", Model.of(csrfToken));
+ csrf.setRequired(true);
+ csrf.add(validatable -> {
+ if (!csrfToken.equals(validatable.getValue()))
+ validatable.error(new org.apache.wicket.validation.ValidationError().setMessage("Invalid form token"));
+ });
+ add(csrf);
+ }
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthIntegrationPanel.html b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthIntegrationPanel.html
new file mode 100644
index 0000000000..1dccf37fb5
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthIntegrationPanel.html
@@ -0,0 +1,13 @@
+<wicket:panel>
+ <div class="card"><div class="card-body">
+ <details>
+ <summary class="font-weight-bold"><wicket:t>Integration and supported scopes</wicket:t></summary>
+ <p class="mt-4"><wicket:t>Discover endpoints at</wicket:t> <code wicket:id="openidDiscoveryUrl" class="text-break"></code> <wicket:t>or</wicket:t> <code wicket:id="oauthDiscoveryUrl" class="text-break"></code>.</p>
+ <p class="text-muted"><wicket:t>Request role scopes to access projects. The user selects projects they have permission to manage during consent, and access is limited to their own permissions.</wicket:t></p>
+ <div class="table-responsive"><table class="table">
+ <thead><tr><th><wicket:t>Scope</wicket:t></th><th><wicket:t>Access</wicket:t></th></tr></thead>
+ <tbody><tr wicket:id="scopes"><td><code wicket:id="name"></code></td><td wicket:id="description"></td></tr></tbody>
+ </table></div>
+ </details>
+ </div></div>
+</wicket:panel>
diff --git a/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthIntegrationPanel.java b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthIntegrationPanel.java
new file mode 100644
index 0000000000..0312c150ac
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/web/page/oauth/OAuthIntegrationPanel.java
@@ -0,0 +1,55 @@
+package io.onedev.server.web.page.oauth;
+
+import static io.onedev.server.web.translation.Translation._T;
+
+import jakarta.inject.Inject;
+
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.head.JavaScriptHeaderItem;
+import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.list.ListItem;
+import org.apache.wicket.markup.html.list.ListView;
+import org.apache.wicket.markup.html.panel.Panel;
+import org.unbescape.javascript.JavaScriptEscape;
+
+import io.onedev.server.oauth.OAuthProviderService;
+import io.onedev.server.service.SettingService;
+import io.onedev.server.web.component.link.copytoclipboard.CopyToClipboardResourceReference;
+
+public class OAuthIntegrationPanel extends Panel {
+
+ @Inject
+ private OAuthProviderService providerService;
+ @Inject
+ private SettingService settingService;
+
+ public OAuthIntegrationPanel(String id) {
+ super(id);
+ }
+
+ @Override protected void onInitialize() {
+ super.onInitialize();
+ setOutputMarkupId(true);
+ var serverUrl = settingService.getSystemSetting().getServerUrl().replaceAll("/+$", "");
+ add(new Label("openidDiscoveryUrl", serverUrl + "/.well-known/openid-configuration"));
+ add(new Label("oauthDiscoveryUrl", serverUrl + "/.well-known/oauth-authorization-server"));
+ var scopes = providerService.getScopes();
+ add(new ListView<>("scopes", scopes.keySet().stream().toList()) {
+ @Override protected void populateItem(ListItem<String> item) {
+ item.add(new Label("name", item.getModelObject()));
+ item.add(new Label("description", scopes.get(item.getModelObject())));
+ }
+ });
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(JavaScriptHeaderItem.forReference(new CopyToClipboardResourceReference()));
+ String script = String.format("onedev.server.copyToClipboard.initCodeSpans($('#%s'), '%s', '%s');",
+ getMarkupId(), JavaScriptEscape.escapeJavaScript(_T("Click to copy")),
+ JavaScriptEscape.escapeJavaScript(_T("Copied")));
+ response.render(OnDomReadyHeaderItem.forScript(script));
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/oauth/OAuthAuthorizationTest.java b/server-core/src/test/java/io/onedev/server/oauth/OAuthAuthorizationTest.java
new file mode 100644
index 0000000000..c7181fb626
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/oauth/OAuthAuthorizationTest.java
@@ -0,0 +1,195 @@
+package io.onedev.server.oauth;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+
+import org.apache.shiro.authz.Permission;
+import org.apache.shiro.subject.Subject;
+import org.apache.shiro.util.ThreadContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.SubscriptionService;
+import io.onedev.server.model.*;
+import io.onedev.server.model.support.administration.GlobalIssueSetting;
+import io.onedev.server.model.support.administration.SecuritySetting;
+import io.onedev.server.model.support.role.CodePrivilege;
+import io.onedev.server.persistence.SessionService;
+import io.onedev.server.security.DefaultAuthorizingService;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.security.permission.*;
+import io.onedev.server.service.*;
+import io.onedev.server.util.facade.ProjectCache;
+
+class OAuthAuthorizationTest {
+
+ private MockedStatic<OneDev> oneDev;
+ private Subject previous;
+ private Subject subject;
+ private DefaultAuthorizingService realm;
+ private AccessToken token;
+ private User owner;
+ private Project selected;
+ private Project child;
+ private Project other;
+ private ProjectCache cache;
+ private Role reader;
+ private Role manager;
+ private final List<ProjectPermission> ownerPermissions = new ArrayList<>();
+
+ @BeforeEach
+ void setUp() throws Exception {
+ oneDev = mockStatic(OneDev.class);
+ previous = ThreadContext.getSubject();
+ var subscription = mock(SubscriptionService.class);
+ oneDev.when(() -> OneDev.getInstance(SubscriptionService.class)).thenReturn(subscription);
+ var settings = mock(SettingService.class);
+ when(settings.getIssueSetting()).thenReturn(new GlobalIssueSetting());
+ when(settings.getSecuritySetting()).thenReturn(new SecuritySetting());
+ oneDev.when(() -> OneDev.getInstance(SettingService.class)).thenReturn(settings);
+ var projects = mock(ProjectService.class);
+ oneDev.when(() -> OneDev.getInstance(ProjectService.class)).thenReturn(projects);
+ selected = project(1L, "selected");
+ child = project(2L, "selected/child");
+ child.setParent(selected);
+ other = project(3L, "other");
+ var defaults = project(Project.DEFAULT_ID, Project.DEFAULT_NAME);
+ when(projects.load(Project.DEFAULT_ID)).thenReturn(defaults);
+ cache = new ProjectCache(new HashMap<>());
+ for (var project: List.of(selected, child, other)) {
+ cache.put(project.getId(), project.getFacade());
+ when(projects.load(project.getId())).thenReturn(project);
+ }
+ reader = new Role();
+ reader.setId(1L);
+ reader.setCodePrivilege(CodePrivilege.READ);
+ manager = new Role();
+ manager.setId(2L);
+ manager.setManageProject(true);
+ owner = spy(new User());
+ owner.setId(100L);
+ owner.setName("reader");
+ var ownerSubject = mock(Subject.class);
+ var ownerPrincipal = SecurityUtils.asUserPrincipal(owner.getId());
+ when(ownerSubject.getPrincipal()).thenReturn(ownerPrincipal);
+ when(ownerSubject.isPermitted(any(Permission.class))).thenAnswer(it -> ownerPermissions.stream().anyMatch(p -> p.implies(it.getArgument(0))));
+ doReturn(ownerSubject).when(owner).asSubject();
+ var users = mock(UserService.class);
+ oneDev.when(() -> OneDev.getInstance(UserService.class)).thenReturn(users);
+ when(users.get(owner.getId())).thenReturn(owner);
+ var userAuthorization = new UserAuthorization();
+ userAuthorization.setUser(owner);
+ userAuthorization.setProject(selected);
+ userAuthorization.setRole(manager);
+ owner.getProjectAuthorizations().add(userAuthorization);
+ ownerPermissions.add(new ProjectPermission(selected, manager));
+ token = new AccessToken();
+ token.setId(10L);
+ token.setOwner(owner);
+ token.setOauthGrant(new OAuthGrant());
+ var authorization = new AccessTokenAuthorization();
+ authorization.setToken(token);
+ authorization.setProject(selected);
+ authorization.setRole(manager);
+ token.getAuthorizations().add(authorization);
+ var tokens = mock(AccessTokenService.class);
+ oneDev.when(() -> OneDev.getInstance(AccessTokenService.class)).thenReturn(tokens);
+ when(tokens.get(token.getId())).thenReturn(token);
+ var sessions = mock(SessionService.class);
+ when(sessions.call(any())).thenAnswer(it -> ((Callable<?>) it.getArgument(0)).call());
+ realm = new DefaultAuthorizingService();
+ inject("sessionService", sessions);
+ inject("settingService", settings);
+ inject("subscriptionService", subscription);
+ inject("issueAuthorizationService", mock(IssueAuthorizationService.class));
+ subject = mock(Subject.class);
+ when(subject.getPrincipal()).thenReturn(SecurityUtils.asAccessTokenPrincipal(token.getId()));
+ when(subject.isPermitted(any(Permission.class))).thenAnswer(it -> realm.doGetAuthorizationInfo(SecurityUtils.asPrincipals((String) subject.getPrincipal()))
+ .getObjectPermissions().stream().anyMatch(p -> p.implies(it.getArgument(0))));
+ ThreadContext.bind(subject);
+ var bases = mock(BaseAuthorizationService.class);
+ oneDev.when(() -> OneDev.getInstance(BaseAuthorizationService.class)).thenReturn(bases);
+ }
+
+ private Project project(Long id, String path) {
+ var project = new Project();
+ project.setId(id); project.setName(path); project.setPath(path);
+ project.setLastActivityDate(new ProjectLastActivityDate());
+ return project;
+ }
+
+ private void inject(String name, Object value) throws Exception {
+ var field = DefaultAuthorizingService.class.getDeclaredField(name);
+ field.setAccessible(true); field.set(realm, value);
+ }
+
+ @AfterEach
+ void tearDown() {
+ ThreadContext.unbindSubject();
+ if (previous != null) ThreadContext.bind(previous);
+ oneDev.close();
+ }
+
+ @Test
+ void existingGrantRequiresOwnerToManageAuthorizedProject() {
+ assertTrue(SecurityUtils.canReadCode(subject, selected));
+ assertTrue(SecurityUtils.canReadCode(subject, child));
+ assertTrue(SecurityUtils.canManageProject(subject, selected));
+ assertTrue(SecurityUtils.isAssignedRole(subject, selected, manager));
+ ownerPermissions.clear();
+ ownerPermissions.add(new ProjectPermission(selected, reader));
+ assertFalse(SecurityUtils.canReadCode(subject, selected));
+ assertFalse(SecurityUtils.canReadCode(subject, child));
+ assertFalse(SecurityUtils.canWriteCode(subject, selected));
+ assertFalse(SecurityUtils.canManageProject(subject, selected));
+ assertFalse(SecurityUtils.isAssignedRole(subject, selected, manager));
+ assertFalse(SecurityUtils.canReadCode(subject, other));
+ assertTrue(SecurityUtils.getAuthorizedProjects(subject, cache, new ReadCode()).isEmpty());
+ }
+
+ @Test
+ void consentRestrictsEvenAnOwnersBroaderProjectPermissions() {
+ ownerPermissions.clear();
+ ownerPermissions.add(new ProjectPermission(selected, manager));
+ token.getAuthorizations().iterator().next().setRole(reader);
+ assertTrue(SecurityUtils.canReadCode(subject, selected));
+ assertTrue(SecurityUtils.isAssignedRole(subject, selected, reader));
+ assertEquals(2, SecurityUtils.getAuthorizedProjects(subject, cache, new ReadCode()).size());
+ assertFalse(SecurityUtils.canWriteCode(subject, selected));
+ assertFalse(SecurityUtils.isAdministrator(subject));
+ }
+
+ @Test
+ void defaultProjectRolesApplyOutsideConsent() {
+ var base = new BaseAuthorization();
+ base.setProject(other); base.setRole(manager);
+ other.getBaseAuthorizations().add(base);
+ manager.getBaseAuthorizations().add(base);
+ when(OneDev.getInstance(BaseAuthorizationService.class).query()).thenReturn(List.of(base));
+ token.getAuthorizations().clear();
+ ownerPermissions.clear();
+ assertTrue(SecurityUtils.canAccessProject(subject, other));
+ assertTrue(SecurityUtils.isAssignedRole(subject, other, manager));
+ assertEquals(Set.of(other), SecurityUtils.getAuthorizedProjects(subject, cache, new ReadCode()));
+ assertEquals(Map.of("build", Set.of("coverage")), SecurityUtils.getAccessibleReportNames(other,
+ Object.class, Map.of("build", List.of("coverage"))));
+ assertFalse(SecurityUtils.canAccessProject(subject, selected));
+ }
+
+ @Test
+ void newlyCheckedDelegationReflectsOwnerPermissionRemoval() {
+ assertTrue(SecurityUtils.canReadCode(subject, selected));
+ ownerPermissions.clear();
+ assertFalse(SecurityUtils.canReadCode(subject, selected));
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/oauth/OAuthEndpointServletTest.java b/server-core/src/test/java/io/onedev/server/oauth/OAuthEndpointServletTest.java
new file mode 100644
index 0000000000..a11c4815aa
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/oauth/OAuthEndpointServletTest.java
@@ -0,0 +1,116 @@
+package io.onedev.server.oauth;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.*;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.Collections;
+import java.util.Map;
+import java.util.concurrent.Callable;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import com.nimbusds.oauth2.sdk.OAuth2Error;
+import com.nimbusds.oauth2.sdk.TokenErrorResponse;
+import com.nimbusds.oauth2.sdk.TokenRequest;
+import com.nimbusds.oauth2.sdk.pkce.CodeVerifier;
+
+import io.onedev.server.persistence.SessionService;
+
+class OAuthEndpointServletTest {
+ private OAuthEndpointServlet servlet;
+ private OAuthProviderService providerService;
+ private HttpServletRequest request;
+ private HttpServletResponse response;
+ private StringWriter output;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ servlet = new OAuthEndpointServlet();
+ providerService = mock(OAuthProviderService.class);
+ when(providerService.isEnabled()).thenReturn(true);
+ var sessions = mock(SessionService.class);
+ when(sessions.call(any())).thenAnswer(it -> ((Callable<?>) it.getArgument(0)).call());
+ for (var name: Map.of("provider", providerService, "sessionService", sessions).entrySet()) {
+ var field = OAuthEndpointServlet.class.getDeclaredField(name.getKey());
+ field.setAccessible(true); field.set(servlet, name.getValue());
+ }
+ request = mock(HttpServletRequest.class);
+ response = mock(HttpServletResponse.class);
+ when(request.getServletPath()).thenReturn("/~oauth/token");
+ when(request.getMethod()).thenReturn("POST");
+ when(request.getContentType()).thenReturn("application/x-www-form-urlencoded");
+ when(request.getRequestURL()).thenReturn(new StringBuffer("https://onedev.example/~oauth/token"));
+ when(request.getHeaders("Authorization")).thenReturn(Collections.emptyEnumeration());
+ output = new StringWriter();
+ when(response.getWriter()).thenReturn(new PrintWriter(output));
+ when(providerService.exchange(any())).thenReturn(new TokenErrorResponse(OAuth2Error.INVALID_GRANT));
+ }
+
+ @Test
+ void usesContainerParsedFormEvenWhenAFilterHasConsumedTheBody() throws Exception {
+ when(request.getParameterMap()).thenReturn(Map.of("grant_type", new String[]{"authorization_code"},
+ "client_id", new String[]{"client"}, "code", new String[]{"1.code"},
+ "redirect_uri", new String[]{"https://client.example/callback"}, "code_verifier", new String[]{new CodeVerifier().getValue()}));
+ servlet.service(request, response);
+ var parsed = ArgumentCaptor.forClass(TokenRequest.class);
+ verify(providerService).exchange(parsed.capture());
+ assertEquals("client", parsed.getValue().getClientID().getValue());
+ verify(request, never()).getInputStream();
+ verify(response).setHeader("Cache-Control", "no-store");
+ }
+
+ @Test
+ void rejectsRepeatedFormParameters() throws Exception {
+ when(request.getParameterMap()).thenReturn(Map.of("client_id", new String[]{"a", "b"}));
+ servlet.service(request, response);
+ verify(providerService, never()).exchange(any());
+ verify(providerService, never()).revoke(any());
+ verify(response).setStatus(400);
+ assertTrue(output.toString().contains("invalid_request"));
+ }
+
+ @Test
+ void rejectsCredentialParametersInQueryString() throws Exception {
+ when(request.getQueryString()).thenReturn("client_secret=secret");
+ servlet.service(request, response);
+ verify(providerService, never()).exchange(any());
+ verify(providerService, never()).revoke(any());
+ verify(response).setStatus(400);
+ }
+
+ @Test
+ void userInfoSupportsBothGetAndPostWithBearerAuthentication() throws Exception {
+ when(request.getServletPath()).thenReturn("/~oauth/userinfo");
+ when(providerService.getUserInfo("access-token")).thenReturn(Map.of("sub", "10"));
+ for (var method: new String[]{"GET", "POST"}) {
+ when(request.getMethod()).thenReturn(method);
+ when(request.getHeaders("Authorization")).thenReturn(Collections.enumeration(java.util.List.of("Bearer access-token")));
+ servlet.service(request, response);
+ }
+ verify(providerService, times(2)).getUserInfo("access-token");
+ verify(response, times(2)).setStatus(200);
+ }
+
+ @Test
+ void disabledProviderHidesAllEndpoints() throws Exception {
+ when(providerService.isEnabled()).thenReturn(false);
+ for (var path: new String[]{"/~oauth/token", "/~oauth/revoke", "/~oauth/userinfo", "/~oauth/jwks",
+ "/.well-known/openid-configuration", "/.well-known/oauth-authorization-server"}) {
+ when(request.getServletPath()).thenReturn(path);
+ servlet.service(request, response);
+ }
+ verify(response, times(6)).setStatus(404);
+ verify(providerService, never()).exchange(any());
+ verify(providerService, never()).revoke(any());
+ verify(providerService, never()).getMetadata();
+ verify(providerService, never()).getJwks();
+ verify(providerService, never()).getUserInfo(any());
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/oauth/OAuthFormTest.java b/server-core/src/test/java/io/onedev/server/oauth/OAuthFormTest.java
new file mode 100644
index 0000000000..97fb87ee6b
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/oauth/OAuthFormTest.java
@@ -0,0 +1,54 @@
+package io.onedev.server.oauth;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.apache.wicket.markup.Markup;
+import org.apache.wicket.util.tester.WicketTester;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import io.onedev.server.web.page.oauth.OAuthForm;
+
+class OAuthFormTest {
+
+ private WicketTester tester;
+ private boolean submitted;
+
+ @BeforeEach
+ void setUp() {
+ tester = new WicketTester();
+ var form = new OAuthForm("form") {
+ @Override protected void onSubmit() { submitted = true; }
+ };
+ tester.startComponentInPage(form, Markup.of("<form wicket:id='form'><input wicket:id='csrf' type='hidden'></form>"));
+ }
+
+ @AfterEach
+ void tearDown() {
+ tester.destroy();
+ }
+
+ @Test
+ void acceptsTheRenderedToken() {
+ tester.newFormTester("form").submit();
+ assertTrue(submitted);
+ }
+
+ @Test
+ void rejectsMissingToken() {
+ var form = tester.newFormTester("form");
+ form.setValue("csrf", "");
+ form.submit();
+ assertFalse(submitted);
+ }
+
+ @Test
+ void rejectsForgedToken() {
+ var form = tester.newFormTester("form");
+ form.setValue("csrf", "forged");
+ form.submit();
+ assertFalse(submitted);
+ tester.assertErrorMessages("Invalid form token");
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/oauth/OAuthProtocolTest.java b/server-core/src/test/java/io/onedev/server/oauth/OAuthProtocolTest.java
new file mode 100644
index 0000000000..37a484b437
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/oauth/OAuthProtocolTest.java
@@ -0,0 +1,112 @@
+package io.onedev.server.oauth;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+
+import com.nimbusds.oauth2.sdk.AuthorizationRequest;
+import com.nimbusds.oauth2.sdk.ParseException;
+import com.nimbusds.oauth2.sdk.pkce.CodeVerifier;
+
+import io.onedev.server.model.OAuthApplication;
+
+class OAuthProtocolTest {
+
+ private static final String CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
+ private static final String REQUEST = "client_id=client&response_type=code&redirect_uri=https%3A%2F%2Fclient.example%2Fcallback"
+ + "&scope=profile&state=return-state&code_challenge_method=S256&code_challenge=" + CHALLENGE;
+
+ @Test
+ void validatesRfc7636Example() throws Exception {
+ OAuthProtocol.validateAuthorization(AuthorizationRequest.parse(REQUEST));
+ assertTrue(OAuthProtocol.verifyPkce(CHALLENGE, new CodeVerifier("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")));
+ assertFalse(OAuthProtocol.verifyPkce(CHALLENGE, new CodeVerifier()));
+ assertFalse(OAuthProtocol.verifyPkce(CHALLENGE, null));
+ }
+
+ @Test
+ void refusesImplicitAndPlainPkce() throws Exception {
+ assertThrows(ParseException.class, () -> OAuthProtocol.validateAuthorization(AuthorizationRequest.parse(REQUEST.replace("response_type=code", "response_type=token"))));
+ assertThrows(ParseException.class, () -> OAuthProtocol.validateAuthorization(AuthorizationRequest.parse(REQUEST.replace("S256", "plain"))));
+ assertThrows(ParseException.class, () -> OAuthProtocol.validateAuthorization(AuthorizationRequest.parse("client_id=client&response_type=code")));
+ }
+
+ @Test
+ void rejectsUnsupportedExtensionsInsteadOfSilentlyIgnoringThem() {
+ for (String parameter: List.of("request_uri=https://client.example/request", "max_age=0", "claims=%7B%7D", "resource=https://api.example"))
+ assertThrows(ParseException.class, () -> OAuthProtocol.validateAuthorization(AuthorizationRequest.parse(REQUEST + "&" + parameter)));
+ }
+
+ @Test
+ void requiresExactRedirectMatch() throws Exception {
+ var application = new OAuthApplication();
+ application.setRedirectUris("https://client.example/callback");
+ assertTrue(OAuthProtocol.hasRegisteredRedirect(application, AuthorizationRequest.parse(REQUEST)));
+ for (String value: List.of("https://client.example/callback/", "https://client.example/callback?x=1", "https://client.example.evil/callback"))
+ assertFalse(OAuthProtocol.hasRegisteredRedirect(application, AuthorizationRequest.parse(REQUEST.replace("https%3A%2F%2Fclient.example%2Fcallback", value))));
+ }
+
+ @Test
+ void publicLoopbackClientsCanChooseAnAvailablePort() throws Exception {
+ var application = new OAuthApplication();
+ for (String host: List.of("127.0.0.1", "[::1]")) {
+ for (String path: List.of("", "/callback?client=git")) {
+ application.setRedirectUris("http://" + host + path);
+ var request = AuthorizationRequest.parse(REQUEST.replace("https%3A%2F%2Fclient.example%2Fcallback",
+ java.net.URLEncoder.encode("http://" + host + ":49152" + path, java.nio.charset.StandardCharsets.UTF_8)));
+ assertTrue(OAuthProtocol.hasRegisteredRedirect(application, request));
+ application.setRedirectUris("http://" + host + ":12345" + path);
+ assertTrue(OAuthProtocol.hasRegisteredRedirect(application, request));
+ application.setConfidential(true);
+ assertFalse(OAuthProtocol.hasRegisteredRedirect(application, request));
+ application.setConfidential(false);
+ }
+ }
+ }
+
+ @Test
+ void loopbackPortExceptionDoesNotRelaxOtherRedirectComponents() throws Exception {
+ var application = new OAuthApplication();
+ application.setRedirectUris("http://127.0.0.1/callback?client=git");
+ for (String uri: List.of("http://127.0.0.1:49152/other?client=git", "http://127.0.0.1:49152/%63allback?client=git",
+ "http://127.0.0.1:49152/callback?client=other", "http://localhost:49152/callback?client=git",
+ "http://[::1]:49152/callback?client=git", "http://127.0.0.1.example:49152/callback?client=git",
+ "http://[email protected]:49152/callback?client=git", "https://127.0.0.1:49152/callback?client=git",
+ "http://127.0.0.1:65536/callback?client=git", "http://127.0.0.1:0/callback?client=git")) {
+ var request = AuthorizationRequest.parse(REQUEST.replace("https%3A%2F%2Fclient.example%2Fcallback",
+ java.net.URLEncoder.encode(uri, java.nio.charset.StandardCharsets.UTF_8)));
+ assertFalse(OAuthProtocol.hasRegisteredRedirect(application, request), uri);
+ }
+ application.setRedirectUris("http://localhost/callback");
+ assertFalse(OAuthProtocol.hasRegisteredRedirect(application,
+ AuthorizationRequest.parse(REQUEST.replace("https%3A%2F%2Fclient.example%2Fcallback", "http://localhost:49152/callback"))));
+ }
+
+ @Test
+ void validatesRegistrationUris() {
+ for (String uri: List.of("https://client.example/callback", "http://127.0.0.1:3456/callback", "http://[::1]:3456/callback"))
+ assertTrue(OAuthProtocol.isValidRedirectUri(uri, true), uri);
+ assertTrue(OAuthProtocol.isValidRedirectUri("com.example.app:/callback", false));
+ assertFalse(OAuthProtocol.isValidRedirectUri("com.example.app:/callback", true));
+ for (String uri: List.of("http://remote.example/callback", "https://client.example/#fragment", "//client.example/callback",
+ "https://user:[email protected]/callback", "https://*.example/callback", "javascript:alert(1)", "http:/callback"))
+ assertFalse(OAuthProtocol.isValidRedirectUri(uri, false), uri);
+ }
+
+ @Test
+ void rejectsDuplicateParameters() {
+ assertThrows(ParseException.class, () -> OAuthProtocol.checkSingleParameters(Map.of("client_id", List.of("first", "second"))));
+ }
+
+ @Test
+ void comparesCredentialHashesAndRejectsMalformedGrantIdentifiers() {
+ assertTrue(OAuthProtocol.matches("secret", OAuthProtocol.hash("secret")));
+ assertFalse(OAuthProtocol.matches("other", OAuthProtocol.hash("secret")));
+ assertFalse(OAuthProtocol.matches("secret", null));
+ assertNull(OAuthProtocol.grantId("abc"));
+ assertNull(OAuthProtocol.grantId("9223372036854775808.value"));
+ }
+}
diff --git a/server-core/src/test/java/io/onedev/server/oauth/OAuthProviderServiceTest.java b/server-core/src/test/java/io/onedev/server/oauth/OAuthProviderServiceTest.java
new file mode 100644
index 0000000000..3987873f72
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/oauth/OAuthProviderServiceTest.java
@@ -0,0 +1,475 @@
+package io.onedev.server.oauth;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+import java.net.URI;
+import java.util.Date;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicReference;
+
+import jakarta.persistence.LockModeType;
+
+import org.hibernate.Session;
+import org.apache.shiro.authc.DisabledAccountException;
+import org.apache.shiro.authz.Permission;
+import org.apache.shiro.authz.UnauthorizedException;
+import org.apache.shiro.subject.Subject;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import com.nimbusds.oauth2.sdk.*;
+import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic;
+import com.nimbusds.oauth2.sdk.auth.Secret;
+import com.nimbusds.oauth2.sdk.id.ClientID;
+import com.nimbusds.oauth2.sdk.pkce.CodeChallenge;
+import com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod;
+import com.nimbusds.oauth2.sdk.pkce.CodeVerifier;
+import com.nimbusds.oauth2.sdk.token.RefreshToken;
+import com.nimbusds.jose.jwk.RSAKey;
+
+import io.onedev.server.model.AccessToken;
+import io.onedev.server.model.AccessTokenAuthorization;
+import io.onedev.server.model.OAuthApplication;
+import io.onedev.server.model.OAuthGrant;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.Role;
+import io.onedev.server.model.Setting;
+import io.onedev.server.model.User;
+import io.onedev.server.persistence.dao.Dao;
+import io.onedev.server.persistence.dao.EntityCriteria;
+import io.onedev.server.persistence.SessionService;
+import io.onedev.server.persistence.TransactionService;
+import io.onedev.server.cluster.ClusterService;
+import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.security.permission.AccessProject;
+import io.onedev.server.security.permission.ManageProject;
+import io.onedev.server.security.permission.ProjectPermission;
+import io.onedev.server.service.AccessTokenService;
+import io.onedev.server.service.AuditService;
+import io.onedev.server.service.ProjectService;
+import io.onedev.server.service.RoleService;
+import io.onedev.server.service.SettingService;
+
+class OAuthProviderServiceTest {
+
+ private DefaultOAuthProviderService provider;
+ private Subject subject;
+ private OAuthApplication application;
+ private OAuthGrant grant;
+ private AccessToken token;
+ private Dao dao;
+ private AccessTokenService accessTokens;
+ private SettingService settings;
+ private AtomicReference<String> signingKey;
+ private final CodeVerifier verifier = new CodeVerifier();
+ private static final URI ENDPOINT = URI.create("https://onedev.example/~oauth/token");
+ private static final URI REDIRECT = URI.create("https://client.example/callback");
+
+ @BeforeEach
+ void setUp() throws Exception {
+ provider = new DefaultOAuthProviderService();
+ subject = mock(Subject.class);
+ dao = mock(Dao.class);
+ var session = mock(Session.class);
+ when(dao.getSession()).thenReturn(session);
+ inject("dao", dao);
+ accessTokens = mock(AccessTokenService.class);
+ inject("accessTokenService", accessTokens);
+ inject("auditService", mock(AuditService.class));
+ settings = mock(SettingService.class);
+ signingKey = new AtomicReference<>("configured");
+ when(settings.getOAuthSigningKey()).thenAnswer(it -> signingKey.get());
+ doAnswer(it -> { signingKey.set(it.getArgument(0)); return null; })
+ .when(settings).saveOAuthSigningKey(any());
+ var systemSetting = new Setting();
+ systemSetting.setKey(Setting.Key.SYSTEM);
+ when(settings.findSetting(Setting.Key.SYSTEM)).thenReturn(systemSetting);
+ inject("settingService", settings);
+ application = new OAuthApplication();
+ application.setId(1L);
+ application.setName("Test application");
+ var applicationOwner = new User();
+ applicationOwner.setId(11L);
+ applicationOwner.setName("application-owner");
+ application.setOwner(applicationOwner);
+ application.setClientId("client");
+ application.setConfidential(true);
+ application.setSecretHash(OAuthProtocol.hash("client-secret"));
+ when(dao.find(any())).thenAnswer(it -> application);
+ var owner = new User();
+ owner.setId(10L);
+ owner.setName("owner");
+ grant = new OAuthGrant();
+ grant.setId(20L);
+ grant.setOwner(owner);
+ grant.setApplication(application);
+ grant.setScopes("profile role:code_reader");
+ grant.setRedirectUri(REDIRECT.toString());
+ grant.setCodeChallenge(CodeChallenge.compute(CodeChallengeMethod.S256, verifier).getValue());
+ grant.setCodeHash(OAuthProtocol.hash("20.code-secret"));
+ grant.setCodeExpireDate(new Date(System.currentTimeMillis() + 120_000));
+ grant.setExpireDate(new Date(System.currentTimeMillis() + 86400_000));
+ token = new AccessToken();
+ token.setId(30L);
+ token.setOauthGrant(grant);
+ token.setOwner(owner);
+ token.setExpireDate(new Date(0));
+ var role = new Role();
+ role.setId(1L);
+ role.setName("Code Reader");
+ var roles = mock(RoleService.class);
+ when(roles.query()).thenReturn(List.of(role));
+ inject("roleService", roles);
+ var authorization = new AccessTokenAuthorization();
+ authorization.setToken(token);
+ authorization.setRole(role);
+ token.getAuthorizations().add(authorization);
+ grant.getAccessTokens().add(token);
+ when(session.find(OAuthGrant.class, 20L, LockModeType.PESSIMISTIC_WRITE)).thenReturn(grant);
+ }
+
+ private void inject(String name, Object value) throws Exception {
+ var field = DefaultOAuthProviderService.class.getDeclaredField(name);
+ field.setAccessible(true);
+ field.set(provider, value);
+ }
+
+ private ClientSecretBasic auth() { return new ClientSecretBasic(new ClientID("client"), new Secret("client-secret")); }
+
+ private TokenRequest code(CodeVerifier value, URI redirect) {
+ return new TokenRequest(ENDPOINT, auth(), new AuthorizationCodeGrant(new AuthorizationCode("20.code-secret"), redirect, value));
+ }
+
+ private TokenRequest refresh(RefreshToken refresh, Scope scope) {
+ return new TokenRequest(ENDPOINT, auth(), new RefreshTokenGrant(refresh), scope);
+ }
+
+ private void assertError(String expected, TokenResponse response) {
+ assertFalse(response.indicatesSuccess());
+ assertEquals(expected, response.toErrorResponse().getErrorObject().getCode());
+ }
+
+ @Test
+ void missingSigningKeyDisablesProviderWithoutGeneratingOne() {
+ signingKey.set(null);
+ assertFalse(provider.isEnabled());
+ assertNull(provider.getPublicSigningKey());
+ assertThrows(io.onedev.commons.utils.ExplicitException.class, provider::getJwks);
+ assertThrows(io.onedev.commons.utils.ExplicitException.class, provider::getMetadata);
+ assertThrows(io.onedev.commons.utils.ExplicitException.class, () -> provider.saveApplication(application));
+ assertError("temporarily_unavailable", provider.exchange(code(verifier, REDIRECT)));
+ assertNull(provider.getUserInfo("token"));
+ verify(settings, never()).saveOAuthSigningKey(any());
+ verify(dao, never()).persist(any());
+ verify(accessTokens, never()).findByValue(any());
+ }
+
+ @Test
+ void generatingRegeneratingAndDeletingSigningKey() throws Exception {
+ signingKey.set(null);
+ provider.generateSigningKey();
+ assertTrue(provider.isEnabled());
+ var first = RSAKey.parse(signingKey.get());
+ assertTrue(first.isPrivate());
+ assertFalse(provider.getPublicSigningKey().isPrivate());
+ assertEquals(first.toPublicJWK().toJSONObject(),
+ ((java.util.List<?>) provider.getJwks().get("keys")).get(0));
+ when(dao.query(org.mockito.ArgumentMatchers.<EntityCriteria<OAuthGrant>>any())).thenReturn(List.of(grant));
+ provider.generateSigningKey();
+ assertNotEquals(first.getKeyID(), provider.getPublicSigningKey().getKeyID());
+ verify(accessTokens).delete(token);
+ verify(dao).remove(grant);
+ verify(dao, never()).remove(application);
+ when(dao.query(org.mockito.ArgumentMatchers.<EntityCriteria<OAuthGrant>>any())).thenReturn(List.of());
+ provider.deleteSigningKey();
+ assertFalse(provider.isEnabled());
+ assertNull(provider.getPublicSigningKey());
+ }
+
+ @Test
+ void deletingSigningKeyRevokesGrantsAndPreservesApplications() {
+ when(dao.query(org.mockito.ArgumentMatchers.<EntityCriteria<OAuthGrant>>any())).thenReturn(List.of(grant));
+ provider.deleteSigningKey();
+ assertFalse(provider.isEnabled());
+ verify(accessTokens).delete(token);
+ verify(dao).remove(grant);
+ verify(dao, never()).remove(application);
+ }
+
+ @Test
+ void consentRequiresTheAccountToManageTheSelectedProject() throws Exception {
+ var owner = grant.getOwner();
+ var project = new Project();
+ project.setId(100L);
+ var projects = mock(ProjectService.class);
+ when(projects.load(project.getId())).thenReturn(project);
+ inject("projectService", projects);
+ application.setRedirectUris(REDIRECT.toString());
+ var request = AuthorizationRequest.parse("client_id=client&response_type=code"
+ + "&redirect_uri=https%3A%2F%2Fclient.example%2Fcallback&scope=profile+role%3Acode_reader"
+ + "&code_challenge_method=S256&code_challenge=" + grant.getCodeChallenge());
+ when(subject.isPermitted(any(Permission.class))).thenAnswer(it ->
+ new ProjectPermission(project, new AccessProject()).implies(it.getArgument(0)));
+ try (var security = mockStatic(SecurityUtils.class)) {
+ security.when(() -> SecurityUtils.getAuthUser(subject)).thenReturn(owner);
+ security.when(() -> SecurityUtils.canAccessProject(subject, project)).thenCallRealMethod();
+ security.when(() -> SecurityUtils.canManageProject(subject, project)).thenCallRealMethod();
+ assertTrue(SecurityUtils.canAccessProject(subject, project));
+ assertThrows(UnauthorizedException.class, () -> provider.authorize(subject, request, List.of(project.getId())));
+ verify(dao, never()).persist(any());
+ verify(accessTokens, never()).createOrUpdate(any());
+
+ when(subject.isPermitted(any(Permission.class))).thenAnswer(it ->
+ new ProjectPermission(project, new ManageProject()).implies(it.getArgument(0)));
+ assertNotNull(provider.authorize(subject, request, List.of(project.getId())));
+ verify(dao).persist(argThat(entity -> entity instanceof AccessTokenAuthorization authorization
+ && authorization.getProject().equals(project) && authorization.getToken().getOwner().equals(owner)));
+ }
+ }
+
+ @Test
+ void exchangesCodeAndRotatesRefreshToken() {
+ var first = provider.exchange(code(verifier, REDIRECT)).toSuccessResponse().getTokens();
+ assertEquals(3600, first.getAccessToken().getLifetime());
+ assertFalse(token.isExpired());
+ assertNotEquals(first.getRefreshToken().getValue(), grant.getRefreshTokenHash());
+ var second = provider.exchange(refresh(first.getRefreshToken(), null)).toSuccessResponse().getTokens();
+ assertNotEquals(first.getAccessToken(), second.getAccessToken());
+ assertNotEquals(first.getRefreshToken(), second.getRefreshToken());
+ assertEquals(1, grant.getUsedRefreshTokenHashes().size());
+ assertEquals(new Scope("profile", "role:code_reader"), second.getAccessToken().getScope());
+ assertEquals(1, token.getAuthorizations().size());
+ }
+
+ @Test
+ void roleScopesUseNormalizedNamesInsteadOfIds() throws Exception {
+ var role = token.getAuthorizations().iterator().next().getRole();
+ assertEquals("Role: Code Reader", provider.getScopes().get("role:code_reader"));
+ assertEquals(List.of(role), provider.getRoles(Scope.parse("profile role:code_reader")));
+ assertEquals(OAuth2Error.INVALID_SCOPE, assertThrows(ParseException.class,
+ () -> provider.getRoles(new Scope("role:1"))).getErrorObject());
+ role.setName("Reader + % / \"é\"");
+ var scope = "role:reader_%2B_%25_%2F_%22%C3%A9%22";
+ assertTrue(provider.getScopes().containsKey(scope));
+ assertEquals(List.of(role), provider.getRoles(Scope.parse(scope)));
+ assertThrows(ParseException.class, () -> provider.getRoles(new Scope("role:code_reader")));
+ }
+
+ @Test
+ void renamedRoleIsRemovedWhenRefreshingAnExistingGrant() {
+ var first = provider.exchange(code(verifier, REDIRECT)).toSuccessResponse().getTokens();
+ token.getAuthorizations().iterator().next().getRole().setName("Renamed Reader");
+ assertTrue(provider.exchange(refresh(first.getRefreshToken(), null)).indicatesSuccess());
+ assertTrue(token.getAuthorizations().isEmpty());
+ }
+
+ @Test
+ void rejectsWrongPkceAndRedirectWithoutConsumingCode() {
+ assertError("invalid_grant", provider.exchange(code(new CodeVerifier(), REDIRECT)));
+ assertError("invalid_grant", provider.exchange(code(verifier, URI.create("https://client.example/other"))));
+ assertNull(grant.getLastUsedDate());
+ assertTrue(provider.exchange(code(verifier, REDIRECT)).indicatesSuccess());
+ }
+
+ @Test
+ void codeExchangeRequiresTheLoopbackPortUsedDuringAuthorization() {
+ var redirect = URI.create("http://127.0.0.1:49152");
+ grant.setRedirectUri(redirect.toString());
+ assertError("invalid_grant", provider.exchange(code(verifier, URI.create("http://127.0.0.1:49153"))));
+ assertNull(grant.getLastUsedDate());
+ assertTrue(provider.exchange(code(verifier, redirect)).indicatesSuccess());
+ }
+
+ @Test
+ void replayingAUsedCodeRevokesItsGrant() {
+ assertTrue(provider.exchange(code(verifier, REDIRECT)).indicatesSuccess());
+ assertError("invalid_grant", provider.exchange(code(verifier, REDIRECT)));
+ verify(dao).remove(grant);
+ verify(accessTokens).delete(token);
+ }
+
+ @Test
+ void replayingRotatedRefreshTokenRevokesItsEntireGrant() {
+ var first = provider.exchange(code(verifier, REDIRECT)).toSuccessResponse().getTokens();
+ var second = provider.exchange(refresh(first.getRefreshToken(), null)).toSuccessResponse().getTokens();
+ assertError("invalid_grant", provider.exchange(refresh(first.getRefreshToken(), null)));
+ verify(dao).remove(grant);
+ verify(accessTokens).delete(token);
+ assertError("invalid_grant", provider.exchange(refresh(second.getRefreshToken(), null)));
+ }
+
+ @Test
+ void refreshScopeCanNarrowButCannotExpand() {
+ var first = provider.exchange(code(verifier, REDIRECT)).toSuccessResponse().getTokens();
+ assertError("invalid_scope", provider.exchange(refresh(first.getRefreshToken(), new Scope("profile", "email"))));
+ var second = provider.exchange(refresh(first.getRefreshToken(), new Scope("profile"))).toSuccessResponse().getTokens();
+ assertEquals(new Scope("profile"), second.getAccessToken().getScope());
+ assertTrue(token.getAuthorizations().isEmpty());
+ assertError("invalid_scope", provider.exchange(refresh(second.getRefreshToken(), new Scope("profile", "role:code_reader"))));
+ }
+
+ @Test
+ void expiredAndDisabledGrantsCannotIssueTokens() {
+ grant.setCodeExpireDate(new Date(0));
+ assertError("invalid_grant", provider.exchange(code(verifier, REDIRECT)));
+ grant.setCodeExpireDate(new Date(System.currentTimeMillis() + 120_000));
+ grant.getOwner().setDisabled(true);
+ assertError("invalid_grant", provider.exchange(code(verifier, REDIRECT)));
+ }
+
+ @Test
+ void publicClientsMustUsePkceAndCannotAuthenticateWithASecret() {
+ application.setConfidential(false);
+ assertError("invalid_client", provider.exchange(code(verifier, REDIRECT)));
+ var request = new TokenRequest(ENDPOINT, new ClientID("client"),
+ new AuthorizationCodeGrant(new AuthorizationCode("20.code-secret"), REDIRECT, verifier));
+ assertTrue(provider.exchange(request).indicatesSuccess());
+ }
+
+ @Test
+ void anotherClientCannotRedeemOrRevokeGrant() {
+ var refresh = provider.exchange(code(verifier, REDIRECT)).toSuccessResponse().getTokens().getRefreshToken();
+ var other = new OAuthApplication();
+ other.setId(2L);
+ grant.setApplication(other);
+ assertError("invalid_grant", provider.exchange(code(verifier, REDIRECT)));
+ assertEquals(200, provider.revoke(new TokenRevocationRequest(ENDPOINT, auth(), refresh)).getStatusCode());
+ verify(dao, never()).remove(grant);
+ verify(accessTokens, never()).delete(token);
+ }
+
+ @Test
+ void unsupportedRefreshRequestDoesNotConsumeTokenOrNarrowScopes() throws Exception {
+ var refresh = provider.exchange(code(verifier, REDIRECT)).toSuccessResponse().getTokens().getRefreshToken();
+ var http = refresh(refresh, new Scope("profile")).toHTTPRequest();
+ http.setBody(http.getBody() + "&resource=https%3A%2F%2Fapi.example");
+ var request = TokenRequest.parse(http);
+ assertError("invalid_request", provider.exchange(request));
+ assertEquals("profile role:code_reader", grant.getScopes());
+ assertTrue(provider.exchange(refresh(refresh, null)).indicatesSuccess());
+ }
+
+ @Test
+ void disabledAccountIsAnInvalidBearerToken() {
+ when(accessTokens.findByValue("disabled")).thenThrow(new DisabledAccountException());
+ assertNull(provider.getUserInfo("disabled"));
+ }
+
+ @Test
+ void revokingOneTokenLeavesAnotherAuthorizationUsable() {
+ var otherGrant = new OAuthGrant();
+ otherGrant.setId(21L);
+ otherGrant.setOwner(grant.getOwner());
+ otherGrant.setApplication(application);
+ otherGrant.setScopes(grant.getScopes());
+ otherGrant.setRedirectUri(grant.getRedirectUri());
+ otherGrant.setCodeChallenge(grant.getCodeChallenge());
+ otherGrant.setCodeHash(OAuthProtocol.hash("21.other-code"));
+ otherGrant.setCodeExpireDate(grant.getCodeExpireDate());
+ otherGrant.setExpireDate(grant.getExpireDate());
+ var otherToken = new AccessToken();
+ otherToken.setId(31L);
+ otherToken.setOwner(grant.getOwner());
+ otherToken.setOauthGrant(otherGrant);
+ otherGrant.getAccessTokens().add(otherToken);
+ when(dao.getSession().find(OAuthGrant.class, 21L, LockModeType.PESSIMISTIC_WRITE)).thenReturn(otherGrant);
+ provider.revokeGrant(grant.getId());
+ verify(accessTokens).delete(token);
+ verify(dao).remove(grant);
+ assertTrue(grant.getAccessTokens().isEmpty());
+ assertError("invalid_grant", provider.exchange(code(verifier, REDIRECT)));
+ assertTrue(provider.exchange(new TokenRequest(ENDPOINT, auth(),
+ new AuthorizationCodeGrant(new AuthorizationCode("21.other-code"), REDIRECT, verifier))).indicatesSuccess());
+ verify(accessTokens, never()).delete(otherToken);
+ }
+
+ @Test
+ void revokingAllTokensDeletesGrantsAndPreservesApplication() {
+ var second = new OAuthGrant();
+ second.setId(21L);
+ second.setOwner(grant.getOwner());
+ second.setApplication(application);
+ second.setCodeExpireDate(grant.getCodeExpireDate());
+ second.setExpireDate(grant.getExpireDate());
+ var secondToken = new AccessToken();
+ secondToken.setId(31L);
+ second.getAccessTokens().add(secondToken);
+ when(dao.getSession().find(OAuthGrant.class, 21L, LockModeType.PESSIMISTIC_WRITE)).thenReturn(second);
+ when(dao.query(org.mockito.ArgumentMatchers.<EntityCriteria<OAuthGrant>>any())).thenReturn(List.of(grant, second));
+ assertEquals(2, provider.getGrants(grant.getOwner()).size());
+ provider.revokeGrants(grant.getOwner(), application.getId());
+ verify(accessTokens).delete(token);
+ verify(accessTokens).delete(secondToken);
+ verify(dao).remove(grant);
+ verify(dao).remove(second);
+ verify(dao, never()).remove(application);
+ }
+
+ @Test
+ void revokingAllApplicationsRemovesTokensAcrossApplications() {
+ var otherApplication = new OAuthApplication();
+ otherApplication.setId(2L);
+ otherApplication.setName("Another application");
+ var otherGrant = new OAuthGrant();
+ otherGrant.setId(21L);
+ otherGrant.setOwner(grant.getOwner());
+ otherGrant.setApplication(otherApplication);
+ var otherToken = new AccessToken();
+ otherToken.setId(31L);
+ otherGrant.getAccessTokens().add(otherToken);
+ when(dao.getSession().find(OAuthGrant.class, 21L, LockModeType.PESSIMISTIC_WRITE)).thenReturn(otherGrant);
+ when(dao.query(org.mockito.ArgumentMatchers.<EntityCriteria<OAuthGrant>>any())).thenReturn(List.of(grant, otherGrant));
+ provider.revokeGrants(grant.getOwner());
+ verify(accessTokens).delete(token);
+ verify(accessTokens).delete(otherToken);
+ verify(dao).remove(grant);
+ verify(dao).remove(otherGrant);
+ }
+
+ @Test
+ void grantListExcludesObsoleteEntriesButKeepsRefreshableTokens() {
+ var expired = new OAuthGrant();
+ expired.setExpireDate(new Date(0));
+ when(dao.query(org.mockito.ArgumentMatchers.<EntityCriteria<OAuthGrant>>any())).thenReturn(List.of(grant, expired));
+ assertEquals(List.of(grant), provider.getGrants(grant.getOwner()));
+ grant.setCodeExpireDate(new Date(0));
+ assertTrue(provider.getGrants(grant.getOwner()).isEmpty());
+ grant.setLastUsedDate(new Date());
+ assertTrue(token.isExpired());
+ assertEquals(List.of(grant), provider.getGrants(grant.getOwner()));
+ }
+
+ @Test
+ void cleanupRemovesExpiredEntriesAndRechecksPendingCodesUnderLock() throws Exception {
+ var cluster = mock(ClusterService.class);
+ when(cluster.isLeaderServer()).thenReturn(true);
+ inject("clusterService", cluster);
+ var sessions = mock(SessionService.class);
+ when(sessions.call(any())).thenAnswer(it -> ((Callable<?>) it.getArgument(0)).call());
+ inject("sessionService", sessions);
+ var transactions = mock(TransactionService.class);
+ doAnswer(it -> { ((Runnable) it.getArgument(0)).run(); return null; }).when(transactions).run(any());
+ inject("transactionService", transactions);
+ @SuppressWarnings("unchecked")
+ var query = (org.hibernate.query.Query<Long>) mock(org.hibernate.query.Query.class);
+ when(dao.getSession().createQuery(anyString(), eq(Long.class))).thenReturn(query);
+ when(query.setParameter(eq("now"), any(Date.class))).thenReturn(query);
+ when(query.setMaxResults(100)).thenReturn(query);
+ when(query.getResultList()).thenReturn(List.of(20L, 21L), List.of());
+ grant.setCodeExpireDate(new Date(0));
+ var redeemed = new OAuthGrant();
+ redeemed.setId(21L);
+ redeemed.setLastUsedDate(new Date());
+ redeemed.setCodeExpireDate(new Date(0));
+ redeemed.setExpireDate(new Date(System.currentTimeMillis() + 86400_000));
+ when(dao.getSession().find(OAuthGrant.class, 21L, LockModeType.PESSIMISTIC_WRITE)).thenReturn(redeemed);
+ provider.execute();
+ verify(dao).remove(grant);
+ verify(accessTokens).delete(token);
+ verify(dao, never()).remove(redeemed);
+ assertTrue(grant.getAccessTokens().isEmpty());
+ }
+}
diff --git a/server-product/src/main/java/io/onedev/server/product/ProductServletConfigurator.java b/server-product/src/main/java/io/onedev/server/product/ProductServletConfigurator.java
index 2f91de8e95..ecde007b9a 100644
--- a/server-product/src/main/java/io/onedev/server/product/ProductServletConfigurator.java
+++ b/server-product/src/main/java/io/onedev/server/product/ProductServletConfigurator.java
@@ -16,6 +16,7 @@ import org.apache.wicket.protocol.http.WicketServlet;
import org.eclipse.jetty.ee11.servlet.FilterHolder;
import org.eclipse.jetty.ee11.servlet.ServletContextHandler;
import org.eclipse.jetty.ee11.servlet.ServletHolder;
+import org.eclipse.jetty.ee11.servlet.ServletMapping;
import org.glassfish.jersey.servlet.ServletContainer;
import io.onedev.commons.bootstrap.Bootstrap;
@@ -30,6 +31,7 @@ import io.onedev.server.git.GoGetFilter;
import io.onedev.server.git.hook.GitPostReceiveCallback;
import io.onedev.server.git.hook.GitPreReceiveCallback;
import io.onedev.server.jetty.ServletConfigurator;
+import io.onedev.server.oauth.OAuthEndpointServlet;
import io.onedev.server.security.CorsFilter;
import io.onedev.server.security.DefaultWebEnvironment;
import io.onedev.server.web.KeepSessionAliveServlet;
@@ -70,6 +72,9 @@ public class ProductServletConfigurator implements ServletConfigurator {
@Inject
private ServerSocketServlet serverServlet;
+ @Inject
+ private OAuthEndpointServlet oauthServlet;
+
@Inject
private Set<SessionListener> sessionListener;
@@ -162,6 +167,15 @@ public class ProductServletConfigurator implements ServletConfigurator {
context.addServlet(new ServletHolder(jerseyServlet), "/~api/*");
context.addServlet(new ServletHolder(serverServlet), "/~server");
+
+ var oauthHolder = new ServletHolder(oauthServlet);
+ oauthHolder.setName("oauth-provider");
+ context.addServlet(oauthHolder, "/~oauth/token");
+ var oauthMapping = new ServletMapping();
+ oauthMapping.setServletName("oauth-provider");
+ oauthMapping.setPathSpecs(new String[] {"/~oauth/revoke", "/~oauth/userinfo", "/~oauth/jwks",
+ "/.well-known/oauth-authorization-server", "/.well-known/openid-configuration"});
+ context.getServletHandler().addServletMapping(oauthMapping);
}
}