Pear, Blackberry and Ginger Strudel

(Contains no pears)

The original recipe I found in “Good Housekeeping” (October 2010, pg 218), but I didn’t actually have any pears, and did have cooking apples, so … no pears. Despite this, the recipe worked well. Or at least the filling did. The filo pastry suffered from a lack of butter; margarine just doesn’t make for the same flavour, however much healthier it might be.

I’ve tried this recipe twice now, and the second time I used olive oil to paint the filo. This was suggested for another recipe I tried recently, and worked fairly well. The filo tasted nicer (much much nicer), and it also was actually crispy! If not as crisp as on the photo in the magazine.

Ingredients

  • 50g butter (or 15g butter, and some olive oil)
  • 4 cooking apples (around 725g), peeled, cored and cut into 1cm chunks. (Use ~5 pears if you like pears)
  • 15 caster sugar
  • half a tablespoon lemon juice
  • 40g stem ginger, chopped finely
  • 150g blackberries
  • Cinnamon, nutmeg, to taste.
  • 6 filo pastry sheets, each 500mm x 240mm. Ish. I’ve never actually found filo on the shelves which measures this.
  • (If you like them) 15g flaked almonds
  • Icing sugar (to dust)

Instructions

Before you start, turn on the oven to 200°C (or 180°C for fan)

  1. Melt 15g of the butter in a large frying pan. Cook the apples/pears and sugar for 2-3 mins, until the fruit is just softening. Apples might take longer than this. Empty the pan into a large bowl, add the lemon juice and ginger, stir in together. It’s at this point you can add some ground cinnamon (half a teaspoon?) and/or fresh grated nutmeg, to add a little more warmth. Leave to cool for a short while then carefully stir in the blackberries.
  2. If you’re using butter to paint the filo, melt the rest now in the pan, and then set it aside.
  3. On a work surface, lay out a large sheet of baking parchment. Place two filo pastry sheets on the baking parchment. The sheets should be overlapping by a few centimetres. Try and make sure the resulting sheet is more-or-less square. (The original recipe reckons it should be 45.5 x 38 cm. Note that is is impossible with the filo dimensions they suggest, but it’s a good guide). Brush with the butter or the olive oil. Layer another two filo sheets on top. Brush, layer, brush.
  4. Spoon out the fruit mix along one of the long edges of the layered filo. Leave about 2.5cm on each end. Fold the ends up over the fruit, then roll up the filo. Et voila, your strudel!
  5. Using the parchment, transfer it to a baking sheet. You might end up needing to trim the baking parchment so it doesn’t overhang the tray in the over. Brush with butter/olive oil. If you like almonds, sprinkle them over now. Bake in your oven for about half an hour, or until crispy and deep gold. Dust with the icing sugar, and serve with custard.

Authentication And A Web App

Introduction

This blog post comes off the back of a question asked on the sinatra mailing list about the mechanisms behind authentication and authorisation in web applications. I wrote a fairly lengthy reply to the question, and this blog post is just going to put it in some order. While the original question was related to sinatra, I’m going to try and present things in a more general context, though direct examples and links are probably going to be ruby. Don’t read this blog post expecting great new revelations, it is pitched at the ‘curious beginner’ level.

I should also note this just relates to storing user passwords and checking them. It doesn’t cover SQL injection, Cross-Site Scripting or anything else you should consider to run a secure site.

First, Some Questions

The most important thing about authentication is to ask yourself what are you actually doing. The answers about appropriate measures depend greatly on what it actually is you’re trying to secure at the very least, but there are other considerations too.

  1. How valuable is the data you’re trying to secure? (Not necessarily monetary value, here)
  2. How many users do you have?
  3. Are all users created equally?

This blog post is assuming the answer to question 1 is “Typical Web Application” (i.e. most assuredly not anything involving sums of money. Please seek more expert advice before doing that). Questions 2 and 3 will be considered for a few separate cases.

One User To Rule Them All

