1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
require "pro_tacts"
require "sentry-ruby"
require "rack/rewindable_input"
require "nokogiri"
require "roda"
require "pro_tacts/debug_logger"
require "pro_tacts/addressbook"
require "pro_tacts/tailscale_auth"
require "pro_tacts/unhandled_requests"
require "roda/plugins/dav_verbs"
module ProTacts
class Web < Roda
# @rbs @addressbook: Addressbook?
# RewindableInput allows us to read the request body for Sentry logging
# and then rewind it so the application can still access it.
use Rack::RewindableInput::Middleware
use Sentry::Rack::CaptureExceptions
# Ahead of the debug logger on purpose: an unauthenticated request should
# not get its body dumped to the log.
use ProTacts::TailscaleAuth
# Below the auth gate: a refused request is not missing functionality,
# and recording one would write an unauthenticated body to disk.
use ProTacts::UnhandledRequests, directory: ProTacts.config.unhandled_dir
if ProTacts.config.debug?
logger = ProTacts::DebugLogger.open_log(ProTacts.config.debug_log_path)
use ProTacts::DebugLogger, logger: logger
end
plugin :all_verbs
plugin :dav_verbs
plugin :not_found do
Sentry.capture_message("404 Not Found", level: :warning)
"Not Found"
end
# Four specs meet in this router: WebDAV itself (RFC 4918), the
# CardDAV profile on top of it (RFC 6352), collection sync (RFC 6578),
# and service discovery (RFC 6764). Each handler cites its section, and
# the texts are vendored under docs/rfcs to check them against.
route do |r|
r.is "" do
# DAV:current-user-principal (RFC 5397 section 3) — what a client
# asks the root for to find the principal it is acting as.
r.propfind do
response["Content-Type"] = "text/xml"
response.status = 207
<<~XML
<?xml version="1.0" encoding="UTF-8"?>
<d:multistatus xmlns:d="DAV:">
<d:response>
<d:href>/</d:href>
<d:propstat>
<d:prop>
<d:current-user-principal>
<d:href>/dav/principal/</d:href>
</d:current-user-principal>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
</d:multistatus>
XML
end
end
# The "carddav" well-known URI (RFC 6764 section 5, registered in
# section 9.1.2), the start of a client's bootstrap.
r.on ".well-known/carddav" do
r.propfind do
response["Content-Type"] = "text/xml"
response.status = 207
<<~XML
<?xml version="1.0" encoding="UTF-8"?>
<d:multistatus xmlns:d="DAV:">
<d:response>
<d:href>/.well-known/carddav</d:href>
<d:propstat>
<d:prop>
<d:current-user-principal>
<d:href>/dav/principal/</d:href>
</d:current-user-principal>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
</d:multistatus>
XML
end
# RFC 6764 section 5 forbids putting the service itself here and
# requires a redirect to the real context path; 301 is one of the
# codes it names.
r.get do
r.redirect "/dav/principal/", 301
end
end
r.on "dav" do
# "addressbook" in the DAV header is how a client detects CardDAV
# support (RFC 6352 section 6.1); the header is RFC 4918 section 10.1.
r.options do
response["DAV"] = "addressbook"
response["Allow"] = "OPTIONS, PROPFIND, REPORT"
""
end
# CARDDAV:addressbook-home-set (RFC 6352 section 7.1.1) is the
# hop from principal to collection.
r.on "principal" do
r.propfind do
response["Content-Type"] = "text/xml"
response.status = 207
<<~XML
<?xml version="1.0" encoding="UTF-8"?>
<d:multistatus xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav">
<d:response>
<d:href>/dav/principal/</d:href>
<d:propstat>
<d:prop>
<card:addressbook-home-set>
<d:href>/dav/addressbook/</d:href>
</card:addressbook-home-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
</d:multistatus>
XML
end
end
r.on "addressbook" do
r.propfind do
body = request.body.read
request.body.rewind
response["Content-Type"] = "text/xml"
response.status = 207
# PROPFIND is RFC 4918 section 9.1, its Depth header section
# 10.2, and the 207 body it returns section 13.
depth = request.env.fetch("HTTP_DEPTH", "infinity")
# Check if this is an etag-only request (Depth:1 listing)
etag_only = body.include?("getetag") && !body.include?("displayname") && !body.include?("resourcetype")
# Etag-only asks want the members; the collection self-entry
# is omitted until a client is found to need it. Full property
# requests (Depth:0 collection info) get the collection entry.
collection_response = ""
unless etag_only
# Every property in this body and where it comes from:
# DAV:resourcetype, which an address book collection MUST report
# as both collection and addressbook (RFC 6352 section 5.2);
# DAV:supported-report-set (RFC 3253 section 3.1.5), which RFC
# 6578 section 3.2 requires list sync-collection;
# DAV:sync-token (RFC 6578 section 4); and
# DAV:current-user-privilege-set (RFC 3744 section 5.4), which
# RFC 6352 section 7 requires of a CardDAV server. getctag alone
# is not standardized — an Apple CalendarServer extension in the
# calendarserver.org namespace, kept because macOS polls it.
#
# The privileges are advertised before the methods granting them
# exist. macOS Contacts asks for this property on every poll and
# attempts no write without it, so claiming the privileges is
# what makes the client send a PUT this server can capture in
# log/unhandled — the point of the experiment, not an oversight.
# DAV:write covers PUT and PROPPATCH (RFC 3744 section 3.2),
# DAV:bind adding a member to the collection (section 3.9), and
# DAV:unbind removing one (section 3.10).
collection_response = <<~XML
<d:response>
<d:href>/dav/addressbook/</d:href>
<d:propstat>
<d:prop>
<d:resourcetype>
<d:collection/>
<card:addressbook/>
</d:resourcetype>
<d:supported-report-set>
<d:supported-report>
<d:report><d:sync-collection/></d:report>
</d:supported-report>
</d:supported-report-set>
<cs:getctag>#{addressbook.ctag}</cs:getctag>
<d:sync-token>#{addressbook.sync_token}</d:sync-token>
<d:current-user-privilege-set>
<d:privilege><d:read/></d:privilege>
<d:privilege><d:write/></d:privilege>
<d:privilege><d:bind/></d:privilege>
<d:privilege><d:unbind/></d:privilege>
</d:current-user-privilege-set>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
XML
end
# Depth: 0 returns only collection, Depth: 1 includes members
members = depth == "0" ? "" : addressbook.contacts.map { etag_response(it) }.join
<<~XML
<?xml version="1.0" encoding="UTF-8"?>
<d:multistatus xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav" xmlns:cs="http://calendarserver.org/ns/">
#{collection_response}
#{members}
</d:multistatus>
XML
end
r.report do
body = request.body.read
request.body.rewind
response["Content-Type"] = "text/xml"
response.status = 207
doc = Nokogiri::XML(body)
doc.remove_namespaces!
# A body that is not XML parses to a document with no root.
# There is no report to dispatch on, so raise and let it 500
# rather than answer as though nothing was asked for.
root = doc.root
raise ArgumentError, "REPORT body is not XML" if root.nil?
# Each branch renders the whole response body: a Roda route
# block cannot return early, so the unsupported case has to be
# a value like the others rather than a return.
case root.name
when "sync-collection"
# DAV:sync-collection (RFC 6578 section 3.2). The warm-sync ask
# is etag-only; a changed etag sends the client back through
# multiget, so no address-data here.
#
# Knowingly violates that section twice: it requires the
# multistatus to carry a DAV:sync-token and to report only what
# changed since the client's token, and this returns every
# contact with no token. macOS resyncs the whole collection
# anyway, so it works; a client that trusts the token would
# break. Fixing it is the incremental-sync work in the backlog.
multistatus(addressbook.contacts.map { etag_response(it) })
when "addressbook-multiget"
# CARDDAV:addressbook-multiget (RFC 6352 section 8.7); the
# address-data the client asks for is section 10.4.
wants_cards = doc.xpath("//address-data").any?
multistatus(doc.xpath("//href").map { it.text }.map { |requested|
id = requested[%r{\A/dav/addressbook/([^/]+)\.vcf\z}, 1]
contact = id && addressbook.contacts.find { it.id == id }
if contact
wants_cards ? card_response(contact) : etag_response(contact)
else
missing_response(requested)
end
})
else
# The DAV:supported-report precondition on REPORT (RFC 3253
# section 3.6) — the report asked for has to be one the
# resource supports. Answering an unsupported report with an
# empty 207 reads to the client as a successful empty result,
# and to us as nothing at all: 207 is not a status
# UnhandledRequests captures, so the one signal that a client
# wanted something unimplemented never fired.
#
# 403 with the precondition named in a DAV:error body is the
# marshalling RFC 4918 section 16 defines, and 403 is its
# "will always fail, do not repeat" case. addressbook-query
# (RFC 6352 section 8.6) is the report this rejects today;
# macOS Contacts has never sent one.
response.status = 403
<<~XML
<?xml version="1.0" encoding="UTF-8"?>
<d:error xmlns:d="DAV:">
<d:supported-report/>
</d:error>
XML
end
end
r.get String do |filename|
contact = addressbook.contacts.find { it.id == filename.delete_suffix(".vcf") }
# No match falls through to the empty-body 404 that the
# not_found handler fills in.
if contact
response["Content-Type"] = "text/vcard; charset=utf-8"
# RFC 7232 section 2.3; must match the getetag reported for
# this contact in PROPFIND and REPORT.
response["ETag"] = contact.etag
contact.vcard
end
end
end
end
end
private
# Loaded once per request — Roda builds a fresh app instance for each
# one — with the directory coming from config. Real etags and ctags
# make an mtime-keyed cache possible, but re-parsing a family address
# book per request is cheap and can never serve a stale change tag.
#: () -> Addressbook
def addressbook
@addressbook ||= Addressbook.load(ProTacts.config.contacts_dir)
end
#: (Array[String] responses) -> String
def multistatus(responses)
<<~XML
<?xml version="1.0" encoding="UTF-8"?>
<d:multistatus xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav">
#{responses.join}
</d:multistatus>
XML
end
#: (String id) -> String
def contact_href(id)
"/dav/addressbook/#{id}.vcf"
end
# DAV:getetag (RFC 4918 section 15.6).
#: (Contact contact) -> String
def etag_response(contact)
<<~XML
<d:response>
<d:href>#{contact_href(contact.id)}</d:href>
<d:propstat>
<d:prop>
<d:getetag>#{contact.etag}</d:getetag>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
XML
end
#: (Contact contact) -> String
def card_response(contact)
<<~XML
<d:response>
<d:href>#{contact_href(contact.id)}</d:href>
<d:propstat>
<d:prop>
<d:getetag>#{contact.etag}</d:getetag>
<card:address-data>#{xml_escape(contact.vcard.chomp)}</card:address-data>
</d:prop>
<d:status>HTTP/1.1 200 OK</d:status>
</d:propstat>
</d:response>
XML
end
# An href with no match is reported as a 404 inside the 207 rather than
# failing the request (RFC 6352 section 8.7).
#: (String requested) -> String
def missing_response(requested)
<<~XML
<d:response>
<d:href>#{xml_escape(requested)}</d:href>
<d:status>HTTP/1.1 404 Not Found</d:status>
</d:response>
XML
end
# Text nodes in XML built by interpolation; hrefs and vCard content
# can all contain &, <, or >.
#: (String text) -> String
def xml_escape(text)
text.gsub(/[&<>]/, "&" => "&", "<" => "<", ">" => ">")
end
end
end