DB table names as a variable?

Status
Not open for further replies.

kagaku

Wise, Aged Ars Veteran
118
Subscriptor
For one reason or another, I've always made a best effort to keep table names as variables in some "config file" and reference them throughout the application as such. Ultimately, I end up with a configuration that looks like this:

$prefix = "blah_";

$__tbl['users'] = $prefix."users";
$__tbl['comments'] = $prefix."comments";
$__tbl['posts'] = $prefix."posts";
..and so on

My queries then end up looking like this:

$sql = "select blah1, blah2, blah3 from ".$__tbl['comments']." where blah1 != 0";

Ultimately I'll get lazy and stop using the variables to reference database tables - which means eventually I'll come back through the code and update it to reference those variable table names - in the process I'm sure I miss one or two and thus those are 'hardcoded'.

Does any of this even make sense? I've been doing this for years and honestly cannot recall a single instance where I said "oh, time to change that table name! let me just edit this config file right here and...."; so is there any point? I don't even know where I picked up this practice and I'm considering dropping it. Thoughts?
 

technophile

Ars Legatus Legionis
23,768
newwb":3otvv11h said:
ShuggyCoUk":3otvv11h said:
Not to mention this implies you aren't using prepared statements...
How so? You can put a SQL query in your code and tell the DB to prepare it. In that case, the DB doesn't know how the table names were concatenated into the query.
The SQL statement in the OP certainly implies he isn't. :p
 

kagaku

Wise, Aged Ars Veteran
118
Subscriptor
It also implies that I am using clear and concise column names such as "blah1", "blah2" and "blah3". ;) Prepared statements are being used, they just didn't make sense for this example.

Ultimately I'm dropping the practice - I just don't see a reason to continue doing it. Now I just wish I knew where I picked this up - I've been doing it nearly as long as I've been programming.
 

ronelson

