Some Bits: Nelson's log

15 posts in April 2015

postgres: setting up permissions for a user

I wanted to give a CGI script access to one specific postgres database, both read and write. This is remarkably complicated. I ended up creating a password protected role named “oarunone” and gave it access to a database named “oarunone” (yes, confusing) and one table named “queue”. Something like:

  • create role oarunone with password ‘secret’;
  • grant all privileges on database oarunone to oarunone
  • grant all privileges on table queue to oarunone

But that’s not good enough. Ubuntu’s default postgres only identifies users via the Unix UID. So you also have to add a line like this to pg_hba.conf. and it has to occur before the catch-all “all” rule.

  • local oarunone oarunone md5

That says allow the role “oarunone” to authenticate with a password (MD5ed), but only from a local Unix domain socket and only to the database “oarunone”.

OpenAddress machine continuous queue

Migurski and I have been working up a new architecture for OpenAddresses, specifically the python code that runs source jobs. Currently everything runs as a big batch job every two days. The primary goal is to get a system that can run a new submitted source instantly, ideally with useful feedback to the submitter.

Mike’s insight was to build a system a little like Travis; something that looks at GitHub commits with a hook, runs a new job every time something is committed, and posts back info via the GitHub status API. GitHub is nice because it provides a file store and change tracking. Ultimately we don’t want to require a GitHub login to submit sources, and we probably want a custom UI, but that can come later.

Here’s the components we’re talking about building:

  1. A GitHub webhook that submits info to our new job server when stuff is checked in.
  2. A new job server that accepts HTTP posts of GitHub events. Mike’s got one working in Flask running on Heroku.
  3. A job queue. New jobs get enqueued by the new job server, then some worker daemon process checks for jobs to run and executes them. Can be a very simple queue, but needs to support job priorities (interactive vs. batch). Right now I’m thinking of writing my own using Postgres running in Amazon RDS, but there’s got to be something I can just use that’s not super overkill. (Update: pq looks good.)
  4. Workers to run jobs. Something to look for new jobs and execute them. Current thought is a persistent Unix server running on EC2. Installs openaddr and its dependencies via pip, then runs jobs via openaddr-process-one, then posts results back to the job queue result queue.
  5. Job completion notifications back to GitHub using the GitHub status API. Mike has been tinkering with code to do this already.
  6. A batch-mode refresher. Something to run sources periodically even if no one’s edited the source specification in awhile. Mostly to catch new data on the remote server.

Here’s some open things to design.

  1. Job status reporting with humane UI. Currently we get very little info back from when a job is run. A few bits of status (did it complete, how long it took), a debug log from the process, and any actual output files. We need more. In particular I think the stuff you currently learn from the debug log needs to be expanded to useful user-level event data. Ie, events like “source JSON parsed”, “source data downloaded”, etc.
  2. UI for creating source specification JSON files. Imagining some guided wizard like UI using Javascript and forms. There’s already a pretty good one on the live site, just needs some expansion. Also ultimately we shouldn’t require a GitHub login.
  3. Security. A bit nervous running completely unreviewed source specs from anonymous people. Isolating the worker in a throwaway machine might help. Or doing some sanitization on inputs.
  4. Statistics reporting. I have a dashboard that works OK for the existing nightly batch mode, but we’ll want something different for this continuous mode thing.

See also OpenAddresses Mark 3, a proposal I sketched in January. What we’re doing here is similar but without the component of breaking any individual source run up into separate tasks.

Cyberduck is responsible for my bad SSL certificate

I figured out what put the rogue SSL certificate on my system, the one that breaks MacOS Mavericks. It came back yesterday 2015-04-27 between 15:38:32 and 16:41:02. The system Console helped me narrow it down to the application Cyberduck, version 4.6.3. I use it sporadically to browse S3 buckets. It’s just the right kind of unusual application that would cause a bug like this that some small group of users on the Internet finds but not everyone.

