require 'sinatra/base' require 'hws_settings' module HelixVersioningEngine # Methods for executing generic Perforce commands. # # These do not actually map to any particular 'resource', but are just a # bucket for random things you can try out. # # thj: I would prefer to remove these methods, and replace them with # 'resources' we would define for people. class App < Sinatra::Base get '/p4/:api/commands/:cmd' do |_, cmd| args = params.select { |k, _| k.start_with?('arg') }.map { |_, v| v } check_whitelist(cmd, args) require_p4 p4 = env['p4'] results = p4.run(cmd, *args) messages = p4.messages if messages && messages.length > 0 messages.map { |m| to_msg(m) }.to_json elsif results results.to_json end end post '/p4/:api/commands/:cmd' do |_, cmd| args = params.select { |key, _| key.start_with?('arg') }.map { |_, x| x } check_whitelist(cmd, args) require_p4 p4 = env['p4'] p4.input = filter_params(params) p4.run(cmd, args) messages = p4.messages messages.map { |m| to_msg(m) }.to_json if messages end def check_whitelist(cmd, args) # Make sure command is whitelisted cmd_whitelisted = HWSSettings.system.COMMAND_WHITELIST.any? do |wl| if wl.is_a?(String) wl == cmd elsif wl.is_a?(Array) wl.first == cmd end end unless cmd_whitelisted halt 403, { MessageCode: 15_360, MessageText: "#{cmd} not whitelisted in configuration", MessageSeverity: :ERROR }.to_json end # If command is whitelisted, double check that we do not have required # arguments required_args = HWSSettings.system.COMMAND_WHITELIST.find do |wl| if wl.is_a?(Array) wl.first == cmd end end if required_args unless required_args.drop(1).all? { |r| args.include?(r) } halt 403, { MessageCode: 15_360, MessageText: "#{cmd} not used with all required arguments #{required_args.drop(1)}", MessageSeverity: :ERROR }.to_json end end end end end