Ars Legatus Legionis
21,399
Subscriptor
Now I just wish I knew where I picked this up - I've been doing it nearly as long as I've been programming.
My guess is that you started something where the info you needed was in a hash or array, and then you migrated to using SQL and never changed your practices. Or do you have similarly named tables for different groups that use your app, where you pull that prefix from the config file that the group creates (i.e. hr has "prefix='hr_', finance has "prefix='finance_'", etc)? I do not see it as that horrible, given the right use case. From what you say, though, it does not sound anything at all like your situation.
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
technophile":36lzb54r said:
kagaku":36lzb54r said:
For one reason or another, I've always made a best effort to keep table names as variables in some "config file" and reference them throughout the application as such.
No. Just no. Stop doing this.
I've noticed (and been guilty of the fact) that MOST stuff programmers throw into config files is totally unnecessary to have in a config file, and never gets changed in the lifetime of the config file by anyone besides the programmer, who has enough access that changing it in code (rather than in a config file) is trivial.

The same basic rules of de-cluttering your house apply to config files. If you haven't changed an entry in the config file for months/years, then maybe it is time to get rid of it from the config file.
 

norton_I

Ars Tribunus Angusticlavius
6,189
Subscriptor++
Some applications allow a configurable table prefix, which allows multiple side-by-side instances on cheap webhosts that restrict the number of mysql databases. Mediawiki allows this. It is not exactly ideal to have to do this, but it is effective.

There are a few other instances where having computed or configurable table names might be useful, but not as a general practice.

Probably the practice comes from an overzealous person telling you to not 'hard code any strings' in your application. However, table names ought to be considered the same as variable names. They are not part of the external interface of your program and they should be hard coded if at all possible.
 

ronelson

Ars Legatus Legionis
21,399
Subscriptor
Some applications allow a configurable table prefix, which allows multiple side-by-side instances on cheap webhosts that restrict the number of mysql databases. Mediawiki allows this. It is not exactly ideal to have to do this, but it is effective.
This is how we test MW upgrades or new extensions. Install it in a different directory, change where it points, and go.
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
norton_I":kyu10bsl said:
Some applications allow a configurable table prefix, which allows multiple side-by-side instances on cheap webhosts that restrict the number of mysql databases. Mediawiki allows this. It is not exactly ideal to have to do this, but it is effective.

There are a few other instances where having computed or configurable table names might be useful, but not as a general practice.
A good rule of thumb is that config files should only contain information that can be easy changed by deployment personnel/end users who have no access to the code. If something requires code access (or anything similar like rights to change the DB schema) it shouldn't be in the config file. Don't create illusions that a change to a config file will actually work if made by a non-developer.
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
I see this as a middle ground between "dynamically generate everything using an ORM" and "put the whole SQL statement in a resource file" that doesn't provide a lot of value.

Much better to just put the entire SQL statement in a text template file (like T4 templates in .NET) and replace specific pieces instead of using in-line string concatenation.
Code:
SELECT col1, col2, col3
FROM  $$TABLE_PREFIX$$.Persons
WHERE personid = @personid
 

tinyMan

Ars Tribunus Angusticlavius
6,149
Subscriptor++
svdsinner":3jmdsgwh said:
technophile":3jmdsgwh said:
kagaku":3jmdsgwh said:
For one reason or another, I've always made a best effort to keep table names as variables in some "config file" and reference them throughout the application as such.
No. Just no. Stop doing this.
I've noticed (and been guilty of the fact) that MOST stuff programmers throw into config files is totally unnecessary to have in a config file, and never gets changed in the lifetime of the config file by anyone besides the programmer, who has enough access that changing it in code (rather than in a config file) is trivial.

The same basic rules of de-cluttering your house apply to config files. If you haven't changed an entry in the config file for months/years, then maybe it is time to get rid of it from the config file.

I soooo agree. I swear to god that some folks/systems have configuration modules with more code and functionality than their core!

I've been spending a year eradicating config files from our environment, which for a C#/WCF based multi-tier application isn't entirely trivial. Convention over configuration has been my mantra. For example, when you have 20-50 services in your middle tier, do you really need individually specified log files for each? Why not just use %hostName%.%serviceName%.log in the standard logging file location? That's actually what most of the services used anyways, and the ones that didn't were just errors where the programmer forgot to update that services config.

At the end of the day, we only had a few true configuration options that an app environment actually needed. We used tools like DNS and Active Directory to provide a simple, automated, repeatable, testable and environment-wide 'knob' for those. For the operations and deployment guy, its very nice. As a developer as well, I find that I make less errors and stuff gets written (somewhat) faster.

In fact this thread has prompted me to print out a little "Configuration Files Considered Harmful" poster to stick on the side of my monitor.
 

ronelson

Ars Legatus Legionis
21,399
Subscriptor
For example, when you have 20-50 services in your middle tier, do you really need individually specified log files for each? Why not just use %hostName%.%serviceName%.log in the standard logging file location?
Nice! Nothing like trying to troubleshoot a problem and spending the first hour just finding which damn log file it writes to. Your users will thank you.
 

kagaku

Wise, Aged Ars Veteran
118
Subscriptor
Richard Berg":gvolj2jm said:
For example, when you have 20-50 services in your middle tier, do you really need individually specified log files for each? Why not just use %hostName%.%serviceName%.log in the standard logging file location?
I hear Windows even has a built-in repository!

/var/log > event viewer

..but that's a discussion for another thread.
 

tinyMan

Ars Tribunus Angusticlavius
6,149
Subscriptor++
Richard Berg":3ikgsdku said:
For example, when you have 20-50 services in your middle tier, do you really need individually specified log files for each? Why not just use %hostName%.%serviceName%.log in the standard logging file location?
I hear Windows even has a built-in repository!

Actually, we DO use Windows Event Logs for ALL exceptional events and ANYTHING that needs to be reacted too. What goes into the log files might be more generally thought of as tracing. But that more is about "There is ONE way to do things" than configuration files.

The primary point is that generally 9 out of 10 things in configuration files ought no be there, and when you're left with just a few actual configurable items, a file might not be the best way to handle those.
 

kagaku

Wise, Aged Ars Veteran
118
Subscriptor
Ultimately I've pared down my "config" file to be nothing more than a developers configuration file. Primary function is for specifying login credentials for email/database, paths and hostnames (because those differ between environments, and some flags to switch when I want to test with/without certain functions enabled.

Code:
/* main */
$__opt['app_name']                        = "Long Name for my Application Database";
$__opt['short_name']                      = "LNA-DB";

/* environment */
$__opt['env']                             = 'dev'; //dev, prod, qa
$__opt['debug']                           = true;  //turns on debug mode (output queries, post/get vars, session vars, etc)
$__opt['send_email_debug']                = false; //true = send email in debug mode, false = do not send

/* caching */
$__opt['cache_db']                        = false; //enable or disable database caching of queries 
$__opt['cache_js']                        = false; //cache javascript into one file
$__opt['ttl_js']                          = 10;    //time in seconds to cache global javascript
$__opt['minify_js']                       = true;  //minify the javascript before caching
$__opt['cache_css']                       = false; //cache css files into one file
$__opt['minify_css']                      = false; //minify the css before caching

/* db config */
$__opt['db']['server']                    = "localhost";
$__opt['db']['user']                      = "lba_database_user";
$__opt['db']['pass']                      = "dbpwd";

/* mail config */
$__opt['mail']['host']                    = "smtp.blah.net";
$__opt['mail']['user']                    = "username";
$__opt['mail']['pass']                    = "password";
$__opt['mail']['sender_address']          = "lna-db@blah.net";
$__opt['mail']['sender_name']             = "LNA-DB Automated";

/* environment switch */
switch($__opt['env']){
  case 'dev':
    /* database schema */
    $__opt['db']['schema']                = "dev_db";
    
    /* hostnames */
    $__server['main']                     = "http://lna.blah.net";
    $__server['static']                   = "http://static.blah.net";
    $__server['admin']                    = "http://admin.blah.net";
    
    /* relative pathes to include */
    $__path['system']                     = 'system/';
    $__path['static']                     = 'static/';
    $__path['templates']                  = 'templates/';
    $__path['dbcache']                    = 'dbcache/';
    $__path['functions']                  = 'functions/';
    $__path['cron']                       = 'cron/';
    $__path['intrasite']                  = 'intrasite/';
    $__path['ajax']                       = 'ajax/';
    
    break;
}
 

tinyMan

Ars Tribunus Angusticlavius
6,149
Subscriptor++
kagaku":sgnjb77j said:
Ultimately I've pared down my "config" file to be nothing more than a developers configuration file. Primary function is for specifying login credentials for email/database, paths and hostnames (because those differ between environments, and some flags to switch when I want to test with/without certain functions enabled.

Hey, I hope you don't think I am picking on you, but you've just laid out a few things that I believe definitely should never be in a config file, and wanted to use you as an example of things that should NOT be in a config file:
  • Specifying login credentials: This means that somewhere in your environment you have login credentials, in clear text. This is bad, evil actually. This is a perfect example of something that should be managed inside your OS security system, like Service Accounts in Active Directory, or pre-shared ssh keys on unix. That way you can use your OS provided tools to force you into expiring and changing those passwords on a regular basis, because you only have to do it once, instead of finding all 10,000 instances of your hard coded passwords in config files.
  • Database Names: Is there some way that you can use a convention for this, like 'db-<hostname>-<serviceAccountName>' where the program can determine the right DB at runtime?
  • Paths: We ended up removing _all_ paths from our configs by figuring it out at runtime. Starting from the root of the web page, or the directory holding the working directory of the script, or the home-dir of the service account, we reference all resources via relative paths. This means that I can drop an instance of anything into any location on the box and as long as the folder structure comes with it, it runs.
  • Hostnames: The world has a solution for mapping services to specific machines, that is supported everywhere and easily managed. Its called DNS and the CNAME is your friend.
  • Functionality Flags: I break this into two categories, where things like modules (say a Tax add-on to an accounting package) that tend to be either present or not present for the lifetime of the install, and things like temporarily re-directing users to another page during a maintenance window. The first use case should be handled in your code by checking to see if the module is present, or similar checks and use it if its there, skip it if it ain't. The second use case isn't right for a config file either, because often times its temporary and something that just gets applied to a subset of your machines for a limited time, not some persistent setting that you want to keep alive through reboots, etc. In reality you probably don't want to have to reboot your services to get the change in config to take effect for most transient things.
 

kagaku

Wise, Aged Ars Veteran
118
Subscriptor
Maxer":1ob2o28u said:
Stupid question... why not just call stored procedures instead of writing your queries in code?

Couldn't you then just worry about updating the sprocs when your table names change (also why do your table names change)?

Some queries I'm running are assembled at run time depending on requirements determined at run time - I'm sure I could pull this off with stored procedures, but what is the advantage?

As for table names, they won't be changing - that's why I'm asking my question. My process made no sense!




tinyMan":1ob2o28u said:
kagaku":1ob2o28u said:
Ultimately I've pared down my "config" file to be nothing more than a developers configuration file. Primary function is for specifying login credentials for email/database, paths and hostnames (because those differ between environments, and some flags to switch when I want to test with/without certain functions enabled.

Hey, I hope you don't think I am picking on you, but you've just laid out a few things that I believe definitely should never be in a config file, and wanted to use you as an example of things that should NOT be in a config file:

I'm the one asking for opinions and yours is definitely welcome - and appreciated!

tinyMan":1ob2o28u said:
  • Specifying login credentials: This means that somewhere in your environment you have login credentials, in clear text. This is bad, evil actually. This is a perfect example of something that should be managed inside your OS security system, like Service Accounts in Active Directory, or pre-shared ssh keys on unix. That way you can use your OS provided tools to force you into expiring and changing those passwords on a regular basis, because you only have to do it once, instead of finding all 10,000 instances of your hard coded passwords in config files.
  • Database Names: Is there some way that you can use a convention for this, like 'db-<hostname>-<serviceAccountName>' where the program can determine the right DB at runtime?
  • Paths: We ended up removing _all_ paths from our configs by figuring it out at runtime. Starting from the root of the web page, or the directory holding the working directory of the script, or the home-dir of the service account, we reference all resources via relative paths. This means that I can drop an instance of anything into any location on the box and as long as the folder structure comes with it, it runs.
  • Hostnames: The world has a solution for mapping services to specific machines, that is supported everywhere and easily managed. Its called DNS and the CNAME is your friend.
  • Functionality Flags: I break this into two categories, where things like modules (say a Tax add-on to an accounting package) that tend to be either present or not present for the lifetime of the install, and things like temporarily re-directing users to another page during a maintenance window. The first use case should be handled in your code by checking to see if the module is present, or similar checks and use it if its there, skip it if it ain't. The second use case isn't right for a config file either, because often times its temporary and something that just gets applied to a subset of your machines for a limited time, not some persistent setting that you want to keep alive through reboots, etc. In reality you probably don't want to have to reboot your services to get the change in config to take effect for most transient things.

Comments to your points:
Specifying login credentials: Honest question here, what is the advantage? I understand risk (I work at a very large firm, we do some crazy paranoid things in the name of risk) is a part of this equation. The environment this application is deployed in will only be accessible by developers, the password won't be changing on any sort of basis (if nobody can access it, I don't see the point), and it almost sounds like increased overhead just to retrieve the password for the database.

