Sleeping Dog

Hacking Sleep

I’ve been hearing more and more about the importance of sleep, so as part of trying to be healthier in general I decided to see what I could do to sleep better. A lot of the stuff I tried is based on Tim Ferriss’s Four Hour Body, and I’d definitely recommend the chapter on sleep to anyone who is interested in hacking theirs, too.

I organized these by what I think worked the best for me, but since I tried a lot of things at once, it’s hard to tease out the differences.

Make your bedroom as dark as possible

My apartment is in a historic building, so the facade is lit up at night. While it looks impressive, it makes my bedroom bright even with blackout curtains. What I did to fix this was unfurl a blackout curtain and tack it to the edges of the window so there is practically no light that comes in. By no light, I mean I cannot even see my hand in front of my face. It does not look great, but it works!

Try this first: remove all electronics with lights (even small LEDs) and black out your windows. Use a heavy blanket or aluminum foil and tape. It will look terrible, but if it helps, you can invest in better curtains later.

Test 66-70F degrees as your bedroom temperature, with a thin blanket

This is from the Four Hour Body and it really made a big difference for me. 64 degrees and I’ll wake up shivering, 72 degrees and I’ll sweat and wake up mildly dehydrated. Try 68 with a sheet and maybe a light blanket.

Also, thermostats can be widely inaccurate so you might want to get a more accurate thermometer to test this. For example, if I set my thermostat to 65 degrees, its actually 72 in my bedroom. Try this one that I was using for a few months. It doesn’t really seem to help except maybe on the margins in the darkest days of winter.

Humidity level was more important than I thought

I went skiing in the mountains a few weeks ago and got a cold due to the very dry air. I also slept really poorly. I thought – maybe humidity is screwing up my sleep at home, too.

I had a humidifier that I never used, so I decided to try it. Turns out 40-45% relative humidity is ideal. This is also a narrow band like temperature. Below 40% and I’ll wake up with a dry throat and over 50% and everything feels somewhat damp in the morning. I actually sleep pretty well at 50-55% humidity, but I’m concerned about mold growing at that high of a level.

Eat almond butter on a carrot before bed

This idea is also from the Four Hour Body. A lot times when I woke up feeling sluggish in the morning, I’d feel better after eating breakfast. I figured this was definitely blood sugar related, so I tried another 4HB suggestion-almond butter before bed.

This worked well and mostly eliminated that groggy mornings. I found that the easiest way to do this was to buy a bag of carrots and a jar of almond butter. Eat one to two carrots, “double dipping” in the almond butter so you get the equivalent of three to four tablespoons. The carrots are great because there will be no spoons or plates to clean up, and takes less than 5 minutes.

Things that haven’t caused much of a difference for me

  • Screen time before bed. I have f.lux on my Mac and similar apps on my phone and tablet, so this might be a different story if I didn’t have those.
  • Melatonin doesn’t seem to do much for me, though I sometimes take it when traveling for jet-lag and it helps a bit.
  • I also have a Phillips goLITE that I was using for a few months. It doesn’t really seem to help except maybe on the margins in the darkest days of winter.

Photo credit: punch drunk

Staying Healthy in Tech

“Health Experts Recommend Standing Up At Desk, Leaving Office, Never Coming Back — Headline from The Onion

A lot of my friends were sharing that Onion article last week on social media, and like most things that are funny, there is definitely a bit of truth in it. No matter what kinds of hacks we do to make desk jobs healthier for us, the truth is, sitting (or standing) inside for large parts of the day isn’t really what the human body was designed to do.

Desk jobs are still a huge improvement over what people were doing just one hundred years ago. We don’t have to worry about black lung, 12-hour shifts on dangerous assembly lines, or back-breaking farm work. Plus, there are plenty of office workers (myself included, most days!) who actually like what they do. So I think the first step in figuring out how to make office jobs healthier is to be grateful of the fact that your job is already relatively safe on the spectrum of jobs that humans have had over the years. Practicing gratitude has been shown to make people happier, so this is an actual first suggestion!

Continue reading

"Choose your way" by alex yosifov

Choosing the Best Ideas

You’ve got ideas. I’ve got ideas. Your employees have ideas. Your customers have ideas. Lots of people would say try them all and fail fast! That’s better advice than “pick one and hope for the best”, but let’s be realistic: you’ve only got so much time so you’ll have to focus. So, how do you choose the most promising ideas to execute?

The most useful exercise I’ve used for this is to first come up with a rough strategy of how to execute the idea. Then ask yourself the two questions below. These will help you reality-check your plan and make the determination if your idea is a good one or one that should be tossed.

Question 1: What has to prove true for this to work?