Cyberduck 4.6.3 placed a bunch of errors in the console, including the smoking gun “4/27/15 3:42:05.621 PM Cyberduck[54126]: Error adding certificate to Keychain”. I also manually verified the login keychain entries show up again as soon as I run Cyberduck after deleting them. (For completeness I should add Cyberduck also complains about an SSL hostname mismatch when connecting to S3, but I think that’s a legitimate and expected error and unrelated to the Verisign certs.)

Version 4.7 (17432) is the latest version of Cyberduck. It doesn’t cause the problem any more. There was a reported and fixed bug in Cyberduck. I’m not sure the Cyberduck authors understand the magnitude of the problem though, or that users of old versions now have broken Macs. We now have a bug report on file, my report text below.

I also don’t understand the root cause of the problem. Cyberduck says they were taking a certificate offered by the server; Amazon S3, in this case. Were they verifying it was a valid cert first? If so, then why is it no longer a valid cert? And why did MacOS security update 2015-004 break it? I’m content to let that all remain a mystery, but I’m curious.

Update: this AWS discussion contains complaints about S3’s SSL certificate. Apparently it’s a key that is weakly signed and various software is deciding it’s no longer valid as they update to stricter requirements. That may explain why 2015-004 changed things.

For the search engines: one of the two bad certificates placed on my keychain by Cyberduck was “VeriSign Class 3 Public Primary Certification Authority – G5”

Bug report for Cyberduck

Prior to version 4.7, Cyberduck had code where it wrote some SSL certificates to the user login keychain. This behavior is documented in ticket #8741 and the code was changed to no longer do that.

However, the certificates old versions of Cyberduck wrote to the Keychain are now causing fairly serious problems with MacOS. Affected Macs can no longer verify Verisign-signed SSL certs in any application. Symptoms are the App Store refuses to load, MacOS software updates won’t get installed, Chrome refuses to load websites and Safari throws errors. It’s pretty bad. The problem seems to be triggered by Mavericks security update 2015-004 (released last week).

The fix is pretty simple: manually delete the spurious entries in the login keychain (so that the system entries are used instead). But users aren’t going to figure that out on their own. There’s no indication to the user there’s a problem with their keychain or that Cyberduck was the app that created the problematic entry. I only figured it out thanks to some lucky timing and a message on the system console.

While Cyberduck 4.7 no longer causes the problem, anyone who used an older version of Cyberduck may still have a broken Mac. Could Cyberduck do something to notify affected users? Maybe a new version of Cyberduck that checks for the bad entries and warns the user, pointing them to a help page?

It’d also be nice to figure out exactly what entries Cyberduck might have written. For me and a bunch of other users it’s two Verisign certs, one named “VeriSign Class 3 Public Primary Certification Authority – G5”. They seem to have come from Amazon S3.

Some references:

http://apple.stackexchange.com/questions/180570/invalid-certificate-after-security-update-2015-004-in-mavericks

https://discussions.apple.com/thread/6984765

https://trac.cyberduck.io/ticket/8741

https://nelsonslog.wordpress.com/2015/04/25/mavericks-security-update-2015-004-has-a-serious-ssl-bug/

inserting lots of data into a remote Postgres efficiently

Update 2017: psycopg2 now has fast execution helpers. Not sure why they didn’t just improve executemany.

I’m using a Postgres server in AWS in the us-east zone. My database client is running in California, so it’s about 150ms away. I do not expect this to be fast. However I don’t expect it to be super-slow either. Inserting 700 rows in a single transaction was taking 60 seconds. That’s absurd! (Rows are ~100 bytes each, this is not a lot of data).

Thanks to StackExchange I found a solution. Here’s some untested code that illustrates the idea:

# Clearly slow to insert one row at a time
for row in myData:
    cur.execute('insert into data values (%s,%s,%s)', row)

# Should be much faster, but isn't
cur.executemany('insert into data values (%s,%s,%s)', myData)

# This hack is much faster
dataText = ','.join(cur.mogrify('(%s,%s,%s)', row) for row in myData)
cur.execute('insert into data values ' + dataText)