Database names: Yes, actually. My current naming convention is prod_db, dev_db, qa_db; this matches perfectly to the settings of my environment flag. I think I'll go with this idea.

Paths: Isn't that essentially the same as what I'm doing? I agree that absolute paths are evil and should never be used, but relative paths make sense. I guess it's another instance of configuring something that won't ever change.

Hostnames: I could determine the self-hostname at runtime, but what about when I send an email? The email might contain a link back to the application, and it obviously needs the hostname to include that hostname.

Functionality flags: I agree on this, however I'm not building a modular application, all components will be included at all times. Debug / caching are set as flags simply to be able to turn them on or off conveniently when I'm developing.
 

Maxer

Ars Legatus Legionis
19,044
Subscriptor
kagaku":1hrxtelc said:
Maxer":1hrxtelc said:
Stupid question... why not just call stored procedures instead of writing your queries in code?

Couldn't you then just worry about updating the sprocs when your table names change (also why do your table names change)?

Some queries I'm running are assembled at run time depending on requirements determined at run time - I'm sure I could pull this off with stored procedures, but what is the advantage?

As for table names, they won't be changing - that's why I'm asking my question. My process made no sense!


......
Fair enough.

Next question: why?

:)

I mean, why do table names change at runtime?

Just curious what the system is trying to do is all.