Do a brainstorming session and list everything you can think of that needs to turn out correctly for your strategy to work. Sometimes you’ll come up with something absurd like “Bob can’t get hit by a bus for the first 6 months of this project”. And sometimes it will be much more insightful: “We need to make a key hire to free up some of Susan’s bandwidth so she can focus on X” or “We need to confirm that Z is technically feasible”.

The idea of this question is to unpack all of the assumptions that you’ve embedded into your strategy. It isn’t to kill the idea, though sometimes that can happen. In fact, if it’s a good idea, once you are finished with this you’ll look at all of your assumptions and say, “yeah, this has a good shot at success!”.

Question 2: Pretend a year from now this strategy has totally flopped. What was the most likely cause?

This is sometimes called a pre-mortem. The goal with this question is to help you identify the most uncertain or risky assumptions. This is important because the answer to this question will help you decide where to focus your risk-mitigation efforts.

None of this can ensure every project will be a success, but a little bit of upfront work can give you confidence to proceed. I also like to refer to my answers to these two questions when deep in the weeds of a project to help determine what I should be working on.

Further Reading

If you are interested in reading more about this, check out these resources.

Photo credit: alex yosifov

 

Business Model Canvas for Social Enterprises

Business model generation is difficult. Despite the startup renaissance currently going on, the battlefields of the marketplace are littered with seemed-great-at-the-time business ideas that were  not so great once they launched. The Lean Startup idea embraces this, teaching entrepreneurs to iterate quickly to find “product-market fit” before they run out of cash and need to get a job or go back to the coffers of their investors. In the Lean Startup school of thought, business models are sketched out on a Business Model Canvas (BMC) that is one page and can be filled out in half an hour or less. The engineer in me loves this idea. It embraces the Keep It Simple, Stupid ethos that underlies the most elegant engineering solutions.

The real world is not so simple, however. One wrinkle to the Lean Startup model I’ve been working on recently with a client is how to adapt it to a double bottom line business. A double-bottom line business is one where financial profit is not the sole goal of the owners. Talk about making an already difficult process more challenging! To solve this problem, I decided if we’re not going to Keep it Simple, let’s at least not make it too much more complex! I thought, how can I modify the traditional Lean Startup BMC to reflect a social enterprise with as little additional complexity as possible.

In some of the literature on social entrepreneurship and impact investing, there is the concept of a concessionary investment. A concessionary investment is, in effect, a grant because the investor is sacrificing a market-rate return in order to support some kind of social return on his investment. This could be providing a loan at a lower rate of interest, given the business’s credit risk, or it could be providing risk capital (equity) to a business that is far more financially risky that a traditional startup (which are risky enough!).

I like this approach to thinking of impact investing because is puts just one more constraint on a traditional business model: the fact that the business is capitalized by an investor who wants a financial return in addition to some kind of social return. This keeps the engineer in my happy, because as any good engineer knows, if you put too many constraints on a problem you will get no solution! This is how I decided to reflect the added complexity of a double bottom line business in the BMC.

I added two new boxes to the traditional BMC to capture this. The first is social good, which is non-financial value you are creating for your customers or society at large. The second is capitalization, which should describe how your impact investor (which could be yourself, if you are bootstrapping) will measure his social impact.

This canvas worked well for us, so I wanted to share it in case anyone else is working on a similar problem. If you’ve applied Lean Startup methodologies to a social enterprise, or if this was helpful to you, please let me know in the comments.

Business Model Canvas - Social Enterprise

Business Model Canvas for Social Enterprises

You can also access a version on Google Drive or a blank version.

Simple Regex to Match Options Symbology Initiative Tickers

This is a simple regular expression to match Options Symbology Initiative (OSI) tickers. It has been tested in C#:

 

Using the Draft OAuth Assertion Grant with Google+

The IETF has been working on a new OAuth standard for “assertions” which enables OAuth to work with other types of authentication systems. This can be used to allow users to authenticate with your API through Google+ or other third-party identity providers.

For example, let’s say you are developing a single-page Javascript app or a mobile app that uses both Google’s APIs as well as your own APIs. You’d like to have users authenticate with Google to obtain access to Google’s APIs, but then you’d also like your app to authenticate with your server to gain access to some additional resources. You’d like to not reinvent the wheel and use OAuth for your own API. You also implicitly trust Google to verify the user’s identity, so you don’t want the user to need to go through another OAuth flow just to use your API.

Assertion grants allow you to do this in a standards-compliant way. This is a draft standard that was just submitted in July of 2014, but for this simple use-case, it is already fairly usable.

How Google+ handles sign in for “combination” apps (with both a client and a server)