If you’re writing a simple site with only one user (for example, a blog with one author, and anonymous comments) a simple solution is to hardcode some username and password pair into the application. This is very easy to accomplish, and can save a lot of worry about storing passwords. Just check the credentials against those a prospective user supplies. If they match, they’re in.

There are a few downsides, though. First, the application is then only as secure as the source code. Fine if it’s all local, less fine if you push the file up to github. Adding more than one user can be problematical. And changing the password requires a restart of the application, in all likelihood.

Multiple Users

If your app requires multiple users (this is the vast bulk of web apps, I imagine) then you probably want to store your users in the database. Which database I’m not going to get into. You’ll probably also be using this database to store other things (the posts users will write, or photos they’ve commented on or ingame items they have) or whatever.

Alongside information like the username, you’ll also want to store the password, so you can check a user is who they claim to be. To be more accurate, you want to store something you can use to check the password. Ideally, you don’t actually store the password in plain text—if you do, and the database or a backup is compromised, then all your user’s passwords, many of them shared, will be available for the world to see. Instead, you can hash the password in some way. Cryptographic hash functions take data (the password) and produce a string of bytes (the hash) via a complex mathematical function. So if you store the hash of the password, it isn’t immediately obvious what the password is, but by running the same hash function on the password the user supplied to log in, you can directly compare hashes and so verify.

This worked great a few years ago. But since then, computers have gotten faster, and there are rainbow tables too. It’s not actually that hard to simply store almost all the information you need to decipher a password from the hash. So, enter salting the password. To do this you add a second, random, value to the password before you hash it and then store the salt along with the hash. When the user logs in, you check the password in the same way. The presence of the salt makes brute-forcing the password from the hashes a lot more difficult.

If this sounds like hard work, I suggest you use BCrypt. It takes care of salting and hashing the password for you, and in addition, unlike most cryptographic hash functions, it’s designed to be slow. Which has almost no impact on your site, trying a password once, but really slows down brute forcing a password from a database dump.

The Padrino framework, built atop sinatra, stores passwords encrypted via symmetric encryption by default. The password is decrypted and checked on a login. I don’t particularly see the benefit of this for a webapp, and think it represents a security hole since compromise of the database is also likely to be compromise of the application, and thus the key is available. I also don’t particularly mind password reset emails. Better that than have passwords and usernames to a bunch of web services sitting around in my inbox. But for internal applications, this might be more appropriate. Only you know which fits better.

Returning Users

Your users probably want to do more than one thing on the site you’ve developed. And typing in their password every time would get annoying in the extreme. To avoid this, you can set cookies. Cookies are small bits of text (more or less) which can be set via a HTTP header from the server. The browser then helpfully sends them back with each request.

So, after a user logs in, you give them back a cookie. This cookie probably contains something to identify them. This could be their username or id number. When the user next makes a http request, this cookie is returned, you check the value they supplied and if it checks out as a valid user, they’re that user. Done!

Or not. Notice what I wrote there. “Check the value they supplied”. The cookie is entirely controlled by the user. They can send anything they want. Like username ‘theAdmin’ rather than ‘joeQUser’ and suddenly your user is an admin; hijinks ensue. How big a problem this is depends on just which identifier you’re using. A username is probably very easy to guess, as is an integer id. A UUID might not be, so long as your code doesn’t give it away on a separate page.

To avoid simple guessing of a valid coookie, the content of the cookies can be signed. This is most easily done via embedding HMAC (Hashing Message Authentication Codes) signatures in the cookie text. The HMAC is calculated using the message (cookie) text, and a secret (which should be selected randomly, and in the case of hmac-sha1, should be 20 bytes long). When a cookie is received from the user, the HMAC can be tested, and if it is valid, used to authenticate the user. Some care needs to be used in testing the signature, to avoid timing attacks and to protect the secret, but other than that, one can be reasonably sure of validity of the cookie.

Another alternative is to avoid sending the user any session data directly. Instead, just return a random string in their cookie. This random string is used as the key in a server based session store. Redis could be used (more on this in a seperate post), a database or even static files. When the cookie is checked, the session is loaded from the datastore, and the user authenticated. This does increase server load, but allows for private (not seen by the user) session data. Which is right, depends on the application.

