Managing Secrets

Managing the secrets must be considered at different levels:

  • Source Code Level for example hard coded in source code.
  • Repository Level for example Git/ Git Hub.
  • Infrastructure Level for example for developing the infrastructure as code.

Source Code Level

To prevent to have secrects at code level, it’s enough not to write the users, passwords, tokens, secrets in source code but in:

  • Config file.
  • Environment variable. Two Examplpe for Python and C#

In both cases must be careful not to commit the .config and .env file to the repository.

Config file

In the case of using the Config file, must pay attention not to commit the config file into the repository.

Environment Variable

C#

Python

The environment variable in Python projects are saved in .env files.

_STORAGE_ACCOUNT_NAME=environ.get('STORAGE_ACCOUNT_NAME', 'storage account')
_STORAGE_ACCOUNT_KEY=environ.get('STORAGE_ACCOUNT_KEY', 'storage key')

Repository Levle

By preventing to write the secrets in source code and save the secrets in aconfig file, we must be careful not to push & commit the code to the repository.

Fluent Interface

In software engineering, a fluent interface is a method for designing object oriented APIs based extensively on method chaining with the goal of making the readability of the source code close to that of ordinary written prose, essentially creating a domain-specific language within the interface [Wiki].

For example for Stablishing a connection to a database and fetch orders data in a table with common developmment.

var connection = new SqlConnection(connectionString);

SqlCommand command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM Orders WHERE OrderId = @OrderId ";

SqlParameter parameter = command.CreateParameter();
parameter.DbType = DbType.Int32;
parameter.ParameterName = "@OrderId ";
parameter.Value = inputOrderId;

var adapter = new SqlDataAdapter();
adapter.SelectCommand = command;

var table = new DataTable();

connection.Open();
adapter.Fill(table);
connection.Close();
connection.Dispose();
command.Dispose();

var orders = new List<Order>();
foreach (DataRow row in table.Rows)
{
    var order = new Order
    {
        OrderId = (int)row["OrderId"],
        OrderedByName = (string)row["OrderedByName"],
        DeliveryAddress = (string)row["DeliveryAddress"]
    };

    orders.Add(order);
}

But of course it can be shorter with using of Fluen Interface

List<Order> Orders= new SqlQuery(connectionString)
    .SetCommandText("SELECT * FROM Orders WHERE OrderId = @OrderId")
    .AddParameter("@OrderId", OrderId, DbType.Int32)
    .GetDataTable()
    .GetList<Order>();