Google has some great documentation on how to authenticate both a client and a server, which is worth reading if you plan on implementing this. The gist of it is that first the client authenticates with Google through a OAuth popup or redirect. This gives the client both an access token and an access code. The code is then passed to the server to authenticate the backend.

This “passing the code to the backend step” is what OAuth assertion grants enable in a standards-compliant way.

OAuth Assertion Grants

The IETF Assertion Grant spec defines a way to define new grant types that are assertions of identity from third parties. An assertion grant looks like this (from the example in the spec):

Assertions are very similar to Resource Owner Password Credential grants in that they are passed as HTTP POSTs directly to the /token endpoint. The “grant_type” for an assertion must be a absolute URI that defines the assertion type, the “assertion” is a Base64-encoded string (using URL-safe encoding) that contains the actual asserrtion, and the “scope” is the same as other OAuth grant types.

An OAuth Assertion Grant for Google+

Since Google has not defined an assertion grant format for Google+ identity, I’ve decided to make one up! You can feel free to steal this format for your own apps.

For my Google+ assertion grant, I’ve just chose “urn:googlepluscode” as the URL. This is arbitrary, but Google would need to standardize this so we currently don’t have a better option. For the assertion itself, I use a Base64-encoded, url-safe version of this JSON:

Verifying the Google+ assertion grant

