Skip to content
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

Implement external identities #296

Merged
merged 26 commits into from
Oct 5, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
ae446bf
add new dependencies
Knerio Sep 3, 2024
f3f3b44
initialize the external identites register service
Knerio Sep 3, 2024
35cdd3c
Merge branch 'refs/heads/main' into 266-implement-external-identities
Knerio Sep 3, 2024
2609640
add spec for the base service
Knerio Sep 3, 2024
7ce29f0
fix gemfile
Knerio Sep 3, 2024
9dd78b3
switch method to stub application settings
Knerio Sep 4, 2024
96a87fd
return user session instead of user in the identity register service
Knerio Sep 4, 2024
0f2472c
implement user identity register service
Knerio Sep 4, 2024
7b2aec9
implement link service
Knerio Sep 4, 2024
d9149c7
implement link service
Knerio Sep 4, 2024
4605387
add login/register mutation to the allowed anonymous mutations
Knerio Sep 5, 2024
7931d67
implement external identities
Knerio Sep 7, 2024
c246fc7
migrate structure.sql
Knerio Sep 8, 2024
dfa582b
fix mutation test
Knerio Sep 8, 2024
58cb370
Apply suggestions from code review
Knerio Sep 18, 2024
a022b41
remove stubbing identities
Knerio Sep 21, 2024
fe36c22
add new uniqueness validation
Knerio Sep 21, 2024
9a0686b
add specs for associations
Knerio Sep 21, 2024
e8395f5
fix unlink service
Knerio Sep 21, 2024
c12f90d
remove empty lines
Knerio Sep 21, 2024
7e9f812
compile docs
Knerio Sep 21, 2024
c4849da
Merge branch 'main' into 266-implement-external-identities
Knerio Sep 21, 2024
d0d7c7e
fix structure.sql
Knerio Sep 21, 2024
1efece7
Update spec/services/users/identity/unlink_service_spec.rb
Knerio Sep 21, 2024
96e8fce
move let into before hook
Knerio Sep 22, 2024
37ab942
Fix specs, db index and some typos
Taucher2003 Oct 5, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,7 @@ gem 'rotp'
gem 'grpc', '~> 1.64', '< 1.65'
gem 'tucana', '0.0.4'

gem 'code0-identities', '~> 0.0.1'

gem 'pry', '~> 0.14.2'
gem 'pry-byebug', '~> 3.10'
10 changes: 10 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,14 @@ GEM
msgpack (~> 1.2)
builder (3.3.0)
byebug (11.1.3)
code0-identities (0.0.1)
httparty (~> 0.22)
code0-license (0.2.0)
coderay (1.1.3)
concurrent-ruby (1.3.4)
connection_pool (2.4.1)
crass (1.0.6)
csv (3.3.0)
database_cleaner-active_record (2.2.0)
activerecord (>= 5.a)
database_cleaner-core (~> 2.0.0)
Expand Down Expand Up @@ -137,6 +140,10 @@ GEM
grpc (1.64.3-x86_64-linux)
google-protobuf (~> 3.25)
googleapis-common-protos-types (~> 1.0)
httparty (0.22.0)
csv
mini_mime (>= 1.0.0)
multi_xml (>= 0.5.2)
i18n (1.14.5)
concurrent-ruby (~> 1.0)
io-console (0.7.2)
Expand Down Expand Up @@ -164,6 +171,8 @@ GEM
minitest (5.25.1)
msgpack (1.7.2)
multi_json (1.15.0)
multi_xml (0.7.1)
bigdecimal (~> 3.1)
mutex_m (0.2.0)
net-imap (0.4.12)
date
Expand Down Expand Up @@ -348,6 +357,7 @@ PLATFORMS
DEPENDENCIES
bcrypt (~> 3.1.7)
bootsnap
code0-identities (~> 0.0.1)
code0-license (~> 0.2.0)
database_cleaner-active_record (~> 2.1)
debug
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/graphql_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def anonymous_mutation?
return false unless selections.length == 1

mutation_name = selections.first.name
%w[usersLogin usersRegister].include?(mutation_name)
%w[usersLogin usersRegister usersIdentityRegister usersIdentityLogin].include?(mutation_name)
end

Authorization = Struct.new(:type, :authorization) do
Expand Down
22 changes: 22 additions & 0 deletions app/graphql/mutations/users/identity/link.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# frozen_string_literal: true

module Mutations
module Users
module Identity
class Link < BaseMutation
description 'Links an external identity to and existing user'

field :user_identity, Types::UserIdentityType, null: true, description: 'The created user session'
Knerio marked this conversation as resolved.
Show resolved Hide resolved

argument :args, Types::Input::IdentityInput, required: true, description: 'The validation object'
argument :provider_id, String, required: true,
description: 'The ID of the external provider (e.g. google, discord, gitlab...) '

