Skip to main content

Part 3: Calendars In and Out

Publish a feed that clients can trust, and read someone else's feed without letting it read you.

So far the calendar has been a private conversation between me and PostgreSQL. That ends today.

Here's an uncomfortable truth about building a calendar: nobody wants to use it. Not really. They want their phone to tell them where to be. Everyone I build for already has a calendar they open forty times a day, usually Google's, Apple's or Outlook's, and my website is not going to become the forty-first. If my events live only on my own pages, they're invisible, and an invisible calendar is a database with a nice font.

So the calendar has to leave the building. In practice that arrives as two requests, usually in the same week. The first is from the person who just wants the schedule: "Can I get these on my phone?" The second comes from the administrator who already keeps the whole schedule in Google Calendar and has no intention of typing it in a second time: "Can you just read mine?"

Both requests have the same answer, and it's a file format older than some of the people using it. A calendar subscription is the clever part. I don't send a file once. I hand the client a URL, and it fetches that URL on a timer, for as long as the person keeps the app. That's the "forever" in a feed. Nobody is logged in and nobody is watching, which makes it both a convenience and a small act of faith.

The format is iCalendar, the .ics file, and it's the one every calendar client on earth agrees to disagree about. It looks like a text file with a spec. It's actually a contract with Google, Apple and Microsoft, three parties who have each read RFC 5545 with great confidence and arrived at three different conclusions.

This part covers both directions. First, publishing: a feed other people's calendars will subscribe to and poll, forever, with no session and no mercy. Second, the more dangerous half: letting a customer paste in a URL that my server will go and fetch.

One housekeeping note. The word "feed" means three unrelated things in this codebase: the JSON the admin month view loads, the .ics file I publish, and the external calendar I import. One service's header comment exists mostly to say which of those it is not. If that sounds like a smell, it is. I'm going to be specific about which feed I mean.

Publishing: three layers that don't trust each other

There are three URLs. A public one for a selection of calendars, a private one per member, and a single-event download. Behind them sit three layers, and the rule is that none of them does another's job:

  • The controller decides who is asking and what they may see.
  • The export service decides what calendar data means in RFC terms.
  • The serializer decides how those meanings are spelled as bytes. It has no idea what a group or a member is, so it can't make a bad authorization decision. It has nothing to decide with.

One detail I'm unreasonably pleased with. The private member feed lives outside the member area. A member area is behind a login. A calendar client polling a feed has no session, so it would be redirected to a sign-in page, forever, on a timer, politely. Outlook would never complain. It would just stop showing events.

Anonymous means anonymous

The public feed is rendered as an anonymous viewer even if a signed-in member requests it. A public URL can never emit members-only content, because there's no code path where it knows who you are.

And every failure looks the same. Unknown host, unknown calendar, archived calendar, members-only without membership, bad token, revoked token, expired token, lost membership: one identical empty 404. An attacker who can distinguish "no such token" from "token revoked" has learned something. They'll learn nothing from me.

The one deliberate exception is the emergency stop, which answers 503 with a Retry-After instead of a 404. Several clients drop a subscription that persistently 404s, and re-subscribing by hand is worse than the incident. That's part five.

Bytes are the contract

The serializer's header declares determinism a contract: identical domain state must give identical bytes. That sounds like a nicety until you remember the next section, where the ETag is a hash of those bytes. If the serializer emits properties in a different order on Tuesday, every subscriber in the world re-downloads everything.

Two small functions show the style.

RFC 5545 says a content line must be folded at 75 octets. Octets, not characters. A French event title with an é in the wrong place can land a fold in the middle of a two-byte UTF-8 sequence, and then somebody's calendar shows a diamond with a question mark in it. So the fold backs off whenever the next byte is a continuation byte:

