Add CallCredentials class to Ruby wrapping code
diff --git a/src/ruby/ext/grpc/rb_call.c b/src/ruby/ext/grpc/rb_call.c
index 4036432..1647d9b 100644
--- a/src/ruby/ext/grpc/rb_call.c
+++ b/src/ruby/ext/grpc/rb_call.c
@@ -39,6 +39,7 @@
 #include <grpc/support/alloc.h>
 
 #include "rb_byte_buffer.h"
+#include "rb_call_credentials.h"
 #include "rb_completion_queue.h"
 #include "rb_grpc.h"
 
@@ -279,6 +280,26 @@
   return rb_ivar_set(self, id_write_flag, write_flag);
 }
 
+/*
+  call-seq:
+  call.set_credentials call_credentials
+
+  Sets credentials on a call */
+static VALUE grpc_rb_call_set_credentials(VALUE self, VALUE credentials) {
+  grpc_call *call = NULL;
+  grpc_call_credentials *creds;
+  grpc_call_error err;
+  TypedData_Get_Struct(self, grpc_call, &grpc_call_data_type, call);
+  creds = grpc_rb_get_wrapped_call_credentials(credentials);
+  err = grpc_call_set_credentials(call, creds);
+  if (err != GRPC_CALL_OK) {
+    rb_raise(grpc_rb_eCallError,
+             "grpc_call_set_credentials failed with %s (code=%d)",
+             grpc_call_error_detail_of(err), err);
+  }
+  return Qnil;
+}
+
 /* grpc_rb_md_ary_fill_hash_cb is the hash iteration callback used
    to fill grpc_metadata_array.
 
@@ -347,7 +368,7 @@
 /* grpc_rb_md_ary_convert converts a ruby metadata hash into
    a grpc_metadata_array.
 */
