Example #1
0
        public List <string> Execute(object options)
        {
            AzmiArgumentsClass opt;

            try
            {
                opt = (AzmiArgumentsClass)options;
            } catch (Exception ex)
            {
                throw AzmiException.WrongObject(ex);
            }

            if (String.IsNullOrEmpty(opt.blob) && String.IsNullOrEmpty(opt.container))
            {
                throw new AzmiException("You must specify either blob or container url");
            }
            else if ((!String.IsNullOrEmpty(opt.blob)) && (!String.IsNullOrEmpty(opt.container)))
            {
                throw new AzmiException("Cannot use both container and blob url");
            }

            if (String.IsNullOrEmpty(opt.blob))
            {
                return(SetBlob.setBlob_byContainer(opt.file, opt.container, opt.identity, opt.force).ToStringList());
            }
            else
            {
                return(SetBlob.setBlob_byBlob(opt.file, opt.blob, opt.identity, opt.force).ToStringList());
            }
        }
Example #2
0
        //
        // Execute GetBlob
        //

        public string Execute(string blobURL, string filePath, string identity = null, bool ifNewer = false, bool deleteAfterCopy = false)
        {
            // method start

            // Connection
            var Cred       = new ManagedIdentityCredential(identity);
            var blobClient = new BlobClient(new Uri(blobURL), Cred);

            if (ifNewer && File.Exists(filePath) && !IsNewer(blobClient, filePath))
            {
                return("Skipped. Blob is not newer than file.");
            }

            try
            {
                string absolutePath = Path.GetFullPath(filePath);
                string dirName      = Path.GetDirectoryName(absolutePath);
                Directory.CreateDirectory(dirName);

                blobClient.DownloadTo(filePath);

                if (deleteAfterCopy)
                {
                    blobClient.Delete();
                }
                return("Success");
            } catch (Azure.RequestFailedException)
            {
                throw;
            } catch (Exception ex)
            {
                throw AzmiException.IDCheck(identity, ex);
            }
        }
Example #3
0
        //
        // execute GetSecret
        //

        public string Execute(string secretIdentifierUrl, string filePath = null, string identity = null)
        {
            (Uri keyVaultUri, string secretName, string secretVersion) = ValidateAndParseSecretURL(secretIdentifierUrl);

            var MIcredential = new ManagedIdentityCredential(identity);
            var secretClient = new SecretClient(keyVaultUri, MIcredential);

            // Retrieve a secret
            try
            {
                KeyVaultSecret secret      = secretClient.GetSecret(secretName, secretVersion);
                string         secretValue = secret.Value;

                if (String.IsNullOrEmpty(filePath))
                {   // print to stdout
                    return(secretValue);
                }
                else
                {   // creates or overwrites file and saves secret into it
                    File.WriteAllText(filePath, secretValue);
                    return("Saved");
                }
            } catch (Exception ex)
            {
                throw AzmiException.IDCheck(identity, ex);
            }
        }
Example #4
0
        //
        // execute GetCertificate
        //

        public string Execute(string certificateIdentifierUrl, string filePath = null, string identity = null)
        {
            (Uri keyVaultUri, string certificateName, string certificateVersion) = ValidateAndParseCertificateURL(certificateIdentifierUrl);

            var MIcredential      = new ManagedIdentityCredential(identity);
            var certificateClient = new CertificateClient(keyVaultUri, MIcredential);

            // Retrieve a certificate (certificate = certificate and private key bundle in Azure terminology)
            // PEM (Privacy Enhanced Mail) or PFX (Personal Information Exchange; PKCS#12 archive file format) formats
            // depends on what content type you set in Azure Key Vault at respective certificate.
            // Both formats usually contain a certificate (possibly with its assorted set of CA certificates) and the corresponding private key

            // Download CER format (X.509 certificate)
            // single certificate, alone and without any wrapping (no private key, no password protection, just the certificate)
            // not supported
            try
            {
                // certificate (and key) is stored as a secret at the end in Azure
                string secretIdentifierUrl;
                if (String.IsNullOrEmpty(certificateVersion))
                {
                    // certificate has no specific version:
                    // https://my-key-vault.vault.azure.net/certificates/readThisCertificate
                    KeyVaultCertificateWithPolicy certificateWithPolicy = certificateClient.GetCertificate(certificateName);
                    secretIdentifierUrl = certificateWithPolicy.SecretId.ToString();
                }
                else
                {
                    // certificate has specific version:
                    // https://my-key-vault.vault.azure.net/certificates/readThisCertificate/103a7355c6094bc78307b2db7b85b3c2
                    KeyVaultCertificate certificate = certificateClient.GetCertificateVersion(certificateName, certificateVersion);
                    secretIdentifierUrl = certificate.SecretId.ToString();
                }

                // filePath: null means get secret into variable only
                // otherwise secret may be unintentionally saved to file by GetSecret() method
                string secret = new GetSecret().Execute(secretIdentifierUrl, filePath: null, identity);

                if (String.IsNullOrEmpty(filePath))
                {   // print to stdout
                    return(secret);
                }
                else
                {   // creates or overwrites file and saves secret into it
                    File.WriteAllText(filePath, secret);
                    return("Saved");
                }
            }
            catch (Exception ex)
            {
                throw AzmiException.IDCheck(identity, ex);
            }
        }