def resolve(provider_id:, args:)
::Users::Identity::LinkService.new(current_user, provider_id,
args).execute.to_mutation_response(success_key: :user_identity)
Knerio marked this conversation as resolved.
Show resolved Hide resolved
end
end
end
end
end
26 changes: 26 additions & 0 deletions app/graphql/mutations/users/identity/login.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# frozen_string_literal: true

module Mutations
module Users
module Identity
class Login < BaseMutation
include Sagittarius::Graphql::AuthorizationBypass

description 'Login to an existing user via an external identity'

field :user_session, Types::UserSessionType, null: true, description: 'The created user session'

argument :args, Types::Input::IdentityInput, required: true, description: 'The validation object'
argument :provider_id, String, required: true,
description: 'The ID of the external provider (e.g. google, discord, gitlab...) '

def resolve(provider_id:, args:)
response = ::Users::Identity::LoginService.new(provider_id,
args).execute.to_mutation_response(success_key: :user_session)
Knerio marked this conversation as resolved.
Show resolved Hide resolved
bypass_authorization! response, object_path: %i[user_session user]
bypass_authorization! response, object_path: :user_session
end
end
end
end
end
28 changes: 28 additions & 0 deletions app/graphql/mutations/users/identity/register.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# frozen_string_literal: true

module Mutations
module Users
module Identity
class Register < BaseMutation
include Sagittarius::Graphql::AuthorizationBypass

description 'Register a new user via a external identity'

field :user_session, Types::UserSessionType, null: true, description: 'The created users session'

argument :args, Types::Input::IdentityInput, required: true, description: 'The validation object'
argument :provider_id, String, required: true,
description: 'The ID of the external provider (e.g. google, discord, gitlab...) '

def resolve(provider_id:, args:)
response = ::Users::Identity::RegisterService.new(
provider_id,
args
).execute.to_mutation_response(success_key: :user_session)
bypass_authorization! response, object_path: %i[user_session user]
bypass_authorization! response, object_path: :user_session
end
end
end
end
end
30 changes: 30 additions & 0 deletions app/graphql/mutations/users/identity/unlink.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# frozen_string_literal: true

module Mutations
module Users
module Identity
class Unlink < BaseMutation
description 'Links an external identity to and existing user'
Knerio marked this conversation as resolved.
Show resolved Hide resolved

field :user_identity, Types::UserIdentityType, null: true, description: 'The removed identity'

argument :identity_id, Types::GlobalIdType[UserIdentity], required: true,
description: 'The ID of the identity to remove'

def resolve(identity_id:)
user_identity = SagittariusSchema.object_from_id(identity_id)

if user_identity.nil?
return { user_identity: nil,
errors: [create_message_error('Invalid identity')] }
end

::Users::Identity::UnlinkService.new(
current_user,
user_identity
).execute.to_mutation_response(success_key: :user_identity)
end
end
end
end
end
12 changes: 12 additions & 0 deletions app/graphql/types/input/identity_input.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

module Types
module Input
class IdentityInput < ::Types::BaseInputObject
description 'Represents the input for external user identity validation'

argument :code, String, required: false,
description: 'This validation code will be used for the oAuth validation process'
end
end
end
4 changes: 4 additions & 0 deletions app/graphql/types/mutation_type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ class MutationType < Types::BaseObject
mount_mutation Mutations::Runtimes::Delete
mount_mutation Mutations::Runtimes::RotateToken
mount_mutation Mutations::Runtimes::Update
mount_mutation Mutations::Users::Identity::Link
mount_mutation Mutations::Users::Identity::Login
mount_mutation Mutations::Users::Identity::Register
mount_mutation Mutations::Users::Identity::Unlink
mount_mutation Mutations::Users::Mfa::BackupCodes::Rotate
mount_mutation Mutations::Users::Mfa::Totp::GenerateSecret
mount_mutation Mutations::Users::Mfa::Totp::ValidateSecret
Expand Down
16 changes: 16 additions & 0 deletions app/graphql/types/user_identity_type.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# frozen_string_literal: true

module Types
class UserIdentityType < Types::BaseObject
description 'Represents an external user identity'

authorize :read_user_identity

field :identifier, String, null: false, description: 'The description for the runtime if present'
field :provider_id, String, null: false, description: 'The name for the runtime'
field :user, Types::UserType, null: false, description: 'The correlating user of the identity'

id_field UserIdentity
timestamps
end
end
1 change: 1 addition & 0 deletions app/models/application_setting.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class ApplicationSetting < ApplicationRecord
SETTINGS = {
user_registration_enabled: 1,
organization_creation_restricted: 2,
identity_providers: 3,
}.with_indifferent_access