-static void grpc_rb_md_ary_convert(VALUE md_ary_hash,
+void grpc_rb_md_ary_convert(VALUE md_ary_hash,
                                    grpc_metadata_array *md_ary) {
   VALUE md_ary_obj = Qnil;
   if (md_ary_hash == Qnil) {
@@ -795,6 +816,8 @@
   rb_define_method(grpc_rb_cCall, "write_flag", grpc_rb_call_get_write_flag, 0);
   rb_define_method(grpc_rb_cCall, "write_flag=", grpc_rb_call_set_write_flag,
                    1);
+  rb_define_method(grpc_rb_cCall, "set_credentials!",
+                   grpc_rb_call_set_credentials, 1);
 
   /* Ids used to support call attributes */
   id_metadata = rb_intern("metadata");
diff --git a/src/ruby/ext/grpc/rb_call.h b/src/ruby/ext/grpc/rb_call.h
index 1d2fbc3..24adb34 100644
--- a/src/ruby/ext/grpc/rb_call.h
+++ b/src/ruby/ext/grpc/rb_call.h
@@ -50,6 +50,12 @@
 /* Converts a metadata array to a hash. */
 VALUE grpc_rb_md_ary_to_h(grpc_metadata_array *md_ary);
 
+/* grpc_rb_md_ary_convert converts a ruby metadata hash into
+   a grpc_metadata_array.
+*/
+void grpc_rb_md_ary_convert(VALUE md_ary_hash,
+                            grpc_metadata_array *md_ary);
+
 /* grpc_rb_eCallError is the ruby class of the exception thrown during call
    operations. */
 extern VALUE grpc_rb_eCallError;
diff --git a/src/ruby/ext/grpc/rb_call_credentials.c b/src/ruby/ext/grpc/rb_call_credentials.c
new file mode 100644
index 0000000..d8c8000
--- /dev/null
+++ b/src/ruby/ext/grpc/rb_call_credentials.c
@@ -0,0 +1,305 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "rb_call_credentials.h"
+
+#include <ruby/ruby.h>
+#include <ruby/thread.h>
+
+#include <grpc/grpc.h>
+#include <grpc/grpc_security.h>
+
+#include "rb_call.h"
+#include "rb_grpc.h"
+
+/* grpc_rb_cCallCredentials is the ruby class that proxies
+ * grpc_call_credentials */
+static VALUE grpc_rb_cCallCredentials = Qnil;
+
+/* grpc_rb_call_credentials wraps a grpc_call_credentials. It provides a peer
+ * ruby object, 'mark' to minimize copying when a credential is created from
+ * ruby. */
+typedef struct grpc_rb_call_credentials {
+  /* Holder of ruby objects involved in contructing the credentials */
+  VALUE mark;
+
+  /* The actual credentials */
+  grpc_call_credentials *wrapped;
+} grpc_rb_call_credentials;
+
+typedef struct callback_params {
+  VALUE get_metadata;
+  grpc_auth_metadata_context context;
+  void *user_data;
+  grpc_credentials_plugin_metadata_cb callback;
+} callback_params;
+
+static VALUE grpc_rb_call_credentials_callback(VALUE callback_args) {
+  VALUE result = rb_hash_new();
+  VALUE empty_md = rb_hash_new();
+  VALUE metadata = rb_funcall(rb_ary_entry(callback_args, 0), rb_intern("call"),
+                              2, empty_md, rb_ary_entry(callback_args, 1));
+  rb_hash_aset(result, rb_str_new2("metadata"), metadata);
+  rb_hash_aset(result, rb_str_new2("status"), INT2NUM(GRPC_STATUS_OK));
+  rb_hash_aset(result, rb_str_new2("details"), rb_str_new2(""));
+  return result;
+}
+
+static VALUE grpc_rb_call_credentials_callback_rescue(VALUE args,
+                                                      VALUE exception_object) {
+  VALUE result = rb_hash_new();
+  rb_hash_aset(result, rb_str_new2("metadata"), Qnil);
+  /* Currently only gives the exception class name. It should be possible get
+     more details */
+  rb_hash_aset(result, rb_str_new2("status"),
+               INT2NUM(GRPC_STATUS_PERMISSION_DENIED));
+  rb_hash_aset(result, rb_str_new2("details"),
+               rb_str_new2(rb_obj_classname(exception_object)));
+  return result;
+}
+
+static void *grpc_rb_call_credentials_callback_with_gil(void *param) {
+  callback_params *const params = (callback_params *)param;
+  VALUE auth_uri = rb_str_new_cstr(params->context.service_url);
+  /* Pass the arguments to the proc in a hash, which currently only has they key
+     'auth_uri' */
+  VALUE callback_args = rb_ary_new();
+  VALUE args = rb_hash_new();
+  VALUE result;
+  grpc_metadata_array md_ary;
+  grpc_status_code status;
+  VALUE details;
+  char *error_details;
+  grpc_metadata_array_init(&md_ary);
+  rb_hash_aset(args, rb_str_new2("jwt_aud_uri"), auth_uri);
+  rb_ary_push(callback_args, params->get_metadata);
+  rb_ary_push(callback_args, args);
+  result = rb_rescue(grpc_rb_call_credentials_callback, callback_args,
+                     grpc_rb_call_credentials_callback_rescue, Qnil);
+  // Both callbacks return a hash, so result should be a hash
+  grpc_rb_md_ary_convert(rb_hash_aref(result, rb_str_new2("metadata")), &md_ary);
+  status = NUM2INT(rb_hash_aref(result, rb_str_new2("status")));
+  details = rb_hash_aref(result, rb_str_new2("details"));
+  error_details = StringValueCStr(details);
+
+  params->callback(params->user_data, md_ary.metadata, md_ary.count, status,
+                   error_details);
+  grpc_metadata_array_destroy(&md_ary);
+
+  return NULL;
+}
+
+static void grpc_rb_call_credentials_plugin_get_metadata(
+    void *state, grpc_auth_metadata_context context,
+    grpc_credentials_plugin_metadata_cb cb, void *user_data) {
+  callback_params params;
+  params.get_metadata = (VALUE)state;
+  params.context = context;
+  params.user_data = user_data;
+  params.callback = cb;
+
+  rb_thread_call_with_gvl(grpc_rb_call_credentials_callback_with_gil,
+                          (void*)(&params));
+}
+
+static void grpc_rb_call_credentials_plugin_destroy(void *state) {
+  // Not sure what needs to be done here
+}
+
+/* Destroys the credentials instances. */
+static void grpc_rb_call_credentials_free(void *p) {
+  grpc_rb_call_credentials *wrapper;
+  if (p == NULL) {
+    return;
+  }
+  wrapper = (grpc_rb_call_credentials *)p;
+
+  /* Delete the wrapped object if the mark object is Qnil, which indicates that
+   * no other object is the actual owner. */
+  if (wrapper->wrapped != NULL && wrapper->mark == Qnil) {
+    grpc_call_credentials_release(wrapper->wrapped);
+    wrapper->wrapped = NULL;
+  }
+
+  xfree(p);
+}
+
+/* Protects the mark object from GC */
+static void grpc_rb_call_credentials_mark(void *p) {
+  grpc_rb_call_credentials *wrapper = NULL;
+  if (p == NULL) {
+    return;
+  }
+  wrapper = (grpc_rb_call_credentials *)p;
+
+  /* If it's not already cleaned up, mark the mark object */
+  if (wrapper->mark != Qnil) {
+    rb_gc_mark(wrapper->mark);
+  }
+}
+
+static rb_data_type_t grpc_rb_call_credentials_data_type = {
+  "grpc_call_credentials",
+  {grpc_rb_call_credentials_mark, grpc_rb_call_credentials_free,
+   GRPC_RB_MEMSIZE_UNAVAILABLE, {NULL, NULL}},
+  NULL,
+  NULL,
+#ifdef RUBY_TYPED_FREE_IMMEDIATELY
+  RUBY_TYPED_FREE_IMMEDIATELY
+#endif
+};
+
+/* Creates a wrapping object for a given call credentials. This should only be
+ * called with grpc_call_credentials objects that are not already associated
+ * with any Ruby object */
+VALUE grpc_rb_wrap_call_credentials(grpc_call_credentials *c) {
+  if (c == NULL) {
+    return Qnil;
+  }
+  return TypedData_Wrap_Struct(grpc_rb_cCallCredentials,
+                               &grpc_rb_call_credentials_data_type, c);
+}
+
+/* Allocates CallCredentials instances.
+   Provides safe initial defaults for the instance fields. */
+static VALUE grpc_rb_call_credentials_alloc(VALUE cls) {
+  grpc_rb_call_credentials *wrapper = ALLOC(grpc_rb_call_credentials);
+  wrapper->wrapped = NULL;
+  wrapper->mark = Qnil;
+  return TypedData_Wrap_Struct(cls, &grpc_rb_call_credentials_data_type, wrapper);
+}
+
+/* Clones CallCredentials instances.
+   Gives CallCredentials a consistent implementation of Ruby's object copy/dup
+   protocol. */
+static VALUE grpc_rb_call_credentials_init_copy(VALUE copy, VALUE orig) {
+  grpc_rb_call_credentials *orig_cred = NULL;
+  grpc_rb_call_credentials *copy_cred = NULL;
+
+  if (copy == orig) {
+    return copy;
+  }
+
+  /* Raise an error if orig is not a credentials object or a subclass. */
+  if (TYPE(orig) != T_DATA ||
+      RDATA(orig)->dfree != (RUBY_DATA_FUNC)grpc_rb_call_credentials_free) {
+    rb_raise(rb_eTypeError, "not a %s",
+             rb_obj_classname(grpc_rb_cCallCredentials));
+  }
+
+  TypedData_Get_Struct(orig, grpc_rb_call_credentials,
+                       &grpc_rb_call_credentials_data_type, orig_cred);
+  TypedData_Get_Struct(copy, grpc_rb_call_credentials,
+                       &grpc_rb_call_credentials_data_type, copy_cred);
+
+  /* use ruby's MEMCPY to make a byte-for-byte copy of the credentials
+   * wrapper object. */
+  MEMCPY(copy_cred, orig_cred, grpc_rb_call_credentials, 1);
+  return copy;
+}
+
+/* The attribute used on the mark object to hold the callback */
+static ID id_callback;
+
+/*
+  call-seq:
+    creds = Credentials.new auth_proc
+  proc: (required) Proc that generates auth metadata
+  Initializes CallCredential instances. */
+static VALUE grpc_rb_call_credentials_init(VALUE self, VALUE proc) {
+  grpc_rb_call_credentials *wrapper = NULL;
+  grpc_call_credentials *creds = NULL;
+  grpc_metadata_credentials_plugin plugin;
+
+  TypedData_Get_Struct(self, grpc_rb_call_credentials,
+                       &grpc_rb_call_credentials_data_type, wrapper);
+
+  plugin.get_metadata = grpc_rb_call_credentials_plugin_get_metadata;
+  plugin.destroy = grpc_rb_call_credentials_plugin_destroy;
+  plugin.state = (void*)proc;
+  plugin.type = "";
+
+  creds = grpc_metadata_credentials_create_from_plugin(plugin, NULL);
+  if (creds == NULL) {
+    rb_raise(rb_eRuntimeError, "could not create a credentials, not sure why");
+    return Qnil;
+  }
+
+  wrapper->wrapped = creds;
+  rb_ivar_set(self, id_callback, proc);
+
+  return self;
+}
+
+static VALUE grpc_rb_call_credentials_compose(int argc, VALUE *argv,
+                                              VALUE self) {
+  grpc_call_credentials *creds;
+  grpc_call_credentials *other;
+  if (argc == 0) {
+    return self;
+  }
+  creds = grpc_rb_get_wrapped_call_credentials(self);
+  for (int i = 0; i < argc; i++) {
+    other = grpc_rb_get_wrapped_call_credentials(argv[i]);
+    creds = grpc_composite_call_credentials_create(creds, other, NULL);
+  }
+  return grpc_rb_wrap_call_credentials(creds);
+}
+
+void Init_grpc_call_credentials() {
+  grpc_rb_cCallCredentials =
+      rb_define_class_under(grpc_rb_mGrpcCore, "CallCredentials", rb_cObject);
+
+  /* Allocates an object managed by the ruby runtime */
+  rb_define_alloc_func(grpc_rb_cCallCredentials,
+                       grpc_rb_call_credentials_alloc);
+
+  /* Provides a ruby constructor and support for dup/clone. */
+  rb_define_method(grpc_rb_cCallCredentials, "initialize",
+                   grpc_rb_call_credentials_init, 1);
+  rb_define_method(grpc_rb_cCallCredentials, "initialize_copy",
+                   grpc_rb_call_credentials_init_copy, 1);
+  rb_define_method(grpc_rb_cCallCredentials, "compose",
+                   grpc_rb_call_credentials_compose, -1);
+
+  id_callback = rb_intern("__callback");
+}
+
+/* Gets the wrapped grpc_call_credentials from the ruby wrapper */
+grpc_call_credentials *grpc_rb_get_wrapped_call_credentials(VALUE v) {
+  grpc_rb_call_credentials *wrapper = NULL;
+  TypedData_Get_Struct(v, grpc_rb_call_credentials,
+                       &grpc_rb_call_credentials_data_type,
+                       wrapper);
+  return wrapper->wrapped;
+}
diff --git a/src/ruby/ext/grpc/rb_call_credentials.h b/src/ruby/ext/grpc/rb_call_credentials.h
new file mode 100644
index 0000000..5350a8f
--- /dev/null
+++ b/src/ruby/ext/grpc/rb_call_credentials.h
@@ -0,0 +1,46 @@
+/*
+ *
+ * Copyright 2015, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_RB_CALL_CREDENTIALS_H_
+#define GRPC_RB_CALL_CREDENTIALS_H_
+
+#include <ruby/ruby.h>
+
+#include <grpc/grpc_security.h>
+
+/* Initializes the ruby CallCredentials class. */
+void Init_grpc_call_credentials();
+
+grpc_call_credentials* grpc_rb_get_wrapped_call_credentials(VALUE v);
+
+#endif /* GRPC_RB_CALL_CREDENTIALS_H_ */
diff --git a/src/ruby/ext/grpc/rb_channel_credentials.c b/src/ruby/ext/grpc/rb_channel_credentials.c
index 072a6f5..c883794 100644
--- a/src/ruby/ext/grpc/rb_channel_credentials.c
+++ b/src/ruby/ext/grpc/rb_channel_credentials.c
@@ -38,6 +38,7 @@
 #include <grpc/grpc.h>
 #include <grpc/grpc_security.h>
 
+#include "rb_call_credentials.h"
 #include "rb_grpc.h"
 
 /* grpc_rb_cChannelCredentials is the ruby class that proxies
@@ -98,6 +99,17 @@
 #endif
 };
 
+/* Creates a wrapping object for a given channel credentials. This should only
+ * be called with grpc_channel_credentials objects that are not already
+ * associated with any Ruby object. */
+VALUE grpc_rb_wrap_channel_credentials(grpc_channel_credentials *c) {
+  if (c == NULL) {
+    return Qnil;
+  }
+  return TypedData_Wrap_Struct(grpc_rb_cChannelCredentials,
+                               &grpc_rb_channel_credentials_data_type, c);
+}
+
 /* Allocates ChannelCredential instances.
    Provides safe initial defaults for the instance fields. */
 static VALUE grpc_rb_channel_credentials_alloc(VALUE cls) {
@@ -199,6 +211,21 @@
   return self;
 }
 
+static VALUE grpc_rb_channel_credentials_compose(int argc, VALUE *argv,
+                                                 VALUE self) {
+  grpc_channel_credentials *creds;
+  grpc_call_credentials *other;
+  if (argc == 0) {
+    return self;
+  }
+  creds = grpc_rb_get_wrapped_channel_credentials(self);
+  for (int i = 0; i < argc; i++) {
+    other = grpc_rb_get_wrapped_call_credentials(argv[i]);
+    creds = grpc_composite_channel_credentials_create(creds, other, NULL);
+  }
+  return grpc_rb_wrap_channel_credentials(creds);
+}
+
 void Init_grpc_channel_credentials() {
   grpc_rb_cChannelCredentials =
       rb_define_class_under(grpc_rb_mGrpcCore, "ChannelCredentials", rb_cObject);
@@ -212,6 +239,8 @@
                    grpc_rb_channel_credentials_init, -1);
   rb_define_method(grpc_rb_cChannelCredentials, "initialize_copy",
                    grpc_rb_channel_credentials_init_copy, 1);
+  rb_define_method(grpc_rb_cChannelCredentials, "compose",
+                   grpc_rb_channel_credentials_compose, -1);
 
   id_pem_cert_chain = rb_intern("__pem_cert_chain");
   id_pem_private_key = rb_intern("__pem_private_key");
diff --git a/src/ruby/ext/grpc/rb_grpc.c b/src/ruby/ext/grpc/rb_grpc.c
index 7c7c2d3..b4b7044 100644
--- a/src/ruby/ext/grpc/rb_grpc.c
+++ b/src/ruby/ext/grpc/rb_grpc.c
@@ -41,6 +41,7 @@
 #include <grpc/grpc.h>
 #include <grpc/support/time.h>
 #include "rb_call.h"
+#include "rb_call_credentials.h"
 #include "rb_channel.h"
 #include "rb_channel_credentials.h"
 #include "rb_completion_queue.h"
@@ -318,6 +319,7 @@
   Init_grpc_channel();
   Init_grpc_completion_queue();
   Init_grpc_call();
+  Init_grpc_call_credentials();
   Init_grpc_channel_credentials();
   Init_grpc_server();
   Init_grpc_server_credentials();