Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

v1.3.3: update to match lib, fix add member

Change-Id: I0e77e5fbbf7ae52117053543816ab2625e8005a2
  • Loading branch information...
commit 042a5c2219a7b536d38a9524a0407d0ba77fa81b 1 parent 1f4a9df
@daleolds daleolds authored
View
5 .yardopts
@@ -0,0 +1,5 @@
+--main README.md
+--no-private
+--title "Cloud Foundry UAA Client CLI"
+lib/**/*.rb - LICENSE.TXT NOTICE.TXT
+
View
12,737 LICENSE.TXT
12,737 additions, 0 deletions not shown
View
10 NOTICE.TXT
@@ -0,0 +1,10 @@
+Cloud Foundry 2012.02.03 Beta
+Copyright (c) [2009-2012] VMware, Inc. All Rights Reserved.
+
+This product is licensed to you under the Apache License, Version 2.0 (the "License").
+You may not use this product except in compliance with the License.
+
+This product includes a number of subcomponents with
+separate copyright notices and license terms. Your use of these
+subcomponents is subject to the terms and conditions of the
+subcomponent's license, as noted in the LICENSE file.
View
6 Rakefile
@@ -10,7 +10,6 @@
# subcomponent's license, as noted in the LICENSE file.
#
-require "rdoc/task"
require "rspec/core/rake_task"
require "bundler/gem_tasks" # only available in bundler >= 1.0.15
require "ci/reporter/rake/rspec"
@@ -27,11 +26,6 @@ RSpec::Core::RakeTask.new("test") do |t|
t.pattern = "spec/**/*_spec.rb"
end
-RDoc::Task.new do |rd|
- rd.rdoc_files.include("lib/**/*.rb")
- rd.rdoc_dir = "doc"
-end
-
task :ci => [:pre_coverage, :rcov_reports, "ci:setup:rspec", :test]
task :cov => [:pre_coverage, :test, :view_coverage]
task :coverage => [:pre_coverage, :test]
View
53 bin/uaas
@@ -2,6 +2,55 @@
$:.unshift File.expand_path File.join __FILE__, '..', '..', 'lib'
require 'stub/uaa'
+require 'cli/base'
+require 'cli/version'
+
+module CF::UAA
+
+Util.default_logger(:trace)
+
+class ServerTopic < Topic
+ topic "", "run"
+ desc "version", "Display version" do say "version #{CLI_VERSION}" end
+ define_option :trace, "--[no-]trace", "-t", "display extra verbose debug information"
+ define_option :debug, "--[no-]debug", "-d", "display debug information"
+ define_option :help, "--[no-]help", "-h", "display helpful information"
+ define_option :version, "--[no-]version", "-v", "show version"
+
+ desc "help [topic|command...]", "Display summary or details of command or topic" do |*args|
+ args.empty? ? say_help : say_command_help(args)
+ end
+
+ define_option :port, "--port <number>", "-p", "port for server to listen on"
+ define_option :root, "--root <path>", "-r", "root path of UAA resources, e.g. /uaa"
+ desc "run", "Run the UAA server", :port, :root do
+ CF::UAA::StubUAA.new(port: (opts[:port] || "8080").to_i, root: opts[:root],
+ logger: Util.default_logger).run
+ end
+
+end
+
+class ServerCli < BaseCli
+ @overview = "UAA Stub Server Command Line\nProvides partial uaa server support suitable for testing uaac."
+ @topics = [ServerTopic]
+ @global_options = [:help, :version, :debug, :trace]
+ @input, @output = $stdin, $stdout
+
+ def self.handle_bad_command(args, msg)
+ @output.puts "\n#{msg}"
+ run args.unshift("help")
+ nil
+ end
+
+ def self.preprocess_options(args, opts)
+ return args.replace(["version"]) if opts[:version]
+ return args.unshift("help") if args.empty? || opts[:help] && args[0] != "version"
+ Util.default_logger(opts[:trace]? :trace: opts[:debug]? :debug: :warn, @output)
+ end
+
+end
+
+end
+
+exit CF::UAA::ServerCli.run ? 0 : 1
-CF::UAA::Util.default_logger(:trace)
-CF::UAA::StubUAA.new.run('localhost', 8080)
View
4 cf-uaac.gemspec
@@ -38,10 +38,10 @@ Gem::Specification.new do |s|
s.add_development_dependency "simplecov"
s.add_development_dependency "simplecov-rcov"
s.add_development_dependency "ci_reporter"
- s.add_runtime_dependency "cf-uaa-lib", ">= 1.3.1"
+ s.add_runtime_dependency "cf-uaa-lib", ">= 1.3.3", "<= 1.3.3"
s.add_runtime_dependency "highline"
s.add_runtime_dependency "eventmachine"
s.add_runtime_dependency "launchy"
s.add_runtime_dependency "em-http-request", ">= 1.0.0.beta.3"
-
+ s.add_runtime_dependency "json_pure"
end
View
25 lib/cli/base.rb
@@ -13,6 +13,7 @@
require 'highline'
require 'optparse'
+require 'json/pure'
module CF; module UAA end end
@@ -56,10 +57,10 @@ def initialize(cli_class, options = {}, input = $stdin, output = $stdout)
@highline = HighLine.new(input, output)
end
- def ask(prompt); @highline.ask("#{prompt}: ") end
- def ask_pwd(prompt); @highline.ask("#{prompt}: ") { |q| q.echo = '*' } end
- def say(msg); @output.puts(msg); msg end
- def gripe(msg); @output.puts(msg) end
+ def ask(prompt) @highline.ask("#{prompt}: ") end
+ def ask_pwd(prompt) @highline.ask("#{prompt}: ") { |q| q.echo = '*' } end
+ def say(msg) @output.puts(msg); msg end
+ def gripe(msg) @output.puts(msg) end
def opts; @options end
def terminal_columns
@@ -232,16 +233,15 @@ class << self
attr_accessor :overview, :topics, :global_options
end
- def self.preprocess_options(args, opts); end # to be implemented in subclass
- def self.too_many_args(cmd); end # to be implemented in subclass
+ def self.preprocess_options(args, opts) end # to be implemented in subclass
+ def self.handle_bad_command(args, msg) end # to be implemented in subclass
def self.run(args = ARGV)
@input ||= $stdin
@output ||= $stdout
- @option_defs = {}
@output.string = "" if @output.respond_to?(:string)
args = args.split if args.respond_to?(:split)
- @parser = OptionParser.new
+ @option_defs, @parser, orig = {}, OptionParser.new, args
opts = @topics.each_with_object({}) do |tpc, o|
tpc.option_defs.each do |k, optdef|
@parser.on(*optdef) { |v| o[k] = v }
@@ -257,11 +257,14 @@ def self.run(args = ARGV)
if v[:argc] == -1
# variable args, leave args alone
elsif args.length > v[:argc]
- too_many_args(v[:parts].dup)
- return nil
+ return handle_bad_command(orig, "Too many command line parameters given.")
elsif args.length < v[:argc]
(v[:argc] - args.length).times { args << nil }
end
+ opts.keys.each do |o|
+ next if v[:options].include?(o) || @global_options.include?(o)
+ return handle_bad_command(orig, "Invalid option: #{o}")
+ end
return tpc.new(self, opts, @input, @output).send(k, *args)
end
end
@@ -269,7 +272,7 @@ def self.run(args = ARGV)
rescue Exception => e
@output.puts "#{File.basename($0)} error", "#{e.class}: #{e.message}", (e.backtrace if opts[:trace])
ensure
- puts @output.string if opts[:trace] && @print_on_trace
+ puts @output.string if opts[:trace] && @print_on_trace && @output.respond_to?(:string)
end
end
View
4 lib/cli/client_reg.rb
@@ -63,7 +63,7 @@ def client_info(defaults)
pp scim_request { |cr|
opts[:client_id] = clientname(name)
opts[:secret] = verified_pwd("New client secret", opts[:secret])
- defaults = opts[:clone] ? Util.hash_keys!(cr.get(opts[:clone]), :tosym) : {}
+ defaults = opts[:clone] ? Util.hash_keys!(cr.get(opts[:clone]), :sym) : {}
defaults.delete(:client_id)
cr.add(:client, client_info(defaults))
}
@@ -73,7 +73,7 @@ def client_info(defaults)
:del_attrs, :interact do |name|
pp scim_request { |cr|
opts[:client_id] = clientname(name)
- orig = Util.hash_keys!(cr.get(:client, opts[:client_id]), :tosym)
+ orig = Util.hash_keys!(cr.get(:client, opts[:client_id]), :sym)
info = client_info(orig)
info.any? { |k, v| v != orig[k] } ? cr.put(:client, info) :
gripe("Nothing to update. Use -i for interactive update.")
View
10 lib/cli/config.rb
@@ -22,7 +22,7 @@ class << self; attr_reader :target, :context end
def self.config; @config ? @config.dup : {} end
def self.loaded?; !!@config end
- def self.yaml; YAML.dump(Util.hash_keys(@config, :tostr)) end
+ def self.yaml; YAML.dump(Util.hash_keys(@config, :str)) end
def self.target?(tgt) tgt if @config[tgt = subhash_key(@config, tgt)] end
# if a yaml string is provided, config is loaded from the string, otherwise
@@ -48,12 +48,12 @@ def self.load(config = nil)
else # file doesn't exist, make sure we can write it now
File.open(@config_file, 'w') { |f| f.write("--- {}\n\n") }
end
- Util.hash_keys!(@config, :tosym)
+ Util.hash_keys!(@config, :sym)
@context = current_subhash(@config[@target][:contexts]) if @target = current_subhash(@config)
end
def self.save
- File.open(@config_file, 'w') { |f| YAML.dump(Util.hash_keys(@config, :tostr), f) } if @config_file
+ File.open(@config_file, 'w') { |f| YAML.dump(Util.hash_keys(@config, :str), f) } if @config_file
true
end
@@ -70,7 +70,7 @@ def self.target_opts(hash)
raise ArgumentError, "target not set" unless @target
return unless hash and !hash.empty?
raise ArgumentError, "'contexts' is a reserved key" if hash.key?(:contexts)
- @config[@target].merge! Util.hash_keys(hash, :tosym)
+ @config[@target].merge! Util.hash_keys(hash, :sym)
save
end
@@ -111,7 +111,7 @@ def self.delete(tgt = nil, ctx = nil)
def self.add_opts(hash)
raise ArgumentError, "target and context not set" unless @target && @context
return unless hash and !hash.empty?
- @config[@target][:contexts][@context].merge! Util.hash_keys(hash, :tosym)
+ @config[@target][:contexts][@context].merge! Util.hash_keys(hash, :sym)
save
end
View
10 lib/cli/group.rb
@@ -41,15 +41,17 @@ def gname(name) name || ask("Group name") end
end
desc "group delete [name]", "Delete group" do |name|
- pp scim_request { |ua|
+ pp scim_request { |ua|
ua.delete(:delete, ua.id(:group, gname(name)))
- "success"
+ "success"
}
end
def id_set(objs)
- objs.each_with_object(Set.new) {|o, s|
- s << (o.is_a?(String)? o: (o["id"] || o["value"]))
+ objs.each_with_object(Set.new) {|o, s|
+ id = o.is_a?(String)? o: (o["id"] || o["value"] || o["memberid"])
+ raise BadResponse, "no id found in response of current members" unless id
+ s << id
}
end
View
9 lib/cli/runner.rb
@@ -25,16 +25,17 @@ class Cli < BaseCli
@topics = [MiscCli, InfoCli, TokenCli, UserCli, GroupCli, ClientCli]
@global_options = [:help, :version, :debug, :trace, :config]
- def self.configure(config_file = "", input = $stdin, output = $stdout,
+ def self.configure(config_file = "", input = $stdin, output = $stdout,
print_on_trace = false)
@config_file, @input, @output = config_file, input, output
@print_on_trace = print_on_trace
self
end
- def self.too_many_args(cmd)
- @output.puts "\nToo many command line parameters given."
- run cmd.unshift("help")
+ def self.handle_bad_command(args, msg)
+ @output.puts "\n#{msg}"
+ run args.unshift("help")
+ nil
end
def self.preprocess_options(args, opts)
View
20 lib/cli/token.rb
@@ -27,7 +27,7 @@ def process_grant(data)
Config.target_value(:token_target))
tkn = secret ? ti.authcode_grant(server.info.delete(:uri), data) :
ti.implicit_grant(server.info.delete(:uri), data)
- server.info.update(Util.hash_keys!(tkn.info, :tosym))
+ server.info.update(Util.hash_keys!(tkn.info, :sym))
reply.text "you are now logged in and can close this window"
rescue TargetError => e
reply.text "#{e.message}:\r\n#{Util.json_pretty(e.info)}\r\n#{e.backtrace}"
@@ -71,7 +71,8 @@ def say_success(grant)
def issuer_request(client_id, secret = nil)
update_target_info
- yield TokenIssuer.new(Config.target.to_s, client_id, secret, Config.target_value(:token_endpoint))
+ yield TokenIssuer.new(Config.target.to_s, client_id, secret,
+ :token_target => Config.target_value(:token_endpoint))
rescue Exception => e
complain e
end
@@ -99,7 +100,7 @@ def issuer_request(client_id, secret = nil)
ti.implicit_grant_with_creds(creds, opts[:scope]).info
}
return gripe "attempt to get token failed\n" unless token && token["access_token"]
- tokinfo = TokenCoder.decode(token["access_token"], nil, nil, false)
+ tokinfo = TokenCoder.decode(token["access_token"], verify: false)
Config.context = tokinfo["user_name"]
Config.add_opts(user_id: tokinfo["user_id"])
Config.add_opts token
@@ -140,8 +141,9 @@ def issuer_request(client_id, secret = nil)
def use_browser(client_id, secret = nil)
catcher = Stub::Server.new(TokenCatcher,
- Util.default_logger(debug? ? :debug : trace? ? :trace : :info),
- client_id: client_id, client_secret: secret).run_on_thread("localhost", opts[:port])
+ logger: Util.default_logger(debug? ? :debug : trace? ? :trace : :info),
+ info: {client_id: client_id, client_secret: secret},
+ port: opts[:port]).run_on_thread
uri = issuer_request(client_id, secret) { |ti|
secret ? ti.authcode_uri("#{catcher.url}/authcode", opts[:scope]) :
ti.implicit_uri("#{catcher.url}/callback", opts[:scope])
@@ -154,7 +156,7 @@ def use_browser(client_id, secret = nil)
sleep 5
print "."
end
- Config.context = TokenCoder.decode(catcher.info[:access_token], nil, nil, false)[:user_name]
+ Config.context = TokenCoder.decode(catcher.info[:access_token], verify: false)[:user_name]
Config.add_opts catcher.info
say_success secret ? "authorization code" : "implicit"
return unless opts[:vmc]
@@ -190,9 +192,9 @@ def use_browser(client_id, secret = nil)
if opts[:client] && opts[:secret]
pp Misc.decode_token(Config.target, opts[:client], opts[:secret], token, ttype)
else
- seckey = opts[:key] || (Config.target_value(:signing_key) if Config.target_value(:signing_alg) !~ /rsa$/i)
- pubkey = opts[:key] || (Config.target_value(:signing_key) if Config.target_value(:signing_alg) =~ /rsa$/i)
- info = TokenCoder.decode(token, seckey, pubkey, seckey || pubkey)
+ seckey = opts[:key] || (Config.target_value(:signing_key) if Config.target_value(:signing_alg) !~ /rsa$/i)
+ pubkey = opts[:key] || (Config.target_value(:signing_key) if Config.target_value(:signing_alg) =~ /rsa$/i)
+ info = TokenCoder.decode(token, skey: seckey, pkey: pubkey, verify: !!(seckey || pubkey))
say seckey || pubkey ? "\nValid token signature\n\n": "\nNote: no key given to validate token signature\n\n"
pp info
end
View
3  lib/cli/version.rb
@@ -11,8 +11,9 @@
# subcomponent's license, as noted in the LICENSE file.
#++
+# Cloud Foundry namespace
module CF
module UAA
- CLI_VERSION = "1.3.1"
+ CLI_VERSION = "1.3.3"
end
end
View
18 lib/stub/scim.rb
@@ -57,11 +57,11 @@ class StubScim
:entitlements, :roles, :x509certificates, :name, :addresses,
:authorizations, :groups].to_set,
client: [*COMMON_ATTRS, :client_id, :client_secret, :authorities,
- :authorized_grant_types, :scope, :auto_approved_scope,
+ :authorized_grant_types, :scope, :auto_approved_scope,
:access_token_validity, :refresh_token_validity, :redirect_uri].to_set,
group: [*COMMON_ATTRS, :displayname, :members, :owners, :readers].to_set }
VISIBLE_ATTRS = {user: Set.new(LEGAL_ATTRS[:user] - HIDDEN_ATTRS),
- client: Set.new(LEGAL_ATTRS[:client] - HIDDEN_ATTRS),
+ client: Set.new(LEGAL_ATTRS[:client] - HIDDEN_ATTRS),
group: Set.new(LEGAL_ATTRS[:group] - HIDDEN_ATTRS)}
ATTR_NAMES = LEGAL_ATTRS.each_with_object(Set.new) { |(k, v), s|
v.each {|a| s << a.to_s }
@@ -76,15 +76,15 @@ def self.searchable_attribute(attr)
attr if ATTR_NAMES.include?(attr) && !HIDDEN_ATTRS.include?(attr = attr.to_sym)
end
- def remove_attrs(stuff, attrs = HIDDEN_ATTRS)
+ def remove_attrs(stuff, attrs = HIDDEN_ATTRS)
attrs.each { |a| stuff.delete(a.to_s) }
stuff
end
- def valid_id?(id, rtype)
- id && (t = @things_by_id[id]) && (rtype.nil? || t[:rtype] == rtype)
+ def valid_id?(id, rtype)
+ id && (t = @things_by_id[id]) && (rtype.nil? || t[:rtype] == rtype)
end
-
+
def ref_by_name(name, rtype) @things_by_name[rtype.to_s + name.downcase] end
def ref_by_id(id, rtype = nil)
@@ -134,10 +134,10 @@ def enforce_schema(rtype, stuff)
end
def input(stuff)
- thing = Util.hash_keys(stuff.dup, :tosym)
+ thing = Util.hash_keys(stuff.dup, :sym)
REFERENCES.each {|a|
next unless thing[a]
- thing[a] = thing[a].each_with_object(Set.new) { |r, s|
+ thing[a] = thing[a].each_with_object(Set.new) { |r, s|
s << (r.is_a?(Hash)? r[:value] : r )
}
}
@@ -146,7 +146,7 @@ def input(stuff)
thing[a] = thing[a].each_with_object({}) { |v, o|
v = {value: v} unless v.is_a?(Hash)
# enforce values are unique by type and value
- k = URI.encode_www_form(t: [v[:type], v: v[:value]]).downcase
+ k = Util.encode_form(t: [v[:type], v: v[:value]]).downcase
o[k] = v
}
}
View
82 lib/stub/server.rb
@@ -89,8 +89,7 @@ class Reply
def initialize(status = 200) @status, @headers, @cookies, @body = status, {}, [], "" end
def to_s
reply = "HTTP/1.1 #{@status} OK\r\n"
- headers["server"] = "stub server"
- headers["date"] = DateTime.now.httpdate
+ headers["server"], headers["date"] = "stub server", DateTime.now.httpdate
headers["content-length"] = body.bytesize
headers.each { |k, v| reply << "#{k}: #{v}\r\n" }
@cookies.each { |c| reply << "Set-Cookie: #{c}\r\n" }
@@ -168,8 +167,14 @@ def initialize(server)
@server, @request, @reply, @match = server, Request.new, Reply.new, nil
end
+ def default_route; reply_in_kind(404, error: "path not handled") end
+
def process
@reply = Reply.new
+ if server.root
+ return default_route unless request.path.start_with?(server.root)
+ request.path.slice!(0..server.root.length - 1)
+ end
@match, handler = self.class.find_route(request)
server.logger.debug "processing request to path #{request.path} for route #{@match ? @match.regexp : 'default'}"
send handler
@@ -177,7 +182,7 @@ def process
server.logger.debug "replying to path #{request.path} with #{reply.body.length} bytes of #{reply.headers['content-type']}"
#server.logger.debug "full reply is: #{reply.body.inspect}"
rescue Exception => e
- server.logger.debug "exception from route handler: #{e.message}"
+ server.logger.debug "exception processing request: #{e.message}"
server.trace { e.backtrace }
reply_in_kind 500, e
end
@@ -190,10 +195,6 @@ def reply_in_kind(status = nil, info)
end
end
- def default_route
- reply_in_kind(404, error: "path not handled")
- end
-
end
#------------------------------------------------------------------------------
@@ -216,38 +217,62 @@ def receive_data(data)
end
end
-#--------------------------------------------------------------------------
+#------------------------------------------------------------------------------
class Server
- attr_reader :host, :port, :status, :logger
+
+ private
+
+ def done
+ fail unless @connections.empty?
+ EM.stop if @em_thread && EM.reactor_running?
+ @connections, @status, @sig, @em_thread = [], :stopped, nil, nil
+ sleep 0.1 unless EM.reactor_thread? # give EM a chance to stop
+ logger.debug EM.reactor_running?? "server done but EM still running": "server really done"
+ end
+
+ def initialize_connection(conn)
+ logger.debug "starting connection"
+ fail unless EM.reactor_thread?
+ @connections << conn
+ conn.req_handler, conn.comm_inactivity_timeout = @req_handler.new(self), 30
+ end
+
+ public
+
+ attr_reader :host, :port, :status, :logger, :root
attr_accessor :info
def url; "http://#{@host}:#{@port}" end
def trace(msg = nil, &blk); logger.trace(msg, &blk) if logger.respond_to?(:trace) end
- def initialize(req_handler, logger = Logger.new($stdout), info = nil)
- @req_handler, @logger, @info = req_handler, logger, info
+ def initialize(req_handler, options)
+ @req_handler = req_handler
+ @logger = options[:logger] || Logger.new($stdout)
+ @info = options[:info]
+ @host = options[:host] || "localhost"
+ @init_port = options[:port] || 0
+ @root = options[:root]
@connections, @status, @sig, @em_thread = [], :stopped, nil, nil
end
- def start(hostname = "localhost", port = nil)
+ def start
raise ArgumentError, "attempt to start a server that's already running" unless @status == :stopped
- @host = hostname
logger.debug "starting #{self.class} server #{@host}"
EM.schedule do
- @sig = EM.start_server(@host, port || 0, Connection) { |c| initialize_connection(c) }
+ @sig = EM.start_server(@host, @init_port, Connection) { |c| initialize_connection(c) }
@port = Socket.unpack_sockaddr_in(EM.get_sockname(@sig))[0]
- logger.debug "#{self.class} server started at #{url}, signature #{@sig}"
+ logger.info "#{self.class} server started at #{url}"
end
@status = :running
self
end
- def run_on_thread(hostname = "localhost", port = 0)
+ def run_on_thread
raise ArgumentError, "can't run on thread, EventMachine already running" if EM.reactor_running?
logger.debug { "starting eventmachine on thread" }
cthred = Thread.current
@em_thread = Thread.new do
begin
- EM.run { start(hostname, port); cthred.run }
+ EM.run { start; cthred.run }
logger.debug "server thread done"
rescue Exception => e
logger.debug { "unhandled exception on stub server thread: #{e.message}" }
@@ -260,10 +285,10 @@ def run_on_thread(hostname = "localhost", port = 0)
self
end
- def run(hostname = "localhost", port = 0)
+ def run
raise ArgumentError, "can't run, EventMachine already running" if EM.reactor_running?
@em_thread = Thread.current
- EM.run { start(hostname, port) }
+ EM.run { start }
logger.debug "server and event machine done"
end
@@ -286,25 +311,6 @@ def delete_connection(conn)
done if @status != :running && @connections.empty?
end
- private
-
- def done
- fail unless @connections.empty?
- EM.stop if @em_thread && EM.reactor_running?
- @connections, @status, @sig, @em_thread = [], :stopped, nil, nil
- sleep 0.1 unless EM.reactor_thread? # give EM a chance to stop
- logger.debug EM.reactor_running? ?
- "server done but EM still running" : "server really done"
- end
-
- def initialize_connection(conn)
- logger.debug "starting connection"
- fail unless EM.reactor_thread?
- @connections << conn
- conn.req_handler = @req_handler.new(self)
- conn.comm_inactivity_timeout = 30
- end
-
end
end
View
33 lib/stub/uaa.rb
@@ -74,7 +74,7 @@ def default_route; reply_in_kind(404, error: "not found", error_description: "un
route :get, '/token_key' do reply_in_kind(alg: "none", value: "none") end
route :post, '/password/score', "content-type" => %r{application/x-www-form-urlencoded} do
- info = Util.decode_form_to_hash(request.body)
+ info = Util.decode_form(request.body)
return bad_request "no password to score" unless pwd = info["password"]
score = pwd.length > 10 || pwd.length < 0 ? 10 : pwd.length
reply_in_kind(score: score, requiredScore: 0)
@@ -110,7 +110,7 @@ def default_route; reply_in_kind(404, error: "not found", error_description: "un
end
route :post, '/login.do', "content-type" => %r{application/x-www-form-urlencoded} do
- creds = Util.decode_form_to_hash(request.body)
+ creds = Util.decode_form(request.body)
user = find_user(creds['username'], creds['password'])
reply.headers[:location] = "login"
reply.status = 302
@@ -118,7 +118,7 @@ def default_route; reply_in_kind(404, error: "not found", error_description: "un
end
route :get, %r{^/logout.do(\?|$)(.*)} do
- query = Util.decode_form_to_hash(match[2])
+ query = Util.decode_form(match[2])
reply.headers[:location] = query['redirect_uri'] || "login"
reply.status = 302
reply.set_cookie(:stubsession, encode_cookie, max_age: -1)
@@ -140,7 +140,7 @@ def token_reply_info(client, scope, user = nil, state = nil, refresh = false)
token_body[:email] = primary_email(user[:emails])
token_body[:user_name] = user[:username]
end
- info = { access_token: TokenCoder.encode(token_body, nil, nil, 'none'),
+ info = { access_token: TokenCoder.encode(token_body, :algorithm => 'none'),
token_type: "bearer", expires_in: interval, scope: scope}
info[:state] = state if state
info[:refresh_token] = "universal_refresh_token" if refresh
@@ -169,14 +169,14 @@ def valid_redir_uri?(client, redir_uri)
def redir_with_fragment(cburi, params)
reply.status = 302
uri = URI.parse(cburi)
- uri.fragment = URI.encode_www_form(params)
+ uri.fragment = Util.encode_form(params)
reply.headers[:location] = uri.to_s
end
def redir_with_query(cburi, params)
reply.status = 302
uri = URI.parse(cburi)
- uri.query = URI.encode_www_form(params)
+ uri.query = Util.encode_form(params)
reply.headers[:location] = uri.to_s
end
@@ -195,7 +195,7 @@ def calc_scope(client, user, requested_scope)
end
route [:post, :get], %r{^/oauth/authorize\?(.*)} do
- query = Util.decode_form_to_hash(match[1])
+ query = Util.decode_form(match[1])
client = server.scim.get_by_name(query["client_id"], :client)
cburi, state = query["redirect_uri"], query["state"]
@@ -209,7 +209,7 @@ def calc_scope(client, user, requested_scope)
end
if request.method == "post"
unless request.headers["content-type"] =~ %r{application/x-www-form-urlencoded} &&
- (creds = Util.decode_form_to_hash(request.body)) &&
+ (creds = Util.decode_form(request.body)) &&
creds["source"] && creds["source"] == "credentials"
return redir_err_f(cburi, state, "invalid_request")
end
@@ -275,7 +275,7 @@ def redeem_auth_code(client_id, redir_uri, code)
reply.headers[:www_authenticate] = "basic"
return reply.json(401, error: "invalid_client")
end
- return if bad_params?(params = Util.decode_form_to_hash(request.body), ['grant_type'])
+ return if bad_params?(params = Util.decode_form(request.body), ['grant_type'])
unless client[:authorized_grant_types].include?(params['grant_type'])
return reply.json(400, error: "unauthorized_client")
end
@@ -419,7 +419,7 @@ def page_query(rtype, query, attrs)
route :get, %r{^/(Users|Groups)(\?|$)(.*)} do
return unless valid_token("scim.read")
rtype = match[1] == "Users"? :user : :group
- page_query(rtype, Util.decode_form_to_hash(match[3], :down), StubScim::VISIBLE_ATTRS[rtype])
+ page_query(rtype, Util.decode_form(match[3], :down), StubScim::VISIBLE_ATTRS[rtype])
end
route :get, %r{^/(Users|Groups)/([^/]+)$} do
@@ -449,7 +449,7 @@ def page_query(rtype, query, attrs)
end
route :get, %r{^/ids/Users(\?|$)(.*)} do
- page_query(:user, Util.decode_form_to_hash(match[2], :down), [:username, :id])
+ page_query(:user, Util.decode_form(match[2], :down), [:username, :id])
end
end
@@ -459,7 +459,9 @@ class StubUAA < Stub::Server
attr_accessor :reply_badly
attr_reader :scim, :auto_groups
- def initialize(boot_client = "admin", boot_secret = "adminsecret", logger = Util.default_logger)
+ def initialize(options = {})
+ client = options[:boot_client] || "admin"
+ secret = options[:boot_secret] || "adminsecret"
@scim = StubScim.new
@auto_groups = ["password.write", "openid"]
.each_with_object([]) { |g, o| o << @scim.add(:group, 'displayname' => g) }
@@ -467,16 +469,17 @@ def initialize(boot_client = "admin", boot_secret = "adminsecret", logger = Util
.each { |g| @scim.add(:group, 'displayname' => g) }
gids = ["clients.write", "clients.read", "clients.secret", "uaa.admin"]
.each_with_object([]) { |s, o| o << @scim.add(:group, 'displayname' => s) }
- @scim.add(:client, 'client_id' => boot_client, 'client_secret' => boot_secret,
+ @scim.add(:client, 'client_id' => client, 'client_secret' => secret,
'authorized_grant_types' => ["client_credentials"], 'authorities' => gids,
'access_token_validity' => 60 * 60 * 24 * 7)
@scim.add(:client, 'client_id' => "vmc", 'authorized_grant_types' => ["implicit"],
'scope' => [@scim.id("openid", :group), @scim.id("password.write", :group)],
'access_token_validity' => 5 * 60 )
info = { commit_id: "not implemented",
- app: {name: "Stub UAA", version: CLI_VERSION, description: "User Account and Authentication Service, test server"},
+ app: {name: "Stub UAA", version: CLI_VERSION,
+ description: "User Account and Authentication Service, test server"},
prompts: {username: ["text", "Username"], password: ["password","Password"]} }
- super(StubUAAConn, logger, info)
+ super(StubUAAConn, options.merge(info: info, logger: options[:logger] || Util.default_logger))
end
end
View
2  spec/group_spec.rb
@@ -23,7 +23,7 @@ module CF::UAA
before :all do
#Util.default_logger(:trace)
Cli.configure("", nil, StringIO.new, true)
- setup_target(authorities: "clients.read,scim.read,scim.write")
+ setup_target(authorities: "clients.read,scim.read,scim.write,uaa.admin")
Cli.run("token client get #{@test_client} -s #{@test_secret}").should be
@test_user, @test_pwd = "sam_#{Time.now.to_i}", "correcthorsebatterystaple"
@test_group = "JaNiToRs_#{Time.now.to_i}"
View
5 spec/http_spec.rb
@@ -36,7 +36,8 @@ def get(target, path = nil, headers = {}) http_get(target, path, headers) end
include SpecHelper
before :all do
- @stub_http = Stub::Server.new(StubHttp, Util.default_logger(:info)).run_on_thread
+ #Util.default_logger(:trace)
+ @stub_http = Stub::Server.new(StubHttp, logger: Util.default_logger).run_on_thread
end
after :all do @stub_http.stop if @stub_http end
@@ -147,7 +148,7 @@ def debug(str = nil) ; @log << (str ? str : yield) end
raise BadTarget, "unable to resolve address" if /unable.*server.*address/.match result[1]
raise HTTPException, result[1]
end
- [result[0], result[1], Util.hash_keys!(result[2], :todash)]
+ [result[0], result[1], Util.hash_keys!(result[2], :dash)]
end
end
it_should_behave_like "http client"
View
6 spec/spec_helper.rb
@@ -51,14 +51,14 @@ def frequest(on_fiber, &blk)
def setup_target(opts = {})
opts = { authorities: "clients.read,scim.read,scim.write,uaa.resource",
- grant_types: "client_credentials,password",
+ grant_types: "client_credentials,password",
scope: "openid,password.write"}.update(opts)
@admin_client = ENV["UAA_CLIENT_ID"] || "admin"
@admin_secret = ENV["UAA_CLIENT_SECRET"] || "adminsecret"
if ENV["UAA_CLIENT_TARGET"]
@target, @stub_uaa = ENV["UAA_CLIENT_TARGET"], nil
else
- @stub_uaa = StubUAA.new(@admin_client, @admin_secret).run_on_thread
+ @stub_uaa = StubUAA.new(boot_client: @admin_client, boot_secret: @admin_secret).run_on_thread
@target = @stub_uaa.url
end
Cli.run("target #{@target}").should be
@@ -67,7 +67,7 @@ def setup_target(opts = {})
test_client = "test_client_#{Time.now.to_i}"
@test_secret = "+=tEsTsEcRet~!@"
Cli.run("client add #{test_client} -s #{@test_secret} " +
- "--authorities #{opts[:authorities]} --scope #{opts[:scope]} " +
+ "--authorities #{opts[:authorities]} --scope #{opts[:scope]} " +
"--authorized_grant_types #{opts[:grant_types]}").should be
opts.each { |k, a| Util.arglist(a).each {|v| Cli.output.string.should include(v) }}
@test_client = test_client
View
2  spec/token_spec.rb
@@ -28,7 +28,7 @@ module CF::UAA
Config.yaml.should include("access_token")
@test_pwd = "TesTpwd$%^"
@test_user = "tEst_UseR+-#{Time.now.to_i}"
- Cli.run("user add #{@test_user} -p #{@test_pwd} " +
+ Cli.run("user add #{@test_user} -p #{@test_pwd} " +
"--emails sam@example.com,joNES@sample.com --given_name SamueL " +
"--phones 801-555-1212 --family_name jonES").should be
end
Please sign in to comment.
Something went wrong with that request. Please try again.