That funky last idiom basically expands all of myData into one giant SQL string with multiple values. For my use case, that 60 second operation went down to 1.5 seconds. This hack works, but you’re going to bump into a query size limit at some point.

Note that mogrify() isn’t doing anything clever, it’s just doing safe expansion of SQL query strings to avoid Little Bobby Tables. (There’s a Unicode error lurking here; I switched to Python2 just to make this work.) Also note that transactions don’t seem to be to blame here. psycopg2 by default runs a transaction for every connection; nothing commits until you call commit().

I think what’s going on is that psycopg2 doesn’t optimize the implementation of executemany(). Internally it’s just doing something like a loop calling execute() for each row. I don’t have proof of that, but my research turned up other people saying that was the problem. (See here)

(As an aside, what is it with database adapters for various languages that make them so universally bad? psycopg2 isn’t terrible, but it’s hardly joyful Python software. At least it’s better than the mess we had with mysql for so many years. Back in the Java days we used to have a terrible time trying to talk to MySQL as well.)

Cloud database prices

I’m looking at buying a hosted/managed Postgres in a cloud server. Amazon or Heroku.

Amazon RDS has a confusing array of pricing options. The smallest instance (db.t2.micro) is $0.018 / hour, or $13 / month if it’s always on. Data costs $0.115 / GB-month, so a 64GB database would be $7 / mo. Total cost for a smallish database: $20 / month.

Heroku Postgres has a very limited free tier. The hobbyist tier is $9 / month and gives you “10M rows” with who knows what performance. The basic standard tier starts at $50 / month for a 64 GB database. Hard to say for sure, but I think that’s roughly comparable to our $20 / month database on Amazon.

Of course what really matters for a service like this is price scaling, how easily you can add more performance and what you pay for it. I’m not worried about that for my small project, just good to have some ballpark numbers.

Scrolling vs headers and footers

More and more web pages have broken the page down key. Fixed-height headers and footers on top of web content don’t bother me, but the article underneath them never pages correctly. Because it’s paging the full window height and the header/footer has hidden part of the document, so you never see it.

This used to only be a problem on shitty websites that had all sorts of bad layout. But now even high design websites like the In Focus photojournalism gallery have broken the paging behavior with a header. Medium was a holdout for a long time, it even had a fancy thing where the header hid itself when you scrolled down a page. It still does that but now there’s a fixed 20px footer that obscures text that disappears when you page down.

What I’m wondering is why no one fixes this with Javascript. Maybe overriding paging behavior is difficult? I asked Marcin Wichary once about Medium and he said it was hard to make it work consistently in all browsers. There’s certainly ways to scroll the window and I imagine you can trap the page down key to invoke your custom scrolling code. Would be worth tinkering if it could be turned into an extension that worked for sites that don’t work right now.

Mavericks security update 2015-004 has a serious SSL bug

My Mac suddenly started throwing SSL errors when connecting to various sites, like search.twitter.com or support.apple.com. The App Store application refused to load content, too. Long story short, MacOS Mavericks 2015-004 has a bug where an incorrect certificate named “VeriSign Class 3 Public Primary Certification Authority - G5” is placed on the user’s login keychain. The fix is to run Keychain Access and remove it. Note: remove the one in the login keychain, not the System Roots.

Update 2: 2015-004 doesn’t put the entry on the login keychain, something else put it there earlier. 2015-004 does seem to change something though that triggers the verification problem. The fix is still to remove the key from the login keychain, I just don’t know what put it there in the first place.

Update 3: turns out it’s Cyberduck that’s writing the certificate entries.

This error seems really serious to me. Macs that are affected can’t get new software updates. Also Chrome will refuse to load any websites with SSL certs signed by that VeriSign certificate, including Apple’s own sites. Safari will load the site but will display SSL errors. Apparently Chrome is more strict in enforcing SSL security.

