Module: Legion::Rbac::Routes

Defined in:
lib/legion/rbac/routes.rb

Defined Under Namespace

Classes: InvalidTimestamp

Constant Summary collapse

DEFAULT_COLLECTION_LIMIT =
100
MAX_COLLECTION_LIMIT =
500

Class Method Summary collapse

Class Method Details

.register_assignments(app) ⇒ Object

rubocop:disable Metrics/AbcSize



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/legion/rbac/routes.rb', line 171

def self.register_assignments(app) # rubocop:disable Metrics/AbcSize
  app.get '/api/rbac/assignments' do
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)
    return json_error('db_unavailable', 'legion-data not connected', status_code: 503) unless Legion::Rbac::Store.db_available?

    dataset = Legion::Data::Model::RbacRoleAssignment.order(:id)
    dataset = dataset.where(team: params[:team]) if params[:team]
    dataset = dataset.where(role: params[:role]) if params[:role]
    dataset = dataset.where(principal_id: params[:principal]) if params[:principal]
    json_collection(dataset)
  end

  app.post '/api/rbac/assignments' do
    Legion::Logging.debug "API: POST /api/rbac/assignments params=#{params.keys}"
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)
    return json_error('db_unavailable', 'legion-data not connected', status_code: 503) unless Legion::Rbac::Store.db_available?

    body = parse_request_body
    record = Legion::Data::Model::RbacRoleAssignment.create(
      principal_type: body[:principal_type] || 'human',
      principal_id:   body[:principal_id],
      role:           body[:role],
      team:           body[:team],
      granted_by:     current_owner_msid || 'api',
      expires_at:     parse_optional_time(body[:expires_at], field: 'expires_at')
    )
    Legion::Logging.info "API: created RBAC assignment #{record.id} role=#{body[:role]} principal=#{body[:principal_id]}"
    emit_rbac_policy_changed('assignment.created', 'role_assignment', record.values)
    json_response(record.values, status_code: 201)
  rescue Legion::Rbac::Routes::InvalidTimestamp => e
    json_error('validation_error', e.message, status_code: 422)
  rescue Sequel::ValidationFailed => e
    Legion::Logging.warn "API POST /api/rbac/assignments returned 422: #{e.message}"
    json_error('validation_error', e.message, status_code: 422)
  end

  app.delete '/api/rbac/assignments/:id' do
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)
    return json_error('db_unavailable', 'legion-data not connected', status_code: 503) unless Legion::Rbac::Store.db_available?

    record = Legion::Data::Model::RbacRoleAssignment[params[:id].to_i]
    halt 404, json_error('not_found', 'Assignment not found', status_code: 404) unless record

    snapshot = record.values.dup
    record.destroy
    Legion::Logging.info "API: deleted RBAC assignment #{params[:id]}"
    emit_rbac_policy_changed('assignment.deleted', 'role_assignment', snapshot)
    json_response({ deleted: true })
  end
end

.register_check(app) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/legion/rbac/routes.rb', line 147

def self.register_check(app)
  app.post '/api/rbac/check' do
    Legion::Logging.debug "API: POST /api/rbac/check params=#{params.keys}"
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)

    body = parse_request_body
    principal = Legion::Rbac::Principal.new(
      id:    body[:principal] || 'anonymous',
      roles: body[:roles] || [],
      team:  body[:team]
    )
    result = Legion::Rbac::PolicyEngine.evaluate(
      principal: principal,
      action:    body[:action] || 'read',
      resource:  body[:resource] || '*',
      enforce:   false
    )
    json_response(result)
  rescue StandardError => e
    Legion::Logging.error "API POST /api/rbac/check: #{e.class}#{e.message}"
    json_error('rbac_error', e.message, status_code: 500)
  end
end

.register_cross_team_grants(app) ⇒ Object



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/legion/rbac/routes.rb', line 267

