Esempio n. 1
0
        private void Init(IPrivateKeySource keySource)
        {
            CheckId = Guid.NewGuid();

            this.jwtHelper = JwtTokenHelper.CreateGitHubJwtFactory(
                keySource,
                int.Parse(GitScanAppConfig.GetValue(Constants.GlobalSection, Constants.GitHubAppIdKey)));

            gitHubInstallationClient = this.CreateGitHubInstallationClientAsync().Result;
        }
Esempio n. 2
0
        private IGitHubClient CreateGitHubAppClient()
        {
            this.appTokenExpirationTime = DateTime.UtcNow.AddSeconds(CheckSuiteRequestHandler.maxAppTokenValidityTimeInSeconds);
            string        jwtToken    = this.CreateAppToken();
            Credentials   credentials = new Credentials(jwtToken, AuthenticationType.Bearer);
            IGitHubClient client      = new GitHubClient(new ProductHeaderValue(GitScanAppConfig.GetValue(Constants.GlobalSection, Constants.AppNameKey)))
            {
                Credentials = credentials
            };

            return(client);
        }
Esempio n. 3
0
        private async Task <IGitHubClient> CreateGitHubInstallationClientAsync()
        {
            AccessToken accessToken = await this.CreateIntallationToken().ConfigureAwait(false);

            this.installationTokenExpirationTime = accessToken.ExpiresAt.UtcDateTime;

            // Create a new GitHubClient using the installation token as authentication
            var installationClient = new GitHubClient(new ProductHeaderValue($"{GitScanAppConfig.GetValue(Constants.GlobalSection, Constants.AppNameKey)}{GithubInstallationId}"))
            {
                Credentials = new Credentials(accessToken.Token)
            };

            return(installationClient);
        }
Esempio n. 4
0
        private string GetOauthLoginUrl()
        {
            string csrf = Membership.GeneratePassword(24, 1);

            Session["CSRF:State"] = csrf;
            // 1. Redirect users to request GitHub access
            var request = new OauthLoginRequest(GitScanAppConfig.GetValue(Constants.GlobalSection, Constants.ClientIdKey))
            {
                Scopes = { "repo" },
                State  = csrf
            };
            var oauthLoginUrl = GetGitHubClient().Oauth.GetGitHubLoginUrl(request);

            return(oauthLoginUrl.ToString());
        }
Esempio n. 5
0
        public static async Task <string> UploadBufferToStorage(byte[] buffer, string blobName)
        {
            try
            {
                string storageConnectionString = GitScanAppConfig.GetValue(Constants.StorageSection, Constants.ConnectionStringKey);

                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
                CloudBlobClient     serviceClient  = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer  container      = serviceClient.GetContainerReference("scanfiles");
                container.CreateIfNotExists();
                CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
                using (var stream = new MemoryStream(buffer, writable: false))
                {
                    await blob.UploadFromStreamAsync(stream);
                }

                //Create an ad-hoc Shared Access Policy with read permissions which will expire in 12 hours
                SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
                {
                    Permissions            = SharedAccessBlobPermissions.Read,
                    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(12),
                };

                //Set content-disposition header for force download
                SharedAccessBlobHeaders headers = new SharedAccessBlobHeaders()
                {
                    ContentDisposition = $"attachment;filename=\"{blobName}.zip\"",
                };
                var sasToken = blob.GetSharedAccessSignature(policy, headers);

                //// For test only
                //WebClient webClient = new WebClient();
                //byte[] response = await webClient.DownloadDataTaskAsync(blob.Uri.AbsoluteUri + sasToken);
                //webClient.Dispose();

                return(blob.Uri.AbsoluteUri + sasToken);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Esempio n. 6
0
        // This is the Callback URL that the GitHub OAuth Login page will redirect back to.h
        public async Task <ActionResult> Authorize(string code, string state)
        {
            if (!String.IsNullOrEmpty(code))
            {
                var expectedState = Session["CSRF:State"] as string;
                if (state != expectedState)
                {
                    throw new InvalidOperationException("SECURITY FAIL!");
                }
                Session["CSRF:State"] = null;

                var token = await GetGitHubClient().Oauth.CreateAccessToken(
                    new OauthTokenRequest(
                        GitScanAppConfig.GetValue(Constants.GlobalSection, Constants.ClientIdKey),
                        GitScanAppConfig.GetValue(Constants.GlobalSection, Constants.ClientSecretKey),
                        code));

                Session["OAuthToken"] = token.AccessToken;
            }
            return(RedirectToAction("List"));
        }
Esempio n. 7
0
        public ActionResult Default()
        {
            string actionName = Request.Headers.Get("X-GITHUB-EVENT");

            // Only the below events will be handled
            if (!actionName.Equals("check_suite", StringComparison.InvariantCultureIgnoreCase) &&
                !actionName.Equals("check_run", StringComparison.InvariantCultureIgnoreCase) &&
                !actionName.Equals("pull_request", StringComparison.InvariantCultureIgnoreCase))
            {
                return(new HttpStatusCodeResult(200));
            }

            // Obtain the body signature
            string messageSignature = Request.Headers.Get("X-HUB-Signature");

            if (string.IsNullOrEmpty(messageSignature))
            {
                return(new HttpStatusCodeResult(400));
            }

            // Read the body
            string body = GetRequestPostData(Request);

            // Validate message integrity
            if (!RequestPayloadHelper.ValidateSender(body, messageSignature, GitScanAppConfig.GetValue(Constants.GlobalSection, Constants.GitHubAppWebhookSecretKey)))
            {
                return(new HttpStatusCodeResult(400));
            }

            Guid requestId = Guid.NewGuid();

            if (actionName.Equals("check_run", StringComparison.InvariantCultureIgnoreCase))
            {
                CheckRunEventPayload checkRunPayload = RequestPayloadHelper.Parse <CheckRunEventPayload>(body);

                if (checkRunPayload.Action.Equals("rerequested", StringComparison.InvariantCultureIgnoreCase))
                {
                    CheckSuiteRequestHandler handler = new CheckSuiteRequestHandler(checkRunPayload, PrivateKeySource.Value, requestId);
                    handler.Go();
                    return(new HttpStatusCodeResult(200));
                }
                else
                {
                    return(new HttpStatusCodeResult(200));
                }
            }

            if (actionName.Equals("pull_request", StringComparison.InvariantCultureIgnoreCase))
            {
                PullRequestEventPayload pullPayload = RequestPayloadHelper.Parse <PullRequestEventPayload>(body);
                if (pullPayload.Action.Equals("opened", StringComparison.InvariantCultureIgnoreCase))
                {
                    CheckSuiteRequestHandler handler = new CheckSuiteRequestHandler(pullPayload, PrivateKeySource.Value, requestId);
                    handler.Go().Wait();
                    return(new HttpStatusCodeResult(200));
                }
                else
                {
                    return(new HttpStatusCodeResult(200));
                }
            }

            CheckSuiteEventPayload payload = RequestPayloadHelper.Parse(body);

            if (!payload.Action.Equals("rerequested", StringComparison.OrdinalIgnoreCase) &&
                (payload.CheckSuite.PullRequests == null || payload.CheckSuite.PullRequests.Count == 0))
            {
                return(new HttpStatusCodeResult(200));
            }

            if (!payload.Action.Equals("completed", StringComparison.OrdinalIgnoreCase))
            {
                CheckSuiteRequestHandler handler = new CheckSuiteRequestHandler(payload, PrivateKeySource.Value, requestId);
                handler.Go();
            }

            return(new HttpStatusCodeResult(200));
        }