(I thought it was particularly interesting that it was impossible to get Chrome to visit Twitter. Twitter only serves HTTPS, not HTTP. And they have HSTS enabled which means Chrome will refuse to load a page without a working SSL certificate. Well that all succeeded, but boy was that a bad experience.)

Here’s some links with more discussion: Ask Different, Security StackExchange, Apple forums. I exported the two Verizon certs that were on my login keychain that were the problem, there’s a zip file here along with some screenshots of failed SSL certs. (That file won’t be online forever.)

I seem to be hitting a serious bug like this in MacOS every couple of months. Along with some broken-by-design things like their SMB client and I really am tempted to try going back to a Windows desktop. Or maybe Linux, if it weren’t so damn ugly.

Update 1: thanks to Ned’s suggestion in the comments I tried figuring out how those VeriSign certificates got in my keychain in the first place. I still don’t know, but looking at backups in Time Machine I can see it was placed there sometime between 2015-01-17 and 2015-02-23 13:48 (the two backups I have from before and after.)
$ grep -i verisign */Macintosh\ HD/Users/nelson/Library/Keychains/login.keychain

The Mac was turned off from 2015-01-08 until 2015-01-17 and again for 2015-01-21 until 2015-02-23. It seems likely the VeriSign entry ended up on my keychain when I turned the Mac back on. But it would have happened quickly; I entered the house at 13:42 and it’s in the keychain at 13:48. And my network is very slow. It could also have happened sometime between 2015-01-17 and 2015-01-21.

FWIW there’s a bunch of updates that installed a few hours after the keychain update, 2015-02-24 04:00 AM, including Security Update 2015-001 and Safari. But the keychain entry precedes those. Between 2015-01-17 and 2015-02-23 I only have a bunch of updates from “Google Voice and Video” and one from Seil, a keyboard kernel hack. Also FWIW I’m not given to manually tampering with my keychain nor blindly approving requests to manipulate it.

Complex QOS rules considered harmful

tl;dr: some router firmware has a catch-all rule that throttles all unidentified UDP traffic to 5% of bandwidth (labelled “Crawl”). This is a stupid rule, disable it.

I just fixed a bug in my router’s configuration that explained why Google QUIC was not working well for me. It may also explain bugs I’ve been seeing in League of Legends, OpenVPN, and other UDP protocols. I’m not entirely certain.

I’ve been running the Tomato v1.28 (Toastman) firmware for a year+ now. It’s an old build. It has 40+ default QoS rules identifying all sorts of protocols from important ones (DNS) to silly ones (RealAudio streaming), and then classifies traffic service level. Unfortunately some of the rules are harmful.

The problem rule in this case was the very last one. “UDP Dst Port: 1-65535, classify Crawl”. And Crawl by default is limited to maximum 5% of total bandwidth! There are a few higher priority rules that classify specific kinds of UDP traffic: DNS, for instance. But any new or unanticipated use of UDP is severely throttled. Such as QUIC, Google’s fancy new web protocol. And Cisco VPN. And maybe OpenVPN.

And maybe League of Legends; it’s a UDP protocol too, and hasn’t performed as well on my slow network as I expected. Just playing a game feels about the same, maybe a little less laggy, but there’s still the same unexpectedly high packet loss. But I think one reproducible bug is gone now. Jayce gates cause a brief surge of UDP packets; it used to be that caused significant lag even when playing alone. Now they don’t cause lag.

The simple fix is to adjust the Crawl class to also get up to 100% of bandwidth (both inbound and outbound). That may still have lower queue priority though. You can also try adding more rules for UDP protocols you care about; QUIC is on ports 80 and 443, for instance. But trying to label all known UDP protocols is a Sisyphean task.

I can’t imagine why anyone ever thought a 5% cap for default traffic was a good idea. Particularly for a UDP protocol which may not even be able to interpret those dropped packets as a signal to rate limit itself. Judging by the comment they were trying to catch unidentified BitTorrent traffic, which must have its own rate limiting. But still, what a dumb rule.