Example #5
0
        public List <string> Execute(object options)
        {
            AzmiArgumentsClass opt;

            try
            {
                opt = (AzmiArgumentsClass)options;
            } catch (Exception ex)
            {
                throw AzmiException.WrongObject(ex);
            }

            return(Execute(opt.blob, opt.file, opt.identity, opt.ifNewer, opt.deleteAfterCopy).ToStringList());
        }
Example #6
0
        public List <string> Execute(object options)
        {
            AzmiArgumentsClass opt;

            try
            {
                opt = (AzmiArgumentsClass)options;
            } catch (Exception ex)
            {
                throw AzmiException.WrongObject(ex);
            }

            return(Execute(opt.endpoint, opt.identity, opt.jwtformat).ToStringList());
        }
Example #7
0
        public List <string> Execute(object options)
        {
            AzmiArgumentsClass opt;

            try
            {
                opt = (AzmiArgumentsClass)options;
            } catch (Exception ex)
            {
                throw AzmiException.WrongObject(ex);
            }

            return(Execute(opt.container, opt.identity, opt.prefix, opt.exclude));
        }
Example #8
0
        public List <string> Execute(object options)
        {
            AzmiArgumentsClass opt;

            try
            {
                opt = (AzmiArgumentsClass)options;
            }
            catch (Exception ex)
            {
                throw AzmiException.WrongObject(ex);
            }

            return(Execute(opt.certificate, opt.file, opt.identity).ToStringList());
        }
Example #9
0
        //
        // Execute SetBlob
        //

        public string Execute(string filePath, string blobUri, string identity = null, bool force = false,
                              IBlobClient blobClient = null)
        {
            var Cred = new ManagedIdentityCredential(identity);

            blobClient ??= new BlobClientImpl(new Uri(blobUri), Cred);

            try
            {
                blobClient.Upload(filePath, force);
                return("Success");
            } catch (Exception ex)
            {
                throw AzmiException.IDCheck(identity, ex);
            }
        }
Example #10
0
        //
        // SetBlobs main method
        //

        public List <string> Execute(string containerUri, string directory, string identity = null, string exclude = null, bool force = false)
        {
            // authentication
            string containerUriTrimmed = containerUri.TrimEnd(blobPathDelimiter);
            var    cred            = new ManagedIdentityCredential(identity);
            var    containerClient = new BlobContainerClient(new Uri(containerUriTrimmed), cred);

            // get list of files to be uploaded
            string fullDirectoryPath = Path.GetFullPath(directory);
            var    fileList          = Directory.EnumerateFiles(fullDirectoryPath, "*", SearchOption.AllDirectories);

            // apply --exclude regular expression
            if (!String.IsNullOrEmpty(exclude))
            {
                Regex excludeRegEx = new Regex(exclude);
                fileList = fileList.Where(file => !excludeRegEx.IsMatch(file));
            }

            // upload blobs
            List <string> results = new List <string>();

            Parallel.ForEach(fileList, file =>
            {
                var blobPath          = file.Substring(fullDirectoryPath.Length).TrimStart(Path.DirectorySeparatorChar);
                BlobClient blobClient = containerClient.GetBlobClient(blobPath);

                try
                {
                    blobClient.Upload(file, force);

                    lock (results)
                    {
                        results.Add($"Success '{blobClient.Uri}'");
                    }
                }
                catch (Exception ex)
                {
                    throw AzmiException.IDCheck(identity, ex);
                }
            });
            return(results);
        }
Example #11
0
        // Sets blob content based on local file content into blob
        public static string setBlob_byBlob(string filePath, string blobUri, string identity = null, bool force = false)
        {
            // sets blob content based on local file content with provided blob url
            if (!(File.Exists(filePath)))
            {
                throw new FileNotFoundException($"File '{filePath}' not found!");
            }

            var Cred       = new ManagedIdentityCredential(identity);
            var blobClient = new BlobClient(new Uri(blobUri), Cred);

            try
            {
                blobClient.Upload(filePath, force);
                return("Success");
            } catch (Exception ex)
            {
                throw AzmiException.IDCheck(identity, ex);
            }
        }