Is it building joins on the fly, or is it always the same query, it just swaps out table names for some reason?
 

kagaku

Wise, Aged Ars Veteran
118
Subscriptor
Maxer":v3clz9p1 said:
Fair enough.

Next question: why?

:)

I mean, why do table names change at runtime?

Just curious what the system is trying to do is all.

Is it building joins on the fly, or is it always the same query, it just swaps out table names for some reason?

I should have been a bit clearer- the table names are not changing at all. In fact, the reason I started this thread was to ask 'what is the point of having my table names as a variable if they never change?'. I have a handful of queries that might have small parts change, either in the WHERE clause or in ORDER BY. Additionally, INSERT and UPDATE queries tend to only reference columns that have changed (by using an array with column name and the new value in the preparation of the query).

In fact the only query I had in my code that was swapping out table names conditionally was a logging query - but I have re-written it. Instead of (for example) four tables: log_errors, log_access, log_emails, log_blah - I just added a "log_type" column to my "log" table. Sometimes I over-think things I guess.
 

Maxer

Ars Legatus Legionis
19,044
Subscriptor
kagaku":3d4k0dzh said:
Maxer":3d4k0dzh said:
Fair enough.

Next question: why?

:)

I mean, why do table names change at runtime?

Just curious what the system is trying to do is all.