After several years of using QoS on home routers I’m of the opinion that QoS rules cause as much trouble as they fix. It’s certainly caused me a lot of problems. In a home network there’s no meaningful way to shape incoming traffic at all. You can shape the outgoing traffic a bit, and I think prioritizing ACK is probably a good idea. (Although weirdly this behavior is not the default). But in general the QoS implementations out there complicate things a lot and don’t provide a lot of value.

It’s time to go back and look at what the Bufferbloat guys have accomplished recently, and whether fq_codel or something similar has gotten traction. Their approach seems much simpler. Last I checked no Tomato variant supported it.

QUIC problem

Update 2: this was a bug in my router, not QUIC. See below, I also posted to the QUIC protocol group about it.

The Google is broken on my computer. This happened once before. Web sessions to every site on the Internet work fine except Google properties. Those hang for ~15 seconds for every web request in Chrome. Safari requests work fine.

Both times this has happened to me have been up in Grass Valley, the place with the shitty fixed wireless Internet. And both times when I’ve looked in Wireshark there’s some QUIC protocol stuff happening, I don’t know what. But my guess is that Chrome is deferring all requests to QUIC and they have a bug / bad interaction with my ISP where it doesn’t work right.

I could swear I once saw some QUIC diagnostic info inside Chrome. Or at least a way to disable QUIC entirely. Can’t find it now. Of course it’s hard to find things when Google doesn’t work. Edit: found the disable, it’s in chrome://flags. The statistics are in chrome://net-internals/#quic. The moment I disabled QUIC Google searches worked better. Interestingly, simply restarting Chrome didn’t help, at least not completely. I lack the patience to test this carefully, no point if no one’s going to pay attention to the result.

In desperation I’ve tried using Bing. It’s not as good as I remember. In the past I didn’t like the UI but the relevance was mostly good. But now the relevance is bad. They were returning URLs for RSS feeds on Metafilter for searches. WTF?

Update: I have a theory! It may be my router QoS settings. Tomato / Toastman 1.28 doesn’t have a rule for QUIC, but does have a default rule that all UDP traffic otherwise not classified is assigned the category “crawl”, which is limited to just 5% (40kbps) on my network. D’oh! I wonder if this also is responsible for my worse-than-expected League of Legends performance here. I added a rule for QUIC (UDP ports 80/443, classify WWW). Also raised the bandwidth cap on “Crawl” to 100% traffic, that was a dumb default rule. Now to try it out for a few hours...

Python3 zip() is a hassle

A Python3 annoyance; zip() now returns an Iterable, not a list. That means you can’t easily slice it.

In Python 2, this idiom for getting back the first column of a database query was useful:

cur.execute('select ...')
r = cur.fetchall()
firstColumn = zip(*r)[0]

In Python 3, this gives you an error

TypeError: 'zip' object is not subscriptable

The workaround is to wrap the zip in a tuple or list

r = cur.fetchall()
firstColumn = tuple(zip(*r))[0]

Annoying, but it doesn’t actually run any slower. I imagine you could use slice() or itertools.islice() to produce an iterator view of a slice of the zip iterator.

Mac fan control

My ~3.5 year old iMac is making noise. Just a small noise, but it’s high pitched and annoying. Something mechanic, presumably a fan bearing. So I started trying to isolate the source of noise. It isn’t the internal spinning drive, you can turn it off by unmounting all the volumes. I’m not using the optical drive. So maybe a fan?

The tool to test a Mac’s fans is smcFanControl, a simple tool to read the temperature and fan speed settings and alter fan speed. When you run it it requires root access, then goes into your menubar. You can set the minimum fan speed for each fan separately. It works pretty well. I used it to run each fan at full speed and crikey, my Mac sounds like a vacuum cleaner. Never heard those fans run before! Didn’t really notice a change in the sound but it’s hard to be sure. Maybe my optical drive fan is to blame. Unfortunately you can’t set turn the fans off entirely; the apps docs say this is possible but not enabled for safety. A quick search didn’t turn up any easy hacks, either.

