forked from DMPRoadmap/roadmap
-
Notifications
You must be signed in to change notification settings - Fork 3
Add Internal v2 API Access Token Generation for Users #1279
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
aaronskiba
merged 19 commits into
aaron/v2-api
from
aaron/feature-v2-api-token-for-internal-users-copy
Feb 23, 2026
Merged
Changes from 12 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
66ed567
Create internal Doorkeeper app via rake task
aaronskiba e7524cc
Create `Api::V2::InternalUserAccessTokenService`
aaronskiba 7067405
Add "POST /api/v2/internal_user_access_token" action & route
aaronskiba 437a9ed
Add API v2 section to `/users/edit#api-details`
aaronskiba 1c3e932
Refactor api_token into v2 & legacy partials
aaronskiba bd16be5
Expose API Access tab to all users / restrict legacy token rendering
aaronskiba 38b1437
Improve styling for v2 + legacy API displays
aaronskiba 1071383
Add handling for missing internal OAuth app
aaronskiba bbe35e4
Add test coverage for internal v2 token generation
aaronskiba 81ca29b
Set default format for internal_user_access_token route
aaronskiba 3601651
Fix string typo in `refresh_token.js.erb`
aaronskiba b5e9c43
Update API Access UI to BS3 (revert after BS5 upgrade)
aaronskiba 1e192a1
Merge branch 'aaron/v2-api' into aaron/feature-v2-api-token-for-inter…
aaronskiba 34815ef
Remove `redirect_uri` from internal OAuth app
aaronskiba 2e8c176
Merge branch 'aaron/v2-api' into aaron/feature-v2-api-token-for-inter…
aaronskiba 16c72d4
Adapt internal user v2 token handling to hashed tokens
aaronskiba 3a39867
Switch "Regenerate token" to button & prevent spamming
aaronskiba f63abd1
Improve styling for API titles in partials
aaronskiba 8802049
Update CHANGELOG.md
aaronskiba File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
20 changes: 20 additions & 0 deletions
20
app/controllers/api/v2/internal_user_access_tokens_controller.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| module Api | ||
| module V2 | ||
| # Controller for managing the current user's internal V2 API access token. | ||
| # Provides token rotation for authenticated internal users. | ||
| # See Api::V2::InternalUserAccessTokenService for token implementation details. | ||
| class InternalUserAccessTokensController < ApplicationController | ||
| # POST "/api/v2/internal_user_access_token" | ||
| def create | ||
| authorize current_user, :internal_user_v2_access_token? | ||
| @token = Api::V2::InternalUserAccessTokenService.rotate!(current_user) | ||
| @success = true | ||
| respond_to do |format| | ||
| format.js { render 'users/refresh_token' } | ||
| end | ||
| end | ||
| end | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| module Api | ||
| module V2 | ||
| # Service responsible for user-scoped v2 API access tokens, strictly for | ||
| # internal users of this application. | ||
| # | ||
| # Tokens issued by this service are functionally equivalent to Personal Access | ||
| # Tokens (PATs) for first-party usage. They are minted directly for a user | ||
| # who is already authenticated in the application, bypassing the standard | ||
| # OAuth 2.0 authorization_code redirect and consent flow. | ||
| # | ||
| # This design is intentional: | ||
| # - tokens are internal to this application (first-party) | ||
| # - tokens are owned by a single user and scoped accordingly | ||
| # - token creation, rotation, and revocation happen entirely within the app UI | ||
| # | ||
| # Tokens are stored as Doorkeeper::AccessToken records to leverage existing | ||
| # scoping, expiry, and revocation mechanisms. | ||
| # | ||
| # This service does NOT support third-party OAuth clients or delegated consent flows. | ||
| class InternalUserAccessTokenService | ||
| READ_SCOPE = 'read' | ||
| INTERNAL_OAUTH_APP_NAME = Rails.application.config.x.application.internal_oauth_app_name | ||
|
|
||
| class << self | ||
| def for_user(user) | ||
| Doorkeeper::AccessToken.find_by( | ||
| application_id: application!.id, | ||
| resource_owner_id: user.id, | ||
| scopes: READ_SCOPE, | ||
| revoked_at: nil | ||
| ) | ||
| end | ||
|
|
||
| def rotate!(user) | ||
| revoke_existing!(user) | ||
|
|
||
| Doorkeeper::AccessToken.create!( | ||
| application_id: application!.id, | ||
| resource_owner_id: user.id, | ||
| scopes: READ_SCOPE, | ||
| expires_in: nil # Overrides Doorkeeper's `access_token_expires_in` | ||
| ) | ||
| end | ||
|
|
||
| # Used by views (e.g. devise/registrations/_v2_api_token.html.erb) to safely | ||
| # gate token UI if the internal OAuth application is missing. | ||
| def application_present? | ||
| application! | ||
| true | ||
| rescue StandardError => e | ||
| Rails.logger.error(e.message) | ||
| false | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def application! | ||
| Doorkeeper::Application.find_by(name: INTERNAL_OAUTH_APP_NAME) || | ||
| raise( | ||
| StandardError, | ||
| "Required Doorkeeper application '#{INTERNAL_OAUTH_APP_NAME}' not found. " \ | ||
| 'Please ensure the application exists in the database.' | ||
| ) | ||
| end | ||
|
|
||
| def revoke_existing!(user) | ||
| Doorkeeper::AccessToken.revoke_all_for(application!.id, user) | ||
| end | ||
| end | ||
| end | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,25 +1,11 @@ | ||
| <%# locals: user %> | ||
|
|
||
| <% api_wikis = Rails.configuration.x.application.api_documentation_urls %> | ||
| <div id="api-token" class="col-xs-12"> | ||
| <div class="form-group col-xs-8"> | ||
| <%= label_tag(:api_token, _('Access token'), class: 'control-label') %> | ||
| <% if user.api_token.present? %> | ||
| <%= user.api_token %> | ||
| <% else %> | ||
| <%= _("Click the button below to generate an API token") %> | ||
| <% end %> | ||
| </div> | ||
| <div class="form-group col-xs-12"> | ||
| <%= label_tag(:api_information, _('Documentation'), class: 'control-label') %> | ||
| <br> | ||
| <%= _('See the <a href="%{api_v0_wiki}">documentation for v0</a> for more details on the original API which includes access to statistics, the full text of plans and the ability to connect users with departments.').html_safe % { api_v0_wiki: api_wikis[:v0] } %></a> | ||
| <br><br> | ||
| <%= _('See the <a href="%{api_v1_wiki}">documentation for v1</a> for more details on the API that supports the <a href="%{rda_standard_url}">RDA Common metadata standard for DMPs.</a>').html_safe % { api_v1_wiki: api_wikis[:v1], rda_standard_url: 'https://github.com/RDA-DMP-Common/RDA-DMP-Common-Standard' } %></a> | ||
| </div> | ||
| <div class="form-group col-xs-8"> | ||
| <%= link_to _("Regenerate token"), | ||
| refresh_token_user_path(user), | ||
| class: "btn btn-default", remote: true %> | ||
| </div> | ||
| <div id="api-tokens"> | ||
| <%# v2 API token %> | ||
| <%= render partial: "devise/registrations/v2_api_token", locals: { user: user } %> | ||
|
|
||
| <% if user.can_use_api? %> | ||
| <%# v0/v1 API token %> | ||
| <%= render partial: "devise/registrations/legacy_api_token", locals: { user: user } %> | ||
| <% end %> | ||
| </div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| <%# locals: user %> | ||
|
|
||
| <% api_wikis = Rails.configuration.x.application.api_documentation_urls %> | ||
| <div id="legacy-api-token" class="panel mb-4" style="border: 1px solid #0a0a0a"> | ||
| <div class="nav nav-tabs"> | ||
| <%= _('Legacy API') %> | ||
momo3404 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| </div> | ||
| <div class="panel-body"> | ||
| <div class="form-group mb-3 col-xs-8"> | ||
| <%= label_tag(:api_token, _('Access token'), class: 'form-label') %> | ||
| <% if user.api_token.present? %> | ||
| <code><%= user.api_token %></code> | ||
| <% else %> | ||
| <%= _("Click the button below to generate an API token") %> | ||
| <% end %> | ||
| </div> | ||
| <div class="form-group mb-3 col-xs-12"> | ||
| <%= label_tag(:api_information, _('Documentation'), class: 'form-label') %> | ||
| <br> | ||
| <%= _('See the <a href="%{api_v0_wiki}">documentation for v0</a> for more details on the original API which includes access to statistics, the full text of plans and the ability to connect users with departments.').html_safe % { api_v0_wiki: api_wikis[:v0] } %></a> | ||
| <br><br> | ||
| <%= _('See the <a href="%{api_v1_wiki}">documentation for v1</a> for more details on the API that supports the <a href="%{rda_standard_url}">RDA Common metadata standard for DMPs.</a>').html_safe % { api_v1_wiki: api_wikis[:v1], rda_standard_url: 'https://github.com/RDA-DMP-Common/RDA-DMP-Common-Standard' } %></a> | ||
| </div> | ||
| <div class="form-group mb-3 col-xs-8"> | ||
| <%= link_to _("Regenerate token"), | ||
| refresh_token_user_path(user), | ||
| class: "btn btn-default", remote: true %> | ||
| </div> | ||
| </div> | ||
| </div> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| <%# locals: user %> | ||
|
|
||
| <div id="v2-api-token" class="panel mb-4" style="border: 1px solid #0a0a0a"> | ||
| <div class="nav nav-tabs"> | ||
| <%= _('V2 API') %> | ||
| </div> | ||
| <div class="panel-body"> | ||
| <% if Api::V2::InternalUserAccessTokenService.application_present? %> | ||
| <% token = Api::V2::InternalUserAccessTokenService.for_user(user) %> | ||
| <div class="form-group mb-3 col-xs-8"> | ||
| <%= label_tag(:api_token, _('Access token'), class: 'form-label') %> | ||
| <% if token.present? %> | ||
| <code><%= token.token %></code> | ||
| <% else %> | ||
| <%= _("Click the button below to generate an API token") %> | ||
| <% end %> | ||
aaronskiba marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| </div> | ||
|
|
||
| <div class="form-group mb-3 col-xs-8"> | ||
| <%= link_to _("Regenerate token"), | ||
| api_v2_internal_user_access_token_path, | ||
| method: :post, | ||
| class: 'btn btn-default', | ||
| remote: true %> | ||
| </div> | ||
| <% else %> | ||
| <div class="alert alert-warning"> | ||
| <%= _("V2 API token service is currently unavailable. Please contact us for help.") %> | ||
| <%= mail_to Rails.application.config.x.organisation.helpdesk_email %> | ||
| </div> | ||
| <% end %> | ||
| </div> | ||
| </div> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| var msg = '<%= @success ? _("Successfully regenerate your API token.") : _("Unable to regenerate your API token.") %>'; | ||
| var msg = '<%= @success ? _("Successfully regenerated your API token.") : _("Unable to regenerate your API token.") %>'; | ||
|
|
||
| var context = $('#api-token'); | ||
| var context = $('#api-tokens'); | ||
| context.html('<%= escape_javascript(render partial: "/devise/registrations/api_token", locals: { user: current_user }) %>'); | ||
| renderNotice(msg); | ||
| toggleSpinner(false); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -64,6 +64,8 @@ class Application < Rails::Application | |
|
|
||
| # Used throughout the system via ApplicationService.application_name | ||
| config.x.application.name = 'DMP Assistant' | ||
| # Name of the internal Doorkeeper OAuth application for v2 API access tokens | ||
| config.x.application.internal_oauth_app_name = 'Internal v2 API Client' | ||
| # Used as the default domain when 'archiving' (aka anonymizing) a user account | ||
| # for example `[email protected]` becomes `1234@removed_accounts-example.org` | ||
| config.x.application.archived_accounts_email_suffix = '@removed_accounts-example.org' | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| namespace :doorkeeper do | ||
| desc 'Ensure internal OAuth application exists' | ||
| task ensure_internal_app: :environment do | ||
| app = Doorkeeper::Application.find_or_create_by!( | ||
| name: Rails.application.config.x.application.internal_oauth_app_name | ||
| ) do |a| | ||
| a.scopes = 'read' | ||
| a.confidential = true | ||
| # redirect_uri value is only used as a placeholder here (required by Doorkeeper). | ||
| # Tokens are minted server-side for already-authenticated first-party users. | ||
| # No redirect, authorization code, or third-party client is involved. | ||
| a.redirect_uri = "#{Rails.application.routes.url_helpers.root_url}oauth/callback" | ||
aaronskiba marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| end | ||
|
|
||
| puts "Internal OAuth app ready (id=#{app.id}, uid=#{app.uid})" | ||
| end | ||
| end | ||
91 changes: 91 additions & 0 deletions
91
spec/requests/api/v2/internal_user_access_tokens_controller_spec.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require 'rails_helper' | ||
|
|
||
| RSpec.describe Api::V2::InternalUserAccessTokensController do | ||
| let(:user) { create(:user) } | ||
| let(:app_name) { Rails.application.config.x.application.internal_oauth_app_name } | ||
| let!(:oauth_app) { create(:oauth_application, name: app_name) } | ||
|
|
||
| describe 'POST #create' do | ||
| def post_create_token | ||
| post api_v2_internal_user_access_token_path | ||
| end | ||
|
|
||
| context 'when user is not authenticated' do | ||
| # In production, CSRF protection would reject the request with a 422 error | ||
| # before it reaches Pundit. However, RSpec bypasses CSRF checks, so this | ||
| # test verifies that Pundit raises NotDefinedError when authorize is called | ||
| # with nil. This error won't occur in production due to CSRF protection. | ||
| it 'raises Pundit::NotDefinedError and does not create a token' do | ||
| expect do | ||
| expect do | ||
| post_create_token | ||
| end.to raise_error(Pundit::NotDefinedError) | ||
| end.not_to change { Doorkeeper::AccessToken.count } | ||
| end | ||
| end | ||
|
|
||
| context 'when user is authenticated' do | ||
| before { sign_in(user) } | ||
|
|
||
| it 'rotates the user token' do | ||
| post_create_token | ||
|
|
||
| expect(response).to have_http_status(:ok) | ||
| end | ||
|
|
||
| it 'creates a new token' do | ||
| expect do | ||
| post_create_token | ||
| end.to change { Doorkeeper::AccessToken.count }.by(1) | ||
| end | ||
|
|
||
| it 'assigns the token' do | ||
| post_create_token | ||
|
|
||
| expect(assigns(:token)).to be_a(Doorkeeper::AccessToken) | ||
| expect(assigns(:token).resource_owner_id).to eq(user.id) | ||
| end | ||
|
|
||
| it 'renders the refresh_token template' do | ||
| post_create_token | ||
|
|
||
| expect(response).to render_template('users/refresh_token') | ||
| end | ||
|
|
||
| context 'when a token already exists' do | ||
| let!(:old_token) do | ||
| create(:oauth_access_token, application: oauth_app, resource_owner_id: user.id, scopes: 'read') | ||
| end | ||
|
|
||
| it 'revokes the old token' do | ||
| post_create_token | ||
|
|
||
| old_token.reload | ||
| expect(old_token.revoked_at).not_to be_nil | ||
| end | ||
|
|
||
| it 'creates a new token' do | ||
| post_create_token | ||
|
|
||
| new_token = assigns(:token) | ||
| expect(new_token).not_to eq(old_token) | ||
| end | ||
| end | ||
| end | ||
|
|
||
| context 'when the internal OAuth application is missing' do | ||
| before do | ||
| sign_in(user) | ||
| oauth_app.destroy | ||
| end | ||
|
|
||
| it 'raises a StandardError' do | ||
| expect do | ||
| post_create_token | ||
| end.to raise_error(StandardError, /not found/) | ||
| end | ||
| end | ||
| end | ||
| end |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For security purposes, maybe we should still set some expiry for these tokens?
Also, in
config/initializers/doorkeeper.rb, we currently haveaccess_token_expires_in 2.hours. Maybe this token expiry should be extended?