Is it building joins on the fly, or is it always the same query, it just swaps out table names for some reason?

I should have been a bit clearer- the table names are not changing at all. In fact, the reason I started this thread was to ask 'what is the point of having my table names as a variable if they never change?'. I have a handful of queries that might have small parts change, either in the WHERE clause or in ORDER BY. Additionally, INSERT and UPDATE queries tend to only reference columns that have changed (by using an array with column name and the new value in the preparation of the query).

In fact the only query I had in my code that was swapping out table names conditionally was a logging query - but I have re-written it. Instead of (for example) four tables: log_errors, log_access, log_emails, log_blah - I just added a "log_type" column to my "log" table. Sometimes I over-think things I guess.

In that case I would suggest that you use sprocs for everything.

You pass in the parameters that you want it to query by, or potentially even ORDER BY I suppose, and then let it do all the work.

That way SQL server can better optimize the query plan so in theory, the query runs faster and you have all the sprocs in one location.

Having them on the server allows you to share them, reuse them, or just more easily find them to update.

Say you want to find all the code that references a certain column on a table, if you have it all in sprocs you can easily query the server for any functions, views, sprocs, that reference that column.

Then if you change out that column for some reason you can update all the code on the server and never have to change/recompile your application. It just keeps calling the sproc like it always has, never knowing things changed behind the scenes.

But, that's just my opinion. Doesn't mean it is a "best practice" in every single case.
 

ronelson

Ars Legatus Legionis
21,399
Subscriptor
Hostnames: I could determine the self-hostname at runtime, but what about when I send an email? The email might contain a link back to the application, and it obviously needs the hostname to include that hostname.
Then they are URI's, not hostnames, and that is much more reasonable even if it is just semantics. Of course, that still assumes that is something you would ever have a user change. If it would only be changed on release of new code to production, probably less useful.
 

tinyMan

Ars Tribunus Angusticlavius
6,149
Subscriptor++
kagaku":1j9md9k6 said:
Comments to your points:
Specifying login credentials: Honest question here, what is the advantage? I understand risk (I work at a very large firm, we do some crazy paranoid things in the name of risk) is a part of this equation. The environment this application is deployed in will only be accessible by developers, the password won't be changing on any sort of basis (if nobody can access it, I don't see the point), and it almost sounds like increased overhead just to retrieve the password for the database.

You just can not have this mindset. Security is the result of a process, one that takes the decision about storing a password in a config file away from the developer. I have also bolded part of your quote that is very problematic for me (and also familiar as I used to think the same way). The professional, and correct thing to do is to plan for a regularly changing password, because that is a requirement in professional environment. On the plus side, once you have a process its really easy.

Paths: Isn't that essentially the same as what I'm doing? I agree that absolute paths are evil and should never be used, but relative paths make sense. I guess it's another instance of configuring something that won't ever change.

Yeah, one example from my environment was this goddamn 'imgSrcDir' that was spread across literally hundreds of config files. Basically they all ended up containing the equivalent of 'img/'. We standardized our file tree, every Javascript in a 'js' folder, every css in a 'css' folder and every image in an 'img' folder. Make that a standard and code to it, and dropped the config options. Lots of stuff for paths is like that.

For stuff like 'where is the tar on this system' well, that is what the .profile and path configs are for. That was the SAs can do their jobs, and the developers can do theirs and the dependencies between the two are minimized.

Functionality flags: I agree on this, however I'm not building a modular application, all components will be included at all times. Debug / caching are set as flags simply to be able to turn them on or off conveniently when I'm developing.

