diff --git a/CHANGELOG.md b/CHANGELOG.md index 735264c2..f88536fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,27 @@ exact tag (`ghcr.io/calnode/calnode:0.1.0`) if you need stability between upgrad was degraded, rather than implying there is none. It appears on the booking and reschedule pages and in the embed widget. Proposed in discussion #254. +- **Booking outside availability through MCP (`skip_availability`).** A workspace owner or + admin can pass `skip_availability` to the `create_booking` and `reschedule_booking` MCP + tools to book, or move a booking to, a time the + public calendar would not offer: outside the hosts' working hours, inside the minimum + notice or beyond the booking window. It is for the appointment agreed on the phone that + still needs its calendar event and confirmation. The double-booking check is not affected; + a time that collides with an existing booking is refused either way, and so is a start that + has already passed. Anyone else sending + the flag gets an explicit error and no booking, as does the stdio transport, which has no + user to record. The acting user is stored in the new `bookings.availability_override_by` + column (migration `00080`), which is cleared again when a normal reschedule, by anyone, + moves the booking into a regular slot. It is recorded only when it was needed: with the + flag on a time that is bookable anyway, the column stays empty. For a round-robin event + type this includes the case where the hosts within their hours are all taken: with the + flag the booking goes to a rotation host outside their hours, and that is recorded. While a + host within their hours is free, the rotation stays with them, also when the flag waived + the minimum notice or the booking window. `reschedule_booking` now also says so when a + target is refused for being outside availability, instead of reporting it as taken. + MCP only: REST, the booking page and the admin UI do not + accept the flag. Requested in #270. + ### Fixed - **Buttons and inputs in the booking UI now use the surrounding font.** Form controls diff --git a/README.md b/README.md index 4ce56269..22b453d9 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,9 @@ the API, not buried in a UI. **Native MCP server.** A Model Context Protocol server is compiled *into* the binary (official Go SDK), exposing eight first-class tools — `list_event_types`, `get_event_type`, `get_available_slots`, `create_booking`, `get_booking`, -`reschedule_booking`, `cancel_booking`, `list_bookings`. The MCP tools call the same internal services as +`reschedule_booking`, `cancel_booking`, `list_bookings`. Owners and admins can pass +`skip_availability` to `create_booking` and `reschedule_booking` for a time outside +normal availability (never past the double-booking check, never in the past). The MCP tools call the same internal services as the REST API (no parallel code path), so booking side effects — calendar events, confirmation emails, webhooks, reminders — fire identically. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1941b859..5f6dfae1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -113,7 +113,8 @@ partial unique index covers) — no TOCTOU between concurrent bookings. (the host-roles table), `event_type_questions` (intake form), `event_type_reminders` (per-ET `hours_before`, UNIQUE). - **Availability:** `availability_rules` (weekly), `availability_overrides` (dated). -- **Bookings:** `bookings` (primary `host_id`, `external_event_id`, status), +- **Bookings:** `bookings` (primary `host_id`, `external_event_id`, status, + `availability_override_by` - see §19), `booking_hosts` (every attending host + `is_primary` + per-host `external_event_id`), `booking_attendees` (organizer + invitees), `booking_answers`, `booking_manage_tokens` (PK is the hashed token; TTL is @@ -497,7 +498,9 @@ The `phone_outbound` location type ("we'll call you") is the outbound counterpar - **Reschedule:** `RescheduleBooking` (admin) + `RescheduleByToken` share `moveCalendarEvents` — `Service.UpdateEvent` moves **every** assigned host's event to the new time. The overlap re-check covers **all** the booking's hosts, not just - the primary. + the primary. `Service.Reschedule` also resets `availability_override_by` on every + move (§19): these two paths always pass "no override", so a normal reschedule clears + it. - **Reassign:** `ReassignHost` swaps the primary host (archive/resolve flow), moves the calendar event old→new, and keeps `booking_hosts` in sync so later cancel/notify fan-out targets the right person. @@ -1085,9 +1088,82 @@ types that have required questions. (`ListByHost`, host-scoped `Cancel`), admins/owner get the whole workspace (`ListAll`/`CancelByID`). The stdio transport has no bound caller → full access (local operator). `list_event_types`/`get_available_slots`/`create_booking` are the public - booking surface (unscoped). Tools translate between the slug they expose as + booking surface (unscoped, apart from `skip_availability` below). Tools translate between the slug they expose as `event_type_id` and the internal booking id. Gap: `create_booking` does not yet honour an `idempotency_key` (REST-only). +- **Availability override (`skip_availability`, #270).** `create_booking` and + `reschedule_booking` accept an + optional `skip_availability` for a time the public calendar would never have offered, + such as an appointment agreed on the phone. It is an admin action with a record, not + "skip validation": + - **What it skips:** minimum notice, `max_future_days` and the hosts' availability + windows (weekly rules and date overrides) - the three rules in `validateBookingTime`, + which takes the bypass as a parameter (`validateRescheduleTime` hands it through). + `filterAvailableHosts`, which re-checks the same windows per host on create, still + runs for round robin (see below) and is left out only for fixed and collective + under a waived refusal, where every candidate has a seat and filtering would drop + the host outside their hours from the booking instead of booking them. + **Nothing else:** the overlap checks in `booking.Service.Create` and `Reschedule`, + host resolution, intake answers, the paid-event refusal and, on create, the + external calendar busy check (`calendarFreeHosts`) all still run. Reschedule has + never had a calendar busy check, with or without the flag, so nothing is lost there. A time that collides with an existing booking is refused with the + flag exactly as without it. + - **Not in the past, flag or not.** Waiving minimum notice does not waive the floor + underneath it: a start that has already passed is refused under the flag with + `errStartInPast`, on create and on reschedule, and is never treated as a waivable + availability refusal. Without the flag it stays the ordinary `errSlotUnavailable` + for every caller; only `reschedule_booking` answers with the same explicit message + in both cases, since "resend with `skip_availability`" would be wrong advice there. + - **Who:** owners and admins only. `mcpAvailabilityOverride` (`mcp_oauth.go`) reads the + caller bound by `MCPCallerMiddleware`; no tool argument can grant it. It runs before + anything is loaded (on reschedule, before the member's "booking not found" check, + so the refusal reads the same whether or not the booking exists), and anyone else + gets an explicit tool error and no booking or change - the flag is never silently + dropped, because that would book and look as if it had worked. The stdio transport + has no bound caller and is refused too: there is no user to record. + - **The record:** `bookings.availability_override_by` (migration 00080; nullable, no + foreign key, so removing a user neither is blocked by it nor erases it) holds the + acting user's id, written in the same INSERT as the booking, or in the same UPDATE + as the new times. Flag and actor travel as one value (`overrideBy`, empty for none) + from the tool down to the SQL, so the checks cannot be skipped without the id being + stored. The column is not exposed in `bookingJSON`, which also serves the public + create response, nor in webhooks. + - **It means "where this booking currently sits".** `booking.Service.Reschedule` takes + `overrideBy` and writes the column on every move: a reschedule under the override + names whoever made that move (replacing an earlier actor), and every ordinary + reschedule clears it to NULL - through MCP, the admin REST endpoint or the guest's + manage link alike, since all three go through `Reschedule`. The gate hangs on the + target time, not on the booking's history: a booking placed by an override can be + moved into a normal slot by anyone who could move it anyway. + - **Reschedule refusals are told apart.** Without the flag, a target that fails notice, + window or hours is refused by `reschedule_booking` with a message naming the reason + and the flag (`errRescheduleOutsideAvailability`); a collision keeps "that time slot + is no longer available". Only the MCP wording differs - REST and the manage page + keep their messages. + - **Recorded only when it was needed.** The rules are always evaluated; + `validateBookingTime` waives a refusal under the flag and reports that it did. For + a time that is normally bookable the flag changes nothing: the ordinary path runs + (including `filterAvailableHosts` on create) and the column stays NULL - or, on a + reschedule, is cleared like on any ordinary move - so it never claims an override + for a booking that sits in a regular slot. + - **Round robin keeps the host filter under the flag.** A waived refusal may have been + minimum notice or the booking window, which say nothing about hours, so the + rotation still gets only the hosts within theirs and cannot land on an out-of-hours + host while an in-hours one is free. Only when the filter finds nobody within hours + (the hours rule itself was waived) does the rotation pick among all candidates. The + booking is recorded either way, because a refusal was waived. + - **Round robin: the one case decided after the rules.** There the slot "exists" as + soon as one rotation host is within hours, so the rules can pass while every such + host is already taken (overlap or calendar busy). Under the flag, and only when + `filterAvailableHosts` actually removed someone, `createBookingForSlug` then tries + once more with exactly the hosts the filter removed - through the same calendar + busy and overlap checks. That pool holds nobody within their hours, so the booking + lands on a rotation host outside their hours by construction, and is recorded as + an override. Without the flag the refusal stands as before. + - **Where:** the MCP tools only. REST, the public booking page, the manage page, the + assistant and the admin UI pass "no override" explicitly; the new parameters on + `validateBookingTime`, `validateRescheduleTime`, `createBookingForSlug` and + `Service.Reschedule` make every caller say so. - **Authorization — the "Connect" flow** (`mcp_oauth.go`, `mcp_oauth_authorize.go`): Calnode is its own **OAuth 2.1 authorization server** for the `/mcp` resource, so an agent (Claude, ChatGPT) adds the server by URL and clicks **Connect** instead of diff --git a/internal/booking/booking.go b/internal/booking/booking.go index 1df41ebc..b531051f 100644 --- a/internal/booking/booking.go +++ b/internal/booking/booking.go @@ -55,6 +55,10 @@ type Booking struct { // InviteDelivery is who sent this booking's invite (InviteByCalendar/InviteByCalnode/ // InviteByNone), fixed at creation; reschedule, cancel and reassign follow it. InviteDelivery string + // AvailabilityOverrideBy is the id of the owner or admin who placed this booking at + // a time outside normal availability (migration 00080); empty when it sits in a + // normally bookable slot. Internal audit data, not part of any API response. + AvailabilityOverrideBy string } // Attendee is a participant in a booking (the person who made the booking). @@ -117,4 +121,9 @@ type CreateParams struct { // Stored on the booking so its reschedule and cancel follow the mode it was created // with, not whatever the event type is set to by then. InviteDelivery string + // AvailabilityOverrideBy is the id of the owner or admin who is placing this booking + // outside normal availability, recorded in the same INSERT as the booking. Empty + // (the default, and what every public path passes) records nothing. It never + // relaxes the overlap checks in Create. + AvailabilityOverrideBy string } diff --git a/internal/booking/manage_test.go b/internal/booking/manage_test.go index 6735ba13..d965af6e 100644 --- a/internal/booking/manage_test.go +++ b/internal/booking/manage_test.go @@ -3,7 +3,9 @@ package booking_test import ( "context" "crypto/sha256" + "database/sql" "encoding/hex" + "errors" "testing" "time" @@ -181,7 +183,7 @@ func TestReschedule_success(t *testing.T) { newStart := slot(10, 0) newEnd := slot(10, 30) - updated, err := svc.Reschedule(context.Background(), b.ID, newStart, newEnd) + updated, err := svc.Reschedule(context.Background(), b.ID, newStart, newEnd, "") if err != nil { t.Fatalf("Reschedule: %v", err) } @@ -205,6 +207,91 @@ func TestReschedule_success(t *testing.T) { } } +// The availability override (#270) follows the booking's current position: Reschedule +// writes it with the new times. An override names whoever made that move, and an +// ordinary move - the path the admin REST endpoint and the guest's manage link take - +// clears it. +func TestReschedule_setsAndClearsAvailabilityOverride(t *testing.T) { + database := newTestDB(t) + svc := booking.New(database) + hostID := seedHost(t, database) + etID := seedEventType(t, database, hostID) + + b, err := svc.Create(context.Background(), booking.CreateParams{ + EventTypeID: etID, + HostIDs: []string{hostID}, + StartAt: slot(22, 0), + EndAt: slot(22, 30), + Organizer: booking.Attendee{Name: "Alice", Email: "alice@example.com"}, + AvailabilityOverrideBy: "admin-one", + }) + if err != nil { + t.Fatalf("Create: %v", err) + } + stored := func() sql.NullString { + t.Helper() + var v sql.NullString + if err := database.QueryRow(`SELECT availability_override_by FROM bookings WHERE id = ?`, b.ID).Scan(&v); err != nil { + t.Fatalf("read column: %v", err) + } + return v + } + + // Moved again under the override by someone else: the column names them. + updated, err := svc.Reschedule(context.Background(), b.ID, slot(23, 0), slot(23, 30), "admin-two") + if err != nil { + t.Fatalf("Reschedule with override: %v", err) + } + if updated.AvailabilityOverrideBy != "admin-two" { + t.Errorf("returned AvailabilityOverrideBy = %q; want %q", updated.AvailabilityOverrideBy, "admin-two") + } + if got := stored(); !got.Valid || got.String != "admin-two" { + t.Errorf("stored availability_override_by = %+v; want %q", got, "admin-two") + } + + // An ordinary move clears it, to NULL. + updated, err = svc.Reschedule(context.Background(), b.ID, slot(10, 0), slot(10, 30), "") + if err != nil { + t.Fatalf("Reschedule without override: %v", err) + } + if updated.AvailabilityOverrideBy != "" { + t.Errorf("returned AvailabilityOverrideBy = %q; want empty", updated.AvailabilityOverrideBy) + } + if got := stored(); got.Valid { + t.Errorf("stored availability_override_by after a normal move = %q; want NULL", got.String) + } + got, err := svc.Get(context.Background(), b.ID) + if err != nil { + t.Fatalf("Get: %v", err) + } + if got.AvailabilityOverrideBy != "" { + t.Errorf("Get AvailabilityOverrideBy = %q; want empty", got.AvailabilityOverrideBy) + } + + // A refused move (overlap) leaves the record as it was. + other, err := svc.Create(context.Background(), booking.CreateParams{ + EventTypeID: etID, + HostIDs: []string{hostID}, + StartAt: slot(20, 0), + EndAt: slot(20, 30), + Organizer: booking.Attendee{Name: "Bob", Email: "bob@example.com"}, + AvailabilityOverrideBy: "admin-one", + }) + if err != nil { + t.Fatalf("Create second: %v", err) + } + if _, err := svc.Reschedule(context.Background(), other.ID, slot(10, 0), slot(10, 30), ""); !errors.Is(err, booking.ErrDoubleBooked) { + t.Fatalf("overlapping Reschedule: err = %v; want ErrDoubleBooked", err) + } + after, err := svc.Get(context.Background(), other.ID) + if err != nil { + t.Fatalf("Get after refused move: %v", err) + } + if after.AvailabilityOverrideBy != "admin-one" { + t.Errorf("after refused move: AvailabilityOverrideBy = %q; want %q", after.AvailabilityOverrideBy, "admin-one") + } +} + func TestReschedule_sameTime(t *testing.T) { // Rescheduling to the same time must succeed (self-exclusion in overlap check). database := newTestDB(t) @@ -223,7 +310,7 @@ func TestReschedule_sameTime(t *testing.T) { t.Fatalf("Create: %v", err) } - _, err = svc.Reschedule(context.Background(), b.ID, slot(9, 0), slot(9, 30)) + _, err = svc.Reschedule(context.Background(), b.ID, slot(9, 0), slot(9, 30), "") if err != nil { t.Errorf("Reschedule to same time: got %v; want nil", err) } @@ -258,7 +345,7 @@ func TestReschedule_doubleBooked(t *testing.T) { } // Try to reschedule to 10:00-10:30 which is already taken. - _, err = svc.Reschedule(context.Background(), b.ID, slot(10, 0), slot(10, 30)) + _, err = svc.Reschedule(context.Background(), b.ID, slot(10, 0), slot(10, 30), "") if err != booking.ErrDoubleBooked { t.Errorf("Reschedule to conflicting slot: got %v; want ErrDoubleBooked", err) } @@ -284,7 +371,7 @@ func TestReschedule_alreadyCancelled(t *testing.T) { t.Fatalf("Cancel: %v", err) } - _, err = svc.Reschedule(context.Background(), b.ID, slot(11, 0), slot(11, 30)) + _, err = svc.Reschedule(context.Background(), b.ID, slot(11, 0), slot(11, 30), "") if err != booking.ErrAlreadyCancelled { t.Errorf("Reschedule of cancelled booking: got %v; want ErrAlreadyCancelled", err) } diff --git a/internal/booking/service.go b/internal/booking/service.go index aae6c77d..381e157b 100644 --- a/internal/booking/service.go +++ b/internal/booking/service.go @@ -160,10 +160,10 @@ func (s *Service) Create(ctx context.Context, p CreateParams) (*Booking, error) _, err = tx.ExecContext(ctx, ` INSERT INTO bookings (id, event_type_id, host_id, start_at, end_at, status, location_value, location_type, - invite_delivery, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, 'confirmed', ?, ?, ?, ?, ?)`, + invite_delivery, availability_override_by, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, 'confirmed', ?, ?, ?, NULLIF(?, ''), ?, ?)`, bookingID, p.EventTypeID, chosenHost, startStr, endStr, p.LocationValue, p.LocationType, - inviteDelivery, now, now) + inviteDelivery, p.AvailabilityOverrideBy, now, now) if err != nil { if db.IsUniqueViolation(err) { return nil, ErrDoubleBooked @@ -228,6 +228,8 @@ func (s *Service) Create(ctx context.Context, p CreateParams) (*Booking, error) InviteDelivery: inviteDelivery, CreatedAt: nowT, UpdatedAt: nowT, + + AvailabilityOverrideBy: p.AvailabilityOverrideBy, }, nil } @@ -307,7 +309,7 @@ const bookingColumns = `id, event_type_id, host_id, start_at, end_at, status, COALESCE(cancellation_reason, ''), COALESCE(location_value, ''), created_at, updated_at, payment_status, amount_paid_cents, amount_paid_currency, location_type, - confirm_failed, invite_delivery` + confirm_failed, invite_delivery, COALESCE(availability_override_by, '')` // hostBusy reports whether hostID has any non-cancelled booking overlapping // [start, end) — the double-booking invariant every write path (Create, Reschedule, @@ -477,7 +479,14 @@ func leastLoadedHost(ctx context.Context, tx *sql.Tx, eventTypeID string, candid // Returns ErrNotFound if the booking doesn't exist, ErrAlreadyCancelled if // it is cancelled, and ErrDoubleBooked if the new slot overlaps another // confirmed booking for the same host. -func (s *Service) Reschedule(ctx context.Context, bookingID string, newStart, newEnd time.Time) (*Booking, error) { +// +// overrideBy is the availability override (#270): the id of the owner or admin moving +// the booking to a time outside normal availability, or "" for an ordinary move. It is +// written to availability_override_by in the same UPDATE as the new times, so the +// column always describes where the booking sits now: an override records whoever made +// this move, and every ordinary move, by any caller, clears it. It has no influence on +// the overlap check below. +func (s *Service) Reschedule(ctx context.Context, bookingID string, newStart, newEnd time.Time, overrideBy string) (*Booking, error) { startStr := newStart.UTC().Format(time.RFC3339Nano) endStr := newEnd.UTC().Format(time.RFC3339Nano) @@ -527,8 +536,10 @@ func (s *Service) Reschedule(ctx context.Context, bookingID string, newStart, ne now := time.Now().UTC().Format(time.RFC3339Nano) if _, err := tx.ExecContext(ctx, ` - UPDATE bookings SET start_at = ?, end_at = ?, updated_at = ? WHERE id = ?`, - startStr, endStr, now, bookingID); err != nil { + UPDATE bookings + SET start_at = ?, end_at = ?, availability_override_by = NULLIF(?, ''), updated_at = ? + WHERE id = ?`, + startStr, endStr, overrideBy, now, bookingID); err != nil { if db.IsUniqueViolation(err) { return nil, ErrDoubleBooked } @@ -541,6 +552,7 @@ func (s *Service) Reschedule(ctx context.Context, bookingID string, newStart, ne b.StartAt = newStart.UTC() b.EndAt = newEnd.UTC() + b.AvailabilityOverrideBy = overrideBy if t, err := time.Parse(time.RFC3339Nano, now); err == nil { b.UpdatedAt = t } @@ -706,7 +718,7 @@ func scanBooking(s scanner) (*Booking, error) { &b.CancellationReason, &b.LocationValue, &createdStr, &updatedStr, &b.PaymentStatus, &b.AmountPaidCents, &b.AmountPaidCurrency, &b.LocationType, - &confirmFailed, &b.InviteDelivery, + &confirmFailed, &b.InviteDelivery, &b.AvailabilityOverrideBy, ) if err == sql.ErrNoRows { return nil, ErrNotFound diff --git a/internal/booking/service_test.go b/internal/booking/service_test.go index 9f656a02..0245d318 100644 --- a/internal/booking/service_test.go +++ b/internal/booking/service_test.go @@ -3,6 +3,7 @@ package booking_test import ( "context" "database/sql" + "errors" "testing" "time" @@ -531,6 +532,68 @@ func TestGet_success(t *testing.T) { } } +// The availability override (#270) is stored by Create in the booking's own INSERT and +// read back by every query that loads a Booking. Without it the column stays NULL. +func TestCreate_recordsAvailabilityOverride(t *testing.T) { + database := newTestDB(t) + svc := booking.New(database) + hostID := seedHost(t, database) + etID := seedEventType(t, database, hostID) + + overridden, err := svc.Create(context.Background(), booking.CreateParams{ + EventTypeID: etID, + HostIDs: []string{hostID}, + StartAt: slot(22, 0), + EndAt: slot(22, 30), + Organizer: booking.Attendee{Name: "Alice", Email: "alice@example.com"}, + AvailabilityOverrideBy: "admin-user", + }) + if err != nil { + t.Fatalf("Create with override: %v", err) + } + if overridden.AvailabilityOverrideBy != "admin-user" { + t.Errorf("returned AvailabilityOverrideBy = %q; want %q", overridden.AvailabilityOverrideBy, "admin-user") + } + got, err := svc.Get(context.Background(), overridden.ID) + if err != nil { + t.Fatalf("Get: %v", err) + } + if got.AvailabilityOverrideBy != "admin-user" { + t.Errorf("stored AvailabilityOverrideBy = %q; want %q", got.AvailabilityOverrideBy, "admin-user") + } + + normal, err := svc.Create(context.Background(), booking.CreateParams{ + EventTypeID: etID, + HostIDs: []string{hostID}, + StartAt: slot(9, 0), + EndAt: slot(9, 30), + Organizer: booking.Attendee{Name: "Bob", Email: "bob@example.com"}, + }) + if err != nil { + t.Fatalf("Create without override: %v", err) + } + var stored sql.NullString + if err := database.QueryRow(`SELECT availability_override_by FROM bookings WHERE id = ?`, normal.ID).Scan(&stored); err != nil { + t.Fatalf("read column: %v", err) + } + if stored.Valid { + t.Errorf("availability_override_by on a normal booking = %q; want NULL", stored.String) + } + + // The override records who, and changes nothing about the overlap check. + _, err = svc.Create(context.Background(), booking.CreateParams{ + EventTypeID: etID, + HostIDs: []string{hostID}, + StartAt: slot(22, 15), + EndAt: slot(22, 45), + Organizer: booking.Attendee{Name: "Carol", Email: "carol@example.com"}, + AvailabilityOverrideBy: "admin-user", + }) + if !errors.Is(err, booking.ErrDoubleBooked) { + t.Errorf("overlapping Create with override: err = %v; want ErrDoubleBooked", err) + } +} + func TestGet_notFound(t *testing.T) { svc := booking.New(newTestDB(t)) _, err := svc.Get(context.Background(), "nonexistent") diff --git a/internal/db/migrations/00080_booking_availability_override.sql b/internal/db/migrations/00080_booking_availability_override.sql new file mode 100644 index 00000000..40211516 --- /dev/null +++ b/internal/db/migrations/00080_booking_availability_override.sql @@ -0,0 +1,16 @@ +-- +goose Up +-- Who booked or moved this booking into a time the public calendar would not have +-- offered (#270). An owner or admin can do that through the MCP tools with +-- skip_availability, which skips minimum notice, the booking window and the hosts' +-- availability windows, never the double-booking check. +-- +-- NULL means the booking sits in a normally bookable slot; otherwise it holds the id +-- of the user who used the override. The column describes where the booking currently +-- sits, so a later normal reschedule sets it back to NULL. +-- +-- Nullable with no default, so existing rows read as "no override". No foreign key on +-- purpose: removing a user must neither be blocked by this record nor silently erase it. +ALTER TABLE bookings ADD COLUMN availability_override_by TEXT; + +-- +goose Down +ALTER TABLE bookings DROP COLUMN availability_override_by; diff --git a/internal/handler/booking_assistant.go b/internal/handler/booking_assistant.go index 2af709cc..d1097332 100644 --- a/internal/handler/booking_assistant.go +++ b/internal/handler/booking_assistant.go @@ -417,7 +417,8 @@ func (h *Handler) runAssistantTool(ctx context.Context, slug, tz, lang, name, ar raw[i] = booking.Answer{QuestionID: a.QuestionID, Value: a.Value} } b, err := h.createBookingForSlug(ctx, slug, startAt, - booking.Attendee{Name: args.Name, Email: args.Email, IANATimezone: tz, Locale: lang}, raw) + booking.Attendee{Name: args.Name, Email: args.Email, IANATimezone: tz, Locale: lang}, raw, + "") // the assistant never books outside availability if err != nil { return "error: " + assistantBookError(err), nil } diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index e1f54313..d68c59ff 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -11,6 +11,7 @@ import ( "net/http" "net/mail" "net/url" + "slices" "strconv" "strings" "sync" @@ -322,7 +323,44 @@ var bookingNow = func() time.Time { return time.Now() } // free/busy fetch, so it stays cheap on the hot path (no external API calls). // routingMode/candidates/required must be exactly what will be passed to // booking.CreateParams — see resolveBookingHostPool. -func (h *Handler) validateBookingTime(ctx context.Context, et *bookableEventType, routingMode string, candidates, required []string, startAt, endAt time.Time) error { +// +// skipAvailability (#270) is the owner/admin availability override, and this is the +// single place it takes effect, so there is no second code path to keep in step. The +// rules are always evaluated. When the time fails them and skipAvailability is set, the +// refusal is waived and overridden reports true; when the time passes them anyway, +// overridden is false even with the flag, so a booking in a normally bookable slot is +// never recorded as an override. Only the MCP tools ever pass true, after +// mcpAvailabilityOverride has authorised the caller. The overlap check in +// booking.Service is not part of this function and is never skipped. +// +// One floor the flag does not lift: a start that has already passed. Minimum notice is +// waived, "not in the past" is not, so under the flag such a time is refused with +// errStartInPast instead of being waived. Without the flag nothing changes: it stays +// the ordinary errSlotUnavailable every caller already maps. +func (h *Handler) validateBookingTime(ctx context.Context, et *bookableEventType, routingMode string, candidates, required []string, startAt, endAt time.Time, skipAvailability bool) (overridden bool, err error) { + err = h.checkBookingTime(ctx, et, routingMode, candidates, required, startAt, endAt) + if skipAvailability && errors.Is(err, errSlotUnavailable) { + if startInPast(startAt) { + return false, errStartInPast + } + return true, nil + } + return false, err +} + +// errStartInPast is the refusal for a start that has already passed when the caller +// asked for the availability override (#270). It is deliberately not errSlotUnavailable: +// that one the override waives, this one it never does. +var errStartInPast = errors.New("the start time is in the past; skip_availability does not lift that, and nothing was booked or changed") + +// startInPast reports whether startAt lies before the booking clock's "now". +func startInPast(startAt time.Time) bool { + return startAt.Before(bookingNow().UTC()) +} + +// checkBookingTime is validateBookingTime's rule set: errSlotUnavailable when the time +// fails minimum notice, the booking window or the hosts' hours, nil when it passes. +func (h *Handler) checkBookingTime(ctx context.Context, et *bookableEventType, routingMode string, candidates, required []string, startAt, endAt time.Time) error { now := bookingNow().UTC() if startAt.Before(now.Add(time.Duration(et.MinNoticeMinutes) * time.Minute)) { return errSlotUnavailable @@ -384,31 +422,37 @@ func (h *Handler) validateBookingTime(ctx context.Context, et *bookableEventType // booking.Service.Reschedule's own "every host keeps their seat, so every host must be // free" semantics — falls back to the booking's primary host_id for a legacy booking with // no booking_hosts rows, the same fallback Reschedule itself uses. -func (h *Handler) validateRescheduleTime(ctx context.Context, bookingID, eventTypeID, fallbackHostID string, newStart, newEnd time.Time) error { +// +// skipAvailability and the overridden result are validateBookingTime's (#270): the +// rules are always evaluated, and overridden reports that a refusal was waived. The gate +// hangs on the target time, not on the booking's history: only the MCP tool passes true, +// for an authorised owner or admin; the admin REST endpoint and the guest's manage link +// always pass false. +func (h *Handler) validateRescheduleTime(ctx context.Context, bookingID, eventTypeID, fallbackHostID string, newStart, newEnd time.Time, skipAvailability bool) (overridden bool, err error) { var et bookableEventType et.ID = eventTypeID if err := h.db.QueryRowContext(ctx, `SELECT min_notice_minutes, max_future_days FROM event_types WHERE id = ?`, eventTypeID). Scan(&et.MinNoticeMinutes, &et.MaxFutureDays); err != nil { - return fmt.Errorf("load event type constraints: %w", err) + return false, fmt.Errorf("load event type constraints: %w", err) } hostRows, err := h.db.QueryContext(ctx, `SELECT user_id FROM booking_hosts WHERE booking_id = ?`, bookingID) if err != nil { - return fmt.Errorf("load booking hosts: %w", err) + return false, fmt.Errorf("load booking hosts: %w", err) } var hostIDs []string for hostRows.Next() { var u string if err := hostRows.Scan(&u); err != nil { hostRows.Close() // #nosec G104 -- already returning the scan error; nothing more actionable - return fmt.Errorf("scan booking host: %w", err) + return false, fmt.Errorf("scan booking host: %w", err) } hostIDs = append(hostIDs, u) } hostRows.Close() // #nosec G104 -- rows already fully consumed above; nothing actionable on close error if err := hostRows.Err(); err != nil { - return err + return false, err } if len(hostIDs) == 0 { // legacy booking with no booking_hosts rows hostIDs = []string{fallbackHostID} @@ -416,7 +460,7 @@ func (h *Handler) validateRescheduleTime(ctx context.Context, bookingID, eventTy // routingMode "fixed" (i.e. not "round_robin") makes validateBookingTime require EVERY // one of hostIDs to be available — there's no pool to pick from on a reschedule, every // assigned host keeps their seat. - return h.validateBookingTime(ctx, &et, "fixed", hostIDs, nil, newStart, newEnd) + return h.validateBookingTime(ctx, &et, "fixed", hostIDs, nil, newStart, newEnd, skipAvailability) } // filterAvailableHosts narrows a candidate pool to the hosts actually free @@ -562,7 +606,15 @@ func (h *Handler) loadBookableEventType(ctx context.Context, slug string) (*book // no parallel code path. Errors are raw (errEventTypeNotFound, *answerError, // booking.ErrDoubleBooked, booking.ErrBookingLimitReached, errNoHostAvailable) for callers to // map to their own protocol. -func (h *Handler) createBookingForSlug(ctx context.Context, slug string, startAt time.Time, organizer booking.Attendee, rawAnswers []booking.Answer) (*booking.Booking, error) { +// +// overrideBy is the availability override (#270): the id of the owner or admin who may +// book outside normal availability, or "" for none, which is what the assistant always +// passes. The flag and the actor are deliberately one value, so the rules cannot be +// waived without the same id reaching the INSERT. It is recorded only when it was +// needed: for a time that is normally bookable the booking takes the ordinary path and +// the column stays NULL. +// A start already in the past is refused under it too (errStartInPast). +func (h *Handler) createBookingForSlug(ctx context.Context, slug string, startAt time.Time, organizer booking.Attendee, rawAnswers []booking.Answer, overrideBy string) (*booking.Booking, error) { // Both callers take the address from something they do not control — an LLM's // extraction from booker chat, or an MCP client's tool arguments — so it is checked // here, once, rather than in each of them. (The REST handler does not come through @@ -604,36 +656,92 @@ func (h *Handler) createBookingForSlug(ctx context.Context, slug string, startAt if len(candidates) == 0 { return nil, errNoHostAvailable } - if err := h.validateBookingTime(ctx, et, et.RoutingMode, candidates, required, startAt.UTC(), endAt); err != nil { - return nil, err - } - if candidates, err = h.filterAvailableHosts(ctx, et, candidates, startAt.UTC(), endAt); err != nil { - return nil, err + // attempt runs the calendar busy check and the transactional create for one host + // pool. recordedBy is what goes into availability_override_by ("" for none). + attempt := func(pool []string, recordedBy string) (*booking.Booking, error) { + pool, opt, err := h.calendarFreeHosts(ctx, et, pool, required, optional, startAt.UTC(), endAt) + if err != nil { + if !errors.Is(err, errSlotUnavailable) { + h.logger.ErrorContext(ctx, "booking calendar check failed", "error", err) + } + return nil, err + } + return h.bookingSvc.Create(ctx, booking.CreateParams{ + EventTypeID: et.ID, + HostIDs: pool, + RoutingMode: et.RoutingMode, + RRStrategy: et.RRStrategy, + RequiredHosts: required, + OptionalHosts: opt, + StartAt: startAt.UTC(), + EndAt: endAt, + LocationValue: locValue, + LocationType: et.LocationType, + Organizer: organizer, + Answers: answers, + MaxActivePerInvitee: et.MaxActiveBookings, + MaxBookingsPerHour: maxBookingsPerEmailPerHour, + InviteDelivery: et.InviteDelivery, + + AvailabilityOverrideBy: recordedBy, + }) } - candidates, optional, err = h.calendarFreeHosts(ctx, et, candidates, required, optional, startAt.UTC(), endAt) + + overridden, err := h.validateBookingTime(ctx, et, et.RoutingMode, candidates, required, startAt.UTC(), endAt, overrideBy != "") if err != nil { - if !errors.Is(err, errSlotUnavailable) { - h.logger.ErrorContext(ctx, "booking calendar check failed", "error", err) - } return nil, err } - b, err := h.bookingSvc.Create(ctx, booking.CreateParams{ - EventTypeID: et.ID, - HostIDs: candidates, - RoutingMode: et.RoutingMode, - RRStrategy: et.RRStrategy, - RequiredHosts: required, - OptionalHosts: optional, - StartAt: startAt.UTC(), - EndAt: endAt, - LocationValue: locValue, - LocationType: et.LocationType, - Organizer: organizer, - Answers: answers, - MaxActivePerInvitee: et.MaxActiveBookings, - MaxBookingsPerHour: maxBookingsPerEmailPerHour, - InviteDelivery: et.InviteDelivery, - }) + // recordedBy: a waived refusal (notice, window or hours) is recorded whoever ends up + // hosting; a normally bookable time records nothing on its first attempt. + recordedBy := "" + if overridden { + recordedBy = overrideBy + } + // pool is who the first attempt may book; outsideHours is who the host filter removed. + pool := candidates + var outsideHours []string + if !overridden || et.RoutingMode == "round_robin" { + // The ordinary host filter (#146). It also runs for round robin when a refusal + // was waived: the waived rule may have been minimum notice or the booking window, + // which say nothing about hours, and the rotation must still prefer a host who + // is within theirs over one who is not. Only when it finds nobody within hours - + // the hours rule itself was what got waived - does the rotation pick among all + // candidates. Fixed and collective under a waiver keep every candidate: there + // each of them has a seat, and filtering would drop the host outside their hours + // from the booking instead of booking them. + available, ferr := h.filterAvailableHosts(ctx, et, candidates, startAt.UTC(), endAt) + switch { + case ferr == nil: + pool = available + for _, id := range candidates { + if !slices.Contains(available, id) { + outsideHours = append(outsideHours, id) + } + } + case overridden && errors.Is(ferr, errSlotUnavailable): + // Nobody is within their hours; pool stays all candidates. + default: + return nil, ferr + } + } + // The calendar busy check and the overlap check in booking.Service.Create always + // run (both inside attempt). + b, err := attempt(pool, recordedBy) + // Round robin only: the slot "exists" as soon as ONE rotation host is within + // hours, so the rules above can pass while every such host turns out to be + // taken. A rotation host outside their hours is then the only one left, and + // booking them is exactly what the override is for. So under the override, and + // only when the filter actually removed someone, a refusal for lack of a free + // in-hours host gets one more try - still through the calendar busy check and + // the overlap check - with exactly the hosts the filter removed. The pool of + // that second try holds nobody who is within their hours, so a booking it makes + // is on a host outside their availability by construction, and is recorded as + // an override. Any other error, and every case without the override, is + // returned as it is. + if err != nil && overrideBy != "" && len(outsideHours) > 0 && + (errors.Is(err, booking.ErrDoubleBooked) || errors.Is(err, errSlotUnavailable)) { + b, err = attempt(outsideHours, overrideBy) + } if err != nil { return nil, err } @@ -950,7 +1058,7 @@ func (h *Handler) CreateBooking(w http.ResponseWriter, r *http.Request) { h.writeError(w, http.StatusConflict, "this slot is no longer available") return } - if err := h.validateBookingTime(r.Context(), et, et.RoutingMode, candidates, required, startAt.UTC(), endAt); err != nil { + if _, err := h.validateBookingTime(r.Context(), et, et.RoutingMode, candidates, required, startAt.UTC(), endAt, false); err != nil { h.writeError(w, http.StatusConflict, "this slot is no longer available") return } diff --git a/internal/handler/invite_delivery_internal_test.go b/internal/handler/invite_delivery_internal_test.go index 383c7e55..99b567f8 100644 --- a/internal/handler/invite_delivery_internal_test.go +++ b/internal/handler/invite_delivery_internal_test.go @@ -367,7 +367,7 @@ func TestInviteDelivery_rescheduleSendsWorkspaceInvite(t *testing.T) { b, etID := f.calnodeBooking(t) newStart := b.StartAt.Add(24 * time.Hour) - updated, err := f.h.bookingSvc.Reschedule(context.Background(), b.ID, newStart, newStart.Add(30*time.Minute)) + updated, err := f.h.bookingSvc.Reschedule(context.Background(), b.ID, newStart, newStart.Add(30*time.Minute), "") if err != nil { t.Fatalf("reschedule: %v", err) } @@ -511,7 +511,7 @@ func TestInviteDelivery_noneRescheduleAndCancelSendNoInvite(t *testing.T) { ctx := context.Background() newStart := b.StartAt.Add(24 * time.Hour) - updated, err := f.h.bookingSvc.Reschedule(ctx, b.ID, newStart, newStart.Add(30*time.Minute)) + updated, err := f.h.bookingSvc.Reschedule(ctx, b.ID, newStart, newStart.Add(30*time.Minute), "") if err != nil { t.Fatalf("reschedule: %v", err) } diff --git a/internal/handler/manage_handler.go b/internal/handler/manage_handler.go index f9a84045..febd4a18 100644 --- a/internal/handler/manage_handler.go +++ b/internal/handler/manage_handler.go @@ -250,7 +250,7 @@ func (h *Handler) RescheduleByToken(w http.ResponseWriter, r *http.Request) { previousEnd := b.EndAt newEnd := newStart.Add(time.Duration(durMins) * time.Minute) - if err := h.validateRescheduleTime(r.Context(), b.ID, b.EventTypeID, b.HostID, newStart, newEnd); err != nil { + if _, err := h.validateRescheduleTime(r.Context(), b.ID, b.EventTypeID, b.HostID, newStart, newEnd, false); err != nil { if errors.Is(err, errSlotUnavailable) { h.writeError(w, http.StatusConflict, "that time slot is no longer available") return @@ -260,7 +260,9 @@ func (h *Handler) RescheduleByToken(w http.ResponseWriter, r *http.Request) { return } - updated, err := h.bookingSvc.Reschedule(r.Context(), b.ID, newStart, newEnd) + // "" = no availability override: a guest never has one, and moving the booking into a + // normal slot clears any that was recorded (see booking.Service.Reschedule). + updated, err := h.bookingSvc.Reschedule(r.Context(), b.ID, newStart, newEnd, "") if errors.Is(err, booking.ErrDoubleBooked) { h.writeError(w, http.StatusConflict, "that time slot is no longer available") return diff --git a/internal/handler/mcp.go b/internal/handler/mcp.go index 855844c3..b5282cdd 100644 --- a/internal/handler/mcp.go +++ b/internal/handler/mcp.go @@ -54,12 +54,12 @@ func (h *Handler) MCPServer() *mcp.Server { mcp.AddTool(s, &mcp.Tool{ Name: "create_booking", - Description: "Book a slot on an event type. slot_start must be an exact start from get_available_slots. Answers the event type's required intake questions if any. Returns the created booking (with its id and assigned host).", + Description: "Book a slot on an event type. slot_start must be an exact start from get_available_slots. Answers the event type's required intake questions if any. Returns the created booking (with its id and assigned host). Workspace owners and admins may set skip_availability to book a time that was never offered (outside working hours, inside the minimum notice, beyond the booking window); it is refused for anyone else, and a time that collides with an existing booking, or that is already in the past, is refused either way.", }, h.mcpCreateBooking) mcp.AddTool(s, &mcp.Tool{ Name: "reschedule_booking", - Description: "Move an existing booking to a new start time (RFC3339). The duration is preserved. Fails if the new slot is taken or the booking is cancelled.", + Description: "Move an existing booking to a new start time (RFC3339). The duration is preserved. Fails if the new slot is taken, outside availability, or the booking is cancelled. Workspace owners and admins may set skip_availability to move it to a time outside availability (working hours, minimum notice, booking window); it is refused for anyone else, and a time that collides with another booking, or that is already in the past, is refused either way.", }, h.mcpRescheduleBooking) mcp.AddTool(s, &mcp.Tool{ @@ -374,9 +374,18 @@ type createBookingIn struct { AttendeeEmail string `json:"attendee_email"` Timezone string `json:"timezone,omitempty" jsonschema:"attendee IANA timezone; defaults to UTC"` Answers []mcpAnswer `json:"answers,omitempty" jsonschema:"answers to the event type's intake questions, if any are required"` + // SkipAvailability is only a request. Whether it is honoured is decided from the + // authenticated caller's role in mcpAvailabilityOverride, never from this field. + SkipAvailability bool `json:"skip_availability,omitempty" jsonschema:"owners and admins only: book this time even though it is outside the hosts' availability, inside the minimum notice or beyond the booking window. Never bypasses the double-booking check, and never books a time in the past. Refused, with nothing booked, for any other caller"` } func (h *Handler) mcpCreateBooking(ctx context.Context, _ *mcp.CallToolRequest, in createBookingIn) (*mcp.CallToolResult, bookingJSON, error) { + // First, before anything is parsed or loaded: a caller who may not use the override + // is refused outright, never booked without it. + overrideBy, err := mcpAvailabilityOverride(ctx, in.SkipAvailability) + if err != nil { + return nil, bookingJSON{}, err + } if in.EventTypeID == "" || in.SlotStart == "" || in.AttendeeName == "" || in.AttendeeEmail == "" { return nil, bookingJSON{}, fmt.Errorf("event_type_id, slot_start, attendee_name, and attendee_email are required") } @@ -398,7 +407,7 @@ func (h *Handler) mcpCreateBooking(ctx context.Context, _ *mcp.CallToolRequest, // Locale intentionally left unset (defaults to English at the DB layer) — an MCP // caller is an agent/automation, not a browser with a resolved page locale. b, err := h.createBookingForSlug(ctx, in.EventTypeID, startAt, - booking.Attendee{Name: in.AttendeeName, Email: in.AttendeeEmail, IANATimezone: tz}, raw) + booking.Attendee{Name: in.AttendeeName, Email: in.AttendeeEmail, IANATimezone: tz}, raw, overrideBy) if err != nil { switch { case errors.Is(err, errCalendarUnavailable): @@ -429,9 +438,25 @@ func (h *Handler) mcpCreateBooking(ctx context.Context, _ *mcp.CallToolRequest, type rescheduleBookingIn struct { BookingID string `json:"booking_id"` NewSlotStart string `json:"new_slot_start" jsonschema:"the new start as RFC3339; the duration is preserved"` + // SkipAvailability is only a request; see createBookingIn. + SkipAvailability bool `json:"skip_availability,omitempty" jsonschema:"owners and admins only: move the booking to this time even though it is outside the hosts' availability, inside the minimum notice or beyond the booking window. Never bypasses the double-booking check, and never moves to a time in the past. Refused, with nothing changed, for any other caller"` } +// errRescheduleOutsideAvailability is reschedule_booking's refusal for a target that +// fails minimum notice, the booking window or the hosts' hours (errSlotUnavailable from +// validateRescheduleTime). It is worded apart from the double-booking refusal on +// purpose: this one an owner or admin can lift with skip_availability, a collision +// nobody can. +var errRescheduleOutsideAvailability = errors.New("the new time is outside availability (working hours, minimum notice or booking window); an owner or admin can resend with skip_availability") + func (h *Handler) mcpRescheduleBooking(ctx context.Context, _ *mcp.CallToolRequest, in rescheduleBookingIn) (*mcp.CallToolResult, bookingJSON, error) { + // First, before the booking is loaded and before the member visibility check below: a + // caller who may not use the override gets the same explicit refusal whether or not + // the booking exists or is theirs. + overrideBy, err := mcpAvailabilityOverride(ctx, in.SkipAvailability) + if err != nil { + return nil, bookingJSON{}, err + } if in.BookingID == "" || in.NewSlotStart == "" { return nil, bookingJSON{}, fmt.Errorf("booking_id and new_slot_start are required") } @@ -455,15 +480,28 @@ func (h *Handler) mcpRescheduleBooking(ctx context.Context, _ *mcp.CallToolReque return nil, bookingJSON{}, fmt.Errorf("load duration: %w", err) } newEnd := newStart.Add(time.Duration(durMins) * time.Minute) - if err := h.validateRescheduleTime(ctx, b.ID, b.EventTypeID, b.HostID, newStart, newEnd); err != nil { + overridden, err := h.validateRescheduleTime(ctx, b.ID, b.EventTypeID, b.HostID, newStart, newEnd, overrideBy != "") + if err != nil { + // A target that has already passed is refused with or without the flag, and + // must not be answered with "resend with skip_availability": that would not help. + if errors.Is(err, errStartInPast) || (errors.Is(err, errSlotUnavailable) && startInPast(newStart)) { + return nil, bookingJSON{}, errStartInPast + } if errors.Is(err, errSlotUnavailable) { - return nil, bookingJSON{}, fmt.Errorf("that time slot is no longer available") + return nil, bookingJSON{}, errRescheduleOutsideAvailability } return nil, bookingJSON{}, fmt.Errorf("validate reschedule time: %w", err) } + if !overridden { + // The target is normally bookable (or no override was asked for): this is an + // ordinary move, which records nothing and clears an earlier override. + overrideBy = "" + } previousStart, previousEnd := b.StartAt, b.EndAt - updated, err := h.bookingSvc.Reschedule(ctx, b.ID, newStart, newEnd) + // overrideBy goes into the same UPDATE as the new times: set to the acting user when + // the override was needed, cleared by a normal move. + updated, err := h.bookingSvc.Reschedule(ctx, b.ID, newStart, newEnd, overrideBy) if err != nil { switch { case errors.Is(err, booking.ErrDoubleBooked): diff --git a/internal/handler/mcp_oauth.go b/internal/handler/mcp_oauth.go index bd2f1638..9190ef05 100644 --- a/internal/handler/mcp_oauth.go +++ b/internal/handler/mcp_oauth.go @@ -3,6 +3,7 @@ package handler import ( "context" "encoding/json" + "errors" "net/http" "net/url" "strings" @@ -61,6 +62,42 @@ func mcpCallerScope(ctx context.Context) (userID string, fullAccess bool) { return "", true } +// Refusals for skip_availability (#270). MCP has no status codes, so each is a tool +// error whose text says outright that nothing was written: a silently ignored flag +// would create the booking and look as if the override had worked. +var ( + errAvailabilityOverrideForbidden = errors.New("skip_availability is restricted to workspace owners and admins; nothing was booked or changed") + errAvailabilityOverrideNoIdentity = errors.New("skip_availability needs an authenticated owner or admin (it records who used it); nothing was booked or changed") +) + +// mcpAvailabilityOverride decides whether this call may skip the availability checks, +// and names who is doing it. It returns the acting user's id when skipAvailability is +// set and the caller is an owner or admin, "" when the flag is not set, and an error +// otherwise. The tools call it before loading anything, so a refusal reads the same +// whether or not the target exists. +// +// The role comes only from the caller MCPCallerMiddleware bound from the database; no +// tool argument can assert it. The returned id is the one value that both switches the +// checks off and is written to bookings.availability_override_by, so the override +// cannot take effect without being recorded. +// +// Unlike mcpCallerScope, no bound caller (the stdio transport) is refused here rather +// than treated as full access: there is no user id to record, and an override that +// names nobody is what the column exists to prevent. +func mcpAvailabilityOverride(ctx context.Context, skipAvailability bool) (overrideBy string, err error) { + if !skipAvailability { + return "", nil + } + c, ok := mcpCallerFromContext(ctx) + if !ok || c.UserID == "" { + return "", errAvailabilityOverrideNoIdentity + } + if !c.IsAdmin { + return "", errAvailabilityOverrideForbidden + } + return c.UserID, nil +} + // userHostsBooking reports whether userID is a host on the booking — the primary host // or any assigned host (matching booking.ListByHost). Used to gate a member's read of a // single booking. diff --git a/internal/handler/mcp_skip_availability_test.go b/internal/handler/mcp_skip_availability_test.go new file mode 100644 index 00000000..7201c2db --- /dev/null +++ b/internal/handler/mcp_skip_availability_test.go @@ -0,0 +1,1139 @@ +package handler + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/modelcontextprotocol/go-sdk/auth" + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/calnode/calnode/internal/booking" + "github.com/calnode/calnode/internal/calendar" + "github.com/calnode/calnode/internal/db" + "github.com/calnode/calnode/internal/slots" + "github.com/calnode/calnode/internal/uid" +) + +// Tests for skip_availability on the MCP booking tools (#270). They call the tool +// handlers directly with a bound caller rather than through connectMCP: the in-memory +// transport binds no caller, which is the stdio case, and every rule under test hangs on +// who the caller is. + +// skipAvailabilityFixture is a workspace with an owner, a second admin and a member, and +// one 30-minute event type hosted by the owner, who works 09:00-17:00 UTC every day. That +// gives an unambiguous "outside availability" (22:00) and "inside" (10:00). +type skipAvailabilityFixture struct { + h *Handler + db *sql.DB + etID string + ownerID string + adminID string + memberID string + + ownerCtx context.Context + adminCtx context.Context + memberCtx context.Context +} + +const skipAvailabilitySlug = "after-hours" + +func newSkipAvailabilityFixture(t *testing.T) *skipAvailabilityFixture { + t.Helper() + database, err := db.Open("sqlite://:memory:") + if err != nil { + t.Fatalf("db open: %v", err) + } + t.Cleanup(func() { database.Close() }) + if err := db.Migrate(database); err != nil { + t.Fatalf("migrate: %v", err) + } + h := New(database, slog.Default()) + + // Owner (first user → owner+admin). + rec := httptest.NewRecorder() + h.Setup(rec, httptest.NewRequest(http.MethodPost, "/v1/setup", + strings.NewReader(`{"name":"Owner","email":"owner@example.com","timezone":"UTC"}`))) + if rec.Code != http.StatusCreated { + t.Fatalf("setup: %d — %s", rec.Code, rec.Body.String()) + } + var setup struct { + UserID string `json:"user_id"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &setup); err != nil { + t.Fatalf("decode setup: %v", err) + } + f := &skipAvailabilityFixture{h: h, db: database, ownerID: setup.UserID, adminID: "admin-2", memberID: "member-1"} + + if _, err := database.Exec(`INSERT INTO users (id, email, name, iana_timezone, is_admin) VALUES (?, ?, ?, ?, 1)`, + f.adminID, "admin@example.com", "Admin", "UTC"); err != nil { + t.Fatalf("insert admin: %v", err) + } + if _, err := database.Exec(`INSERT INTO users (id, email, name, iana_timezone) VALUES (?, ?, ?, ?)`, + f.memberID, "member@example.com", "Member", "UTC"); err != nil { + t.Fatalf("insert member: %v", err) + } + + ereq := httptest.NewRequest(http.MethodPost, "/v1/event-types", + strings.NewReader(`{"slug":"`+skipAvailabilitySlug+`","name":"After hours","duration_minutes":30,"location_type":"phone","location_value":"+1 555 111 2222","max_future_days":0}`)) + ereq = ereq.WithContext(context.WithValue(ereq.Context(), ctxKeyUser, AuthUser{ID: f.ownerID, IsAdmin: true, IsOwner: true})) + erec := httptest.NewRecorder() + h.CreateEventType(erec, ereq) + if erec.Code != http.StatusCreated { + t.Fatalf("create event type: %d — %s", erec.Code, erec.Body.String()) + } + if err := database.QueryRow(`SELECT id FROM event_types WHERE slug = ?`, skipAvailabilitySlug).Scan(&f.etID); err != nil { + t.Fatalf("event type id: %v", err) + } + + for day := 0; day < 7; day++ { + if _, err := database.Exec( + `INSERT INTO availability_rules (id, user_id, day_of_week, start_time, end_time) VALUES (?, ?, ?, '09:00', '17:00')`, + uid.New(), f.ownerID, day); err != nil { + t.Fatalf("seed availability day %d: %v", day, err) + } + } + + f.ownerCtx = withMCPCaller(context.Background(), mcpCaller{UserID: f.ownerID, IsAdmin: true}) + f.adminCtx = withMCPCaller(context.Background(), mcpCaller{UserID: f.adminID, IsAdmin: true}) + f.memberCtx = withMCPCaller(context.Background(), mcpCaller{UserID: f.memberID, IsAdmin: false}) + return f +} + +// at is a time on 2027-02-01, inside the 365-day window of the pinned test clock +// (2026-06-01, see testmain_test.go). +func (f *skipAvailabilityFixture) at(hour, minute int) time.Time { + return time.Date(2027, 2, 1, hour, minute, 0, 0, time.UTC) +} + +// create calls the create_booking tool. Every call uses its own attendee address so the +// per-invitee limits never decide the outcome. +func (f *skipAvailabilityFixture) create(ctx context.Context, start time.Time, attendee string, skip bool) (bookingJSON, error) { + _, out, err := f.h.mcpCreateBooking(ctx, nil, createBookingIn{ + EventTypeID: skipAvailabilitySlug, + SlotStart: start.Format(time.RFC3339), + AttendeeName: "Pat Booker", + AttendeeEmail: attendee, + SkipAvailability: skip, + }) + return out, err +} + +func (f *skipAvailabilityFixture) mustCreate(t *testing.T, ctx context.Context, start time.Time, attendee string, skip bool) string { + t.Helper() + out, err := f.create(ctx, start, attendee, skip) + if err != nil { + t.Fatalf("create_booking at %s (skip_availability=%v): %v", start.Format(time.RFC3339), skip, err) + } + return out.ID +} + +func (f *skipAvailabilityFixture) bookingCount(t *testing.T) int { + t.Helper() + var n int + if err := f.db.QueryRow(`SELECT COUNT(*) FROM bookings`).Scan(&n); err != nil { + t.Fatalf("count bookings: %v", err) + } + return n +} + +// overrideBy reads the stored column as it is, so "cleared" means NULL and not an empty +// string. +func (f *skipAvailabilityFixture) overrideBy(t *testing.T, bookingID string) sql.NullString { + t.Helper() + var v sql.NullString + if err := f.db.QueryRow(`SELECT availability_override_by FROM bookings WHERE id = ?`, bookingID).Scan(&v); err != nil { + t.Fatalf("read availability_override_by: %v", err) + } + return v +} + +// Test 1 of #270: the override never bypasses the double-booking check on create. +func TestMCP_skipAvailability_createStillRefusesConflict(t *testing.T) { + f := newSkipAvailabilityFixture(t) + f.mustCreate(t, f.ownerCtx, f.at(22, 0), "first@example.com", true) + + // 22:15 overlaps the 22:00-22:30 booking. + _, err := f.create(f.ownerCtx, f.at(22, 15), "second@example.com", true) + if err == nil { + t.Fatal("create_booking with skip_availability on a colliding time succeeded; want a refusal") + } + if n := f.bookingCount(t); n != 1 { + t.Fatalf("bookings after refused override = %d; want 1 (no row created)", n) + } + + // The tool reports a conflict in the same words as an unavailable slot, so pin the + // cause one layer down: it is the overlap check that refuses, not availability. + _, err = f.h.createBookingForSlug(context.Background(), skipAvailabilitySlug, f.at(22, 15), + booking.Attendee{Name: "Pat Booker", Email: "third@example.com", IANATimezone: "UTC"}, nil, f.ownerID) + if !errors.Is(err, booking.ErrDoubleBooked) { + t.Fatalf("override on a colliding time: err = %v; want booking.ErrDoubleBooked", err) + } + if n := f.bookingCount(t); n != 1 { + t.Fatalf("bookings after second refused override = %d; want 1", n) + } + + // Control: the same request on a free time outside availability goes through, so the + // refusals above are about the collision and nothing else. + f.mustCreate(t, f.ownerCtx, f.at(23, 0), "fourth@example.com", true) + if n := f.bookingCount(t); n != 2 { + t.Fatalf("bookings after override on a free time = %d; want 2", n) + } +} + +// Test 3 of #270: a caller who is not owner or admin is refused explicitly, and nothing +// is booked. The flag is never silently dropped, not even for a time the member could +// have booked without it. +func TestMCP_skipAvailability_memberRefused(t *testing.T) { + f := newSkipAvailabilityFixture(t) + + for name, start := range map[string]time.Time{ + "outside availability": f.at(22, 0), + "inside availability": f.at(10, 0), + } { + _, err := f.create(f.memberCtx, start, "member-guest@example.com", true) + if !errors.Is(err, errAvailabilityOverrideForbidden) { + t.Errorf("%s: member with skip_availability: err = %v; want errAvailabilityOverrideForbidden", name, err) + } + } + if n := f.bookingCount(t); n != 0 { + t.Fatalf("bookings after refused member requests = %d; want 0", n) + } + + // Control: without the flag the member's ordinary booking still works. + f.mustCreate(t, f.memberCtx, f.at(10, 0), "member-guest@example.com", false) +} + +// The stdio transport binds no caller, so there is nobody to record. The flag is refused +// there instead of being attributed to no one; a bound caller without a user id is the +// same case. +func TestMCP_skipAvailability_needsAnIdentity(t *testing.T) { + f := newSkipAvailabilityFixture(t) + + for name, ctx := range map[string]context.Context{ + "no caller bound (stdio)": context.Background(), + "caller without user id": withMCPCaller(context.Background(), mcpCaller{UserID: "", IsAdmin: true}), + } { + _, err := f.create(ctx, f.at(22, 0), "guest@example.com", true) + if !errors.Is(err, errAvailabilityOverrideNoIdentity) { + t.Errorf("%s: err = %v; want errAvailabilityOverrideNoIdentity", name, err) + } + } + if n := f.bookingCount(t); n != 0 { + t.Fatalf("bookings after refused requests = %d; want 0", n) + } + + // Control: stdio without the flag keeps working as before. + f.mustCreate(t, context.Background(), f.at(10, 0), "guest@example.com", false) +} + +// Test 4 of #270: an authorised override that succeeds records the acting user. +func TestMCP_skipAvailability_recordsActingUser(t *testing.T) { + f := newSkipAvailabilityFixture(t) + + // Without the flag the same time is refused as before, also for the owner. + if _, err := f.create(f.ownerCtx, f.at(22, 0), "late@example.com", false); err == nil { + t.Fatal("create_booking outside availability without skip_availability succeeded; want the existing refusal") + } + if n := f.bookingCount(t); n != 0 { + t.Fatalf("bookings after refused request = %d; want 0", n) + } + + id := f.mustCreate(t, f.ownerCtx, f.at(22, 0), "late@example.com", true) + if got := f.overrideBy(t, id); !got.Valid || got.String != f.ownerID { + t.Errorf("availability_override_by = %+v; want the owner's id %q", got, f.ownerID) + } + + // The acting user is the caller, not the host: a second admin booking the owner's + // event type is the one recorded. + id = f.mustCreate(t, f.adminCtx, f.at(23, 0), "later@example.com", true) + if got := f.overrideBy(t, id); !got.Valid || got.String != f.adminID { + t.Errorf("availability_override_by = %+v; want the acting admin's id %q", got, f.adminID) + } + + // An ordinary booking records nothing. + id = f.mustCreate(t, f.ownerCtx, f.at(10, 0), "morning@example.com", false) + if got := f.overrideBy(t, id); got.Valid { + t.Errorf("availability_override_by on a normal booking = %q; want NULL", got.String) + } +} + +// The override is recorded only when it was needed. An owner who sends the flag for a +// time that is normally bookable gets an ordinary booking: the column means "where this +// booking currently sits", and this one sits in a regular slot. +func TestMCP_skipAvailability_notRecordedForBookableSlot(t *testing.T) { + f := newSkipAvailabilityFixture(t) + id := f.mustCreate(t, f.ownerCtx, f.at(10, 0), "morning@example.com", true) + if got := f.overrideBy(t, id); got.Valid { + t.Errorf("availability_override_by for a normally bookable slot = %q; want NULL", got.String) + } +} + +// makeRoundRobin turns the fixture event type into a round robin between the owner +// (works 09:00-17:00) and the member, who has no availability at all and is therefore +// outside their hours at any time. +func (f *skipAvailabilityFixture) makeRoundRobin(t *testing.T) { + t.Helper() + if _, err := f.db.Exec(`UPDATE event_types SET routing_mode = 'round_robin' WHERE id = ?`, f.etID); err != nil { + t.Fatalf("set round_robin: %v", err) + } + if _, err := f.db.Exec(`DELETE FROM event_type_hosts WHERE event_type_id = ?`, f.etID); err != nil { + t.Fatalf("clear hosts: %v", err) + } + for i, id := range []string{f.ownerID, f.memberID} { + if _, err := f.db.Exec(`INSERT INTO event_type_hosts (id, event_type_id, user_id, role, priority) VALUES (?, ?, ?, 'rotation', ?)`, + uid.New(), f.etID, id, i); err != nil { + t.Fatalf("insert rotation host: %v", err) + } + } +} + +func (f *skipAvailabilityFixture) hostOf(t *testing.T, bookingID string) string { + t.Helper() + var hostID string + if err := f.db.QueryRow(`SELECT host_id FROM bookings WHERE id = ?`, bookingID).Scan(&hostID); err != nil { + t.Fatalf("read host: %v", err) + } + return hostID +} + +// Round robin, where "the slot exists" and "who takes it" are two questions. The slot +// exists as soon as one rotation host is within hours, so the rules can pass while that +// host is already taken. The host outside their hours is then the only one left, and +// booking them is what the override is for: it goes through, lands on that host, and is +// recorded. Without the flag it is refused as before, and when the in-hours host is +// free the flag changes nothing. +func TestMCP_skipAvailability_roundRobinFallsBackToHostOutsideHours(t *testing.T) { + f := newSkipAvailabilityFixture(t) + f.makeRoundRobin(t) + + // The owner is within hours and free: an ordinary booking on the owner, with the flag + // or without it, and nothing recorded. + first := f.mustCreate(t, f.ownerCtx, f.at(10, 0), "first@example.com", true) + if got := f.hostOf(t, first); got != f.ownerID { + t.Fatalf("host of the first booking = %q; want the in-hours host %q", got, f.ownerID) + } + if got := f.overrideBy(t, first); got.Valid { + t.Errorf("availability_override_by on a regular round-robin booking = %q; want NULL", got.String) + } + + // Now the owner is taken at 10:00 and the member is outside their hours. Without the + // flag nobody is left. + if _, err := f.create(f.ownerCtx, f.at(10, 0), "second@example.com", false); err == nil { + t.Fatal("create_booking without skip_availability succeeded with the only in-hours host taken") + } + if n := f.bookingCount(t); n != 1 { + t.Fatalf("bookings after the refused request = %d; want 1", n) + } + + // With the flag the member is booked, outside their hours, and that is recorded. + second := f.mustCreate(t, f.adminCtx, f.at(10, 0), "second@example.com", true) + if got := f.hostOf(t, second); got != f.memberID { + t.Errorf("host of the override booking = %q; want the host outside their hours %q", got, f.memberID) + } + if got := f.overrideBy(t, second); !got.Valid || got.String != f.adminID { + t.Errorf("availability_override_by = %+v; want the acting admin's id %q", got, f.adminID) + } + + // Both hosts are taken now: the override does not get past the overlap check. + _, err := f.h.createBookingForSlug(context.Background(), skipAvailabilitySlug, f.at(10, 0), + booking.Attendee{Name: "Pat Booker", Email: "third@example.com", IANATimezone: "UTC"}, nil, f.ownerID) + if !errors.Is(err, booking.ErrDoubleBooked) { + t.Errorf("override with every rotation host taken: err = %v; want booking.ErrDoubleBooked", err) + } + if n := f.bookingCount(t); n != 2 { + t.Fatalf("bookings = %d; want 2", n) + } + + // A time outside everyone's hours still works under the override and is recorded. + late := f.mustCreate(t, f.ownerCtx, f.at(22, 0), "late@example.com", true) + if got := f.overrideBy(t, late); !got.Valid || got.String != f.ownerID { + t.Errorf("availability_override_by at 22:00 = %+v; want %q", got, f.ownerID) + } +} + +// busyCalendar is a fake calendar provider that reports the given users as busy. +type busyCalendar struct { + calendar.Provider + busy map[string][]slots.Interval +} + +func (p *busyCalendar) Name() string { return "google" } +func (p *busyCalendar) FreeBusy(_ context.Context, id string, from, to time.Time) ([]slots.Interval, error) { + var out []slots.Interval + for _, iv := range p.busy[id] { + if iv.Start.Before(to) && iv.End.After(from) { + out = append(out, iv) + } + } + return out, nil +} + +// The same round-robin fallback when what takes the in-hours host is their external +// calendar rather than another booking. The calendar busy check is never waived: with +// the flag the booking goes to the host outside their hours, whose calendar is free; a +// host whose calendar is busy is not booked, in hours or out. +func TestMCP_skipAvailability_roundRobinFallbackOnCalendarBusy(t *testing.T) { + f := newSkipAvailabilityFixture(t) + f.makeRoundRobin(t) + slot := slots.Interval{Start: f.at(10, 0), End: f.at(10, 30)} + provider := &busyCalendar{busy: map[string][]slots.Interval{f.ownerID: {slot}}} + svc := calendar.NewService(f.db) + svc.Register(provider) + f.h.SetCalendar(svc) + + if _, err := f.create(f.ownerCtx, f.at(10, 0), "first@example.com", false); err == nil { + t.Fatal("create_booking without skip_availability succeeded with the in-hours host's calendar busy") + } + if n := f.bookingCount(t); n != 0 { + t.Fatalf("bookings after the refused request = %d; want 0", n) + } + + id := f.mustCreate(t, f.ownerCtx, f.at(10, 0), "first@example.com", true) + if got := f.hostOf(t, id); got != f.memberID { + t.Errorf("host = %q; want the host outside their hours %q", got, f.memberID) + } + if got := f.overrideBy(t, id); !got.Valid || got.String != f.ownerID { + t.Errorf("availability_override_by = %+v; want %q", got, f.ownerID) + } + + // At 11:00 the owner's calendar is free but the member's is busy: the regular booking + // goes to the owner, unrecorded. At 12:00 both calendars are busy: the override does + // not get past the calendar check for the host outside their hours either. + provider.busy = map[string][]slots.Interval{ + f.memberID: {{Start: f.at(11, 0), End: f.at(12, 30)}}, + f.ownerID: {{Start: f.at(12, 0), End: f.at(12, 30)}}, + } + id = f.mustCreate(t, f.ownerCtx, f.at(11, 0), "second@example.com", true) + if got := f.hostOf(t, id); got != f.ownerID { + t.Errorf("host at 11:00 = %q; want the in-hours host %q", got, f.ownerID) + } + if got := f.overrideBy(t, id); got.Valid { + t.Errorf("availability_override_by at 11:00 = %q; want NULL", got.String) + } + if _, err := f.create(f.ownerCtx, f.at(12, 0), "third@example.com", true); err == nil { + t.Error("create_booking with skip_availability succeeded although every host's calendar is busy") + } + if n := f.bookingCount(t); n != 2 { + t.Fatalf("bookings = %d; want 2", n) + } +} + +// The override waives the availability refusal (errSlotUnavailable) and nothing else. +// Every other reason a booking cannot be made is reported as it is, with the flag as +// without it, and nothing is written. +func TestMCP_skipAvailability_waivesOnlyTheAvailabilityRefusal(t *testing.T) { + f := newSkipAvailabilityFixture(t) + outside := f.at(22, 0) + + // An infrastructure error from the rules themselves is not a refusal to waive. + cancelled, cancel := context.WithCancel(context.Background()) + cancel() + et := &bookableEventType{ID: f.etID} + overridden, err := f.h.validateBookingTime(cancelled, et, "fixed", []string{f.ownerID}, nil, outside, outside.Add(30*time.Minute), true) + if err == nil || errors.Is(err, errSlotUnavailable) || overridden { + t.Errorf("validateBookingTime on a failing lookup: overridden=%v err=%v; want the error back and nothing waived", overridden, err) + } + + // Unknown event type. + _, _, err = f.h.mcpCreateBooking(f.ownerCtx, nil, createBookingIn{ + EventTypeID: "no-such-event", SlotStart: outside.Format(time.RFC3339), + AttendeeName: "Pat Booker", AttendeeEmail: "pat@example.com", SkipAvailability: true, + }) + if err == nil || !strings.Contains(err.Error(), "event type not found") { + t.Errorf("unknown event type: err = %v; want \"event type not found\"", err) + } + + // Invalid attendee address and unparsable time. + if _, err := f.create(f.ownerCtx, outside, "not-an-address", true); err == nil { + t.Error("invalid attendee email was accepted under skip_availability") + } + _, _, err = f.h.mcpCreateBooking(f.ownerCtx, nil, createBookingIn{ + EventTypeID: skipAvailabilitySlug, SlotStart: "tomorrow at ten", + AttendeeName: "Pat Booker", AttendeeEmail: "pat@example.com", SkipAvailability: true, + }) + if err == nil { + t.Error("unparsable slot_start was accepted under skip_availability") + } + + // A paid event type cannot be booked through MCP at all. + if _, err := f.db.Exec(`UPDATE event_types SET price_cents = 5000 WHERE id = ?`, f.etID); err != nil { + t.Fatalf("set price: %v", err) + } + if _, err := f.create(f.ownerCtx, outside, "pat@example.com", true); !errors.Is(err, errPaymentRequired) { + t.Errorf("paid event type: err = %v; want errPaymentRequired", err) + } + if _, err := f.db.Exec(`UPDATE event_types SET price_cents = 0 WHERE id = ?`, f.etID); err != nil { + t.Fatalf("reset price: %v", err) + } + + // An event type that is not bookable (deactivated). + if _, err := f.db.Exec(`UPDATE event_types SET is_active = 0 WHERE id = ?`, f.etID); err != nil { + t.Fatalf("deactivate: %v", err) + } + if _, err := f.create(f.ownerCtx, outside, "pat@example.com", true); err == nil { + t.Error("deactivated event type was booked under skip_availability") + } + + if n := f.bookingCount(t); n != 0 { + t.Fatalf("bookings after refused requests = %d; want 0", n) + } +} + +// setBookingWindow changes the fixture event type's minimum notice and booking window. +func (f *skipAvailabilityFixture) setBookingWindow(t *testing.T, minNoticeMinutes, maxFutureDays int) { + t.Helper() + if _, err := f.db.Exec(`UPDATE event_types SET min_notice_minutes = ?, max_future_days = ? WHERE id = ?`, + minNoticeMinutes, maxFutureDays, f.etID); err != nil { + t.Fatalf("set booking window: %v", err) + } +} + +// The other two rules the override waives, each on its own and inside the hosts' hours, +// so the availability windows cannot be what decides: minimum notice, and the booking +// window (max_future_days). The test clock is pinned to 2026-06-01T00:00Z. +func TestMCP_skipAvailability_waivesMinNoticeAndBookingWindow(t *testing.T) { + cases := []struct { + name string + minNoticeMinutes int + maxFutureDays int + start time.Time + }{ + { + name: "inside the minimum notice", + minNoticeMinutes: 48 * 60, + start: time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC), // 10h ahead, 48h required + }, + { + name: "beyond the booking window", + maxFutureDays: 30, + start: time.Date(2026, 9, 1, 10, 0, 0, 0, time.UTC), // 92 days ahead, 30 allowed + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newSkipAvailabilityFixture(t) + f.setBookingWindow(t, tc.minNoticeMinutes, tc.maxFutureDays) + + if _, err := f.create(f.ownerCtx, tc.start, "guest@example.com", false); err == nil { + t.Fatal("create_booking without skip_availability succeeded; the fixture does not exercise the rule") + } + if n := f.bookingCount(t); n != 0 { + t.Fatalf("bookings after refused request = %d; want 0", n) + } + if _, err := f.create(f.memberCtx, tc.start, "guest@example.com", true); !errors.Is(err, errAvailabilityOverrideForbidden) { + t.Errorf("member with skip_availability: err = %v; want errAvailabilityOverrideForbidden", err) + } + + id := f.mustCreate(t, f.ownerCtx, tc.start, "guest@example.com", true) + if got := f.overrideBy(t, id); !got.Valid || got.String != f.ownerID { + t.Errorf("availability_override_by = %+v; want the owner's id %q", got, f.ownerID) + } + }) + } +} + +// mcpOverHTTP serves the MCP endpoint the way the server mounts /mcp: bearer +// authentication, then MCPCallerMiddleware, then the streamable handler. It returns a +// function that opens a client session authenticated with the given API key. +func (f *skipAvailabilityFixture) mcpOverHTTP(t *testing.T) func(apiKey string) *mcp.ClientSession { + t.Helper() + srv := f.h.MCPServer() + streamable := mcp.NewStreamableHTTPHandler( + func(*http.Request) *mcp.Server { return srv }, + &mcp.StreamableHTTPOptions{Stateless: true}, + ) + ts := httptest.NewServer(auth.RequireBearerToken(f.h.VerifyMCPBearer, nil)(f.h.MCPCallerMiddleware(streamable))) + t.Cleanup(ts.Close) + + return func(apiKey string) *mcp.ClientSession { + t.Helper() + client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0"}, nil) + cs, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{ + Endpoint: ts.URL, + HTTPClient: &http.Client{Transport: bearerRoundTripper{token: apiKey}}, + DisableStandaloneSSE: true, + }, nil) + if err != nil { + t.Fatalf("MCP connect over HTTP: %v", err) + } + t.Cleanup(func() { _ = cs.Close() }) + return cs + } +} + +type bearerRoundTripper struct{ token string } + +func (b bearerRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { + r = r.Clone(r.Context()) + r.Header.Set("Authorization", "Bearer "+b.token) + return http.DefaultTransport.RoundTrip(r) +} + +// issueAPIKey stores an API key for userID and returns the raw key. +func (f *skipAvailabilityFixture) issueAPIKey(t *testing.T, userID string) string { + t.Helper() + raw := "cno_test_" + uid.New() + if _, err := f.db.Exec(`INSERT INTO api_keys (id, user_id, name, key_hash, created_at) VALUES (?, ?, 'test', ?, ?)`, + uid.New(), userID, hashAPIKey(raw), time.Now().UTC().Format(time.RFC3339Nano)); err != nil { + t.Fatalf("insert api key: %v", err) + } + return raw +} + +func toolResultText(res *mcp.CallToolResult) string { + var sb strings.Builder + for _, c := range res.Content { + if tc, ok := c.(*mcp.TextContent); ok { + sb.WriteString(tc.Text) + } + } + return sb.String() +} + +// Test 3 of #270 end to end: the privilege comes from the authenticated caller, resolved +// server-side by MCPCallerMiddleware from the bearer token, and from nothing in the +// request. A member's token with skip_availability is refused explicitly and books +// nothing, also when the arguments try to claim a role; the owner's token with the very +// same arguments books and is recorded. +func TestMCP_skipAvailability_overHTTP_identityComesFromTheToken(t *testing.T) { + f := newSkipAvailabilityFixture(t) + connect := f.mcpOverHTTP(t) + args := map[string]any{ + "event_type_id": skipAvailabilitySlug, + "slot_start": f.at(22, 0).Format(time.RFC3339), + "attendee_name": "Pat Booker", + "attendee_email": "pat@example.com", + "skip_availability": true, + } + + member := connect(f.issueAPIKey(t, f.memberID)) + res, err := member.CallTool(context.Background(), &mcp.CallToolParams{Name: "create_booking", Arguments: args}) + if err != nil { + t.Fatalf("member create_booking call: %v", err) + } + if !res.IsError { + t.Fatalf("member create_booking with skip_availability was not refused: %+v", res.Content) + } + if got := toolResultText(res); !strings.Contains(got, errAvailabilityOverrideForbidden.Error()) { + t.Errorf("member refusal = %q; want it to carry %q", got, errAvailabilityOverrideForbidden.Error()) + } + if n := f.bookingCount(t); n != 0 { + t.Fatalf("bookings after the member's refused request = %d; want 0", n) + } + + // Fields that assert a privilege are not part of the tool's input. Whatever the SDK + // does with them (it rejects unknown arguments), no booking may come of it. + claiming := map[string]any{"is_admin": true, "role": "owner", "user_id": f.ownerID, "availability_override_by": f.ownerID} + for k, v := range args { + claiming[k] = v + } + res, err = member.CallTool(context.Background(), &mcp.CallToolParams{Name: "create_booking", Arguments: claiming}) + if err == nil && !res.IsError { + t.Errorf("member create_booking claiming a role in its arguments was not refused: %+v", res.Content) + } + if n := f.bookingCount(t); n != 0 { + t.Fatalf("bookings after the member's role-claiming request = %d; want 0", n) + } + + owner := connect(f.issueAPIKey(t, f.ownerID)) + res, err = owner.CallTool(context.Background(), &mcp.CallToolParams{Name: "create_booking", Arguments: args}) + if err != nil || res.IsError { + t.Fatalf("owner create_booking with skip_availability: err=%v result=%+v", err, res) + } + var id string + var by sql.NullString + if err := f.db.QueryRow(`SELECT id, availability_override_by FROM bookings`).Scan(&id, &by); err != nil { + t.Fatalf("read the owner's booking: %v", err) + } + if !by.Valid || by.String != f.ownerID { + t.Errorf("availability_override_by = %+v; want the owner's id %q, taken from the token", by, f.ownerID) + } +} + +// reschedule calls the reschedule_booking tool. +func (f *skipAvailabilityFixture) reschedule(ctx context.Context, bookingID string, newStart time.Time, skip bool) error { + _, _, err := f.h.mcpRescheduleBooking(ctx, nil, rescheduleBookingIn{ + BookingID: bookingID, + NewSlotStart: newStart.Format(time.RFC3339), + SkipAvailability: skip, + }) + return err +} + +func (f *skipAvailabilityFixture) startAt(t *testing.T, bookingID string) time.Time { + t.Helper() + b, err := f.h.bookingSvc.Get(context.Background(), bookingID) + if err != nil { + t.Fatalf("get booking: %v", err) + } + return b.StartAt +} + +// rescheduleConflictText is what reschedule_booking says when the target collides with +// another booking. Tests 2 and 5 hold it apart from the availability refusal. +const rescheduleConflictText = "that time slot is no longer available" + +// Test 2 of #270: the override never bypasses the double-booking check on reschedule +// either. Its own test, because reschedule is a separate path from create. +func TestMCP_skipAvailability_rescheduleStillRefusesConflict(t *testing.T) { + f := newSkipAvailabilityFixture(t) + f.mustCreate(t, f.ownerCtx, f.at(22, 0), "evening@example.com", true) + normal := f.mustCreate(t, f.ownerCtx, f.at(10, 0), "morning@example.com", false) + + for name, target := range map[string]time.Time{ + "exact start": f.at(22, 0), + "overlap": f.at(22, 15), + } { + err := f.reschedule(f.ownerCtx, normal, target, true) + if err == nil { + t.Fatalf("%s: reschedule_booking with skip_availability onto a taken time succeeded; want a refusal", name) + } + if err.Error() != rescheduleConflictText { + t.Errorf("%s: err = %q; want the conflict refusal %q", name, err, rescheduleConflictText) + } + if errors.Is(err, errRescheduleOutsideAvailability) { + t.Errorf("%s: a collision was reported as an availability refusal", name) + } + } + if got := f.startAt(t, normal); !got.Equal(f.at(10, 0)) { + t.Errorf("start_at after refused reschedule = %s; want it unchanged at 10:00", got) + } + if got := f.overrideBy(t, normal); got.Valid { + t.Errorf("availability_override_by after refused reschedule = %q; want NULL", got.String) + } + + // Control: the same request onto a free time outside availability goes through. + if err := f.reschedule(f.ownerCtx, normal, f.at(23, 0), true); err != nil { + t.Fatalf("reschedule_booking with skip_availability onto a free time: %v", err) + } +} + +// Test 3 of #270, reschedule half: a member sending the flag is refused explicitly and +// the booking does not move - for their own booking, for someone else's, and for one +// that does not exist, all with the same error. +func TestMCP_skipAvailability_memberRefusedOnReschedule(t *testing.T) { + f := newSkipAvailabilityFixture(t) + start := f.at(10, 0) + own, err := f.h.bookingSvc.Create(context.Background(), booking.CreateParams{ + EventTypeID: f.etID, + HostIDs: []string{f.memberID}, + RoutingMode: "fixed", + StartAt: start, + EndAt: start.Add(30 * time.Minute), + Organizer: booking.Attendee{Name: "Booker", Email: "booker@example.com", IANATimezone: "UTC"}, + }) + if err != nil { + t.Fatalf("create member-hosted booking: %v", err) + } + others := f.mustCreate(t, f.ownerCtx, f.at(11, 0), "other@example.com", false) + + for name, id := range map[string]string{ + "own booking": own.ID, + "owner's booking": others, + "unknown booking": "does-not-exist", + } { + for _, target := range []time.Time{f.at(22, 0), f.at(14, 0)} { + err := f.reschedule(f.memberCtx, id, target, true) + if !errors.Is(err, errAvailabilityOverrideForbidden) { + t.Errorf("%s → %s: err = %v; want errAvailabilityOverrideForbidden", name, target.Format("15:04"), err) + } + } + } + if got := f.startAt(t, own.ID); !got.Equal(start) { + t.Errorf("member's booking moved to %s; want it unchanged", got) + } + if got := f.overrideBy(t, own.ID); got.Valid { + t.Errorf("availability_override_by = %q; want NULL", got.String) + } + + // The stdio transport is refused here as on create: nobody to record. + if err := f.reschedule(context.Background(), others, f.at(22, 0), true); !errors.Is(err, errAvailabilityOverrideNoIdentity) { + t.Errorf("stdio with skip_availability: err = %v; want errAvailabilityOverrideNoIdentity", err) + } + if got := f.startAt(t, others); !got.Equal(f.at(11, 0)) { + t.Errorf("owner's booking moved to %s; want it unchanged", got) + } +} + +// Test 4 of #270, reschedule half: an override on reschedule records whoever made this +// move, replacing an earlier actor, in the same statement as the new time. +func TestMCP_skipAvailability_rescheduleRecordsActingUser(t *testing.T) { + f := newSkipAvailabilityFixture(t) + + // A normal booking moved outside availability by the owner. + id := f.mustCreate(t, f.ownerCtx, f.at(10, 0), "guest@example.com", false) + if err := f.reschedule(f.ownerCtx, id, f.at(22, 0), true); err != nil { + t.Fatalf("reschedule_booking with skip_availability: %v", err) + } + if got := f.startAt(t, id); !got.Equal(f.at(22, 0)) { + t.Fatalf("start_at = %s; want 22:00", got) + } + if got := f.overrideBy(t, id); !got.Valid || got.String != f.ownerID { + t.Errorf("availability_override_by = %+v; want the owner's id %q", got, f.ownerID) + } + + // A second admin moves it again under the override: the column now names them. + if err := f.reschedule(f.adminCtx, id, f.at(23, 0), true); err != nil { + t.Fatalf("second reschedule_booking with skip_availability: %v", err) + } + if got := f.overrideBy(t, id); !got.Valid || got.String != f.adminID { + t.Errorf("availability_override_by = %+v; want the second admin's id %q", got, f.adminID) + } +} + +// Test 5 of #270: moving a booking to a target outside availability without the flag is +// refused with a message that names the reason and the way out, not the generic slot +// error. The gate hangs on the target time, not on the booking's history, so it reads +// the same for a normal booking and for one placed by an override. +func TestMCP_reschedule_unavailableTargetNeedsFlag(t *testing.T) { + f := newSkipAvailabilityFixture(t) + normal := f.mustCreate(t, f.ownerCtx, f.at(10, 0), "morning@example.com", false) + overridden := f.mustCreate(t, f.ownerCtx, f.at(20, 0), "evening@example.com", true) + + for name, id := range map[string]string{"normal booking": normal, "override booking": overridden} { + err := f.reschedule(f.ownerCtx, id, f.at(22, 0), false) + if !errors.Is(err, errRescheduleOutsideAvailability) { + t.Fatalf("%s: err = %v; want errRescheduleOutsideAvailability", name, err) + } + if !strings.Contains(err.Error(), "skip_availability") { + t.Errorf("%s: refusal %q does not name skip_availability", name, err) + } + if err.Error() == rescheduleConflictText || err.Error() == errSlotUnavailable.Error() { + t.Errorf("%s: refusal %q is the generic slot error", name, err) + } + } + if got := f.startAt(t, normal); !got.Equal(f.at(10, 0)) { + t.Errorf("normal booking moved to %s; want it unchanged", got) + } + if got := f.overrideBy(t, normal); got.Valid { + t.Errorf("normal booking: availability_override_by = %q; want NULL", got.String) + } + // A refused move leaves an existing record alone. + if got := f.startAt(t, overridden); !got.Equal(f.at(20, 0)) { + t.Errorf("override booking moved to %s; want it unchanged", got) + } + if got := f.overrideBy(t, overridden); !got.Valid || got.String != f.ownerID { + t.Errorf("override booking: availability_override_by = %+v; want it still %q", got, f.ownerID) + } +} + +// Test 6 of #270: a normal reschedule into a valid slot succeeds and clears the column, +// which means "where this booking currently sits". +func TestMCP_reschedule_normalMoveClearsOverride(t *testing.T) { + f := newSkipAvailabilityFixture(t) + id := f.mustCreate(t, f.ownerCtx, f.at(22, 0), "evening@example.com", true) + if got := f.overrideBy(t, id); !got.Valid || got.String != f.ownerID { + t.Fatalf("availability_override_by before the move = %+v; want %q", got, f.ownerID) + } + + if err := f.reschedule(f.ownerCtx, id, f.at(11, 0), false); err != nil { + t.Fatalf("normal reschedule_booking into a valid slot: %v", err) + } + if got := f.startAt(t, id); !got.Equal(f.at(11, 0)) { + t.Errorf("start_at = %s; want 11:00", got) + } + if got := f.overrideBy(t, id); got.Valid { + t.Errorf("availability_override_by after a normal move = %q; want NULL", got.String) + } +} + +// The override is recorded only when it was needed, on reschedule as on create: with +// the flag, a move into a normally bookable slot is an ordinary move. It records nothing +// for a normal booking and clears the column of one an override had placed. +func TestMCP_skipAvailability_rescheduleNotRecordedForBookableTarget(t *testing.T) { + f := newSkipAvailabilityFixture(t) + + normal := f.mustCreate(t, f.ownerCtx, f.at(10, 0), "morning@example.com", false) + if err := f.reschedule(f.ownerCtx, normal, f.at(14, 0), true); err != nil { + t.Fatalf("reschedule_booking with skip_availability into a bookable slot: %v", err) + } + if got := f.startAt(t, normal); !got.Equal(f.at(14, 0)) { + t.Errorf("start_at = %s; want 14:00", got) + } + if got := f.overrideBy(t, normal); got.Valid { + t.Errorf("availability_override_by after a move into a bookable slot = %q; want NULL", got.String) + } + + overridden := f.mustCreate(t, f.ownerCtx, f.at(22, 0), "evening@example.com", true) + if got := f.overrideBy(t, overridden); !got.Valid { + t.Fatal("availability_override_by before the move is NULL; the fixture booking is not an override") + } + if err := f.reschedule(f.adminCtx, overridden, f.at(11, 0), true); err != nil { + t.Fatalf("reschedule_booking with skip_availability into a bookable slot: %v", err) + } + if got := f.overrideBy(t, overridden); got.Valid { + t.Errorf("availability_override_by after a move into a bookable slot = %q; want NULL (cleared)", got.String) + } +} + +// Minimum notice and the booking window on reschedule, each on its own and inside the +// hosts' hours: refused with the specific message without the flag, waived and recorded +// with it. The test clock is pinned to 2026-06-01T00:00Z. +func TestMCP_skipAvailability_rescheduleWaivesMinNoticeAndBookingWindow(t *testing.T) { + cases := []struct { + name string + minNoticeMinutes int + maxFutureDays int + target time.Time + }{ + { + name: "inside the minimum notice", + minNoticeMinutes: 48 * 60, + target: time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC), + }, + { + name: "beyond the booking window", + maxFutureDays: 30, + target: time.Date(2026, 9, 1, 10, 0, 0, 0, time.UTC), + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newSkipAvailabilityFixture(t) + f.setBookingWindow(t, tc.minNoticeMinutes, tc.maxFutureDays) + // 2026-06-10 10:00 satisfies both rules, so the booking itself is ordinary. + origin := time.Date(2026, 6, 10, 10, 0, 0, 0, time.UTC) + id := f.mustCreate(t, f.ownerCtx, origin, "guest@example.com", false) + + if err := f.reschedule(f.ownerCtx, id, tc.target, false); !errors.Is(err, errRescheduleOutsideAvailability) { + t.Fatalf("without skip_availability: err = %v; want errRescheduleOutsideAvailability", err) + } + if got := f.startAt(t, id); !got.Equal(origin) { + t.Fatalf("booking moved to %s by a refused request", got) + } + + if err := f.reschedule(f.ownerCtx, id, tc.target, true); err != nil { + t.Fatalf("with skip_availability: %v", err) + } + if got := f.startAt(t, id); !got.Equal(tc.target) { + t.Errorf("start_at = %s; want %s", got, tc.target) + } + if got := f.overrideBy(t, id); !got.Valid || got.String != f.ownerID { + t.Errorf("availability_override_by = %+v; want the owner's id %q", got, f.ownerID) + } + }) + } +} + +// The guest's manage link is one of the "normal reschedules" that clear the column: the +// booker of an override booking moves it into a regular slot through the public +// endpoint, which accepts no flag. The same link cannot move it to another time outside +// availability. +func TestRescheduleByToken_clearsAvailabilityOverride(t *testing.T) { + f := newSkipAvailabilityFixture(t) + id := f.mustCreate(t, f.ownerCtx, f.at(22, 0), "evening@example.com", true) + if got := f.overrideBy(t, id); !got.Valid || got.String != f.ownerID { + t.Fatalf("availability_override_by before the move = %+v; want %q", got, f.ownerID) + } + tok, err := f.h.bookingSvc.IssueManageToken(context.Background(), id) + if err != nil { + t.Fatalf("issue manage token: %v", err) + } + viaLink := func(startAt time.Time, extra string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/manage/"+tok+"/reschedule", + strings.NewReader(`{"start_at":"`+startAt.Format(time.RFC3339)+`"`+extra+`}`)) + req.Header.Set("Content-Type", "application/json") + req.SetPathValue("token", tok) + rec := httptest.NewRecorder() + f.h.RescheduleByToken(rec, req) + return rec + } + + // Outside availability stays out of reach for the link holder, flag in the body or not. + if rec := viaLink(f.at(23, 0), `,"skip_availability":true`); rec.Code != http.StatusConflict { + t.Fatalf("manage-link move outside availability: status = %d; want 409 — %s", rec.Code, rec.Body.String()) + } + if got := f.startAt(t, id); !got.Equal(f.at(22, 0)) { + t.Fatalf("booking moved to %s by a refused manage-link request", got) + } + if got := f.overrideBy(t, id); !got.Valid || got.String != f.ownerID { + t.Errorf("availability_override_by after a refused move = %+v; want it still %q", got, f.ownerID) + } + + if rec := viaLink(f.at(11, 0), ""); rec.Code != http.StatusOK { + t.Fatalf("manage-link move into a valid slot: status = %d; want 200 — %s", rec.Code, rec.Body.String()) + } + if got := f.startAt(t, id); !got.Equal(f.at(11, 0)) { + t.Errorf("start_at = %s; want 11:00", got) + } + if got := f.overrideBy(t, id); got.Valid { + t.Errorf("availability_override_by after a manage-link move = %q; want NULL", got.String) + } +} + +// Test 3 of #270 end to end, reschedule half: a member's token with skip_availability is +// refused by reschedule_booking through the real /mcp stack, and the booking stays put. +func TestMCP_skipAvailability_overHTTP_memberRefusedOnReschedule(t *testing.T) { + f := newSkipAvailabilityFixture(t) + id := f.mustCreate(t, f.ownerCtx, f.at(10, 0), "morning@example.com", false) + + member := f.mcpOverHTTP(t)(f.issueAPIKey(t, f.memberID)) + res, err := member.CallTool(context.Background(), &mcp.CallToolParams{Name: "reschedule_booking", Arguments: map[string]any{ + "booking_id": id, + "new_slot_start": f.at(22, 0).Format(time.RFC3339), + "skip_availability": true, + }}) + if err != nil { + t.Fatalf("member reschedule_booking call: %v", err) + } + if !res.IsError { + t.Fatalf("member reschedule_booking with skip_availability was not refused: %+v", res.Content) + } + if got := toolResultText(res); !strings.Contains(got, errAvailabilityOverrideForbidden.Error()) { + t.Errorf("member refusal = %q; want it to carry %q", got, errAvailabilityOverrideForbidden.Error()) + } + if got := f.startAt(t, id); !got.Equal(f.at(10, 0)) { + t.Errorf("booking moved to %s by the member's refused request", got) + } +} + +// On reschedule, too, the override waives only the availability refusal: a cancelled or +// unknown booking and an unparsable time are reported as they are. +func TestMCP_skipAvailability_rescheduleWaivesOnlyTheAvailabilityRefusal(t *testing.T) { + f := newSkipAvailabilityFixture(t) + id := f.mustCreate(t, f.ownerCtx, f.at(10, 0), "guest@example.com", false) + + if err := f.reschedule(f.ownerCtx, "does-not-exist", f.at(22, 0), true); err == nil || !strings.Contains(err.Error(), "booking not found") { + t.Errorf("unknown booking: err = %v; want \"booking not found\"", err) + } + _, _, err := f.h.mcpRescheduleBooking(f.ownerCtx, nil, rescheduleBookingIn{BookingID: id, NewSlotStart: "tomorrow at ten", SkipAvailability: true}) + if err == nil { + t.Error("unparsable new_slot_start was accepted under skip_availability") + } + + if err := f.h.bookingSvc.CancelByID(context.Background(), id, "test"); err != nil { + t.Fatalf("cancel: %v", err) + } + if err := f.reschedule(f.ownerCtx, id, f.at(22, 0), true); err == nil || !strings.Contains(err.Error(), "cancelled") { + t.Errorf("cancelled booking: err = %v; want the cancelled refusal", err) + } + if got := f.startAt(t, id); !got.Equal(f.at(10, 0)) { + t.Errorf("cancelled booking moved to %s", got) + } + if got := f.overrideBy(t, id); got.Valid { + t.Errorf("availability_override_by = %q; want NULL", got.String) + } +} + +// Round robin under a waived minimum notice (review of #305). The waived rule says +// nothing about hours, so the rotation must still prefer the host who is within theirs. +// The rotation is by priority with the member first, so over the unfiltered pool it +// would pick the member, who is outside their hours. The booking is still recorded as +// an override, because the notice was waived. +func TestMCP_skipAvailability_roundRobinKeepsHostFilterUnderWaivedNotice(t *testing.T) { + f := newSkipAvailabilityFixture(t) + f.makeRoundRobin(t) + f.setBookingWindow(t, 48*60, 0) + if _, err := f.db.Exec(`UPDATE event_types SET rr_strategy = 'priority' WHERE id = ?`, f.etID); err != nil { + t.Fatalf("set priority strategy: %v", err) + } + if _, err := f.db.Exec(`UPDATE event_type_hosts SET priority = -1 WHERE event_type_id = ? AND user_id = ?`, f.etID, f.memberID); err != nil { + t.Fatalf("put the member first: %v", err) + } + + // 10h ahead of the pinned clock with 48h required, inside the owner's hours. + soon := time.Date(2026, 6, 1, 10, 0, 0, 0, time.UTC) + if _, err := f.create(f.adminCtx, soon, "soon@example.com", false); err == nil { + t.Fatal("create_booking inside the minimum notice succeeded without skip_availability") + } + id := f.mustCreate(t, f.adminCtx, soon, "soon@example.com", true) + if got := f.hostOf(t, id); got != f.ownerID { + t.Errorf("host = %q; want the host within their hours %q, not the one outside", got, f.ownerID) + } + if got := f.overrideBy(t, id); !got.Valid || got.String != f.adminID { + t.Errorf("availability_override_by = %+v; want the acting admin's id %q (the notice was waived)", got, f.adminID) + } + + // The in-hours host is now taken at that time: the fallback to the host outside + // their hours still applies, and is recorded. + second := f.mustCreate(t, f.adminCtx, soon, "second@example.com", true) + if got := f.hostOf(t, second); got != f.memberID { + t.Errorf("host of the second booking = %q; want the host outside their hours %q", got, f.memberID) + } + if got := f.overrideBy(t, second); !got.Valid || got.String != f.adminID { + t.Errorf("availability_override_by on the fallback = %+v; want %q", got, f.adminID) + } +} + +// A collective event type under the override keeps every host: the one outside their +// hours is booked along with the others, not filtered out of the booking. +func TestMCP_skipAvailability_collectiveKeepsEveryHost(t *testing.T) { + f := newSkipAvailabilityFixture(t) + f.makeRoundRobin(t) + if _, err := f.db.Exec(`UPDATE event_types SET routing_mode = 'collective' WHERE id = ?`, f.etID); err != nil { + t.Fatalf("set collective: %v", err) + } + if _, err := f.db.Exec(`UPDATE event_type_hosts SET role = 'required' WHERE event_type_id = ?`, f.etID); err != nil { + t.Fatalf("set required hosts: %v", err) + } + // 10:00 is inside the owner's hours and outside the member's (who has none). + if _, err := f.create(f.ownerCtx, f.at(10, 0), "group@example.com", false); err == nil { + t.Fatal("collective booking with a host outside their hours succeeded without skip_availability") + } + id := f.mustCreate(t, f.ownerCtx, f.at(10, 0), "group@example.com", true) + var n int + if err := f.db.QueryRow(`SELECT COUNT(*) FROM booking_hosts WHERE booking_id = ?`, id).Scan(&n); err != nil { + t.Fatalf("count booking hosts: %v", err) + } + if n != 2 { + t.Errorf("hosts on the collective override booking = %d; want both", n) + } + if got := f.overrideBy(t, id); !got.Valid || got.String != f.ownerID { + t.Errorf("availability_override_by = %+v; want %q", got, f.ownerID) + } +} + +// "Not in the past" is a floor the override does not lift (review of #305): waiving the +// minimum notice does not make a start bookable that has already passed. The time is +// inside the host's hours, so the floor alone decides. The test clock is pinned to +// 2026-06-01T00:00Z. +func TestMCP_skipAvailability_createRefusesStartInPast(t *testing.T) { + f := newSkipAvailabilityFixture(t) + past := time.Date(2026, 5, 31, 10, 0, 0, 0, time.UTC) + + if _, err := f.create(f.ownerCtx, past, "past@example.com", true); !errors.Is(err, errStartInPast) { + t.Errorf("create_booking in the past with skip_availability: err = %v; want errStartInPast", err) + } + // Without the flag it is the ordinary refusal, as before. + if _, err := f.create(f.ownerCtx, past, "past@example.com", false); err == nil || errors.Is(err, errStartInPast) { + t.Errorf("create_booking in the past without skip_availability: err = %v; want the ordinary refusal", err) + } + // One second ago is in the past as well; minimum notice 0 does not change that. + if _, err := f.create(f.ownerCtx, time.Date(2026, 5, 31, 23, 59, 59, 0, time.UTC), "past@example.com", true); !errors.Is(err, errStartInPast) { + t.Errorf("create_booking one second in the past: err = %v; want errStartInPast", err) + } + if n := f.bookingCount(t); n != 0 { + t.Fatalf("bookings = %d; want 0", n) + } +} + +// The same floor on reschedule: a target in the past is refused with the flag, the +// booking stays where it was and its override record is untouched. The refusal is not +// the "resend with skip_availability" one, with or without the flag. +func TestMCP_skipAvailability_rescheduleRefusesTargetInPast(t *testing.T) { + f := newSkipAvailabilityFixture(t) + origin := f.at(22, 0) + id := f.mustCreate(t, f.adminCtx, origin, "guest@example.com", true) + past := time.Date(2026, 5, 31, 10, 0, 0, 0, time.UTC) + + for _, skip := range []bool{true, false} { + err := f.reschedule(f.ownerCtx, id, past, skip) + if !errors.Is(err, errStartInPast) { + t.Errorf("reschedule_booking into the past (skip_availability=%v): err = %v; want errStartInPast", skip, err) + } + if got := f.startAt(t, id); !got.Equal(origin) { + t.Fatalf("booking moved to %s by a refused request (skip_availability=%v)", got, skip) + } + if got := f.overrideBy(t, id); !got.Valid || got.String != f.adminID { + t.Errorf("availability_override_by after the refused move = %+v; want it untouched (%q)", got, f.adminID) + } + } +} diff --git a/internal/handler/mcp_test.go b/internal/handler/mcp_test.go index e937d92b..fa82d7c7 100644 --- a/internal/handler/mcp_test.go +++ b/internal/handler/mcp_test.go @@ -257,3 +257,85 @@ func TestMCP_rescheduleBooking_rejectsPastDate(t *testing.T) { t.Errorf("reschedule_booking to a past date should error; got %+v", res.Content) } } + +// TestMCP_skipAvailability_overTheWire sends skip_availability through the real MCP +// transport (#270). The in-memory transport binds no caller, like stdio, so the flag +// must come back as a tool error on both tools with nothing written - which also proves +// the argument is in the published schema rather than dropped on the way in. The rules +// that depend on who the caller is are tested in mcp_skip_availability_test.go. +func TestMCP_skipAvailability_overTheWire(t *testing.T) { + h, database, apiKey, _ := setupWorkspaceWithDB(t) + body := `{"slug":"mcp-skip","name":"MCP Skip","duration_minutes":30,"location_type":"phone","location_value":"+1 555 000 1111","max_future_days":0}` + rec := httptest.NewRecorder() + h.RequireAuth(h.CreateEventType)(rec, authReq(http.MethodPost, "/v1/event-types", body, apiKey)) + if rec.Code != http.StatusCreated { + t.Fatalf("create event type: %d — %s", rec.Code, rec.Body.String()) + } + seedFullAvailability(t, h, apiKey) + + cs := connectMCP(t, h) + ctx := context.Background() + + tools, err := cs.ListTools(ctx, nil) + if err != nil { + t.Fatalf("list tools: %v", err) + } + for _, tool := range tools.Tools { + if tool.Name != "create_booking" && tool.Name != "reschedule_booking" { + continue + } + schema, err := json.Marshal(tool.InputSchema) + if err != nil { + t.Fatalf("marshal %s schema: %v", tool.Name, err) + } + if !strings.Contains(string(schema), `"skip_availability"`) { + t.Errorf("%s input schema does not offer skip_availability", tool.Name) + } + } + + res, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "create_booking", Arguments: map[string]any{ + "event_type_id": "mcp-skip", + "slot_start": "2027-01-15T10:00:00Z", + "attendee_name": "Pat Booker", + "attendee_email": "pat@example.com", + }}) + if err != nil || res.IsError { + t.Fatalf("create_booking: err=%v result=%+v", err, res) + } + created := decodeBooking(t, res) + + res, err = cs.CallTool(ctx, &mcp.CallToolParams{Name: "create_booking", Arguments: map[string]any{ + "event_type_id": "mcp-skip", + "slot_start": "2027-01-16T10:00:00Z", + "attendee_name": "Sam Booker", + "attendee_email": "sam@example.com", + "skip_availability": true, + }}) + if err != nil { + t.Fatalf("create_booking with skip_availability: %v", err) + } + if !res.IsError { + t.Errorf("create_booking with skip_availability and no caller identity should be a tool error; got %+v", res.Content) + } + + res, err = cs.CallTool(ctx, &mcp.CallToolParams{Name: "reschedule_booking", Arguments: map[string]any{ + "booking_id": created.ID, + "new_slot_start": "2027-01-17T10:00:00Z", + "skip_availability": true, + }}) + if err != nil { + t.Fatalf("reschedule_booking with skip_availability: %v", err) + } + if !res.IsError { + t.Errorf("reschedule_booking with skip_availability and no caller identity should be a tool error; got %+v", res.Content) + } + + var n int + var startAt string + if err := database.QueryRow(`SELECT COUNT(*), MIN(start_at) FROM bookings`).Scan(&n, &startAt); err != nil { + t.Fatalf("read bookings: %v", err) + } + if n != 1 || !strings.HasPrefix(startAt, "2027-01-15T10:00:00") { + t.Errorf("bookings = %d starting %s; want the one original booking, unmoved", n, startAt) + } +} diff --git a/internal/handler/reschedule_handler.go b/internal/handler/reschedule_handler.go index c0c147f6..1cd8e921 100644 --- a/internal/handler/reschedule_handler.go +++ b/internal/handler/reschedule_handler.go @@ -84,7 +84,7 @@ func (h *Handler) RescheduleBooking(w http.ResponseWriter, r *http.Request) { newEnd := newStart.Add(time.Duration(durMins) * time.Minute) - if err := h.validateRescheduleTime(r.Context(), id, etID, hostID, newStart, newEnd); err != nil { + if _, err := h.validateRescheduleTime(r.Context(), id, etID, hostID, newStart, newEnd, false); err != nil { if errors.Is(err, errSlotUnavailable) { h.writeError(w, http.StatusConflict, "this slot is no longer available") return @@ -94,7 +94,9 @@ func (h *Handler) RescheduleBooking(w http.ResponseWriter, r *http.Request) { return } - updated, err := h.bookingSvc.Reschedule(r.Context(), id, newStart, newEnd) + // "" = no availability override: REST does not accept one, and a normal move clears + // any that was recorded (see booking.Service.Reschedule). + updated, err := h.bookingSvc.Reschedule(r.Context(), id, newStart, newEnd, "") if errors.Is(err, booking.ErrDoubleBooked) { h.writeError(w, http.StatusConflict, "that time slot is no longer available") return