BOOLEAN_OPTIONS = %i[user_registration_enabled organization_creation_restricted].freeze
Expand Down
2 changes: 2 additions & 0 deletions app/models/audit_event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ class AuditEvent < ApplicationRecord
mfa_enabled: 24,
backup_codes_rotated: 25,
user_updated: 26,
user_identity_linked: 27,
user_identity_unlinked: 28,
}.with_indifferent_access

# rubocop:disable Lint/StructNewOverride
Expand Down
2 changes: 2 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class User < ApplicationRecord
has_many :namespace_memberships, class_name: 'NamespaceMember', inverse_of: :user
has_many :namespaces, through: :namespace_memberships, inverse_of: :users

has_many :user_identities, inverse_of: :user

def mfa_enabled?
totp_secret != nil
end
Expand Down
10 changes: 10 additions & 0 deletions app/models/user_identity.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# frozen_string_literal: true

class UserIdentity < ApplicationRecord
Knerio marked this conversation as resolved.
Show resolved Hide resolved
belongs_to :user, inverse_of: :user_identities

validates :provider_id, presence: true
validates :identifier, presence: true

validates :identifier, uniqueness: { scope: :provider_id }
end
5 changes: 5 additions & 0 deletions app/policies/user_identity_policy.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# frozen_string_literal: true

class UserIdentityPolicy < BasePolicy
delegate { @subject.user }
end
2 changes: 2 additions & 0 deletions app/policies/user_policy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ class UserPolicy < BasePolicy

rule { user_is_admin }.policy do
enable :update_user
enable :read_user_identity
end

rule { user_is_self }.policy do
enable :read_user_identity
enable :manage_mfa
enable :update_user
end
Expand Down
17 changes: 17 additions & 0 deletions app/services/users/identity/base_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# frozen_string_literal: true

module Users
module Identity
class BaseService
def identity_provider
identity_provider = Code0::Identities::IdentityProvider.new
enabled_providers = ApplicationSetting.current[:identity_providers]
enabled_providers.each do |provider|
provider.deep_symbolize_keys!
identity_provider.add_named_provider(provider[:id], provider[:type], -> { provider[:config] })
end
identity_provider
end
end
end
end
55 changes: 55 additions & 0 deletions app/services/users/identity/link_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# frozen_string_literal: true

module Users
module Identity
class LinkService < BaseService
include Sagittarius::Database::Transactional

attr_reader :current_user, :provider_id, :args

def initialize(current_user, provider_id, args)
super()
@current_user = current_user
@provider_id = provider_id
@args = args
end

def execute
begin
identity = identity_provider.load_identity(provider_id, args)
rescue Code0::Identities::Error => e
return ServiceResponse.error(payload: e, message: 'An error occurred while loading external identity')
end
if identity.nil?
return ServiceResponse.error(payload: :invalid_external_identity, message: 'External identity is nil')
end

transactional do |t|
user_identity = UserIdentity.create(user: current_user, identifier: identity.identifier,
provider_id: provider_id)

unless user_identity.valid?
Knerio marked this conversation as resolved.
Show resolved Hide resolved
t.rollback_and_return! ServiceResponse.error(payload: user_identity.errors,
message: 'An error occurred while creating user identity')
end

current_user.user_identities << user_identity

unless current_user.save
t.rollback_and_return! ServiceResponse.error(payload: current_user.errors, message: 'Failed to save user')
end

AuditService.audit(
:user_identity_linked,
author_id: current_user.id,
entity: current_user,
details: { provider_id: user_identity.provider_id, identifier: identity.identifier },
target: current_user
)

ServiceResponse.success(payload: user_identity)
end
end
end
end
end
55 changes: 55 additions & 0 deletions app/services/users/identity/login_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# frozen_string_literal: true

module Users
module Identity
class LoginService < BaseService
include Sagittarius::Database::Transactional

attr_reader :provider_id, :args

def initialize(provider_id, args)
super()
@provider_id = provider_id
@args = args
end

def execute
begin
identity = identity_provider.load_identity(provider_id, args)
rescue Code0::Identities::Error => e
return ServiceResponse.error(payload: e, message: 'An error occurred while loading external identity')
end
if identity.nil?
return ServiceResponse.error(payload: :invalid_external_identity, message: 'External identity is nil')
end

user_identity = UserIdentity.find_by(provider_id: identity.provider.to_s, identifier: identity.identifier)

if user_identity.nil?
return ServiceResponse.error(payload: :external_identity_does_not_exist,
message: 'No user with that external identity exists, please register first')
end

user = user_identity.user

transactional do |t|
user_session = UserSession.create(user: user)
unless user_session.persisted?
t.rollback_and_return! ServiceResponse.error(message: 'UserSession is invalid',
payload: user_session.errors)
end

AuditService.audit(
:user_logged_in,
author_id: user.id,
entity: user,
details: { provider_id: user_identity.provider_id, identifier: identity.identifier },
target: user
)

ServiceResponse.success(payload: user_session)
end
end
end
end
end
Loading