Just another anecdote from my experiences. We very recently completed a project to make the 'debug' attribute dynamic on a per-request basis. For the persona-enabled systems where we can associate a request with a particular user, we make 'debug' an attribute of that user. For stateless/user-less requests, the debug flag gets passed to the call as a parameter. This way, in development I can run debug all I want and then in production skip it most of the time, but if something crops up that needs some introspection, its easy to conjure up the correct user/call parameter to spit back debug output. Our debug code also includes detailed timing/performance metrics so the automated monitoring requests we run can get and track hyper-detailed performance statistics instead of just a total request time, which was another side bonus.

ronelson":1j9md9k6 said:
Hostnames: I could determine the self-hostname at runtime, but what about when I send an email? The email might contain a link back to the application, and it obviously needs the hostname to include that hostname.
Then they are URI's, not hostnames, and that is much more reasonable even if it is just semantics. Of course, that still assumes that is something you would ever have a user change. If it would only be changed on release of new code to production, probably less useful.

In my opinion, that is something that that web-host or container should be controlling and the application would be completely agnostic to it. For example, perhaps your load-balancers or proxies do the re-writing for you, or an IIS module uses the sites definition to figure out what the presented URL should be. Pushing these types of decisions so low into the stack makes it very hard to be agile.
 

kagaku

Wise, Aged Ars Veteran
118
Subscriptor
tinyMan":27al35y1 said:
You just can not have this mindset. Security is the result of a process, one that takes the decision about storing a password in a config file away from the developer. I have also bolded part of your quote that is very problematic for me (and also familiar as I used to think the same way). The professional, and correct thing to do is to plan for a regularly changing password, because that is a requirement in professional environment. On the plus side, once you have a process its really easy.

I'm still not understanding the actual risks of storing it there versus not storing it there? The explanation I'm seeing here is more along the lines of "that's just the way it's done, so do it this way". Security is my first thought when developing the application, however my mindset is that if the server is compromised in any way and the password is stored _somewhere_ on the server (regardless of whether it is within the config file, or an 'external' storage) won't it be vulnerable any way? To give some background on my server and application back end: FreeBSD 8.1 server, PostgreSQL database, lighttpd, PHP and Perl. The application is accessed via the web via LAN, but also has jobs that run via cron. The database and application are housed on the same server (cost) for the time being, though eventually I hope to have a separate database and application server. If the server is compromised, the database password is almost the least of my worries. Finally, the application is exclusively internal and will not be accessible outside of the company intranet.

I'm not being sarcastic - I truly want to understand the point of these extra layers of security. "Just because" isn't a valid explanation for doing one thing over another, even in the case of security. However, I'm definitely open to learning a new practice that might have benefits in future applications; while this one is internal only the next could be customer facing for all I know.

tinyMan":27al35y1 said:
Yeah, one example from my environment was this goddamn 'imgSrcDir' that was spread across literally hundreds of config files. Basically they all ended up containing the equivalent of 'img/'. We standardized our file tree, every Javascript in a 'js' folder, every css in a 'css' folder and every image in an 'img' folder. Make that a standard and code to it, and dropped the config options. Lots of stuff for paths is like that.

For stuff like 'where is the tar on this system' well, that is what the .profile and path configs are for. That was the SAs can do their jobs, and the developers can do theirs and the dependencies between the two are minimized.

Agreed. Thinking through the decision to include some of the paths it really boils down to trying to force myself to write to those directories and only those directories. I don't plan to change them, I don't plan to update them, I just want standardization.

tinyMan":27al35y1 said:
Just another anecdote from my experiences. We very recently completed a project to make the 'debug' attribute dynamic on a per-request basis. For the persona-enabled systems where we can associate a request with a particular user, we make 'debug' an attribute of that user. For stateless/user-less requests, the debug flag gets passed to the call as a parameter. This way, in development I can run debug all I want and then in production skip it most of the time, but if something crops up that needs some introspection, its easy to conjure up the correct user/call parameter to spit back debug output. Our debug code also includes detailed timing/performance metrics so the automated monitoring requests we run can get and track hyper-detailed performance statistics instead of just a total request time, which was another side bonus.

This approach sounds very nice (and helpful) for accessing debug information in the production environment. My biggest fear of exposing this functionality (in any form) to production is that, should a 'privileged' account be compromised (via any means) not only do I have a user account out there that an attacker has access to, the attacker can also see some of the behind the scenes mechanics of the application through the debug information; possibly leading to more attack vectors. Security through obscurity is the first thing that comes to mind; my application should obviously be secure even if an attacker knows some of the behind the scenes logic - but why risk making it easier?