def self.register_cross_team_grants(app)
  app.get '/api/rbac/grants/cross-team' do
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)
    return json_error('db_unavailable', 'legion-data not connected', status_code: 503) unless Legion::Rbac::Store.db_available?

    dataset = Legion::Data::Model::RbacCrossTeamGrant.order(:id)
    json_collection(dataset)
  end

  app.post '/api/rbac/grants/cross-team' do
    Legion::Logging.debug "API: POST /api/rbac/grants/cross-team params=#{params.keys}"
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)
    return json_error('db_unavailable', 'legion-data not connected', status_code: 503) unless Legion::Rbac::Store.db_available?

    body = parse_request_body
    record = Legion::Data::Model::RbacCrossTeamGrant.create(
      source_team:    body[:source_team],
      target_team:    body[:target_team],
      runner_pattern: body[:runner_pattern],
      actions:        Array(body[:actions]).join(','),
      granted_by:     current_owner_msid || 'api',
      expires_at:     parse_optional_time(body[:expires_at], field: 'expires_at')
    )
    Legion::Logging.info "API: created cross-team RBAC grant #{record.id} #{body[:source_team]}->#{body[:target_team]}"
    emit_rbac_policy_changed('cross_team_grant.created', 'cross_team_grant', record.values)
    json_response(record.values, status_code: 201)
  rescue Legion::Rbac::Routes::InvalidTimestamp => e
    json_error('validation_error', e.message, status_code: 422)
  rescue Sequel::ValidationFailed => e
    Legion::Logging.warn "API POST /api/rbac/grants/cross-team returned 422: #{e.message}"
    json_error('validation_error', e.message, status_code: 422)
  end

  app.delete '/api/rbac/grants/cross-team/:id' do
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)
    return json_error('db_unavailable', 'legion-data not connected', status_code: 503) unless Legion::Rbac::Store.db_available?

    record = Legion::Data::Model::RbacCrossTeamGrant[params[:id].to_i]
    halt 404, json_error('not_found', 'Grant not found', status_code: 404) unless record

    snapshot = record.values.dup
    record.destroy
    Legion::Logging.info "API: deleted cross-team RBAC grant #{params[:id]}"
    emit_rbac_policy_changed('cross_team_grant.deleted', 'cross_team_grant', snapshot)
    json_response({ deleted: true })
  end
end

.register_grants(app) ⇒ Object



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/legion/rbac/routes.rb', line 222

def self.register_grants(app)
  app.get '/api/rbac/grants' do
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)
    return json_error('db_unavailable', 'legion-data not connected', status_code: 503) unless Legion::Rbac::Store.db_available?

    dataset = Legion::Data::Model::RbacRunnerGrant.order(:id)
    dataset = dataset.where(team: params[:team]) if params[:team]
    json_collection(dataset)
  end

  app.post '/api/rbac/grants' do
    Legion::Logging.debug "API: POST /api/rbac/grants params=#{params.keys}"
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)
    return json_error('db_unavailable', 'legion-data not connected', status_code: 503) unless Legion::Rbac::Store.db_available?

    body = parse_request_body
    record = Legion::Data::Model::RbacRunnerGrant.create(
      team:           body[:team],
      runner_pattern: body[:runner_pattern],
      actions:        Array(body[:actions]).join(','),
      granted_by:     current_owner_msid || 'api'
    )
    Legion::Logging.info "API: created RBAC grant #{record.id} team=#{body[:team]} pattern=#{body[:runner_pattern]}"
    emit_rbac_policy_changed('runner_grant.created', 'runner_grant', record.values)
    json_response(record.values, status_code: 201)
  rescue Sequel::ValidationFailed => e
    Legion::Logging.warn "API POST /api/rbac/grants returned 422: #{e.message}"
    json_error('validation_error', e.message, status_code: 422)
  end

  app.delete '/api/rbac/grants/:id' do
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)
    return json_error('db_unavailable', 'legion-data not connected', status_code: 503) unless Legion::Rbac::Store.db_available?

    record = Legion::Data::Model::RbacRunnerGrant[params[:id].to_i]
    halt 404, json_error('not_found', 'Grant not found', status_code: 404) unless record

    snapshot = record.values.dup
    record.destroy
    Legion::Logging.info "API: deleted RBAC grant #{params[:id]}"
    emit_rbac_policy_changed('runner_grant.deleted', 'runner_grant', snapshot)
    json_response({ deleted: true })
  end