On a side note, apparently there’s no good CPU/GPU/Memory burn-in tool for Macs. At least not a free one. The #1 suggestion from Google searches is “run yes > /dev/null”. Which, well, that works a tiny bit but it’s not even exercising the whole core of a single CPU, much less the whole system. There’s a bunch of good tools that run under Windows, too bad no one’s bothered to port one. The core load generator doesn’t need to change (much?) but the GUI is a problem.

Simple Javascript time series charts

I want to draw a time series graph in Javascript. This is one of the simplest kinds of regular data visualizations and all of the libraries I find to do it suck. I looked at this a year ago, is anything better now?

What I want is a library that will automatically assign axes and draw correct time series graphs. The time intervals are not regular. Also sometimes data is missing. Not zero, null. Remarkably, very few charting libraries seem to be able to handle these common requirements. Here is some very quick evaluation, I spent ~3 minutes on each library so may have mischaracterized something or overlooked some greatness.

  • Charts.js: too low level, really a graphics library for drawing colors in canvas
  • Flot: good ol’ flot, just seems too old. Maybe that’s foolish and it’s solid?
  • D3.js: great library but too low level. I don’t want to build my own axis and don’t really want to program at all, just declare data.
  • Metricsgraphics: promising library at the right level, but seemed buggy. I spent about 90 minutes trying to get a time series to render and depending on my Date range, either got a decent graph or got confusing SVG rendering errors involving NaN.
  • Rickshaw, xCharts, Ember, and d3.chart look to all have very slow or no development. Rickshaw was promising, I wonder if it’s just “mature”.
  • Dimple’s time series seems to assume equal spacing
  • NVD3 has been around a long time and is still active. It’s kind of a sloppy project though. The example code on the site doesn’t match what’s live. Some of the examples kill Google Chrome when run. There are no reference docs. I give up.
  • Vega looks too toolkitty and not enough libraryish. It frames itself as an analog to Protovis or D3, and I already know one of those. Also no time series example.
  • new TauCharts looks promising.

I need to investigate Highcharts. It’s not free software, but is free for non-commercial use.

dygraphs is sort of promising. It actually plots my data correctly but the default style is ugly. Also I’m not wild about canvas. It does a lot of fancy time series stuff out of the box though.

dygraph sample

Python3 est arrivé

I’m now using Python3 by default for all new projects. Almost entirely because I prefer sane Unicode handling. But really because Py3 has turned the corner and is now useful for most things. Probably it turned that corner a year or more ago, but it was the OpenAddresses work that made me start using Python 3 regularly. It helps that Homebrew and Debian both make it very easy to install ‘python3’ and ‘pip3’. And of course that most packages I care about are now ported over.

It took Python five years longer than I expected for the Py3 transition to get to this point. Let’s hope we don’t have to do it again.

Address schema

Some stuff of possible interest to OpenAddresses. The US government’s Federal Geographic Data Committee standardized street address schema. The docs are 140 pages of text describing an XML schema, which sure seems wordy, but then it’s also very precise. They even put the XML schema online, here’s a text rendering.

It’s super wordy and contains a lot of detail, but at the core is a schema we could repurpose that says things like “a street address consists of a number, a prefix, a street name, ...”

There’s a good summary of the schema on page 3 of the executive summary. Here’s the meat of it:

Screen Shot 2015-04-09 at 10.57.41 AM

MacOS security update only for Yosemite

Apple designed MacOS with an API that lets you escalate privileges from any user to root without proper authentication. No, really. This leads to CVE-2015-1130, details not yet published. It’s a pretty severe bug from the looks of it; not quite a remote exploit, but once an attacker can run code on your system they are root. Apple pushed a patch for it this week. But only to Yosemite.

The shape of the bug is really ugly too. It looks like Apple put in some weird backdoor API for stuff to escalate to root, so you can run Preferences or the like as a normal user. And they tried to lock that down in various ineffectual ways, like userspace binaries checking if they are running as root, but left the API in the kernel. Ugh.