<commit_before>// ----------------------------------------------------------------------------------
// 
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Management.RecoveryServices.Models;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery;
using Microsoft.Azure.Portal.RecoveryServices.Models.Common;
using Newtonsoft.Json;
using Formatting = System.Xml.Formatting;

namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
    /// <summary>
    ///     Recovery services convenience client.
    /// </summary>
    public partial class PSRecoveryServicesClient
    {
        /// <summary>
        ///     Amount of time to sleep before fetching job details again.
        /// </summary>
        public const int TimeToSleepBeforeFetchingJobDetailsAgain = 30000;

        /// <summary>
        ///     Resource credentials holds vault, cloud service name, vault key and other details.
        /// </summary>
        [SuppressMessage(
            "Microsoft.StyleCop.CSharp.MaintainabilityRules",
            "SA1401:FieldsMustBePrivate",
            Justification = "For Resource Credentials.")]
        public static ASRVaultCreds asrVaultCreds = new ASRVaultCreds();

        private static AzureContext AzureContext;

        /// <summary>
        ///     Subscription Cloud credentials
        /// </summary>
        private static SubscriptionCloudCredentials cloudCredentials;

        /// <summary>
        ///     End point Uri
        /// </summary>
        private static Uri endPointUri;

        public static string idPrefixtillvaultName = string.Empty;

        /// <summary>
        ///     Recovery services vault management client.
        /// </summary>
        private readonly RecoveryServicesClient recoveryServicesVaultClient;

        /// <summary>
        ///     Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with
        ///     required current subscription.
        /// </summary>
        /// <param name="azureSubscription">Azure Subscription</param>
        public PSRecoveryServicesClient(
            IAzureContextContainer azureProfile)
        {
            AzureContext = (AzureContext)azureProfile.DefaultContext;

            var resourceNamespace = ARMResourceTypeConstants
                .RecoveryServicesResourceProviderNameSpace;
            var resourceType = ARMResourceTypeConstants.RecoveryServicesVault;

            // Get Resource provider namespace and type from config only if Vault context is not set
            // (hopefully it is required only for Vault related cmdlets)
            if (string.IsNullOrEmpty(asrVaultCreds.ResourceNamespace) ||
                string.IsNullOrEmpty(asrVaultCreds.ARMResourceType))
            {
                Utilities.UpdateCurrentVaultContext(
                    new ASRVaultCreds
                    {
                        ResourceNamespace = resourceNamespace,
                        ARMResourceType = resourceType
                    });
            }

            if (null == endPointUri)
            {
                endPointUri =
                    azureProfile.DefaultContext.Environment.GetEndpointAsUri(
                        AzureEnvironment.Endpoint.ResourceManager);
            }

            cloudCredentials = AzureSession.Instance.AuthenticationFactory
                .GetSubscriptionCloudCredentials(azureProfile.DefaultContext);
            this.recoveryServicesVaultClient = AzureSession.Instance.ClientFactory
                .CreateArmClient<RecoveryServicesClient>(
                    AzureContext,
                    AzureEnvironment.Endpoint.ResourceManager);
        }

        /// <summary>
        ///     client request id.
        /// </summary>
        public string ClientRequestId { get; set; }

        /// <summary>
        ///     Gets the value of recovery services vault management client.
        /// </summary>
        public RecoveryServicesClient GetRecoveryServicesVaultClient => this
            .recoveryServicesVaultClient;

        /// <summary>
        ///     Site Recovery requests that go to on-premise components (like the Provider installed
        ///     in VMM) require an authentication token that is signed with the vault key to indicate
        ///     that the request indeed originated from the end-user client.
        ///     Generating that authentication token here and sending it via http headers.
        /// </summary>
        /// <param name="clientRequestId">Unique identifier for the client's request</param>
        /// <returns>The authentication token for the provider</returns>
        public string GenerateAgentAuthenticationHeader(
            string clientRequestId)
        {
            var cikTokenDetails = new CikTokenDetails();

            var currentDateTime = DateTime.Now;
            currentDateTime = currentDateTime.AddHours(-1);
            cikTokenDetails.NotBeforeTimestamp = TimeZoneInfo.ConvertTimeToUtc(currentDateTime);
            cikTokenDetails.NotAfterTimestamp = cikTokenDetails.NotBeforeTimestamp.AddDays(7);
            cikTokenDetails.ClientRequestId = clientRequestId;
            cikTokenDetails.Version = new Version(
                1,
                2);
            cikTokenDetails.PropertyBag = new Dictionary<string, object>();

            var shaInput = JsonConvert.SerializeObject(cikTokenDetails);

            if (null == asrVaultCreds.ChannelIntegrityKey)
            {
                throw new ArgumentException(Resources.MissingChannelIntergrityKey);
            }

            var sha = new HMACSHA256(Encoding.UTF8.GetBytes(asrVaultCreds.ChannelIntegrityKey));
            cikTokenDetails.Hmac =
                Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(shaInput)));
            cikTokenDetails.HashFunction = CikSupportedHashFunctions.HMACSHA256.ToString();

            return JsonConvert.SerializeObject(cikTokenDetails);
        }

        /// <summary>
        ///     Get extendVault Info.
        /// </summary>
        /// <param name="vaultResourceGroupName">Vault ResourceGroup Name</param>
        /// <param name="vaultName">Vault Name</param>
        /// <returns>VaultExtendedInfo Resource Object</returns>
        public VaultExtendedInfoResource GetVaultExtendedInfo(String vaultResourceGroupName, String vaultName)
        {
            return this.recoveryServicesVaultClient
                .VaultExtendedInfo
                .GetWithHttpMessagesAsync(vaultResourceGroupName, vaultName, this.GetRequestHeaders(false))
                .GetAwaiter()
                .GetResult()
                .Body;
        }

        public static string GetJobIdFromReponseLocation(
            string responseLocation)
        {
            const string operationResults = "operationresults";
<commit_msg>CIK token push<commit_after>// ----------------------------------------------------------------------------------
// 
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Management.RecoveryServices.Models;
using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery;
using Microsoft.Azure.Portal.RecoveryServices.Models.Common;
using Newtonsoft.Json;
using Formatting = System.Xml.Formatting;

namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
    /// <summary>
    ///     Recovery services convenience client.
    /// </summary>
    public partial class PSRecoveryServicesClient
    {
        /// <summary>
        ///     Amount of time to sleep before fetching job details again.
        /// </summary>
        public const int TimeToSleepBeforeFetchingJobDetailsAgain = 30000;

        /// <summary>
        ///     Resource credentials holds vault, cloud service name, vault key and other details.
        /// </summary>
        [SuppressMessage(
            "Microsoft.StyleCop.CSharp.MaintainabilityRules",
            "SA1401:FieldsMustBePrivate",
            Justification = "For Resource Credentials.")]
        public static ASRVaultCreds asrVaultCreds = new ASRVaultCreds();

        private static AzureContext AzureContext;

        /// <summary>
        ///     Subscription Cloud credentials
        /// </summary>
        private static SubscriptionCloudCredentials cloudCredentials;

        /// <summary>
        ///     End point Uri
        /// </summary>
        private static Uri endPointUri;

        public static string idPrefixtillvaultName = string.Empty;

        /// <summary>
        ///     Recovery services vault management client.
        /// </summary>
        private readonly RecoveryServicesClient recoveryServicesVaultClient;

        /// <summary>
        ///     Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with
        ///     required current subscription.
        /// </summary>
        /// <param name="azureSubscription">Azure Subscription</param>
        public PSRecoveryServicesClient(
            IAzureContextContainer azureProfile)
        {
            AzureContext = (AzureContext)azureProfile.DefaultContext;

            var resourceNamespace = ARMResourceTypeConstants
                .RecoveryServicesResourceProviderNameSpace;
            var resourceType = ARMResourceTypeConstants.RecoveryServicesVault;

            // Get Resource provider namespace and type from config only if Vault context is not set
            // (hopefully it is required only for Vault related cmdlets)
            if (string.IsNullOrEmpty(asrVaultCreds.ResourceNamespace) ||
                string.IsNullOrEmpty(asrVaultCreds.ARMResourceType))
            {
                Utilities.UpdateCurrentVaultContext(
                    new ASRVaultCreds
                    {
                        ResourceNamespace = resourceNamespace,
                        ARMResourceType = resourceType
                    });
            }

            if (null == endPointUri)
            {
                endPointUri =
                    azureProfile.DefaultContext.Environment.GetEndpointAsUri(
                        AzureEnvironment.Endpoint.ResourceManager);
            }

            cloudCredentials = AzureSession.Instance.AuthenticationFactory
                .GetSubscriptionCloudCredentials(azureProfile.DefaultContext);
            this.recoveryServicesVaultClient = AzureSession.Instance.ClientFactory
                .CreateArmClient<RecoveryServicesClient>(
                    AzureContext,
                    AzureEnvironment.Endpoint.ResourceManager);
        }

        /// <summary>
        ///     client request id.
        /// </summary>
        public string ClientRequestId { get; set; }

        /// <summary>
        ///     Gets the value of recovery services vault management client.
        /// </summary>
        public RecoveryServicesClient GetRecoveryServicesVaultClient => this
            .recoveryServicesVaultClient;

        /// <summary>
        ///     Site Recovery requests that go to on-premise components (like the Provider installed
        ///     in VMM) require an authentication token that is signed with the vault key to indicate
        ///     that the request indeed originated from the end-user client.
        ///     Generating that authentication token here and sending it via http headers.
        /// </summary>
        /// <param name="clientRequestId">Unique identifier for the client's request</param>
        /// <returns>The authentication token for the provider</returns>
        public string GenerateAgentAuthenticationHeader(
            string clientRequestId)
        {
            var cikTokenDetails = new CikTokenDetails();

            var currentDateTime = DateTime.Now;
            currentDateTime = currentDateTime.AddHours(-1);
            cikTokenDetails.NotBeforeTimestamp = TimeZoneInfo.ConvertTimeToUtc(currentDateTime);
            cikTokenDetails.NotAfterTimestamp = cikTokenDetails.NotBeforeTimestamp.AddDays(7);
            cikTokenDetails.ClientRequestId = clientRequestId;
            cikTokenDetails.Version = new Version(
                1,
                2);
            cikTokenDetails.PropertyBag = new Dictionary<string, object>();

            var shaInput = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(cikTokenDetails);

            if (null == asrVaultCreds.ChannelIntegrityKey)
            {
                throw new ArgumentException(Resources.MissingChannelIntergrityKey);
            }

            var sha = new HMACSHA256(Encoding.UTF8.GetBytes(asrVaultCreds.ChannelIntegrityKey));
            cikTokenDetails.Hmac =
                Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(shaInput)));
            cikTokenDetails.HashFunction = CikSupportedHashFunctions.HMACSHA256.ToString();

            return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(cikTokenDetails);
        }

        /// <summary>
        ///     Get extendVault Info.
        /// </summary>
        /// <param name="vaultResourceGroupName">Vault ResourceGroup Name</param>
        /// <param name="vaultName">Vault Name</param>
        /// <returns>VaultExtendedInfo Resource Object</returns>
        public VaultExtendedInfoResource GetVaultExtendedInfo(String vaultResourceGroupName, String vaultName)
        {
            return this.recoveryServicesVaultClient
                .VaultExtendedInfo
                .GetWithHttpMessagesAsync(vaultResourceGroupName, vaultName, this.GetRequestHeaders(false))
                .GetAwaiter()
                .GetResult()
                .Body;
        }

        public static string GetJobIdFromReponseLocation(
            string responseLocation)
        {
            const string operationResults = "operationresults";

{'fraction_non_alphanumeric': 0.09856262833675565, 'fraction_numerical': 0.0037334328915437746, 'mean_word_length': 2.1569436260066785, 'pattern_counts': {'":': 0, '<': 77, '<?xml version=': 0, '>': 79, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1225787', 'n_tokens_mistral': 3734, 'n_tokens_neox': 3613, 'n_words': 944}