Winding Down

So, that was a brief introduction to safely storing passwords and authenticating users, as well as persisting their logins over more than one request. This might seem like a lot of things to worry about, but in ruby at least, a lot of these things are taken care of for you. Rack, the ruby web standard, HMAC signs cookies if you provide a secret. Many of the ruby authentication libraries produce user models which at least SHA1 hash + salt passwords, and support using BCrypt. There are also implementations available for storing sessions in Redis or database. If ruby isn’t your thing, your own language probably supplies it too.

Tune in later for a look at authorisation. This will cover how to handle the case where all users arn’t equal.

Bara Brith

Bara Brith is a Welsh tea bread. This particular recipe is taken from “Mary Berry’s Ultimate Cake Book”. It’s an exceedingly easy recipe to make, though it does need some planning ahead. Bara brith is great to bake for a snack, either for after lunch, or when you get in from work. The loaf you end up with keeps well for a few days … if you can manage not to eat it. ;)

The recipe itself is pretty forgiving. The ingredients I’ll list below are from the book, but they can be changed about. The last bara brith I made used dark muscovado sugar, and used raisins, not currants. I’ve also experimented with adding some chopped up stem ginger when its set to soak, and a little powdered ginger to the mix, but I haven’t got the quantities right yet. For my tea, I just use Tetley’s, but one of these days I’ll try it with something like Assam or English No 1 tea.

Ingredients

  • 175g currants
  • 175g sultanas
  • 225g light muscovado sugar
  • 300ml strong hot tea
  • 275g self-raising flour
  • 1 egg, beaten

Instructions

  1. Measure the fruit into a bowl. Brew the tea (I use 4 teabags, left to seep for 3-4 minutes). Mix the sugar into the tea, then pour over the fruit. Leave to soak overnight.
  2. Preheat the oven to 150°C. Lightly grease and base line a 900g/2lb loaf tin with greased greaseproof paper.
  3. Stir the flour and egg into the fruit mixture and mix thoroughly.
  4. Turn into the prepared tin, and level the surface.
  5. Bake for an hour and a half to an hour and three-quarters, or until well risen and firm in the centre. To test, a fine skewer inserted into the centre should come out clean.
  6. Leave to cool in the tin for around 10 minutes, before turning out to cool completely on a wire rack.
  7. Enjoy sliced and buttered.
Tagged baking

Magical Reloading Sparkles

A little background

I write web applications in sinatra. It’s great for the small applications I use to make my days a little smoother. I currently have an app to track and graph my weight, another which acts as a simple feed aggregator and a third for jotting down random notes. I hope to expand the repertoire fairly soon with an addressbook application and perhaps a personal wiki. To serve the sinatra applications, I use unicorn. It’s a rack webserver, based on the fork model. So you have one master process, and at least 1 worker which is forked from the master process. The worker actually deals with the requests, the master just hands them out.

With those introductions out the way, lets get to the point. One “problem” with developing on sinatra is it has no code reloading. Code reloading is the process which lets you change a file on the disk and have those changes reflected in the running webserver without needing to manually restart the whole thing. It saves a lot of tabbing about and repetitive effort. I say “problem” because there are a few solutions out there for it. Shotgun was one of the first. It forks a new process to handle each request, guaranteeing a clean memory space for each. This process loads the code and serves the request. This works, but can get very slow. Especially if, as is usual in development, CSS and javascript are being served by the rack process; shotgun doesn’t care, it forks anyway. Another solution is rerun. Rerun watches the filesystem for changes, restarting the whole application when it sees them. This is generally a better solution than shotgun’s restart model, and I used it for a while; restarting takes longer, but its done less often. There is also sinatra-reloader which is sinatra specific, and I haven’t tried. There are probably more, too.

My own solution

rerun has one problem, from a certain point of view: It does too much work. Since it reloads the whole application, it reloads all the gems and other library code as well. If you’re using the array of gems ruby offers to you, this can be a significant part of the boot time. And that’s just unneeded; code in gems is generally static, at least over the timescale of a coding session.