When the backend receives the Google+ assertion grant, it should do these steps to verify it:

  1. Convert the access code into an access token
  2. Call the /oauth/tokeninfo endpoint with the access token from the previous step
  3. In the response from the tokeninfo endpoint, confirm these things:
    1. The user_id matches the google_plus_user_id in the assertion
    2. The issued_to from the tokeninfo response matches the client_id of your application (both the front-end and back-end share the same client_id.

Stay tuned for a future post on how to implement this with Rails and Doorkeeper!

How secure is the OAuth2 “Resource Owner Password Credential” flow for single-page apps?

I’ve been working on a single-page, browser-based app and I was investigating using the OAuth2 “Resource Owner Password Credential” (ROPC) flow to log users in without needing a normal OAuth popup or redirect. The single-page app is written by the same developers as the backend API, so it is more trusted than a third-party application (which should never touch a user’s password). However, since it is a client-side application in Javascript, it was unclear to me how to take steps to make this as secure as possible, so I did some research. In this post, I’ll describe what I found.

What the OAuth spec says

The OAuth spec is a dense monster, but is worth digging into since so many sites are using OAuth today. The relevant section of the spec says that the ROPC flow can be used when the resource owner (the user) “has a trust relationship with the client, such as the device operating system or a highly privileged application”, which would apply to an application developed by the same developers as the API server. The spec also says that it should only be used when other flows are “not viable”. This isn’t strictly the case for single-page Javascript applications, which can use the Implicit Grant flow or the Authorization Code flow. However, for clients “owned” by the same owner as the authorization server, the OAuth popup or redirect can be a poor user experience and may confuse users since they wouldn’t expect to “authorize” an app that they perceive as one and the same as the service itself. So, assuming you trust the client and are willing to consider “bad user experience” as “not viable”, you could use the ROPC flow for a front-end client.

The other issue is that Javascript clients cannot disguise their client credentials because the user may just “view source” to retrieve the credentials. This makes client impersonation possible. It also means the the client is a “public” client for the purposes of the OAuth spec, and client authentication is not possible. The OAuth spec states that when client authentication is not possible, the authorization server SHOULD employ other means to validate the client’s identity.

How can we “validate the client’s identity” as best as possible with Javascript clients?

First, we need to accept that because that this is a public client under control of the user, we’ll have to accept that it is impossible to completely prevent client impersonation. You always could impersonate a client with cURL or a web scraper, which is something that is out of the control of the API owner. To prevent this, we’d need some kind of trusted computing architecture where we are 100% certain that the client credentials are protected from prying eyes.

Since we can’t completely prevent client impersonation, we need to define what types of impersonation we are trying to prevent. For Javascript clients, I want to prevent two types of impersonation:

  1. Impersonation by another Javascript client running in a standards-compliant browser on a domain other the official client’s domain
  2. Compromised client Javascript or HTML

Both types of impersonation are already well-known and have solutions in other Internet standards that we can use for this case.

Preventing compromised client source code

For this one, we can simply use SSL for the client’s domain. If the source code has been compromised through a man-in-the-middle attack, the user will see an SSL error in the browser. The OAuth spec already requires that communication to the authorization server’s token and authorization endpoints occur over SSL. It is permitted in the OAuth spec to have a client delivered over HTTP, however.

In order to use the ROPC grant type for Javascript clients, we need to be more strict than the spec and absolutely ensure that the client is delivered over SSL. If the Javascript client is not delivered over SSL, a middleman could tamper with the client’s Javascript to intercept either the resource owner’s credentials or the access token. This makes it impossible for the resource owner to trust the client, which breaks the first chain of trust between the resource owner and the authorization server.

Preventing impersonation by other Javascript clients

The other kind of impersonation we’d like to prevent is another Javascript client (on some other domain) using the official client’s credentials to retrieve access tokens. To do this, we can use the browser’s cross-origin security model.

If your client is on the same origin as your authentication server

If you are running a client on the same origin as the authentication server, requests to the authentication server will be permitted through “normal” AJAX and I believe that all you will need to do is not permit cross-domain requests (i.e. don’t enable CORS) on your authentication server and the ROPC flow will be unavailable to impersonating clients. Here’s why:

  • It is possible to submit a form from another domain to kick off the ROPC flow (a POST to your token endpoint), however, it is not possible for Javascript running on that other domain to access the response. This means that the impersonating Javascript may cause your API server to return an access token via a form submission, but it wouldn’t be possible for it to read that token. Since we are not using cookie-based authentication, the client needs to parse the token response for it to become authorized.
  • It is not possible for a third-party (an intermediate proxy) to intercept the token in this way because the browser will be communicating with your server over SSL (you are using SSL for your authentication server, right!?).
  • You need to ensure that potentially-impersonated POSTs to your token endpoint are not in any way destructive. Typically, CSRF attacks (of which this technically is one) lead to a compromise by either setting a cookie that is later used to access a protected resource or cause a POST that takes an abusive action (withdrawing money). You’ll need to ensure that a POST to your token endpoint doesn’t do either of these things.

If your client is on a different origin from your authentication server

If you are running your client on “yourdomain.com” and your API server on “api.yourdomain.com”, you will need to implement CORS anyway. In this case, you should leverage CORS to validate the client. Here’s how you can do it:

  • For every ROPC-enabled client, record in your API server’s database the acceptable Javascript origins for that client.
  • When an incoming ROPC grant type comes in, require your client to provide a client ID. Look up that client ID in your database and confirm that the CORS “Origin” header matches the expected origin. Browsers do not permit Javascript clients to forge the “Origin” header, making this robust against Javascript client spoofing.

Additional considerations

Since IE9 and below don’t implement CORS correctly, many sites implement work-arounds such as iframe proxies or Flash-based work-arounds. I haven’t looked into the implications of using these, but they definitely need careful consideration to make sure they are not exploitable.

You absolutely should implement some kind of rate-limiting on your token endpoint to prevent brute-force attacks.

Finally, you should never issue public clients a refresh token (or any long-lived access token). The reason for this is that, depending on your backend architecture, these could be difficult to revoke should you need to revoke access to a specific client. For example, if you are using a JSON Web Token instead of a database record, you would need to blacklist all of them it to revoke them.

Comments welcome!

OAuth2 is still relatively new (as is CORS), so if I’ve missed any ways for this to be exploited, let me know in the comments! Thanks.

Installing WxPython and RunSnakeRun on Mac OSX 10.9

I just posted about my Ctrl-C strategy for profiling and now I’m going to completely flip-flop and explain how I installed RunSnakeRun, a way to visualize the output of Python’s cProfile. The Ctrl-C way of profiling worked really well for optimizing append performance of my time series storage library, but doesn’t work so great for profiling things that are already very fast (on the order of milliseconds) and need to be faster.

For that, RunSnakeRun worked really well. RunSnakeRun gives you a nice rectangle chart showing in which functions your program spends most of its time.

RunSnakeRun's rectangle plot of function cumulative run time

RunSnakeRun’s rectangle plot of function cumulative run time

To install RunSnakeRun on Mac OSX, you’ll need Homebrew and PIP. You can install it like this:

Next, you’ll need to export a pstats database with your profiler information. Use cProfile to do this. For TsTables, you can run the benchmark with profiling information like this:

This will create a tstables.profile file in the current directory, which you can open with RunSnakeRun. Start RunSnakeRun by running runsnake  (assuming that PIP’s bin folder is in your path).

The barebones profiling method that is surprisingly effective

I’m working on profiling my time series database (TsTables) because append performance is not what I want it to be. I know that the issue is a few loops that are written in Python instead of using NumPy’s optimized vector operations. I’m not exactly sure which loop is the slowest.

I started trying to get cProfile to work, but ended up with way too much data to be useful. So I reverted to my old school, barebones profiling method: Ctrl-C.

How do you use this method you might ask? Start your program and randomly hit Ctrl-C. Wherever your program stops most frequently is the probably the slowest part. Speed that up and repeat!