end

.register_helpers(app) ⇒ Object

rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/legion/rbac/routes.rb', line 29

def self.register_helpers(app) # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/MethodLength,Metrics/PerceivedComplexity
  app.helpers do # rubocop:disable Metrics/BlockLength
    unless method_defined?(:parse_request_body)
      define_method(:parse_request_body) do
        raw = request.body.read
        return {} if raw.nil? || raw.empty?

        begin
          parsed = Legion::JSON.load(raw)
        rescue StandardError
          halt 400, { 'Content-Type' => 'application/json' },
               Legion::JSON.dump({ error: { code: 'invalid_json', message: 'request body is not valid JSON' } })
        end

        unless parsed.respond_to?(:transform_keys)
          halt 400, { 'Content-Type' => 'application/json' },
               Legion::JSON.dump({ error: { code:    'invalid_request_body',
                                            message: 'request body must be a JSON object' } })
        end

        parsed.transform_keys(&:to_sym)
      end
    end

    unless method_defined?(:json_response)
      define_method(:json_response) do |data, status_code: 200|
        content_type :json
        status status_code
        Legion::JSON.dump({ data: data })
      end
    end

    unless method_defined?(:json_error)
      define_method(:json_error) do |code, message, status_code: 400|
        content_type :json
        status status_code
        Legion::JSON.dump({ error: { code: code, message: message } })
      end
    end

    unless method_defined?(:json_collection)
      define_method(:json_collection) do |dataset|
        content_type :json
        Legion::JSON.dump(Legion::Rbac::Routes.send(:collection_payload, dataset, params))
      end
    end

    unless method_defined?(:current_owner_msid)
      define_method(:current_owner_msid) do
        env['legion.owner_msid']
      end
    end

    unless method_defined?(:current_rbac_actor_id)
      define_method(:current_rbac_actor_id) do
        current_owner_msid || env['legion.principal']&.id || 'api'
      end
    end

    unless method_defined?(:rbac_request_correlation_id)
      define_method(:rbac_request_correlation_id) do
        Legion::Rbac::Routes.send(:request_correlation_id, env)
      end
    end

    unless method_defined?(:rbac_request_source)
      define_method(:rbac_request_source) do
        Legion::Rbac::Routes.send(:request_source, env)
      end
    end

    unless method_defined?(:emit_rbac_policy_changed)
      define_method(:emit_rbac_policy_changed) do |change_type, target_type, record_values|
        Legion::Rbac::Routes.send(
          :emit_policy_changed,
          change_type:   change_type,
          target_type:   target_type,
          record_values: record_values,
          context:       Legion::Rbac::Routes.send(
            :policy_change_context,
            actor_id:       current_rbac_actor_id,
            source:         rbac_request_source,
            correlation_id: rbac_request_correlation_id,
            method:         request.request_method,
            path:           request.path_info
          )
        )
      end
    end
  end
end

.register_roles(app) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/legion/rbac/routes.rb', line 121

def self.register_roles(app)
  app.get '/api/rbac/roles' do
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)

    roles = Legion::Rbac.role_index.transform_values do |role|
      { name: role.name, description: role.description, cross_team: role.cross_team? }
    end
    json_response(roles)
  end

  app.get '/api/rbac/roles/:name' do
    return json_error('rbac_unavailable', 'legion-rbac not installed', status_code: 501) unless defined?(Legion::Rbac)

    role = Legion::Rbac.role_index[params[:name].to_sym]
    halt 404, json_error('not_found', "Role #{params[:name]} not found", status_code: 404) unless role

    json_response({
                    name:        role.name,
                    description: role.description,
                    cross_team:  role.cross_team?,
                    permissions: role.permissions.map { |p| { resource: p.resource_pattern, actions: p.actions } },
                    deny_rules:  role.deny_rules.map { |d| { resource: d.resource_pattern, above_level: d.above_level } }
                  })
  end
end

.registered(app) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/legion/rbac/routes.rb', line 20

def self.registered(app)
  register_helpers(app)
  register_roles(app)
  register_check(app)
  register_assignments(app)
  register_grants(app)
  register_cross_team_grants(app)
end