Git Product home page Git Product logo

dotnet-env's Issues

.env.local support

Hi. I've started using this library recently, but I noticed there's no option to pass a list of files to be read (it's just .env, always .env), not even .env.local (which is a standard feature while using Symfony (pretty popular PHP framework))
Would it be possible to add the following features?

  • A better, custom list of files instead of 1 file to load (.env that is later overriden by .env.local)
  • A way to override said list of files (So if I get some options I can add .env.prod as well)

Very nice and clean lib, I'd love if those features could be added.

Env file not loading

Description

After running DotNetEnv.Env.Load(); no environment variables are added.

Specifications

I am running EndeavourOS Linux.
My code is running on .NET Core 6.

Code

DotNetEnv.Env.Load();
Console.WriteLine("token: " + Environment.GetEnvironmentVariable("TOKEN"));

...with the output of token:

My .env

Located at root/MyProject/.env, where root is where the solution file is located and MyProject is where the project file is located.

TOKEN=token

Make change to README file

When reading this section of the README: A Note about Production and the Purpose of This Library. This caught my attention:

When the application is deployed into production, actual env vars should be used, not a static .env file!

Here a "good practice" is implied when in reality it is a bad practice. In production you never use environment variables to store sensitive data such as passwords in plain text. The environment variables of a running process can be easily inspected by programs like mogrify or any cracker could create his own malicious software for such an action. Using a static ".env" is just as insecure as using "actual env vars". In addition, environment variables may remain visible in the shell history (although there is a way around this but new users may overlook it).

In production what is used are secret files, where sensitive data is stored but encrypted! or you can also use a secrets manager provider such as AWS.

Encryption

How do I encrypt this file on windows server?

Suggestion: Defaults Are Unexpected

My .env had vars with empty values. I wish variables like this would not clobber on default, but the behavior was not as bad as I originally expected. I'll just remove my blank .env file.

[question] How can I set empty string value to the variable?

I have the .env file with this content:

SOME_VAR=

and a string template, something like this: begin of %SOME_VAR%.
After ExpandEnvironmentVariables I want to see a string 'begin of '. But now I see 'begin of %SOME_VAR%' as a result. As I can understand, SOME_VAR= means to delete the variable.
Is there any way to assign an empty string to the environment variable?

Enhancement - Recursively search directories for .env

I have a project that has a configuration class that loads keys from the environment. If no directory is specified then .Load() uses the CurrentDirectory, which is likely to be /someDir/MyProject/bin/Debug/netcoreapp2.1/.

It would be better if .Load() could traverse the directory upwards, looking for a .env file to load.

I am currently using this function which does a rudimentary traverse of the directory.

private string FindDotEnv(string currentDirectory)
{
    try
    {
        var envFile = Directory.GetFiles(currentDirectory, ".env");
        if (envFile.Length == 0)
        {
            var parentDirectory = Directory.GetParent(currentDirectory);
            return FindDotEnv(parentDirectory.FullName);
        }

        Console.WriteLine($"found .env in {envFile[0]}");
        return envFile[0];
    }
    catch (UnauthorizedAccessException)
    {
        Console.WriteLine("no .env found in directory");
        return null;
    }
}

public MyConfigClass()
{
    var envDirectory = FindDotEnv(Directory.GetCurrentDirectory());
    DotNetEnv.Env.Load(envDirectory);
}

It would be great if .Load() could do this out of the box.

support parsing .env and returning a Dictionary<string,string> instead of modifying environment

in Microsoft.Extensions.Configuration, ConfigurationBuilder has the ability to load configuration from a dictionary.

Because of that, it would be nice to support using DotNetEnv to parse the .env file (and all the support it has there, including the trimming, quoted values, etc) and return it as a dictionary then allow the caller to use that dictionary.

Currently because it doesn't support returning a dictionary instead of modifying the environment, a .net core test project wanting to use it must switch their <Project Sdk= value from Microsoft.NET.Sdk to Microsoft.NET.Sdk.Web so they can use AddEnvironmentVariables

Interpolation stops working with `SetEnvVars == false`

Interpolation is not properly working without SetEnvVars.

TestCase to show that:
Add LoadOptions.NoEnvVars() in EnvConfigurationTests-->AddSourceToBuilderAndParseInterpolatedTest:

this.configuration = new ConfigurationBuilder()
                .AddDotNetEnv("./.env_embedded", LoadOptions.NoEnvVars())
                .Build();

The test fails now with the first interpolation as shown here:
grafik

Originally posted by @Philipp-Binder in #90 (comment)

Is there support for hierarchical settings?

Not sure if I am maybe doing this wrong but I have the following settings in my .env file, which I have been using with my docker-compose script and it has worked fine but when trying to use your library for local dev I get an error.

Values:FUNCTIONS_WORKER_RUNTIME=dotnet-isolated
Values:AZURITE_TABLESTORAGE_CONNECTIONSTRING=DefaultEndPoint...

And the error I get is:

Unhandled exception. Sprache.ParseException: Parsing failure: unexpected ':'; expected = (Line 1, Column 7); recently consumed: Values

From what I understand this is a valid way to do config, in JSON it would be:

{
   "Values": {
                 "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
                 "AZURITE_TABLESTORAGE_CONNECTIONSTRING"="DefaultEndPoint..."
    }
}

Fails to parse when environment file has dash (-)

I want to thank you for this library. It seems to be the most complete dotnet libraries out there supporting env file parsing. I did run into one issue regarding environment variables with a dash in them:

Example file:

test-dash=value

Result: Sprache.ParseException : Parsing failure: unexpected '-'; expected = (Line 1, Column 5); recently consumed: test

This is a perfectly legal environment variable name. In fact, it appears that both Windows & Linux support all characters but equals character (=) and NUL in environment variable names. It looks like this library is basically supporting the pattern "[a-zA-Z_]+[a-zA-Z0-9_]*". I'm wondering if you'd be open to at least allowing the dash? I'd be willing to contribute a PR - it seems like it'd be easy to support.

how to use .env file in production?

In code I have used TraversePath().Load() and it's working good when testing, but when I publish the application as standalone it's not using the .env file. How can I use .env file?

Not compatible with Kubernetes .env

First of all thank you for the library. It's helping me a lot and I use it across all my projects. Now here is a problem.

When I use .env file with the library, I have to use quotes for some config values e.g.:

ConnectionString="Server=tcp:xyz;Password....."

Then if I want to use same file to create configmap in Kubernetes I run the command

kubectl create configmap my-config --from-env-file .env

But I need to remove all quotes, e.g.:

ConnectionString=Server=tcp:xyz;Password.....

It seems like it's a new issue introduced in v2.0.0.

Parse ${ENV_VAR} in env_file

I have Env like this:

BASENAME=${BASENAME}

and ref in tye.yaml

env_file: 
 - .env

Tye will not replace ${BASENAME} with value of currently set env var in process.

Related to #377, but this one is for env_file, 377 is for env. Feel free to combine issues.

azsdke2e
azsdke2e2

Failure to parse on $

After upgrading from 1.4 to 2.1, this line of my .env file started to fail to parse:

GROUP_FILTER_REGEX=^((?!Everyone).)*$

Stack Trace:

Sprache.ParseException: Parsing failure: unexpected 'T'; expected end of input (Line 27, Column 1); recently consumed: IDER=okta

   at Sprache.ParserExtensions.Parse[T](Parser`1 parser, String input)
   at DotNetEnv.Parsers.ParseDotenvFile(String contents, Func`2 tranform)
   at DotNetEnv.Env.LoadContents(String contents, LoadOptions options)
   at DotNetEnv.Env.Load(String path, LoadOptions options)

The next line starts with T so I think that is what the error is talking about.

Removing the $ allows it to load but as that it is a necessary part of the value, I can't remove it permanently.

Denial of Service (DoS) - v2.5.0

Info from snyk.io

Introduced through: project@* › [email protected][email protected][email protected]
Fix: No remediation path available.
Security information
Factors contributing to the scoring:
Snyk: CVSS 7.5 - High Severity

NVD: CVSS 7.5 - High Severity
Why are the scores different? Learn how Snyk evaluates vulnerability scores
Overview
System.Net.Http is an Provides a programming interface for modern HTTP applications, including HTTP client components that allow applications to consume web services over HTTP and HTTP components that can be used by both clients and servers for parsing HTTP headers.

Affected versions of this package are vulnerable to Denial of Service (DoS) as ASP.NET Core fails to properly validate web requests.

NOTE: Microsoft has not commented on third-party claims that the issue is that the TextEncoder.EncodeCore function in the System.Text.Encodings.Web package in ASP.NET Core Mvc before 1.0.4 and 1.1.x before 1.1.3 allows remote attackers to cause a denial of service by leveraging failure to properly calculate the length of 4-byte characters in the Unicode Non-Character range.

Environment variables for .NET Framework 4.7.2 set on a run basis rather than on a project root folder basis

I'm not using NET Core, I'm developing using NET Framework 4.7.2.

The project is using a function called Directory.GetCurrentDirectory() to find the root folder.

NET Framework, the function finds the location where the project was launched, not the root folder of the project.

Because of this, the path changes depending on the execution environment, and when you build with IIS Express in Visual Studio 2022, the root folder is applied as "C:\Program Files\IIS Express" rather than the project folder.

Because of this, putting ".env" in the project root folder doesn't work.

This issue was in the past "dotnet/aspnetcore#4206" and was fixed in Net Core but not in Net Framework.

According to what I checked on https://stackoverflow.com/a/53655514, in NET Framework, you should use System.AppContext.BaseDirectory instead of System.IO.Directory.GetCurrentDirectory() to work properly. At this time, I confirmed that it normally finds the project root folder.

Loading Configuration from File - Parsed it to an object

Hi,

I am trying to load the environment variables into the environment along with parsing the object from it. I was wondering if I am doing it the right way.

I am not able to see the updated values from the file loaded into the object though.

  var configuration = new ConfigurationBuilder()
            .AddDotNetEnv(".env", DotNetEnv.LoadOptions.NoEnvVars().TraversePath().NoClobber()) // Simply add the DotNetEnv configuration source!
            .Build();
            
     services.AddSingleton<IConfiguration>(configuration);       

Then I am trying to bind these settings in my object

var appSettings = new VeneliteConfiguration();
            Configuration.Bind(appSettings);

But It is still loading settings from the appsettings.Json and not from the environment variables. Any help would be appreciated. Thank you.

Not Able to read env variables for project type .NET Framework 4.7.2

I have created .env file in the root of the asp.net mvc application and is trying to load using below code

DotNetEnv.Env.Load();
var value = System.Environment.GetEnvironmentVariable("HELLO");

value is always Null. I tried using below code aswell but no luck. Are you sure this works with .NET Framework 4.6 + ??
DotNetEnv.Env.TraversePath().Load();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.