Enter unicorn. I mentioned earlier that the worker process is forked from the master process. Unless you set preload_app true, the worker loads the sinatra application when it forks; the master has no copy of the application code in this case and each worker is a clean slate.

What is forking? The fork(2) system call creates a duplicate of the parent process with its own pid, but shared file descriptors and more importantly, with the same structures loaded in memory. In linux, this is literally the same memory, the kernel implements copy-on-write, so only changed pages are actually in separate memory locations. If this is combined with the fact that ruby doesn’t require the same file twice, any code we load in the master process is code the worker doesn’t have to. And unicorn helpfully provides a before_fork hook.

The important details in this file are the list of gems and libraries to require in the before_fork hook. This could easily be replaced with a require statement to a more centrally located file the application uses. These files will only be required once per session, so it should only be used for stable code; only you can decide what that means for your app. For details of the other options, see the configurator docs.

Now for the reloading. One great thing about unicorn is it listens to signals. These can be used to control it in a number of ways, but the one we’re interested in is SIGHUP. This makes unicorn respawn its workers, which will reload the application. So now all that’s needed is something to watch the appliction for changes, and do something about that. This is accomplished with the excellent directory_watcher gem, which hooks into the kernel’s file notification system, so no loops for polling on file mtime.

This script starts the application using a daemonized unicorn. It then sets up a couple of watchers. The first one looks at the logfile unicorn provides, spooling that out into the terminal as lines are written to the file. The second watches a glob of files, reloading the application as they change. But thanks to the prefork model of unicorn, only your application code needs reparsing. On my laptop, this cuts restart time approximately in half.

Closing remarks

This solution works for me, but it is a little rough around the edges. The file watching script could probably be cleaned a lot, and use some command line option parsing to make it more flexible. As it stands, the script lives in the application root.

Another problem is if you introduce any errors on loading files, the worker process will thrash. It tries to load, dies on loading, and then gets respawned; repeat ad infinitum. It would be neat if some logic could be added to stop this somehow.

But other than that, it works great. And it was fun putting the pieces together.

Edit: Thanks to khaase for pointing out a few simplifications to the watcher script.

Tagged rack ruby unicorn

Chocolate Brownies

This recipe was taken from “101 Cakes & Bakes: tried-and-tested recipes”, from BBC books. I made them for my cousin’s 21st birthday present, as a little extra treat. They were exceedingly rich, exceedingly chocolate-y and exceedingly delicious. I’ve made them again, but only if I know I have someone to share the results with.

As recipes go, it’s pretty simple to make and didn’t take too long. I used a different shaped tray than the one called for here, that was a little smaller, but deeper. As a result, I had to keep the brownies in the oven for a little longer than the recipe called for.

Ingredients

  • 350g dark chocolate (preferably around 50-60% cocoa solids), broken into pieces. I used Green&Blacks 72% organic cooks chocolate. Mmmm~
  • 250g unsalted butter, cut into pieces
  • 3 large eggs
  • 250g dark muscovado sugar (or molasses)
  • 85g plain flour
  • 1 tsp baking powder

Instructions

  1. Preheat the oven to 160C (or 140C for fan). Butter and line the base of a shallow 23cm/9in square cake tin.
  2. Melt the chocolate and butter together, then stir well and cool. This was done in a glass bowl over boiling water.
  3. Whisk the eggs until pale, then whisk in the sugar until thick and glossy and well combined. Gently fold in the melted chocolate mixture, then sift in the flour and baking powder and stir gently until smooth. The resulting mixture should be fairly gloopy, but will pour.
  4. Pour into the tin and bake for 30-35 mins, or until firm to the touch. Test to see if the recipe is ready by inserting a wooden cocktail stick in the middle – there will be a few moist crumbs sticking to it. Ideally, the mixture should still be soft in the centre; it will firm up on cooling.
  5. Leave it in the tin to cool for at least an hour, then cut into squares and finish cooling on the rack.
Tagged baking chocolate