My current debug process for production problems is to attempt to replicate it on the QA build. QA runs a copy of production code (albeit with a usually outdated database, but that can be easily remedied) and is limited in access - thus I feel I can safely enable any sort of debugging functionality there.

tinyMan":27al35y1 said:
In my opinion, that is something that that web-host or container should be controlling and the application would be completely agnostic to it. For example, perhaps your load-balancers or proxies do the re-writing for you, or an IIS module uses the sites definition to figure out what the presented URL should be. Pushing these types of decisions so low into the stack makes it very hard to be agile.

This makes sense with the web-facing portion of the application - but the behind the scenes stuff (cron, emails) won't know much aside from the hostname of the machine that executes the job. A script run via cron controls many functions (including sending emails) and runs strictly though invocation of the script it self. How then can I know the hostname (besides pulling that info from the application process that is generating the email, storing that in the database and referencing it that way?).
 

norton_I

Ars Tribunus Angusticlavius
6,189
Subscriptor++
tinyMan":2vq6cipz said:
[*]Specifying login credentials: This means that somewhere in your environment you have login credentials, in clear text. This is bad, evil actually. This is a perfect example of something that should be managed inside your OS security system, like Service Accounts in Active Directory, or pre-shared ssh keys on unix. That way you can use your OS provided tools to force you into expiring and changing those passwords on a regular basis, because you only have to do it once, instead of finding all 10,000 instances of your hard coded passwords in config files.

There is simply no way around this. If your application can operate it has the equivalent of clear-text credentials for whatever services it needs to operate. SSH keys are just one form of login credentials stored in a config file. There are better or worse ways to do this, but if you try to claim that credentials must never be stored in cleartext you are doomed to fail and will probably create something less secure in a misguided attempt to achieve the impossible. AD is nice because a principal's access can be granted or revoked to individual services in a centralized manner. The application must still have a clear-text version of its key, but at least there is some manageability there. SSH keys on the other hand has no native mechanism for doing this, so I don't really see any argument that it is better or worse than having passwords: the answer is whichever you can manage better. Some people use SSH keys to get around requirements that passwords be changed regularly, but that is simply stupid, or at best a pointless workaround to a misguided rule. If you think that 200 character random machine passwords need to be changed every 6 months, then you should require SSH keys to be rotated as well, and vice versa.

[*]Database Names: Is there some way that you can use a convention for this, like 'db-<hostname>-<serviceAccountName>' where the program can determine the right DB at runtime?

Database name is probably the single best identifier of a unique instance of an application. In fact, my ideal web application configuration would be one to three lines containing the database name and possibly the database host and password/key.
 

ronelson

Ars Legatus Legionis
21,399
Subscriptor
In my opinion, that is something that that web-host or container should be controlling and the application would be completely agnostic to it. For example, perhaps your load-balancers or proxies do the re-writing for you, or an IIS module uses the sites definition to figure out what the presented URL should be. Pushing these types of decisions so low into the stack makes it very hard to be agile.
It depends on your use case. I would also think you will have a problem with your URI forwarding idea if you happen to lose control of the initial URI. If you are writing the whole stack, top to bottom, not a huge deal. If you are just writing a component, then putting the URI in a config file makes a lot more sense. It also makes sense if multiple components are sharing a config file, with some constraints.
There is simply no way around this.
There are *some* ways, though you are right, nothing will be perfect. We have a user on the DB server that has access to the password table and the fetch utility is the only command it can run. Remote users with the appropriate key and permissions can "ssh user@remotehost <args>" to get the passwords. So the password is stored somewhere, especially in memory, but anyone who lucks into the config file just gets the PID. We have deemed "application --user=281 --enable=834" to be more secure than "application --user=lkd2!--3#*&,A; --enable=OU812vAnh4L3nR0X!", or the appropriate config file options, to be more secure especially in locations like crontab.

There are obviously some issues with that as well (securing the keys, ensuring that no information tying the password to an account/system is given, and ensuring valid users are making requests regardless of the keys used). We're working on robots who can enter their PIN codes off their fobs (and click OK on server error dialogs!), but until then, this is life.
 

Maxer