Example #12
0
        //
        // Execute GetToken
        //

        public string Execute(string endpoint = "management", string identity = null, bool JWTformat = false)
        {
            // method start
            var Cred = new ManagedIdentityCredential(identity);

            if (String.IsNullOrEmpty(endpoint))
            {
                endpoint = "management";
            }
            var Scope   = new String[] { $"https://{endpoint}.azure.com" };
            var Request = new TokenRequestContext(Scope);

            try
            {
                var Token = Cred.GetToken(Request);
                return((JWTformat) ? Decode_JWT(Token.Token) : Token.Token);
            } catch (Exception ex)
            {
                throw AzmiException.IDCheck(identity, ex, false);
            }
        }
Example #13
0
        //
        // Execute ListBlobs
        //


        public List <string> Execute(string containerUri, string identity = null, string prefix = null, string exclude = null)
        {
            var Cred            = new ManagedIdentityCredential(identity);
            var containerClient = new BlobContainerClient(new Uri(containerUri), Cred);

            containerClient.CreateIfNotExists();

            try
            {
                List <string> blobListing = containerClient.GetBlobs(prefix: prefix).Select(i => i.Name).ToList();

                if (exclude != null)
                { // apply --exclude regular expression
                    var rx = new Regex(exclude);
                    blobListing = blobListing.Where(b => !rx.IsMatch(b)).ToList();
                }
                return(blobListing.Count == 0 ? null : blobListing);
            } catch (Exception ex)
            {
                throw AzmiException.IDCheck(identity, ex);
            }
        }
Example #14
0
        //
        // Execute SetBlob
        //

        public static string setBlob_byContainer(string filePath, string containerUri, string identity = null, bool force = false)
        {
            if (!(File.Exists(filePath)))
            {
                throw new FileNotFoundException($"File '{filePath}' not found!");
            }

            var Cred            = new ManagedIdentityCredential(identity);
            var containerClient = new BlobContainerClient(new Uri(containerUri), Cred);

            containerClient.CreateIfNotExists();
            var blobClient = containerClient.GetBlobClient(filePath.TrimStart('/'));

            try
            {
                blobClient.Upload(filePath, force);
                return("Success");
            } catch (Exception ex)
            {
                throw AzmiException.IDCheck(identity, ex);
            }
        }
Example #15
0
        //
        // GetBlobs main method
        //

        public List <string> Execute(string containerUri, string directory, string identity = null, string prefix = null, string[] exclude = null, bool ifNewer = false, bool deleteAfterCopy = false)
        {
            // authentication
            string containerUriTrimmed = containerUri.TrimEnd(blobPathDelimiter);
            var    cred            = new ManagedIdentityCredential(identity);
            var    containerClient = new BlobContainerClient(new Uri(containerUriTrimmed), cred);

            // get list of blobs
            List <string> blobListing = containerClient.GetBlobs(prefix: prefix).Select(i => i.Name).ToList();

            // apply --exclude regular expression
            if (exclude != null)
            {
                var rx = new Regex(String.Join('|', exclude));
                blobListing = blobListing.Where(b => !rx.IsMatch(b)).ToList();
            }

            // create root folder for blobs
            Directory.CreateDirectory(directory);

            // download blobs
            var results = new List <string>();

            Parallel.ForEach(blobListing, blobItem =>
            {
                BlobClient blobClient = containerClient.GetBlobClient(blobItem);

                string filePath = Path.Combine(directory, blobItem);
                if (ifNewer && File.Exists(filePath) && !IsNewer(blobClient, filePath))
                {
                    lock (results)
                    {
                        results.Add($"Skipped. Blob '{blobClient.Uri}' is not newer than file.");
                    }
                }

                string absolutePath = Path.GetFullPath(filePath);
                string dirName      = Path.GetDirectoryName(absolutePath);
                Directory.CreateDirectory(dirName);

                try
                {
                    blobClient.DownloadTo(filePath);

                    lock (results)
                    {
                        results.Add($"Success '{blobClient.Uri}'");
                    }

                    if (deleteAfterCopy)
                    {
                        blobClient.Delete();
                    }
                }
                catch (Azure.RequestFailedException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    throw AzmiException.IDCheck(identity, ex);
                }
            });
            return(results);
        }