Project

General

Profile

Feature #43881 » personal-access-tokens-43881.patch

Bogdan Egikov, 2026-08-20 13:58

View differences:

app/controllers/application_controller.rb
end
before_action :api_session, :session_expiration, :user_setup, :check_if_login_required, :set_localization, :check_password_change, :check_twofa_activation
# Wraps the whole filter chain so that denied requests (halted by a
# before_action) are audited too
prepend_around_action :log_api_request
after_action :record_project_usage
rescue_from ::Unauthorized, :with => :deny_access
......
end
if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
if (key = api_key_from_request)
# Use API key
user = User.find_by_api_key(key)
# Personal access token or legacy API key
if (personal_access_token = PersonalAccessToken.find_active(key))
user = user_from_personal_access_token(personal_access_token)
@api_auth_credential = "pat:#{personal_access_token.id}"
elsif (user = User.find_by_api_key(key))
@api_auth_credential = 'api_key'
end
elsif access_token = Doorkeeper.authenticate(request)
# Oauth
if access_token.accessible?
user = User.active.find_by_id(access_token.resource_owner_id)
user.oauth_scope = access_token.scopes.all.map(&:to_sym)
@api_auth_credential = "oauth:#{access_token.id}"
else
doorkeeper_render_error
end
......
return
end
user ||= User.find_by_api_key(username)
if user.nil?
if (personal_access_token = PersonalAccessToken.find_active(username))
user = user_from_personal_access_token(personal_access_token)
@api_auth_credential = "pat:#{personal_access_token.id}"
elsif (user = User.find_by_api_key(username))
@api_auth_credential = 'api_key'
end
end
end
if user && user.must_change_password?
render_error :message => 'You must change your password', :status => 403
......
%w(xml json).include? params[:format]
end
# Writes a structured audit line for requests authenticated with an API
# credential (personal access token, legacy API key or OAuth token).
# The request path is logged without the query string, which may carry
# a plaintext key.
def log_api_request
yield
ensure
# When an exception is in flight the client will receive a 500 from the
# exception-handling middleware, not the status currently on response
write_api_audit_entry($! ? 500 : response.status)
end
def write_api_audit_entry(status)
return unless @api_auth_credential
return unless Setting.api_audit_logging_enabled?
Redmine::ApiAudit.log(
'at' => Time.now.utc.iso8601,
'user_id' => User.current.id,
'user' => User.current.login,
'credential' => @api_auth_credential,
'method' => request.request_method,
'path' => request.path,
'ip' => request.remote_ip,
'status' => status
)
rescue => e
# Audit logging must degrade silently: a full disk or unwritable log
# directory should not turn into API failures (we run inside an ensure,
# so raising here would also mask the original response or exception)
logger&.error("Unable to write API audit entry: #{e.class}: #{e.message}")
end
# Returns the user authenticated by the given personal access token,
# restricted to the token's scopes when it has any (reusing the OAuth
# scope enforcement in User#allowed_to? and User#admin?)
def user_from_personal_access_token(token)
user = token.user
user.oauth_scope = token.scope_list if token.scopes.present?
user
end
# Returns the API key present in the request
def api_key_from_request
if params[:key].present?
app/controllers/personal_access_tokens_controller.rb
# frozen_string_literal: true
# Redmine - project management software
# Copyright (C) 2006- Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class PersonalAccessTokensController < ApplicationController
self.main_menu = false
before_action :require_login
before_action :find_token, :only => :destroy
require_sudo_mode :create, :destroy
def index
@tokens = User.current.personal_access_tokens.order(:id).to_a
# One-time display of a value generated by the create action. Deleted
# from the flash so that render_flash_messages does not repeat it.
@new_token_value = flash[:personal_access_token_value]
flash.delete(:personal_access_token_value)
end
helper_method :default_expiration_days
def new
@token = PersonalAccessToken.new(:expires_on => default_expiration_days.days.from_now.to_date)
end
def create
@token = PersonalAccessToken.new(:user => User.current)
@token.safe_attributes = params[:personal_access_token]
if @token.save
flash[:personal_access_token_value] = @token.plaintext_value
flash[:notice] = l(:notice_personal_access_token_created, :name => @token.name)
redirect_to my_personal_access_tokens_path
else
render :action => 'new'
end
end
def destroy
@token.destroy
flash[:notice] = l(:notice_successful_delete)
redirect_to my_personal_access_tokens_path
end
private
# Default expiration offered by the form, clamped to the admin
# max-lifetime policy so the prefilled date is always valid
def default_expiration_days
max = Setting.personal_access_token_max_lifetime.to_i
max > 0 ? [30, max].min : 30
end
def find_token
@token = User.current.personal_access_tokens.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
end
app/models/personal_access_token.rb
# frozen_string_literal: true
# Redmine - project management software
# Copyright (C) 2006- Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
class PersonalAccessToken < ApplicationRecord
include Redmine::SafeAttributes
belongs_to :user
# Plaintext token values are "rmpat_" followed by 40 hex characters.
# Only the SHA256 digest of the full value is persisted.
TOKEN_PREFIX = 'rmpat_'
# Delay between two updates of last_used_on for the same token
LAST_USED_THROTTLE = 1.hour
validates_presence_of :name, :expires_on
validates_length_of :name, maximum: 255
validates_uniqueness_of :name, scope: :user_id, case_sensitive: true
validate :validate_expires_on
validate :validate_scopes
before_save :include_public_permissions_in_scopes
before_create :generate_value
safe_attributes 'name', 'expires_on', 'scopes'
# The plaintext value, only available on the instance that created it
attr_reader :plaintext_value
# Creates a token for +user+ and returns [record, plaintext value].
# The plaintext value cannot be retrieved afterwards.
def self.generate!(user:, name:, expires_on:, scopes: nil)
token = create!(user: user, name: name, expires_on: expires_on, scopes: scopes)
[token, token.plaintext_value]
end
# Converts legacy plaintext API keys (Token rows with action='api') into
# hashed personal access tokens and deletes the plaintext rows. The keys
# keep authenticating unchanged since lookup is done by digest. Intended
# to be called by the data migration of the release that removes legacy
# API keys (kept unit-tested here until then). Irreversible by design.
def self.import_legacy_api_tokens!(grace_days: nil)
grace_days ||= Setting.personal_access_token_max_lifetime.to_i
grace_days = 365 if grace_days <= 0
Token.where(:action => 'api').find_each do |legacy|
digest = hash_value(legacy.value)
next if exists?(:token_digest => digest)
next unless legacy.user
transaction do
create!(
:user => legacy.user,
:name => available_import_name(legacy.user_id),
:expires_on => grace_days.days.from_now.to_date,
:token_digest => digest
)
legacy.destroy
end
end
end
def self.hash_value(plaintext)
Digest::SHA256.hexdigest(plaintext)
end
# Returns the token matching the given plaintext value, or nil when the
# token is unknown, expired or its user is not active.
#
# Equality lookup on the digest is sufficient here: the digest is computed
# server-side from the presented value, so there is no user-controlled
# stored value that a case-insensitive collation could mis-match (unlike
# Token.find_token, which re-checks with secure_compare for that reason),
# and a timing side channel would only compare two SHA256 digests.
#
# Note: this finder deliberately writes (throttled last_used_on tracking) -
# authenticating a request is the usage being recorded.
def self.find_active(plaintext)
return nil if plaintext.blank?
token = find_by(token_digest: hash_value(plaintext.to_s))
return nil unless token
return nil if token.expired?
return nil unless token.user&.active?
token.touch_last_used_on
token
end
# Returns the active user owning the given plaintext token value
def self.find_active_user(plaintext)
find_active(plaintext)&.user
end
# Permission names a token may be restricted to, mirroring the scopes
# accepted for OAuth applications (all permissions plus 'admin')
def self.valid_scope_names
Redmine::AccessControl.permissions.map {|p| p.name.to_s} + ['admin']
end
# Accepts an array of scope names (as submitted by the form checkboxes)
# and stores them as a space-separated string, like OAuth scopes
def scopes=(value)
value = value.reject(&:blank?).join(' ') if value.is_a?(Array)
super
end
# Returns the scopes as an array of symbols, empty when unrestricted
def scope_list
scopes.to_s.split.map(&:to_sym)
end
def expired?
expires_on < Date.today
end
def touch_last_used_on
if last_used_on.nil? || last_used_on < LAST_USED_THROTTLE.ago
update_column(:last_used_on, Time.now)
end
end
def self.available_import_name(user_id)
name = 'Migrated legacy API key'
i = 1
while exists?(:user_id => user_id, :name => name)
i += 1
name = "Migrated legacy API key #{i}"
end
name
end
private_class_method :available_import_name
private
def generate_value
return if token_digest.present?
@plaintext_value = TOKEN_PREFIX + Redmine::Utils.random_hex(20)
self.token_digest = self.class.hash_value(@plaintext_value)
end
def validate_scopes
return if scopes.blank?
unknown = scope_list.map(&:to_s) - self.class.valid_scope_names
errors.add(:scopes, :invalid) if unknown.any?
end
# A restricted token must still allow what is public to everyone,
# mirroring Oauth2ApplicationsController#application_params
def include_public_permissions_in_scopes
if scopes.present?
public_names = Redmine::AccessControl.public_permissions.map {|p| p.name.to_s}
self.scopes = (scope_list.map(&:to_s) | public_names).join(' ')
end
end
def validate_expires_on
return if expires_on.blank?
max_lifetime = Setting.personal_access_token_max_lifetime.to_i
if expires_on < Date.today ||
(max_lifetime > 0 && expires_on > max_lifetime.days.from_now.to_date)
errors.add(:expires_on, :invalid)
end
end
end
app/models/user.rb
has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
has_one :atom_token, lambda {where "#{table.name}.action='feeds'"}, :class_name => 'Token'
has_one :api_token, lambda {where "#{table.name}.action='api'"}, :class_name => 'Token'
has_many :personal_access_tokens, :dependent => :delete_all
has_many :email_addresses, :dependent => :delete_all
has_many :reactions, dependent: :delete_all
has_many :webhooks, dependent: :destroy
app/views/my/_sidebar.html.erb
</p>
<% if Setting.rest_api_enabled? %>
<h4><%= l(:label_api_access_key) %></h4>
<h4><%= l(:label_personal_access_token_plural) %></h4>
<p><%= link_to l(:label_personal_access_token_plural), my_personal_access_tokens_path %></p>
<h4><%= l(:label_api_access_key) %> <%= l(:label_legacy) %></h4>
<div data-controller="api-key-copy">
<div class="api-key-actions">
<%= link_to l(:button_show), my_api_key_path, :remote => true %>
app/views/my/account.html.erb
<%= additional_emails_link(@user) %>
<%= link_to(sprite_icon('key', l(:button_change_password)), { :action => 'password'}, :class => 'icon icon-passwd') if @user.change_password_allowed? %>
<%= link_to sprite_icon('webhook', l(:label_webhook_plural)), webhooks_path, class: 'icon icon-webhook' if Webhook.enabled? && @user.allowed_to?(:use_webhooks, nil, global: true) %>
<%= link_to(sprite_icon('key', l(:label_personal_access_token_plural)), my_personal_access_tokens_path, :class => 'icon icon-passwd') if Setting.rest_api_enabled? %>
<%= link_to(sprite_icon('apps', l('label_oauth_authorized_application_plural')), oauth_authorized_applications_path, :class => 'icon icon-applications') if Setting.rest_api_enabled? %>
<%= call_hook(:view_my_account_contextual, :user => @user)%>
</div>
app/views/personal_access_tokens/index.html.erb
<div class="contextual">
<%= link_to sprite_icon('add', l(:label_personal_access_token_new)), new_my_personal_access_token_path, :class => 'icon icon-add' %>
</div>
<%= title [l(:label_my_account), my_account_path], l(:label_personal_access_token_plural) %>
<p><%= l(:text_personal_access_tokens_info) %></p>
<% if @new_token_value %>
<div class="box">
<p><strong><%= l(:text_personal_access_token_show_once) %></strong></p>
<pre class="personal-access-token-value"><%= @new_token_value %></pre>
</div>
<% end %>
<% if @tokens.any? %>
<div class="autoscroll">
<table class="list">
<thead>
<tr>
<th class="name"><%= l(:field_name) %></th>
<th><%= l(:field_created_on) %></th>
<th><%= l(:field_expires_on) %></th>
<th><%= l(:field_scopes) %></th>
<th><%= l(:label_last_used) %></th>
<th></th>
</tr>
</thead>
<tbody>
<% @tokens.each do |token| %>
<tr id="personal-access-token-<%= token.id %>" class="<%= cycle('odd', 'even') %>">
<td class="name"><%= token.name %></td>
<td><%= format_date(token.created_at) %></td>
<td>
<%= format_date(token.expires_on) %>
<% if token.expired? %>(<%= l(:label_token_expired) %>)<% end %>
</td>
<td class="scopes">
<% if token.scopes.present? %>
<span title="<%= token.scope_list.join(', ') %>"><%= token.scope_list.size %></span>
<% else %>
<%= l(:label_scopes_full_access) %>
<% end %>
</td>
<td><%= token.last_used_on ? time_tag(token.last_used_on) : l(:label_never_used) %></td>
<td class="buttons">
<%= delete_link my_personal_access_token_path(token), {}, l(token.expired? ? :button_delete : :button_revoke) %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
<% else %>
<p class="nodata"><%= l(:label_no_data) %></p>
<% end %>
<% content_for :sidebar do %>
<% @user = User.current %>
<%= render :partial => 'my/sidebar' %>
<% end %>
app/views/personal_access_tokens/new.html.erb
<%= title [l(:label_my_account), my_account_path],
[l(:label_personal_access_token_plural), my_personal_access_tokens_path],
l(:label_personal_access_token_new) %>
<%= labelled_form_for @token, :url => my_personal_access_tokens_path do |f| %>
<%= error_messages_for @token %>
<div class="box tabular">
<p>
<%= f.text_field :name, :required => true, :size => 40 %>
<em class="info"><%= l(:text_personal_access_token_name_info) %></em>
</p>
<p>
<%= f.date_field :expires_on, :required => true %>
<em class="info">
<%= l(:text_personal_access_token_expiration_info, :days => default_expiration_days) %>
<% if Setting.personal_access_token_max_lifetime.to_i > 0 %>
<%= l(:text_personal_access_token_max_lifetime_info, :max => Setting.personal_access_token_max_lifetime.to_i) %>
<% end %>
</em>
</p>
</div>
<h3><%= l(:field_scopes) %></h3>
<p><em class="info"><%= l(:text_personal_access_token_scopes_info) %></em></p>
<div class="box tabular" id="scopes">
<fieldset><legend><%= l(:label_administration) %></legend>
<label class="floating" style="width: auto;">
<%= check_box_tag 'personal_access_token[scopes][]', 'admin', @token.scope_list.include?(:admin),
:id => 'personal_access_token_scopes_admin' %>
<%= l(:text_personal_access_token_admin_scope) %>
</label>
</fieldset>
<% perms_by_module = Redmine::AccessControl.permissions.group_by {|p| p.project_module.to_s} %>
<% perms_by_module.keys.sort.each do |mod| %>
<fieldset><legend><%= mod.blank? ? l(:label_project) : l_or_humanize(mod, :prefix => 'project_module_') %></legend>
<% perms_by_module[mod].each do |permission| %>
<label class="floating">
<%= check_box_tag 'personal_access_token[scopes][]', permission.name.to_s,
(permission.public? || @token.scope_list.include?(permission.name)),
:id => "personal_access_token_scopes_#{permission.name}",
:disabled => permission.public? %>
<%= l_or_humanize(permission.name, :prefix => 'permission_') %>
</label>
<% end %>
</fieldset>
<% end %>
<br /><%= check_all_links 'scopes' %>
<%= hidden_field_tag 'personal_access_token[scopes][]', '' %>
</div>
<%= submit_tag l(:button_create) %>
<%= link_to l(:button_cancel), my_personal_access_tokens_path %>
<% end %>
<% content_for :sidebar do %>
<% @user = User.current %>
<%= render :partial => 'my/sidebar' %>
<% end %>
app/views/settings/_api.html.erb
<p><%= setting_check_box :jsonp_enabled %></p>
<p><%= setting_check_box :webhooks_enabled %></p>
<p><%= setting_text_field :personal_access_token_max_lifetime, :size => 6 %>
<em class="info"><%= l(:text_personal_access_token_max_lifetime_setting_info) %></em></p>
<p><%= setting_check_box :api_audit_logging_enabled %>
<em class="info"><%= l(:text_api_audit_logging_info) %></em></p>
</div>
<%= submit_tag l(:button_save) %>
config/application.rb
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password, :salt, :twofa_totp_key]
# The exact-match regexp filters the API key passed as ?key=... without
# over-filtering unrelated parameters such as "keywords".
config.filter_parameters += [:password, :salt, :twofa_totp_key, /\Akey\z/]
config.action_mailer.perform_deliveries = false
config/locales/en.yml
reaction_text_x_other_users:
one: "1 other"
other: "%{count} others"
label_personal_access_token: Personal access token
label_personal_access_token_plural: Personal access tokens
label_personal_access_token_new: New token
field_expires_on: Expires
label_last_used: Last used
label_token_expired: expired
label_legacy: (legacy)
button_revoke: Revoke
notice_personal_access_token_created: "Personal access token %{name} was created."
text_personal_access_token_show_once: "Copy your new token now. For security reasons it is stored hashed and cannot be displayed again."
text_personal_access_tokens_info: "Personal access tokens can be used instead of your API access key to authenticate against the REST API. Each token has its own expiration date and can be revoked individually. The token value is only displayed once, at creation."
text_personal_access_token_name_info: "A short label so you can recognize this token later, e.g. \"CI pipeline\"."
text_personal_access_token_expiration_info: "Defaults to %{days} days."
text_personal_access_token_max_lifetime_info: "Maximum lifetime allowed by the administrator: %{max} days."
setting_personal_access_token_max_lifetime: Maximum lifetime of personal access tokens (days)
text_personal_access_token_max_lifetime_setting_info: "Upper bound for the expiration date of newly created personal access tokens, in days. 0 means no limit. Existing tokens are not affected."
field_scopes: Scopes
label_scopes_full_access: Full access
text_personal_access_token_scopes_info: "Optionally restrict this token to selected permissions. Leaving all boxes unchecked grants the token the full permissions of your account."
text_personal_access_token_admin_scope: Grants administrator permissions
setting_api_audit_logging_enabled: Enable API audit logging
text_api_audit_logging_info: "Writes one structured line per authenticated API request to log/api_audit.log (timestamp, user, credential, method, path, IP, response status)."
config/routes.rb
get 'my/api_key', :to => 'my#show_api_key', :as => 'my_api_key'
post 'my/api_key', :to => 'my#reset_api_key'
post 'my/atom_key', :to => 'my#reset_atom_key', :as => 'my_atom_key'
get 'my/personal_access_tokens', :to => 'personal_access_tokens#index', :as => 'my_personal_access_tokens'
get 'my/personal_access_tokens/new', :to => 'personal_access_tokens#new', :as => 'new_my_personal_access_token'
post 'my/personal_access_tokens', :to => 'personal_access_tokens#create'
delete 'my/personal_access_tokens/:id', :to => 'personal_access_tokens#destroy', :as => 'my_personal_access_token'
match 'my/password', :controller => 'my', :action => 'password', :via => [:get, :post]
match 'my/add_block', :controller => 'my', :action => 'add_block', :via => :post
match 'my/remove_block', :controller => 'my', :action => 'remove_block', :via => :post
config/settings.yml
default: 0
reactions_enabled:
default: 1
personal_access_token_max_lifetime:
format: int
default: 0
security_notifications: 1
api_audit_logging_enabled:
default: 0
security_notifications: 1
db/migrate/20260820120000_create_personal_access_tokens.rb
class CreatePersonalAccessTokens < ActiveRecord::Migration[8.1]
def change
create_table :personal_access_tokens do |t|
t.references :user, null: false
t.string :name, limit: 255, null: false
t.string :token_digest, limit: 64, null: false
t.date :expires_on, null: false
t.datetime :last_used_on
t.text :scopes
t.timestamps null: false
end
add_index :personal_access_tokens, :token_digest, unique: true
add_index :personal_access_tokens, [:user_id, :name], unique: true
end
end
lib/redmine/api_audit.rb
# frozen_string_literal: true
# Redmine - project management software
# Copyright (C) 2006- Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
module Redmine
# Structured audit log of authenticated REST API requests, one JSON
# line per request, written to log/api_audit.log by default
module ApiAudit
mattr_accessor :logger
def self.log(payload)
self.logger ||= default_logger
logger.info(payload.to_json)
end
def self.default_logger
logger = Logger.new(Rails.root.join('log', 'api_audit.log'), 'weekly')
logger.formatter = proc {|_severity, _time, _progname, msg| "#{msg}\n"}
logger
end
end
end
test/fixtures/personal_access_tokens.yml
---
personal_access_tokens_001:
id: 1
user_id: 2
name: CI pipeline
token_digest: <%= Digest::SHA256.hexdigest("rmpat_1234567890abcdef1234567890abcdef12345678") %>
expires_on: 2050-01-01
last_used_on:
created_at: 2026-08-01 10:00:00
updated_at: 2026-08-01 10:00:00
personal_access_tokens_002:
id: 2
user_id: 2
name: Expired token
token_digest: <%= Digest::SHA256.hexdigest("rmpat_expired67890abcdef1234567890abcdef123456") %>
expires_on: 2020-01-01
last_used_on: 2019-12-01 10:00:00
created_at: 2019-01-01 10:00:00
updated_at: 2019-01-01 10:00:00
personal_access_tokens_003:
id: 3
user_id: 5
name: Locked user token
token_digest: <%= Digest::SHA256.hexdigest("rmpat_locked7890abcdef1234567890abcdef12345678") %>
expires_on: 2050-01-01
last_used_on:
created_at: 2026-08-01 10:00:00
updated_at: 2026-08-01 10:00:00
test/functional/my_controller_test.rb
assert_select 'pre', User.find(2).api_key
end
def test_account_should_link_to_personal_access_tokens_when_rest_api_is_enabled
with_settings :rest_api_enabled => '1' do
get :account
assert_response :success
assert_select 'a[href="/my/personal_access_tokens"]', :minimum => 1
end
end
def test_account_should_not_link_to_personal_access_tokens_when_rest_api_is_disabled
with_settings :rest_api_enabled => '0' do
get :account
assert_response :success
assert_select 'a[href="/my/personal_access_tokens"]', :count => 0
end
end
def test_reset_api_key_with_existing_key
@previous_token_value = User.find(2).api_key # Will generate one if it's missing
post :reset_api_key
test/functional/personal_access_tokens_controller_test.rb
# frozen_string_literal: true
# Redmine - project management software
# Copyright (C) 2006- Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require_relative '../test_helper'
class PersonalAccessTokensControllerTest < Redmine::ControllerTest
def setup
@request.session[:user_id] = 2
end
def test_index_should_list_only_own_tokens
get :index
assert_response :success
assert_select 'table.list tbody' do
assert_select 'tr', 2
assert_select 'td', :text => 'CI pipeline'
assert_select 'td', :text => 'Locked user token', :count => 0
end
end
def test_index_should_require_login
@request.session[:user_id] = nil
get :index
assert_response :redirect
end
def test_new_should_display_the_form
get :new
assert_response :success
assert_select 'input[name=?]', 'personal_access_token[name]'
assert_select 'input[name=?]', 'personal_access_token[expires_on]'
end
def test_new_should_display_scope_checkboxes
get :new
assert_response :success
assert_select 'input[type=checkbox][name=?]', 'personal_access_token[scopes][]', :minimum => 10
assert_select 'input[type=checkbox][name=?][value=admin]', 'personal_access_token[scopes][]'
end
def test_index_should_show_a_scopes_summary
PersonalAccessToken.find(1).update_column(:scopes, 'view_issues add_issues')
get :index
assert_response :success
assert_select 'tr#personal-access-token-1 td.scopes', :text => '2'
assert_select 'tr#personal-access-token-2 td.scopes', :text => 'Full access'
end
def test_create_with_scopes_should_store_them
post :create, :params => {
:personal_access_token => {
:name => 'Scoped token',
:expires_on => 30.days.from_now.to_date.to_s,
:scopes => ['', 'view_issues']
}
}
assert_redirected_to '/my/personal_access_tokens'
assert_includes PersonalAccessToken.order(:id => :desc).first.scope_list, :view_issues
end
def test_new_should_clamp_the_default_expiration_to_the_max_lifetime
with_settings :personal_access_token_max_lifetime => '7' do
get :new
assert_response :success
assert_select 'input[name=?][value=?]', 'personal_access_token[expires_on]',
7.days.from_now.to_date.to_s
end
end
def test_create_should_add_a_token_and_show_its_value_once
assert_difference 'PersonalAccessToken.count', 1 do
post :create, :params => {
:personal_access_token => {
:name => 'Deploy script',
:expires_on => 30.days.from_now.to_date.to_s
}
}
end
assert_redirected_to '/my/personal_access_tokens'
token = PersonalAccessToken.order(:id => :desc).first
assert_equal users(:users_002), token.user
follow_redirect_and_assert_token_displayed
end
def test_create_with_invalid_params_should_redisplay_the_form
assert_no_difference 'PersonalAccessToken.count' do
post :create, :params => {
:personal_access_token => {:name => '', :expires_on => 30.days.from_now.to_date.to_s}
}
end
assert_response :success
assert_select_error /Name/
end
def test_destroy_should_remove_own_token
assert_difference 'PersonalAccessToken.count', -1 do
delete :destroy, :params => {:id => 1}
end
assert_redirected_to '/my/personal_access_tokens'
end
def test_destroy_should_not_remove_another_users_token
assert_no_difference 'PersonalAccessToken.count' do
delete :destroy, :params => {:id => 3}
end
assert_response :not_found
end
private
def follow_redirect_and_assert_token_displayed
# The plaintext value is passed through the flash and displayed once
get :index
assert_response :success
assert_select 'pre.personal-access-token-value', :text => /\Armpat_[0-9a-f]{40}\z/
# A second render must not display it again
get :index
assert_select 'pre.personal-access-token-value', :count => 0
end
end
test/functional/settings_controller_test.rb
assert_equal 'Test footer', Setting.emails_footer
end
def test_edit_integrations_tab_should_include_personal_access_token_max_lifetime
get :edit, :params => {:tab => 'integrations'}
assert_response :success
assert_select 'input[name=?]', 'settings[personal_access_token_max_lifetime]'
assert_select 'input[name=?]', 'settings[api_audit_logging_enabled]'
end
def test_edit_commit_update_keywords
with_settings :commit_update_keywords => [
{"keywords" => "fixes, resolves", "status_id" => "3"},
test/integration/api_test/api_audit_test.rb
# frozen_string_literal: true
# Redmine - project management software
# Copyright (C) 2006- Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require_relative '../../test_helper'
class Redmine::ApiTest::ApiAuditTest < Redmine::ApiTest::Base
VALID_PLAINTEXT = "rmpat_1234567890abcdef1234567890abcdef12345678"
def setup
super
@io = StringIO.new
@previous_logger = Redmine::ApiAudit.logger
Redmine::ApiAudit.logger = Logger.new(@io)
Redmine::ApiAudit.logger.formatter = proc {|_severity, _time, _progname, msg| "#{msg}\n"}
end
def teardown
super
Redmine::ApiAudit.logger = @previous_logger
end
test "should log a personal access token request when enabled" do
with_settings :api_audit_logging_enabled => '1' do
get '/users/current.json', :headers => {'X-Redmine-API-Key' => VALID_PLAINTEXT}
end
assert_response :success
entry = last_entry
assert_equal 'pat:1', entry['credential']
assert_equal 2, entry['user_id']
assert_equal 'jsmith', entry['user']
assert_equal 'GET', entry['method']
assert_equal '/users/current.json', entry['path']
assert_equal 200, entry['status']
assert entry['at'].present?
assert entry['ip'].present?
end
test "should log a legacy api key request when enabled" do
token = Token.create!(:user => users(:users_002), :action => 'api')
with_settings :api_audit_logging_enabled => '1' do
get '/users/current.json', :headers => {'X-Redmine-API-Key' => token.value}
end
assert_response :success
assert_equal 'api_key', last_entry['credential']
end
test "should log denied requests" do
_token, plaintext = PersonalAccessToken.generate!(
user: User.find(1), name: 'Scoped audit token',
expires_on: 30.days.from_now.to_date, scopes: 'view_issues'
)
with_settings :api_audit_logging_enabled => '1' do
get '/users.json', :headers => {'X-Redmine-API-Key' => plaintext}
end
assert_response :forbidden
assert_equal 403, last_entry['status']
end
test "should not log anything when disabled" do
with_settings :api_audit_logging_enabled => '0' do
get '/users/current.json', :headers => {'X-Redmine-API-Key' => VALID_PLAINTEXT}
end
assert_response :success
assert_equal '', @io.string
end
test "should log status 500 when the action raises" do
UsersController.any_instance.stubs(:show).raises(StandardError.new('boom'))
with_settings :api_audit_logging_enabled => '1' do
get '/users/current.json', :headers => {'X-Redmine-API-Key' => VALID_PLAINTEXT}
end
assert_response :internal_server_error
assert_equal 500, last_entry['status']
end
test "an audit logging failure should not break the API response" do
Redmine::ApiAudit.stubs(:log).raises(Errno::ENOSPC.new('disk full'))
with_settings :api_audit_logging_enabled => '1' do
get '/users/current.json', :headers => {'X-Redmine-API-Key' => VALID_PLAINTEXT}
end
assert_response :success
end
test "should never log the token value" do
with_settings :api_audit_logging_enabled => '1' do
get "/users/current.json?key=#{VALID_PLAINTEXT}"
end
assert_response :success
assert_not_includes @io.string, VALID_PLAINTEXT
assert_equal '/users/current.json', last_entry['path']
end
private
def last_entry
ActiveSupport::JSON.decode(@io.string.lines.last)
end
end
test/integration/api_test/personal_access_token_test.rb
# frozen_string_literal: true
# Redmine - project management software
# Copyright (C) 2006- Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require_relative '../../test_helper'
class Redmine::ApiTest::PersonalAccessTokenTest < Redmine::ApiTest::Base
VALID_PLAINTEXT = "rmpat_1234567890abcdef1234567890abcdef12345678"
EXPIRED_PLAINTEXT = "rmpat_expired67890abcdef1234567890abcdef123456"
test "should authenticate with a personal access token in the X-Redmine-API-Key header" do
get '/users/current.json', :headers => {'X-Redmine-API-Key' => VALID_PLAINTEXT}
assert_response :success
assert_equal users(:users_002).login, ActiveSupport::JSON.decode(response.body)['user']['login']
end
test "should authenticate with a personal access token as the key parameter" do
get "/users/current.json?key=#{VALID_PLAINTEXT}"
assert_response :success
assert_equal users(:users_002).login, ActiveSupport::JSON.decode(response.body)['user']['login']
end
test "should authenticate with a personal access token as HTTP Basic username" do
get '/users/current.json', :headers => credentials(VALID_PLAINTEXT, 'X')
assert_response :success
assert_equal users(:users_002).login, ActiveSupport::JSON.decode(response.body)['user']['login']
end
test "should deny an expired personal access token" do
get '/users/current.json', :headers => {'X-Redmine-API-Key' => EXPIRED_PLAINTEXT}
assert_response :unauthorized
end
test "should deny a revoked personal access token" do
PersonalAccessToken.find(1).destroy
get '/users/current.json', :headers => {'X-Redmine-API-Key' => VALID_PLAINTEXT}
assert_response :unauthorized
end
test "should still authenticate with a legacy api key" do
user = users(:users_002)
token = Token.create!(:user => user, :action => 'api')
get '/users/current.json', :headers => {'X-Redmine-API-Key' => token.value}
assert_response :success
assert_equal user.login, ActiveSupport::JSON.decode(response.body)['user']['login']
end
test "scoped token of an admin should not grant admin-only endpoints" do
_token, plaintext = PersonalAccessToken.generate!(
user: User.find(1), name: 'Scoped admin token',
expires_on: 30.days.from_now.to_date, scopes: 'view_issues'
)
get '/users.json', :headers => {'X-Redmine-API-Key' => plaintext}
assert_response :forbidden
end
test "unscoped token of an admin should grant admin-only endpoints" do
_token, plaintext = PersonalAccessToken.generate!(
user: User.find(1), name: 'Unscoped admin token',
expires_on: 30.days.from_now.to_date
)
get '/users.json', :headers => {'X-Redmine-API-Key' => plaintext}
assert_response :success
end
test "scoped token should grant endpoints covered by its scopes" do
_token, plaintext = PersonalAccessToken.generate!(
user: users(:users_002), name: 'Issues token',
expires_on: 30.days.from_now.to_date, scopes: 'view_issues'
)
get '/issues.json', :headers => {'X-Redmine-API-Key' => plaintext}
assert_response :success
end
test "scoped token should deny endpoints outside its scopes" do
_token, plaintext = PersonalAccessToken.generate!(
user: users(:users_002), name: 'Issues only token',
expires_on: 30.days.from_now.to_date, scopes: 'view_issues'
)
get '/time_entries.json', :headers => {'X-Redmine-API-Key' => plaintext}
assert_response :forbidden
end
# Known limitation inherited from the OAuth scope mechanism (upstream
# defect https://www.redmine.org/issues/44271): Issue#attributes_editable?
# authorizes through the private Issue#user_tracker_permission?, which
# selects roles directly and never calls User#allowed_to?, so the scope
# intersection is bypassed for issue attribute mutations. A token scoped
# to view_issues + add_issue_notes (a typical comment-bot token) can
# therefore still edit issue attributes when the user's role allows it,
# because add_issue_notes maps to issues#update and passes the controller
# authorize. This test pins the current behavior and will start failing
# once #44271 is fixed upstream - update it then.
test "KNOWN LIMITATION (#44271): add_issue_notes scope does not prevent issue attribute edits" do
_token, plaintext = PersonalAccessToken.generate!(
user: users(:users_002), name: 'Notes-only token',
expires_on: 30.days.from_now.to_date, scopes: 'view_issues add_issue_notes'
)
put '/issues/1.json',
:params => {:issue => {:subject => 'Changed through a notes-only token'}},
:headers => {'X-Redmine-API-Key' => plaintext}
assert_response :no_content
assert_equal 'Changed through a notes-only token', Issue.find(1).subject
end
test "should deny personal access tokens when the REST API is disabled" do
with_settings :rest_api_enabled => '0', :login_required => '1' do
get '/users/current.json', :headers => {'X-Redmine-API-Key' => VALID_PLAINTEXT}
assert_response :forbidden
end
end
end
test/unit/lib/parameter_filtering_test.rb
# frozen_string_literal: true
# Redmine - project management software
# Copyright (C) 2006- Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require_relative '../../test_helper'
class ParameterFilteringTest < ActiveSupport::TestCase
def filter(params)
ActiveSupport::ParameterFilter.new(Rails.application.config.filter_parameters).filter(params)
end
test "the key parameter should be filtered from logs" do
filtered = filter('key' => 'rmpat_1234567890abcdef1234567890abcdef12345678')
assert_equal '[FILTERED]', filtered['key']
end
test "passwords should be filtered from logs" do
assert_equal '[FILTERED]', filter('password' => 'secret')['password']
assert_equal '[FILTERED]', filter('sudo_password' => 'secret')['sudo_password']
end
test "parameters merely containing key should not be over-filtered" do
assert_equal 'fixes', filter('keywords' => 'fixes')['keywords']
end
end
test/unit/personal_access_token_test.rb
# frozen_string_literal: true
# Redmine - project management software
# Copyright (C) 2006- Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require_relative '../test_helper'
class PersonalAccessTokenTest < ActiveSupport::TestCase
VALID_PLAINTEXT = "rmpat_1234567890abcdef1234567890abcdef12345678"
EXPIRED_PLAINTEXT = "rmpat_expired67890abcdef1234567890abcdef123456"
LOCKED_USER_PLAINTEXT = "rmpat_locked7890abcdef1234567890abcdef12345678"
test "generate! should return the record and a prefixed plaintext value" do
token, plaintext = PersonalAccessToken.generate!(
user: users(:users_002), name: 'Deploy script', expires_on: 30.days.from_now.to_date
)
assert token.persisted?
assert plaintext.start_with?('rmpat_')
assert_equal 46, plaintext.length
end
test "generate! should store only the SHA256 digest of the value" do
token, plaintext = PersonalAccessToken.generate!(
user: users(:users_002), name: 'Deploy script', expires_on: 30.days.from_now.to_date
)
assert_equal Digest::SHA256.hexdigest(plaintext), token.token_digest
assert_not token.attributes.value?(plaintext)
end
test "should require a name" do
token = PersonalAccessToken.new(
user: users(:users_002), name: '', expires_on: 30.days.from_now.to_date
)
assert_not token.valid?
assert token.errors[:name].present?
end
test "should require a unique name per user" do
duplicate = PersonalAccessToken.new(
user: users(:users_002), name: 'CI pipeline', expires_on: 30.days.from_now.to_date
)
assert_not duplicate.valid?
assert duplicate.errors[:name].present?
other_user = PersonalAccessToken.new(
user: users(:users_003), name: 'CI pipeline', expires_on: 30.days.from_now.to_date
)
assert other_user.valid?
end
test "should require an expiration date" do
token = PersonalAccessToken.new(user: users(:users_002), name: 'No expiry')
assert_not token.valid?
assert token.errors[:expires_on].present?
end
test "should reject an expiration date in the past" do
token = PersonalAccessToken.new(
user: users(:users_002), name: 'Past expiry', expires_on: Date.yesterday
)
assert_not token.valid?
assert token.errors[:expires_on].present?
end
test "should enforce the admin max lifetime setting" do
with_settings :personal_access_token_max_lifetime => '30' do
too_far = PersonalAccessToken.new(
user: users(:users_002), name: 'Too far', expires_on: 31.days.from_now.to_date
)
assert_not too_far.valid?
assert too_far.errors[:expires_on].present?
at_limit = PersonalAccessToken.new(
user: users(:users_002), name: 'At limit', expires_on: 30.days.from_now.to_date
)
assert at_limit.valid?
end
end
test "max lifetime setting should only accept integers" do
setting = Setting.new(:name => 'personal_access_token_max_lifetime', :value => 'abc')
assert_not setting.valid?
setting.value = '30'
assert setting.valid?
end
test "should not limit lifetime when the setting is zero" do
with_settings :personal_access_token_max_lifetime => '0' do
token = PersonalAccessToken.new(
user: users(:users_002), name: 'Far future', expires_on: 10.years.from_now.to_date
)
assert token.valid?
end
end
test "expired? should be true only after the expiration date" do
assert personal_access_tokens(:personal_access_tokens_002).expired?
assert_not personal_access_tokens(:personal_access_tokens_001).expired?
end
test "find_active_user should return the owner for a valid token" do
assert_equal users(:users_002), PersonalAccessToken.find_active_user(VALID_PLAINTEXT)
end
test "find_active_user should return nil for an expired token" do
assert_nil PersonalAccessToken.find_active_user(EXPIRED_PLAINTEXT)
end
test "find_active_user should return nil for a locked user" do
assert_nil PersonalAccessToken.find_active_user(LOCKED_USER_PLAINTEXT)
end
test "find_active_user should return nil for unknown or blank keys" do
assert_nil PersonalAccessToken.find_active_user('rmpat_unknown')
assert_nil PersonalAccessToken.find_active_user('')
assert_nil PersonalAccessToken.find_active_user(nil)
end
test "find_active_user should record last_used_on" do
token = personal_access_tokens(:personal_access_tokens_001)
assert_nil token.last_used_on
PersonalAccessToken.find_active_user(VALID_PLAINTEXT)
assert_not_nil token.reload.last_used_on
end
test "scope_list should return scopes as symbols" do
token = PersonalAccessToken.new(:scopes => 'view_issues add_issues')
assert_equal [:view_issues, :add_issues], token.scope_list
assert_equal [], PersonalAccessToken.new(:scopes => nil).scope_list
end
test "scopes should accept an array and normalize it" do
token = PersonalAccessToken.new(:scopes => ['', 'view_issues', 'admin'])
assert_equal 'view_issues admin', token.scopes
end
test "should reject unknown scope names" do
token = PersonalAccessToken.new(
:user => users(:users_002), :name => 'Bad scope',
:expires_on => 30.days.from_now.to_date, :scopes => 'view_issues not_a_permission'
)
assert_not token.valid?
assert token.errors[:scopes].present?
end
test "blank scopes should be valid and mean full access" do
token = PersonalAccessToken.new(
:user => users(:users_002), :name => 'Full access',
:expires_on => 30.days.from_now.to_date, :scopes => ''
)
assert token.valid?
assert_equal [], token.scope_list
end
test "saving a scoped token should force-include public permissions" do
token = PersonalAccessToken.create!(
:user => users(:users_002), :name => 'Scoped',
:expires_on => 30.days.from_now.to_date, :scopes => 'view_issues'
)
Redmine::AccessControl.public_permissions.map(&:name).each do |public_permission|
assert_includes token.scope_list, public_permission
end
assert_includes token.scope_list, :view_issues
end
test "find_active should return the token for a valid value" do
assert_equal personal_access_tokens(:personal_access_tokens_001),
PersonalAccessToken.find_active(VALID_PLAINTEXT)
assert_nil PersonalAccessToken.find_active(EXPIRED_PLAINTEXT)
assert_nil PersonalAccessToken.find_active(LOCKED_USER_PLAINTEXT)
end
test "import_legacy_api_tokens! should convert legacy api keys to hashed tokens" do
user = users(:users_003)
legacy = Token.create!(:user => user, :action => 'api')
legacy_value = legacy.value
assert_difference 'PersonalAccessToken.count', 1 do
assert_difference 'Token.where(:action => "api").count', -1 do
PersonalAccessToken.import_legacy_api_tokens!
end
end
imported = PersonalAccessToken.order(:id => :desc).first
assert_equal user, imported.user
assert_equal Digest::SHA256.hexdigest(legacy_value), imported.token_digest
assert_equal 365.days.from_now.to_date, imported.expires_on
# The same key keeps authenticating after the import
assert_equal user, PersonalAccessToken.find_active_user(legacy_value)
end
test "import_legacy_api_tokens! should be idempotent" do
Token.create!(:user => users(:users_003), :action => 'api')
PersonalAccessToken.import_legacy_api_tokens!
assert_no_difference 'PersonalAccessToken.count' do
PersonalAccessToken.import_legacy_api_tokens!
end
end
test "import_legacy_api_tokens! should honor the max lifetime setting" do
Token.create!(:user => users(:users_003), :action => 'api')
with_settings :personal_access_token_max_lifetime => '30' do
PersonalAccessToken.import_legacy_api_tokens!
end
assert_equal 30.days.from_now.to_date, PersonalAccessToken.order(:id => :desc).first.expires_on
end
test "find_active_user should throttle last_used_on updates" do
token = personal_access_tokens(:personal_access_tokens_001)
recent = 5.minutes.ago
token.update_column(:last_used_on, recent)
PersonalAccessToken.find_active_user(VALID_PLAINTEXT)
assert_equal recent.to_i, token.reload.last_used_on.to_i
stale = 2.hours.ago
token.update_column(:last_used_on, stale)
PersonalAccessToken.find_active_user(VALID_PLAINTEXT)
assert_operator token.reload.last_used_on, :>, 1.minute.ago
end
end
(3-3/3)