public string function foldLine( required string line ) {
    var bytes = charsetDecode( arguments.line, "utf-8" );
    var total = arrayLen( bytes );
    if ( total <= variables.FOLD_OCTETS ) return arguments.line;

    var arrays_class = createObject( "java", "java.util.Arrays" );
    var folded_text = createObject( "java", "java.lang.StringBuilder" ).init();
    var byte_position = 0;
    var limit = variables.FOLD_OCTETS;

    while ( byte_position < total ) {
        var take = min( limit, total - byte_position );
        if ( byte_position + take < total ) {
            // bytes is 1-indexed in CFML; bytes[ byte_position + take + 1 ] is the
            // first byte we would leave behind.
            var backoff = take;
            while ( backoff > 1 && isContinuationByte( bytes[ byte_position + backoff + 1 ] ) ) {
                backoff--;
            }
            take = backoff;
        }
        var chunk = charsetEncode(
            arrays_class.copyOfRange( bytes, javacast( "int", byte_position ), javacast( "int", byte_position + take ) ),
            "utf-8"
        );
        if ( byte_position > 0 ) folded_text.append( variables.CRLF & " " );
        folded_text.append( chunk );
        byte_position += take;
        // Continuation lines spend one of their 75 octets on the leading space.
        limit = variables.FOLD_OCTETS - 1;
    }
    return folded_text.toString();
}

And text escaping, where the order of the replacements is the whole trick. Backslash goes first, or you escape your own escapes:

