summaryrefslogtreecommitdiff
path: root/app/models/api_token.rb
diff options
context:
space:
mode:
authorelijah <elijah@riseup.net>2016-03-20 01:13:24 -0700
committerelijah <elijah@riseup.net>2016-03-28 16:03:54 -0700
commitc63791c7ffacb7c6cfc685e2654ffe66f0a6b185 (patch)
treebe68b1c5906d06f2669e102d99ea6ca02b7d2856 /app/models/api_token.rb
parentef5f9636863a8bddb704714027c6540dc5a0b781 (diff)
api tokens: allow for special api tokens that work like session tokens but are configured in the static config, to be used for infrastructure monitoring.
Diffstat (limited to 'app/models/api_token.rb')
-rw-r--r--app/models/api_token.rb76
1 files changed, 76 insertions, 0 deletions
diff --git a/app/models/api_token.rb b/app/models/api_token.rb
new file mode 100644
index 0000000..49b1870
--- /dev/null
+++ b/app/models/api_token.rb
@@ -0,0 +1,76 @@
+#
+# Works like a regular authentication Token, but is configured in the conf file for
+# use by admins or testing.
+#
+# This is not actually a model, but it used in the place of the normal Token model
+# when appropriate
+#
+
+require 'digest/sha2'
+
+class ApiToken
+
+ #
+ # Searches static config to see if there is a matching api token string.
+ # Return an ApiToken if successful, or nil otherwise.
+ #
+ def self.find_by_token(token)
+ if APP_CONFIG["api_tokens"].nil? || APP_CONFIG["api_tokens"].empty?
+ # no api auth tokens are configured
+ return nil
+ elsif !token.is_a?(String) || token.size < 24
+ # don't allow obviously invalid token strings
+ return nil
+ else
+ token_digest = Digest::SHA512.hexdigest(token)
+ username = self.static_auth_tokens[token_digest]
+ if username
+ if username == "test"
+ return ApiTestToken.new
+ elsif username == "admin"
+ # not yet supported
+ return nil
+ end
+ else
+ return nil
+ end
+ end
+ end
+
+ private
+
+ #
+ # A static hash to represent the configured api auth tokens, in the form:
+ #
+ # {
+ # "<sha521 of token>" => "<username>"
+ # }
+ #
+ # SHA512 is used here in order to prevent an attacker from discovering
+ # the value for an auth token by measuring the string comparison time.
+ #
+ def self.static_auth_tokens
+ @static_auth_tokens ||= APP_CONFIG["api_tokens"].inject({}) {|hsh, entry|
+ hsh[Digest::SHA512.hexdigest(entry[1])] = entry[0]
+ hsh
+ }.freeze
+ end
+
+end
+
+class ApiAdminToken < Token
+ # not yet supported
+ #def authenticate
+ # AdminUser.new
+ #end
+end
+
+#
+# These tokens used by the platform to run regular monitor tests
+# of a production infrastructure.
+#
+class ApiTestToken < Token
+ def authenticate
+ ApiTestUser.new
+ end
+end