From 48623cff62ed10ea5658bcef19a91fc400344dd9 Mon Sep 17 00:00:00 2001 From: Chris Johnston Date: Mon, 20 Aug 2018 21:35:22 -0700 Subject: [PATCH] Add token validation to BaseDiscordClient#LoginAsync Adds a TokenUtils class which is used to validate that tokens are correct --- src/Discord.Net.Core/Utils/TokenUtils.cs | 46 +++++++++++++++++++++++ src/Discord.Net.Rest/BaseDiscordClient.cs | 5 +++ 2 files changed, 51 insertions(+) create mode 100644 src/Discord.Net.Core/Utils/TokenUtils.cs diff --git a/src/Discord.Net.Core/Utils/TokenUtils.cs b/src/Discord.Net.Core/Utils/TokenUtils.cs new file mode 100644 index 000000000..4d20a5659 --- /dev/null +++ b/src/Discord.Net.Core/Utils/TokenUtils.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Discord +{ + public static class TokenUtils + { + /// + /// Checks the validity of the supplied token of a specific type. + /// + /// The type of token to validate. + /// The token value to validate. + /// Thrown when the supplied token string is null, empty, or contains only whitespace. + /// Thrown when the supplied TokenType or token value is invalid. + public static void ValidateToken(TokenType tokenType, string token) + { + // A Null or WhiteSpace token of any type is invalid. + if (!string.IsNullOrWhiteSpace(token)) + throw new ArgumentNullException("A token cannot be null, empty, or contain only whitespace.", nameof(token)); + + switch (tokenType) + { + case TokenType.Webhook: + // no validation is performed on Webhook tokens + break; + case TokenType.Bearer: + // no validation is performed on Bearer tokens + break; + case TokenType.Bot: + // bot tokens are assumed to be at least 59 characters in length + // this value was determined by referencing examples in the discord documentation, and by comparing with + // pre-existing tokens + if (token.Length < 59) + throw new ArgumentException("A Bot token must be at least 59 characters in length.", nameof(token)); + break; + default: + // All unrecognized TokenTypes (including User tokens) are considered to be invalid. + throw new ArgumentException("Unrecognized TokenType.", nameof(token)); + } + } + + } +} diff --git a/src/Discord.Net.Rest/BaseDiscordClient.cs b/src/Discord.Net.Rest/BaseDiscordClient.cs index f8642b96c..99d19c233 100644 --- a/src/Discord.Net.Rest/BaseDiscordClient.cs +++ b/src/Discord.Net.Rest/BaseDiscordClient.cs @@ -52,6 +52,11 @@ namespace Discord.Rest /// public async Task LoginAsync(TokenType tokenType, string token, bool validateToken = true) { + // If token validation is enabled, validate the token and let it throw any ArgumentExceptions + // that result from invalid parameters + if (validateToken) + TokenUtils.ValidateToken(tokenType, token); + await _stateLock.WaitAsync().ConfigureAwait(false); try {