public string function escapeText( required string value ) {
    var escaped_text = stripControlChars( arguments.value );
    escaped_text = replace( escaped_text, "\", "\\", "all" );
    escaped_text = replace( escaped_text, ";", "\;", "all" );
    escaped_text = replace( escaped_text, ",", "\,", "all" );
    // Normalize every line-ending form to a single literal \n. This is
    // also what makes property injection impossible: no CR or LF survives.
    escaped_text = replace( escaped_text, chr( 13 ) & chr( 10 ), "\n", "all" );
    escaped_text = replace( escaped_text, chr( 13 ), "\n", "all" );
    escaped_text = replace( escaped_text, chr( 10 ), "\n", "all" );
    return escaped_text;
}

Read the comment in the middle again. An event description is user-controlled text, and iCalendar is a line-oriented format. If a description can contain a newline followed by ATTENDEE: or ATTACH:, I've let a user write properties into my feed. No CR or LF survives that function, so they can't.

The 1:30 that happens twice, again

Part one made the interactive form refuse an ambiguous wall time. The feed has its own version of that problem, and it needs the opposite policy.

If I write DTSTART;TZID=America/Halifax:20261101T013000, I've written a time that happens twice. Every client resolves that by its own rule, and my own importer deliberately picks the earlier one. Round-tripping through my own system would silently move the later of two events by an hour.

So an ambiguous instant is emitted in UTC instead:

// AMBIGUOUS WALL TIMES.
//
// During a fall-back overlap a local wall time occurs TWICE - 01:30 in
// Halifax on the November changeover is two different instants an hour
// apart. TZID + local wall time cannot distinguish them: every client
// picks one by its own rule, and Rosterli's own inbound parser
// deliberately picks the EARLIER offset. Emitting the local form there
// would silently move the later of the two events by an hour on every
// export/import round trip.
//
// So an instant whose local time is ambiguous is emitted in the
// UNAMBIGUOUS UTC form instead. It costs the TZID label on exactly
// those occurrences and preserves the instant exactly, which is the
// correct trade: every client understands the Z form.
if ( isAmbiguousLocalTime( zone, arguments.spec.utc ?: "" ) ) {
    return property_name & ":" & formatUtcStamp( arguments.spec.utc ?: "" );
}

return property_name & ";TZID=" & escapeParamValue( zone ) & ":" & formatLocalStamp( arguments.spec.utc ?: "", zone );

It costs me a time zone label on one hour of one day per year. I'll take that trade every time.

What a recurring event looks like on the wire

Part two ended on a promise. Here's what the feed does with an exception.

A pure cancellation becomes an EXDATE on the master: that occurrence simply isn't generated. A moved or modified occurrence becomes its own override component with a RECURRENCE-ID set to the original rule-generated slot, never the moved time. Same idea as part two. The identity is where the rule put it.

Some other rules that keep me honest:

  • RRULE is built only from what the native model actually holds. YEARLY carries no BY* parts, because deriving them is, in the code's words, the classic yearly-recurrence bug.
  • COUNT is emitted only when nothing truncates the series first. Otherwise it's UNTIL. An honest bound beats an over-promising one.
  • The EXDATE window starts at the earliest master start, not the horizon, because a client generates occurrences from the exported DTSTART, including ones before the window.

ETag or nothing

A calendar client may poll a feed every few minutes for years. I'd like most of those polls to cost me one hash and no bandwidth. That's what a 304 is for. The part that matters is what I'm willing to grant one on.

The ETag is a strong validator over the exact authorized bytes:

// A strong validator over the exact authorized bytes: identical
// output is identical ETag, and ANY visible change - including a
// deletion, which leaves no timestamp behind - changes it. This is
// the ONLY validator a 304 may be granted on; see
// calendar_ics_http_service.isNotModified.
etag: """" & lCase( left( hash( body, "SHA-256" ), 32 ) ) & """",

And a 304 is granted on exactly one thing:

public boolean function isNotModified(
    required string etag,
    required string http_last_modified,
    string if_none_match = "",
    string if_modified_since = ""
) {
    var trimmed_if_none_match = trim( arguments.if_none_match );
    if ( !len( trimmed_if_none_match ) ) return false;
    if ( trimmed_if_none_match == "*" ) return true;
    for ( var candidate in listToArray( trimmed_if_none_match, "," ) ) {
        var normalized = trim( candidate );
        // A cache is allowed to weaken a strong validator in transit.
        if ( left( normalized, 2 ) == "W/" ) normalized = trim( mid( normalized, 3, len( normalized ) - 2 ) );
        if ( normalized == arguments.etag ) return true;
    }
    return false;
}

Look at what it does with if_modified_since. Nothing. It's in the signature and it's never read. I never honour If-Modified-Since, not even an exact echo.

Here's why. Last-Modified is derived from the rows that contributed to the feed. A deleted event leaves no row behind to carry a timestamp. A public-to-private flip, an archived calendar, a removed exception, a revoked token, a lost membership, a horizon that aged an event out: all of those change the bytes without moving any timestamp. A client that echoes back the old Last-Modified would be told "nothing changed" about content it's no longer allowed to see.

The cost is one full body for the rare client that sends only If-Modified-Since. I'll pay it.

This was the second answer, by the way. The first version of the feed shipped with a five-minute max-age. That meant a five-minute window after flipping a calendar from public to private in which every cache between me and a subscriber could keep serving it, and there is no CDN to purge. The policy is no-cache, which means "revalidate", not "don't store." Those are different words and I'd like them tattooed somewhere.

One honest footnote: a 304 still costs me a full render, because the ETag is a hash of the render. I don't cache rendered feeds either. A correct cache key would have to include member identity, live membership, token state, every calendar's visibility and every event's revision, which is nearly everything the render already reads. A stale entry would be a privacy leak, not a slow page. I measured instead: tens of events render in tens of milliseconds, and the worst case is about half a second.

UIDs are promises

Every calendar component has a UID, and a subscriber's client uses it to decide whether an event is new, changed or gone. Change it and the client reads that as "deleted, then added." Reminders reset. Notes vanish.

Native events get their public ID plus an @ and my own domain. Imported events keep the source's own UID verbatim, so a client subscribed to both the origin and my feed de-duplicates them.

Which gives me an interesting problem. Two imported feeds can carry the same source UID. Exactly one family can export the bare UID. Who gets it?

My first answer was "whichever is in this render." The 90-day-back, 365-day-forward horizon then made the UID a function of time: when one duplicate aged out of the window, the other one's UID flipped, and every subscriber saw a delete and an add on a day nobody touched anything.

The fix was to make ownership a property of the tenant, not of the render: earliest created, then id, over every row with that UID in scope, including soft-deleted, detached and excluded ones.

if ( len( candidate_family.uid_override ?: "" ) ) {
    resolved_uid[ family_index ] = candidate_family.uid_override;
    continue;
}

if ( !len( candidate_family.external_uid ) ) {
    resolved_uid[ family_index ] = nativeUid( candidate_family.public_id );
    continue;
}

var source_uid = icalendar_serializer_service.sanitizeUid( candidate_family.external_uid );
if ( !len( source_uid ) ) {
    resolved_uid[ family_index ] = nativeUid( candidate_family.public_id );
    continue;
}

// Absent from the map = no other row in this tenant carries this
// uid, or the lookup was unavailable. Either way the source UID is
// the right answer; PASS 2 is the collision backstop.
var owner_public_id = toString( owners[ candidate_family.external_uid ] ?: "" );
if ( len( owner_public_id ) && owner_public_id != candidate_family.public_id ) {
    arrayAppend( arguments.stats.warnings, { code: "duplicate_uid_namespaced", public_id: candidate_family.public_id } );
    resolved_uid[ family_index ] = nativeUid( candidate_family.public_id );
    continue;
}
resolved_uid[ family_index ] = source_uid;

Two related choices keep the bytes stable. DTSTAMP is the row's publication revision time, not now(), because a clock-stamped DTSTAMP changes the bytes on every poll. And SEQUENCE comes from a counter a database trigger maintains, which moves only when a source-visible column changes. A row edit that changes nothing a subscriber could see doesn't bump it.

Truncating without lying

A feed can't be infinite. There's a horizon (90 days back, a year forward), a cap on components and a cap on bytes. The interesting question is what you drop.

Dropping from a flat list is wrong. If I drop the tail of a recurring series' override components but keep its master, a client will render a moved or cancelled occurrence at its original rule-generated time. The calendar shows a practice that was cancelled last week. So truncation is family-atomic: a master and all its overrides are kept or dropped together.

var retained = [];
var component_total = 0;
for ( var retained_index = 1; retained_index <= arrayLen( arguments.families ); retained_index++ ) {
    var family = arguments.families[ retained_index ];
    if ( component_total + arrayLen( family.components ) > variables.MAX_COMPONENTS ) {
        // The very first family already exceeding the cap is the
        // oversized-family case: keep it whole rather than emit nothing.
        if ( !arrayLen( retained ) ) {
            arrayAppend( arguments.stats.warnings, { code: "oversized_family", public_id: family.public_id } );
        }
        arguments.stats.truncated = true;
        arrayAppend( arguments.stats.warnings, { code: "component_limit", limit: variables.MAX_COMPONENTS } );
        if ( !arrayLen( retained ) ) {
            for ( var pinned in family.components ) pinned.uid = resolved_uid[ retained_index ];
            arrayAppend( retained, family );
        }
        break;
    }
    for ( var component in family.components ) component.uid = resolved_uid[ retained_index ];
    component_total += arrayLen( family.components );
    arrayAppend( retained, family );
}

And the same rule at the byte cap, with a comment I'd like to frame:

// One family that alone exceeds the cap is emitted WHOLE. Never a
// partial family, and never an empty feed - a subscriber reads an empty
// feed as "every event was deleted".

A key that opens exactly one door

A private feed has no session, so it needs a bearer secret in the URL. A URL that is also a password.

I treat it like one. The token is opaque, long, and random. It encodes nothing. Only a hash is stored; the raw value is returned exactly once, at creation or rotation. Revocation is immediate. And every single request re-checks everything that was true when the token was issued:

// Live membership, every request. The state captured when the token was
// created is worth nothing here: a member removed, suspended or
// disabled since then must lose the feed immediately.
var still_a_member = false;
try {
    still_a_member = len( group_id )
        ? member_auth_service.hasActiveMembership( user_id = user_id, group_id = group_id )
        : member_auth_service.hasActiveMembership( user_id = user_id, organization_id = organization_id );
} catch ( any membership_error ) {
    still_a_member = false;
}
if ( !still_a_member ) {
    denied.code = "membership_inactive";
    return denied;
}

Note the catch. If the membership check itself blows up, the answer is "no". The failure mode of an authorization check must never be "yes."

The stored list of calendars can only narrow what the member can currently see, never widen it, so archiving a calendar drops it from every subscription with no migration. An empty stored selection is an empty feed, never "all". A token that lost every calendar mustn't quietly re-broaden.

I'll tell you about a mistake, because it's a good one. I redacted secrets from logs by key name. A key called token, password, secret. Then one 500 on a feed request wrote a live subscription URL into my error tables, because the secret was in the request path, and no key in the world is called PATH_INFO. Redaction now works by value and by route shape. The log line for a feed request carries counts, timings and codes, and nothing else.

The fixed window I called a token bucket

A feed endpoint needs a budget. Mine is a small in-process counter per node, keyed by a hash of the kind of request, the client address and the scope:

var entry = store[ key ] ?: "";
if ( !isStruct( entry ) || ( entry.window_start ?: 0 ) + variables.WINDOW_SECONDS <= epoch ) {
    entry = { window_start: epoch, count: 0 };
}
entry.count = entry.count + 1;
store[ key ] = entry;

if ( entry.count > budget ) {
    var elapsed = epoch - entry.window_start;
    var retry_after = variables.WINDOW_SECONDS - elapsed;
    if ( retry_after < 1 ) retry_after = 1;
    decision = { allowed: false, retry_after_seconds: retry_after, remaining: 0 };
} else {
    decision = { allowed: true, retry_after_seconds: 0, remaining: budget - entry.count };
}

My notes call this a token bucket. It's a fixed-window counter. There's no refill. A client can spend roughly double its budget across a window edge. I'm telling you this because I'd rather you read the code than my adjectives.

Three choices around it matter more than the counter. Over budget answers 429 with Retry-After, which clients read as "poll later", not "subscription broken." It's in process, not a table, because a limiter that writes a row per request becomes the load it exists to prevent; the price is that two nodes give a client twice the budget, and I've accepted that on the record. And when its map fills, it fails open, and counts that it did, so "the limiter stopped limiting" is an alert instead of a post-mortem.

Reading: a URL is an invitation

Now the other direction. A group administrator pastes a Google Calendar address into a form. My server will fetch it, parse it, and turn it into events.

Let me state the problem plainly. A feature that fetches a user-supplied URL is a feature that lets a user choose where your server makes requests from inside your network. Every SSRF write-up you've read begins here.

So the design starts from refusal. Feeds are group-scoped by schema. Exactly one provider is authorized, on exactly one hostname. The schema's vocabulary names others, and they're preserved and skipped. And a fetch has to pass layers that are each independently sufficient to stop it:

  1. A feature gate that defaults to off, and fails closed.
  2. A kill switch.
  3. The provider must be authorized. A client-supplied provider_type=google is a claim, not evidence.
  4. The host must be authorized, by whole-host equality, after canonicalization that refuses rather than repairs.
  5. The URL validator: HTTPS only, the default port, no embedded credentials, and every resolved address must be public.
  6. The transport, which has its own bounds.
  7. Steps 3 to 5 again on every redirect hop, before the next request is made.

A rejected attempt makes zero network requests. There's a spec for that.

Step 4 is where I'd point you. Most host allow-lists are written as "does it end in google.com?" and are broken by evilgoogle.com, by google.com.evil.example, by a Unicode lookalike, by a trailing dot, by userinfo smuggled in front of the real host. So canonicalization has one rule: if it isn't a plain ASCII hostname that I'd write by hand, it's not a candidate.

public string function canonicalHost( any candidate = "" ) {
    var raw = trim( toString( arguments.candidate ?: "" ) );
    if ( !len( raw ) ) return "";

    // The DNS root form "host." is legitimate and equal to "host".
    while ( len( raw ) && right( raw, 1 ) == "." ) {
        raw = left( raw, len( raw ) - 1 );
    }
    if ( !len( raw ) || len( raw ) > variables.MAX_HOST_LENGTH ) return "";

    // Any non-ASCII byte is refused outright. Every approved host is plain
    // ASCII, so a Unicode lookalike has nothing legitimate to be.
    for ( var character_index = 1; character_index <= len( raw ); character_index++ ) {
        if ( asc( mid( raw, character_index, 1 ) ) > 127 ) return "";
    }

    var lower = lCase( raw );
    // A plain dotted LDH hostname and nothing else: no userinfo, no port,
    // no path, no brackets, no underscore.
    if ( !reFind( "^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$", lower ) ) {
        return "";
    }

    var labels = listToArray( lower, "." );
    if ( arrayLen( labels ) < 2 ) return "";
    for ( var label in labels ) {
        if ( !len( label ) || len( label ) > 63 ) return "";
        // Punycode cannot be a legitimate spelling of an ASCII host.
        if ( left( label, 4 ) == "xn--" ) return "";
    }
    // A final label of digits only means this was an IPv4 literal.
    if ( reFind( "^[0-9]+$", labels[ arrayLen( labels ) ] ) ) return "";

    return lower;
}

Then the comparison is the dullest line in the file, which is the point:

public boolean function hostIsAuthorizedFor( required string provider_type, required string host ) {
    var canonical = canonicalHost( arguments.host );
    if ( !len( canonical ) ) return false;
    for ( var approved in authorizedHostsFor( arguments.provider_type ) ) {
        // compare() is case-sensitive; both sides are already lowercased,
        // so this is an exact byte comparison and not a CFML loose match.
        if ( compare( canonical, lCase( approved ) ) == 0 ) return true;
    }
    return false;
}

The URL validator beneath it is also a list of things I refuse, in the order I refuse them:

public struct function validate( required string url ) {
    var trimmed_url = trim( arguments.url );
    if ( !len( trimmed_url ) ) return { valid: false, code: "calendar_external_feed_error_url_required", message: "Feed URL is required." };

    // Scheme check. webcal://... should have been normalized to https:// before this.
    if ( !reFindNoCase( "^https://", trimmed_url ) ) {
        return { valid: false, code: "calendar_external_feed_error_url_not_https", message: "Rosterli only supports secure HTTPS calendar feed URLs." };
    }
    if ( len( trimmed_url ) > 2048 ) return { valid: false, code: "calendar_external_feed_error_url_too_long", message: "Feed URL is too long." };

    var parsed = parseUrl( trimmed_url );
    if ( !parsed.ok ) return { valid: false, code: "calendar_external_feed_error_url_malformed", message: "Feed URL is not a valid URL." };
    if ( !len( parsed.host ) ) return { valid: false, code: "calendar_external_feed_error_url_no_host", message: "Feed URL is missing a host." };

    // Credential-bearing URL forms (https://user:pass@host/...) are not
    // supported: they smuggle secrets into logs and enable confusing
    // same-host bypass tricks.
    if ( len( parsed.userinfo ) ) {
        return { valid: false, code: "calendar_external_feed_error_url_credentials", message: "Feed URLs with embedded credentials are not supported." };
    }

    // HTTPS on the default port only. Feeds on exotic ports are not a
    // real-world calendar-provider shape and widen the SSRF surface.
    if ( parsed.port != -1 && parsed.port != 443 ) {
        return { valid: false, code: "calendar_external_feed_error_url_port", message: "Feed URLs must use the standard HTTPS port." };
    }

    var host_check = hostIsSafe( parsed.host );
    if ( !host_check.safe ) return { valid: false, code: "calendar_external_feed_error_url_host_blocked", message: host_check.message };

    return { valid: true, code: "", message: "" };
}

Why there's a Java file in my CFML repository

This is the part I'd least expected to write.

The obvious tool for fetching a URL in ColdFusion is cfhttp. It works. It also has no maximum-response-size setting, and it buffers the whole body before handing it to you. I measured it: a chunked 4 MiB body delivered 4,196,433 bytes to a transport whose configured limit was 65,536. The limit was a suggestion.

So I reached for Java's HttpClient. And ColdFusion promptly stopped being able to use it. The Java module system refuses to let CFML reflect into JDK-internal classes, so the first time CFML touched the returned object, it threw InaccessibleObjectException.

Here's what that looked like in production. Starting on August 15, every inbound feed fetch failed with one unclassified sentence: "The feed request failed." Meanwhile curl from the same server returned HTTP 200. It took about a week. Every sync test had used a scripted fake transport, so every test passed.

The answer was a small compiled Java helper, BoundedHttpFetcher, with one rule: the connection, the response and the stream stay inside Java, and only plain strings, numbers and a byte array cross into CFML. It's built reproducibly by a pinned container, committed as a jar, and a CI check fails the build if the jar and its source disagree.

What it guarantees:

  • GET only. There's no method parameter to get wrong.
  • Redirects are never followed. A 3xx is a status plus a Location. Policy lives in the sync layer, which re-validates the next hop.
  • At most limit + 1 bytes are consumed, whatever the framing claims.
  • gzip is bounded twice: wire bytes, then inflated bytes.
  • Three timeouts: connect, read inactivity, and a total wall-clock deadline.
  • A 200 that delivers fewer bytes than it declared is a failure, not a short calendar. A truncated feed still starts with BEGIN:VCALENDAR, which is the whole problem.

The reader's last lines are the ones I like best:

final boolean overLimit = consumed > maxBytes;
// An over-limit body is refused, so its bytes are not handed back at
// all. That makes "the returned body never exceeds N" structural
// rather than a promise the caller has to keep.
final byte[] body = overLimit ? new byte[ 0 ] : Arrays.copyOf( accumulator, filled );
return new BoundedRead( body, consumed, overLimit );

And the second, independent bound on decompression, in CFML:

private struct function boundedGunzip( required any bytes, required numeric maximum_bytes ) {
    try {
        var input_stream = createObject( "java", "java.io.ByteArrayInputStream" ).init( arguments.bytes );
        var gzip_stream = createObject( "java", "java.util.zip.GZIPInputStream" ).init( input_stream );
        var inflated_bytes = "";
        try {
            inflated_bytes = gzip_stream.readNBytes( javacast( "int", int( arguments.maximum_bytes ) + 1 ) );
        } finally {
            try { gzip_stream.close(); } catch ( any close_error ) {}
        }
        if ( byteLength( inflated_bytes ) > arguments.maximum_bytes ) {
            return { ok: false, error_code: "response_too_large", message: "The feed response exceeded the allowed size after decompression." };
        }
        return { ok: true, bytes: inflated_bytes };
    } catch ( any decode_error ) {
        return { ok: false, error_code: "transport_error", message: "The compressed feed response could not be decoded." };
    }
}

One more thing about deadlines, because I got this wrong in a way I found instructive. I declared a four-second total deadline, and a test sent a response header one byte at a time. It took 7,835 milliseconds. A "deadline" that isn't enforced across the header phase is a claim, not a deadline. The fix was a watchdog plus a reader that won't enter a blocking read it can't finish, and the same test now ends at about 4,006.

Parse everything or write nothing

A feed is untrusted input twice: once as bytes, once as meaning.

I wrote the parser myself, in plain CFML plus java.time, on purpose. A library would have added several unpinned transitive JARs to the engine's classpath, and the hard part (mapping iCalendar onto my schema) is mine either way. It's bounded: payload size, line count, line length, number of events, number of EXDATE and RDATE values, and per-field text. It keeps a real component stack, so a VALARM's DESCRIPTION can't bleed into its VEVENT. And it never throws. It returns a complete flag that is true only when every BEGIN had its END and no limit truncated the walk.

That flag is the hinge of the whole importer:

  • complete is false? The sync fails as partial_parse and writes nothing.
  • Zero events? That's a failure too, so the "missing from source means cancelled" pass can't fire on a degraded response. An empty calendar from a hiccuping server must never be read as "the club cancelled everything."
  • Each recurring family (a master and its overrides) reconciles in its own transaction. One family failing rolls back that family only and protects its rows from the cancel pass.
  • An unsupported recurrence is marked unsupported and the existing row is left exactly as it is. I'd rather keep a slightly stale event than approximate one.

Remember the weekly series that rendered as an empty calendar? That one came from here. Weekly imports stored the RFC's MO and WE weekday tokens verbatim, and my engine expected its own vocabulary, so every such series expanded to nothing, with no error and no trace. Now the tokens are mapped on import, and the expansion logs the tokens it rejected, instead of quietly returning an empty list. It's another instance of the lesson from part one: never let a validation failure render as silence.

Draft first

An imported event is somebody else's data, appearing under my customer's name. It shouldn't be public because a feed said so.

A new feed defaults to draft. After that, only one axis is source-driven: whether the source cancelled the event. The administrator's draft-or-published choice survives every future sync.

// ── Rosterli-owned status axis (R10) ──────────────────────────
var incoming_cancelled = ( arguments.parsed_event.status == "cancelled" );
var feed_default_status = arguments.feed.getDefault_status() ?: "published";
var status = "";
var cancel_reason = "";
if ( incoming_cancelled ) {
    status = "cancelled";
    cancel_reason = "source_cancelled";
} else if ( !isObject( arguments.stored ) ) {
    status = feed_default_status;
} else if ( ( arguments.stored.getStatus() ?: "" ) == "cancelled" ) {
    status = feed_default_status; // source reappeared: revive
} else {
    status = arguments.stored.getStatus(); // preserve the admin's draft/published choice
}

The draft default is set in the administrator's controller, where a form creates the feed. The column default in the database is still published, so a programmatic caller that sets nothing gets a published feed. I'd call that a gap, and I'm leaving it on the page where you can see it.

A background sync also never sends a schedule-change notification. Nobody approved that message. Part four explains why that sentence matters so much.

What an identity is

Inbound identity is (group, feed, source UID, recurrence id) under a unique index that covers only managed, non-detached, non-excluded, non-deleted rows:

CREATE UNIQUE INDEX IF NOT EXISTS ux_calevent_external_identity_active
	ON public.calendar_event (
		group_id,
		external_feed_id,
		external_uid,
		(COALESCE(external_recurrence_id, ''))
	)
	WHERE external_feed_id IS NOT NULL
	  AND is_external_managed = true
	  AND external_detached_at IS NULL
	  AND external_excluded_at IS NULL
	  AND deleted IS NULL;

That WHERE clause lets an administrator detach an imported event (it becomes theirs) or exclude it (never show it), and a later sync can't collide with it. It also gave me a bug. A detached or excluded event falls outside that index, and outside the lookup that finds existing rows, so on the next sync it was inserted again, as a fresh visible event, on every sync. The fix is a check for a hidden twin before inserting.

There's another one worth telling. Imported UIDs were once interpolated into the SQL that cancels events missing from the source. An imported UID is attacker-controlled text. That's a SQL injection, delivered by calendar. Now they're bound lists with separator characters that RFC 5545 forbids inside content lines, so no UID can contain one.

What I haven't solved

I'd rather you hear this from me.

There's a gap between validating a hostname and connecting to it. DNS can answer differently between the two. The single-provider, single-host policy narrows that, because it limits who controls the name, but it doesn't close it. Network egress from the application isn't isolated either, and I'm not going to claim the network is a second wall. That's the reason other providers are not enabled: each added host multiplies the surface of a bounded egress tool for a need nobody has actually stated.

I also have no recorded observation of a real Google feed fetched through the new transport on a deployed machine. There's indirect evidence: production syncs ran without an alert. That's not the same as a log line that says "fetched a real feed." The acceptance item is open in my notes, and a design isn't done until somebody writes down that they watched it work.

One more honest note about validation. I wrote an independent RFC 5545 validator in Python, sharing no code or constants with the CFML serializer and parser, because a serializer-to-parser round trip only proves the two halves agree with each other. It has a self-test whose job is to fail on purpose: eleven deliberately malformed documents and one good one. A validator that passes everything is worse than none.

CI runs it against a corpus of sanitized fixtures from Apple, Google and Outlook. It does not run it over live serializer output. The "zero findings" run against real bytes served from staging was done by hand, once, and recorded. Both are legitimate. They are different claims, and I try not to let one wear the other's badge.

What I'd keep

  • A feed is a contract with clients you don't control. Determinism is a feature.
  • Grant 304 on one validator. Don't honour a header you can't prove.
  • Identity (UIDs) must not depend on the render. If it moves with the window, subscribers see deletes.
  • Truncate by family. An empty feed reads as "everything was deleted."
  • A token in a URL is a password. Re-check everything on every request.
  • An allow-list must refuse what it can't canonicalize, not repair it.
  • Bound the reader at the byte level, in the language that can actually do it.
  • Parse everything or write nothing, and never let an empty answer mean "cancel."
  • Imported data is a draft until a person says otherwise.

In the next part, the calendar starts talking to people. Reminders, change notices, and the discipline of sending exactly one message, which I'll call "exactly once" in the way that a person on a diet calls a croissant "one."