-
-
Notifications
You must be signed in to change notification settings - Fork 168
feat: implement initial root API token management #470
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
Draft
jay7x
wants to merge
5
commits into
voxpupuli:master
Choose a base branch
from
jay7x:manage_token
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
75c74b7
feat: implement initial root API token management
jay7x 96dd08a
fix: some small fixes to be squashed
jay7x 4047c0d
feat: add token rotation script
jay7x 78b9566
chore: rename token renewal script
jay7x 30b1e38
wip: rename parameters
jay7x 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
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,105 @@ | ||
#!/usr/bin/env ruby | ||
|
||
require 'net/http' | ||
require 'json' | ||
require 'time' | ||
require 'uri' | ||
require 'tempfile' | ||
|
||
class GitlabApiTokenRenewer | ||
def initialize | ||
@api_url = ENV.fetch('GITLAB_API_URL', 'http://localhost') | ||
@token_file = ENV.fetch('GITLAB_API_TOKEN_FILE', '/var/opt/gitlab/.tokens/puppet_token') | ||
@token_renew_days = ENV.fetch('GITLAB_API_TOKEN_RENEW_DAYS', '7').to_i | ||
@new_token_ttl_days = ENV.fetch('GITLAB_API_NEW_TOKEN_TTL_DAYS', '30').to_i | ||
@token = File.read(@token_file).strip | ||
|
||
uri = URI(@api_url) | ||
@http = Net::HTTP.new(uri.host, uri.port) | ||
@http.use_ssl = uri.scheme == 'https' | ||
end | ||
|
||
def write_token | ||
f = Tempfile.create('.tkn', File.dirname(@token_file)) | ||
f.write(token) | ||
f.flush | ||
f.close | ||
File.rename(f, @token_file) | ||
end | ||
|
||
def api_request(method, endpoint, body = nil) | ||
request_class = case method.downcase | ||
when :get then Net::HTTP::Get | ||
when :post then Net::HTTP::Post | ||
else raise "Unsupported HTTP method" | ||
end | ||
|
||
request = request_class.new(uri) | ||
request['Authorization'] = "Bearer #{token}" | ||
request['Content-Type'] = 'application/json' if body | ||
request.body = body.to_json if body | ||
|
||
@http.request(request) | ||
end | ||
|
||
def get_current_token_info | ||
response = api_request(:get, 'personal_access_tokens/self') | ||
|
||
case response | ||
when Net::HTTPSuccess | ||
JSON.parse(response.body) | ||
when Net::HTTPUnauthorized | ||
abort "Token is invalid, revoked, or expired." | ||
else | ||
abort "Failed to get token info: #{response.code} #{response.body}" | ||
end | ||
end | ||
|
||
def rotate_current_token(new_expiry = nil) | ||
payload = {} | ||
payload[:expires_at] = new_expiry if new_expiry | ||
|
||
response = api_request(:post, 'personal_access_tokens/self/rotate', payload) | ||
|
||
case response | ||
when Net::HTTPSuccess | ||
@token = JSON.parse(response.body)['token'] | ||
when Net::HTTPUnauthorized | ||
abort "Token cannot be rotated (revoked, expired, or invalid)." | ||
when Net::HTTPForbidden | ||
abort "Token lacks permission to rotate (needs 'api' or 'self_rotate' scope)." | ||
else | ||
abort "Rotation failed: #{response.code} #{response.body}" | ||
end | ||
end | ||
|
||
def run | ||
info = get_current_token_info | ||
expires_at_str = info['expires_at'] | ||
|
||
if expires_at_str.nil? | ||
warn "Token has no expiration." | ||
else | ||
expires_at = Time.parse(expires_at_str).utc | ||
threshold = Time.now.utc + (@token_renew_days * 86400) | ||
if expires_at > threshold | ||
puts "Token expires on #{expires_at}, still valid. No rotation needed." | ||
exit 0 | ||
end | ||
puts "Token expires on #{expires_at}, rotating..." | ||
end | ||
|
||
new_expiry = (Time.now + 30 * 24 * 60 * 60).strftime('%Y-%m-%d') | ||
rotate_current_token(new_expiry) | ||
puts "Token rotated in GitLab." | ||
|
||
write_token | ||
puts "New token written to #{@token_file}." | ||
|
||
puts "Rotation complete." | ||
end | ||
end | ||
|
||
if __FILE__ == $0 | ||
GitlabApiTokenRenewer.new.run | ||
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,49 @@ | ||
# @summary Manages initial root token | ||
# | ||
# **NOTE** This hack allows to use the gitlab instance via API immediately. | ||
# While this way is quite convenient, it cannot be called a good one.. | ||
# Use it at your own risk! | ||
# | ||
# Remove the /etc/gitlab/initial_root_token file to regenerate the token in a | ||
# next Puppet run. | ||
# | ||
# @see https://docs.gitlab.com/administration/operations/rails_console/#using-the-rails-runner | ||
# @see https://docs.gitlab.com/user/profile/personal_access_tokens/#create-a-personal-access-token-programmatically | ||
# | ||
# @api private | ||
class gitlab::initial_root_token { | ||
$api_token_file = $gitlab::api_token_file | ||
$script_path = '/etc/gitlab/create_initial_root_token.rb' | ||
|
||
if $gitlab::create_initial_root_token { | ||
$script_ensure = 'file' | ||
$script_content = epp('gitlab/create_initial_root_token.rb.epp', | ||
token => $gitlab::initial_root_token, | ||
token_ttl_minutes => $gitlab::initial_root_token_ttl_minutes, | ||
token_file_path => $token_file_path, | ||
) | ||
|
||
# Execute after the script is created, but only if token is managed | ||
exec { 'create_initial_root_token': | ||
command => "/usr/bin/gitlab-rails runner '${script_path}'", | ||
creates => $token_file_path, | ||
require => File[$script_path], | ||
} | ||
} else { | ||
$script_ensure = 'absent' | ||
$script_content = undef | ||
|
||
# Ensure there is no token file left if it was created before | ||
file { $token_file_path: | ||
ensure => 'absent', | ||
} | ||
} | ||
|
||
file { $script_path: | ||
ensure => $script_ensure, | ||
owner => 'root', | ||
group => 'git', # gitlab-rails runner executes this script as 'git' user | ||
mode => '0640', | ||
content => $script_content, | ||
} | ||
} |
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,24 @@ | ||
<%-| | ||
Optional[Sensitive[String[1]]] $token, | ||
Integer[0] $token_ttl_minutes, | ||
Stdlib::AbsolutePath $token_file_path, | ||
|-%> | ||
# This script should be executed with 'gitlab-rails runner' command. | ||
# | ||
# This scripts creates an initial root token and stores it to the | ||
# <%= $token_file_path %> file. | ||
token = <%= $token.then |$x| { "'${$x.unwrap}'" }.lest || { nil } %> | ||
token_ttl_minutes = <%= $token_ttl_minutes %> | ||
token_file_path = '<%= $token_file_path %>' | ||
|
||
require 'securerandom' | ||
token_value = token || 'glpat-' + SecureRandom.alphanumeric(20) | ||
|
||
t = User.find(1).personal_access_tokens.create( | ||
scopes: [:api], | ||
name: 'Gitlab Puppet module initial root token', | ||
expires_at: token_ttl_minutes.minutes.from_now, | ||
) | ||
t.set_token(token_value) | ||
t.save! | ||
File.write(token_file_path, token_value, perm: 0600) |
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.
how about a shebang line?
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.
It's executed through the Gitlab Rails Runner, so it shouldn't need one.
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.
I'll add comment there to reduce confusion :)