Ars Legatus Legionis
19,044
Subscriptor
jxl":2r1h2st4 said:
At least when it comes to SQL Server, the execution plan of "ad hoc" queries is cached just the same as the execution plan of sprocs. There's no performance penalty/benefit to be found there.
Parametrized queries are still very useful for avoiding SQL injection attacks.
That doesn't seem right...?

How could an ad hoc query be cached if it is being run for the first time by its definition?

The sproc gets a query plan generated and then that plan can be re-used to (in theory) save time on running the query.

Unless I am missing something somewhere along the line?
 
Maxer":1yhuc9yn said:
That doesn't seem right...?

How could an ad hoc query be cached if it is being run for the first time by its definition?
It isn't necessarily. The ad hoc query might match a previously cached ad hoc query. Imagine a naïve cache that is a map keyed off of the query text. Running the same query twice, even if it's generated in an ad hoc way, could hit the cache.
 

technophile

Ars Legatus Legionis
23,768
norton_I":1xjrb4bw said:
tinyMan":1xjrb4bw said:
[*]Specifying login credentials: This means that somewhere in your environment you have login credentials, in clear text. This is bad, evil actually. This is a perfect example of something that should be managed inside your OS security system, like Service Accounts in Active Directory, or pre-shared ssh keys on unix. That way you can use your OS provided tools to force you into expiring and changing those passwords on a regular basis, because you only have to do it once, instead of finding all 10,000 instances of your hard coded passwords in config files.

There is simply no way around this. If your application can operate it has the equivalent of clear-text credentials for whatever services it needs to operate.
An ASP.NET application whose app pool is set to run as a specific account, and which is using Windows auth to connect to a database, does not have the "equivalent of clear-text credentials". All of that is protected by DPAPI and its moral equivalents. You will not be able to get the clear-text password from that, period. The only way you can even act as that service is to hijack its process somehow, via code injection, debugging, etc (which all naturally require administrative-level privileges) or a process-level exploit (i.e. a bug in your code that allows execution of arbitrary code).

Claiming that using clear-text passwords in config files is "ok" is just false. It should not be done in modern code. Even if you have to store the password, DPAPI (again, on Windows; I am sure there are equivalents on other modern platforms) can be used to securely encrypt and decrypt the password so that the plain text is not stored nor accessible to any non-superuser.
 
technophile":6bpp42u9 said:
Claiming that using clear-text passwords in config files is "ok" is just false. It should not be done in modern code. Even if you have to store the password, DPAPI (again, on Windows; I am sure there are equivalents on other modern platforms) can be used to securely encrypt and decrypt the password so that the plain text is not stored nor accessible to any non-superuser.
Where's the decryption key to decrypt the password stored? Why not store the password in its place? The point is that if an application has enough information to access a service, a "bad guy" with the application does as well. Information theoretically, that much is obvious; more practically, a bad guy could run the application in a VM and shuttle every challenge and response between the service and the application to simulate the application connecting to the server.
 

technophile

Ars Legatus Legionis
23,768
newwb":17vv5ag9 said:
technophile":17vv5ag9 said:
Claiming that using clear-text passwords in config files is "ok" is just false. It should not be done in modern code. Even if you have to store the password, DPAPI (again, on Windows; I am sure there are equivalents on other modern platforms) can be used to securely encrypt and decrypt the password so that the plain text is not stored nor accessible to any non-superuser.
Where's the decryption key to decrypt the password stored? Why not store the password in its place?
That's the beauty; you don't have to store the key. Windows takes care of all of that for you; DPAPI protects it using a per-user encryption key that is itself protected from unauthorized access.

Yes, at some level there's a key that decrypts the key that decrypts the password (or the credentials token, more likely; I'm not sure at that level) -- but good luck getting it out of Windows (again, all bets off if you have admin access). I'll put my trust in Microsoft's security guys over your corporation not ever allowing access to that file to anyone who shouldn't have it, including current-but-about-to-quit-and-really-pissed-off-developer, or little-bit-dim-susceptible-to-spearfishing-attempts-developer.

The point is that if an application has enough information to access a service, a "bad guy" with the application does as well. Information theoretically, that much is obvious; more practically, a bad guy could run the application in a VM and shuttle every challenge and response between the service and the application to simulate the application connecting to the server.
No, he doesn't, and no he can't; because he can run it as himself, but he does not know the auth info for the service account. And that's not stored anywhere he can get to just by copying files that were accidentally available on a public FTP or misconfigured .htaccess deny rule or whatever.
 
Status
Not open for further replies.