Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/rules/backend/oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ paths:
# OAuth for the MCP server

- Hi.Events is its own small OAuth 2.1 authorization server for `/mcp`. It is hand-rolled, not Passport: authorization code + PKCE (S256 only), refresh rotation, Dynamic Client Registration and RFC 7009 revocation. Public clients only (`token_endpoint_auth_method: none`). CIMD is not supported yet; Claude falls back to DCR.
- Access tokens are ordinary Sanctum `personal_access_tokens` rows (1h, `hie_` prefix) with `oauth_connection_id` set, so every API-key safeguard applies. Anything that lists, counts, reminds about or deletes API keys one at a time must filter `oauth_connection_id IS NULL` (key list, cap, expiry reminders, single-key delete).
- Access tokens are ordinary Sanctum `personal_access_tokens` rows (1h, `hie_` prefix) with `oauth_connection_id` set, so every API-key safeguard applies. They only work through `/mcp`: `EnforceAccountUserAccess` answers any other API route with 403 `OAUTH_TOKEN_MCP_ONLY` unless the request is a tool's inner dispatch, which `ApiRouteDispatcher` marks with a request attribute (never a header, since the inner request copies the outer headers). Without this the user's consent to the MCP tools would also cover refunds, messaging and webhooks. Anything that lists, counts, reminds about or deletes API keys one at a time must filter `oauth_connection_id IS NULL` (key list, cap, expiry reminders, single-key delete).
- An `oauth_connection` (user + account + client + access) owns its access and refresh tokens (FK cascades). Every API-key revocation also deletes connections: `UserSessionRevocationService`, `ApiKeyService::revokeAllForMember`, both anonymizers and `AccountHardDeletionService`. Otherwise a refresh token re-mints access after a credential reset.
- Refresh tokens rotate on every use and last 90 days, sliding. Reusing a rotated token more than `REFRESH_REUSE_GRACE_SECONDS` later revokes the whole connection. Replaying an authorization code revokes the connection that code created. Revocation runs outside the refresh transaction, so the delete isn't rolled back by the `invalid_grant` that follows.
- Pending authorization requests (10 min, claimed once via `cache->add` so two approvals can't both issue a code) and codes (60 s, single use via `cache->add`) live in the cache (`OAuthAuthorizationStore`). The connection is created on code exchange, not on approval, so an abandoned code leaves nothing behind. Exchange replaces any existing connection for the same user, account and client, and re-checks the connection cap.
Expand Down
2 changes: 1 addition & 1 deletion INSTALL_WITHOUT_DOCKER.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ For development and testing, you can set `APP_LICENCE_KEY` to `development` inst

13. **Optional: Reverse proxies and rate limiting:**

Rate limits are keyed by client IP. The default, `APP_TRUSTED_PROXIES=*`, trusts whichever proxy connects to the app and reads the client IP from its `X-Forwarded-For`. That works with no proxy or a single proxy, but lets clients that reach the app directly spoof their IP. Behind two or more proxies (for example Cloudflare in front of Traefik, Caddy or nginx) the default sees the outer proxy as the client, so many visitors share one rate limit. In both cases, list every proxy between the visitor and the app instead (`cloudflare` expands to Cloudflare's published ranges), including the frontend server if it calls the API from another host:
Rate limits are keyed by client IP. The default, `APP_TRUSTED_PROXIES=*`, trusts every address, so the app takes the client IP from the first entry of `X-Forwarded-For`. Proxies append to that header rather than replace it, so a client can send its own value and get around per-IP rate limits, behind a proxy or not. List every proxy between the visitor and the app instead (`cloudflare` expands to Cloudflare's published ranges), including the frontend server if it calls the API from another host:

```bash
APP_TRUSTED_PROXIES=127.0.0.1,10.0.0.0/8,cloudflare
Expand Down
4 changes: 2 additions & 2 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ APP_FRONTEND_URL=https://localhost:8443
APP_CDN_URL=http://localhost:9000/hievents-public
APP_SAAS_MODE_ENABLED=false
APP_LICENCE_KEY=
# Optional. Proxies allowed to set X-Forwarded-For. The default `*` trusts the nearest proxy only. Behind more than one
# proxy, list every hop (`cloudflare` adds Cloudflare's ranges), e.g. 127.0.0.1,172.16.0.0/12,cloudflare
# Optional. Proxies allowed to set X-Forwarded-For. The default `*` trusts every address, so clients can spoof their IP
# and get around per-IP rate limits. List every proxy hop instead (`cloudflare` adds Cloudflare's ranges), e.g. 127.0.0.1,172.16.0.0/12,cloudflare
APP_TRUSTED_PROXIES=*
# Optional. Only needed when APP_TRUSTED_PROXIES doesn't include the frontend server; set the same value on the frontend
APP_SSR_SHARED_SECRET=
Expand Down
15 changes: 15 additions & 0 deletions backend/app/Exceptions/OAuthTokenMcpOnlyException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace HiEvents\Exceptions;

use Throwable;

class OAuthTokenMcpOnlyException extends CodedAccessException
{
public const ERROR_CODE = 'OAUTH_TOKEN_MCP_ONLY';

public function __construct(?string $message = null, ?Throwable $previous = null)
{
parent::__construct($message ?? __('This token was issued to a connected app and only works with the MCP server. Use an API key to call the API.'), $previous);
}
}
2 changes: 2 additions & 0 deletions backend/app/Http/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use HiEvents\Http\Middleware\EnsureAccountIsNotPendingDeletion;
use HiEvents\Http\Middleware\EnsureAccountIsNotSuspended;
use HiEvents\Http\Middleware\EnsureLifecycleEmailsAvailable;
use HiEvents\Http\Middleware\EnsureOrderBelongsToEvent;
use HiEvents\Http\Middleware\EnsureTokenNotRevoked;
use HiEvents\Http\Middleware\EnsureTwoFactorEnrolled;
use HiEvents\Http\Middleware\HandleDeprecatedTimezones;
Expand Down Expand Up @@ -107,6 +108,7 @@ class Kernel extends HttpKernel
'auth.basic' => AuthenticateWithBasicAuth::class,
'box-office.session' => AuthenticateBoxOfficeSession::class,
'ee.licensed' => RequireLicensedFeature::class,
'order.event' => EnsureOrderBelongsToEvent::class,
'lifecycle-emails' => EnsureLifecycleEmailsAvailable::class,
'auth.session' => AuthenticateSession::class,
'cache.guest' => CacheGuestJsonResponse::class,
Expand Down
6 changes: 6 additions & 0 deletions backend/app/Http/Middleware/EnforceAccountUserAccess.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
use HiEvents\DomainObjects\Enums\Permission;
use HiEvents\DomainObjects\Status\UserStatus;
use HiEvents\Exceptions\ApiKeyReadOnlyException;
use HiEvents\Exceptions\OAuthTokenMcpOnlyException;
use HiEvents\Exceptions\PermissionRequiredException;
use HiEvents\Exceptions\ReadOnlyAccessException;
use HiEvents\Exceptions\UnauthorizedException;
use HiEvents\Http\Actions\Admin\Users\StopImpersonationAction;
use HiEvents\Http\Attributes\AllowedForReadOnlyUsers;
use HiEvents\Http\Attributes\RequiresPermission;
use HiEvents\Mcp\Routing\ApiRouteDispatcher;
use HiEvents\Services\Domain\Auth\Access\AccountUserAccess;
use HiEvents\Services\Domain\Auth\Access\AccountUserAccessService;
use HiEvents\Services\Domain\Auth\AuthUserService;
Expand All @@ -32,6 +34,10 @@ public function handle(Request $request, Closure $next)
return $next($request);
}

if ($this->authUserService->isOAuthAccessTokenRequest() && ! $request->attributes->get(ApiRouteDispatcher::INNER_REQUEST_ATTRIBUTE)) {
throw new OAuthTokenMcpOnlyException;
}

$controller = $request->route()?->getControllerClass();
$accountUser = $this->authUserService->getUser()?->getCurrentAccountUser();

Expand Down
41 changes: 41 additions & 0 deletions backend/app/Http/Middleware/EnsureOrderBelongsToEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace HiEvents\Http\Middleware;

use Closure;
use HiEvents\DomainObjects\Generated\OrderDomainObjectAbstract;
use HiEvents\Exceptions\ResourceNotFoundException;
use HiEvents\Repository\Interfaces\OrderRepositoryInterface;
use Illuminate\Http\Request;

class EnsureOrderBelongsToEvent
{
public function __construct(
private readonly OrderRepositoryInterface $orderRepository,
) {}

/**
* @throws ResourceNotFoundException
*/
public function handle(Request $request, Closure $next)
{
$eventId = $request->route('event_id');
$orderShortId = $request->route('order_short_id');

$order = is_numeric($eventId) && is_string($orderShortId)
? $this->orderRepository->findFirstWhere(
where: [
OrderDomainObjectAbstract::SHORT_ID => $orderShortId,
OrderDomainObjectAbstract::EVENT_ID => (int) $eventId,
],
columns: [OrderDomainObjectAbstract::ID],
)
: null;

if ($order === null) {
throw new ResourceNotFoundException(__('Order not found'));
}

return $next($request);
}
}
3 changes: 3 additions & 0 deletions backend/app/Mcp/Routing/ApiRouteDispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

class ApiRouteDispatcher
{
public const INNER_REQUEST_ATTRIBUTE = 'mcp.inner_request';

private const JSON = 'application/json';

private const MULTIPART = 'multipart/form-data';
Expand Down Expand Up @@ -69,6 +71,7 @@ private function dispatch(
server: $this->innerServerVariables($outerRequest, $contentType),
content: $content,
);
$innerRequest->attributes->set(self::INNER_REQUEST_ATTRIBUTE, true);

try {
$response = $this->kernel->handle($innerRequest);
Expand Down
4 changes: 3 additions & 1 deletion backend/app/Repository/Eloquent/AttendeeRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,9 @@ public function getAttendeesByCheckInShortId(string $shortId, QueryParamsDTO $pa
->orWhere('attendees.'.AttendeeDomainObjectAbstract::LAST_NAME, 'ilike', '%'.$params->query.'%')
->orWhere('attendees.'.AttendeeDomainObjectAbstract::FIRST_NAME, 'ilike', '%'.$params->query.'%')
->orWhere('attendees.'.AttendeeDomainObjectAbstract::PUBLIC_ID, 'ilike', '%'.$params->query.'%')
->orWhere('attendees.'.AttendeeDomainObjectAbstract::EMAIL, 'ilike', '%'.$params->query.'%')
->orWhere(static fn (Builder $emailMatch) => $emailMatch
->where('check_in_lists.public_show_order_details', true)
->where('attendees.'.AttendeeDomainObjectAbstract::EMAIL, 'ilike', '%'.$params->query.'%'))
->orWhere('attendees.'.AttendeeDomainObjectAbstract::SEAT_LABEL, 'ilike', '%'.$params->query.'%');
};
}
Expand Down
18 changes: 14 additions & 4 deletions backend/app/Resources/User/UserResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace HiEvents\Resources\User;

use HiEvents\DomainObjects\Enums\Permission;
use HiEvents\DomainObjects\Status\UserStatus;
use HiEvents\DomainObjects\UserDomainObject;
use HiEvents\Resources\BaseResource;
use HiEvents\Services\Domain\Auth\Access\AccountUserAccessService;
Expand All @@ -20,17 +21,20 @@ public function toArray(Request $request): array
$authUserService = app(AuthUserService::class);
$isImpersonating = $authUserService->isImpersonating();
$impersonatorId = $authUserService->getImpersonatorId();
$hideSettings = $this->isPendingInvitationOfAnotherUser();

return [
'id' => $this->getId(),
'timezone' => $this->getTimezone(),
'timezone' => $hideSettings ? config('app.default_timezone') : $this->getTimezone(),
'first_name' => $this->getFirstName(),
'last_name' => $this->getLastName(),
'full_name' => $this->getFullName(),
'email' => $this->getEmail(),
'is_email_verified' => $this->getEmailVerifiedAt() !== null,
'locale' => $this->getLocale(),
'two_factor_enabled' => $this->getTwoFactorConfirmedAt() !== null,
/** @var bool */
'is_email_verified' => ! $hideSettings && $this->getEmailVerifiedAt() !== null,
'locale' => $hideSettings ? config('app.locale') : $this->getLocale(),
/** @var bool */
'two_factor_enabled' => ! $hideSettings && $this->getTwoFactorConfirmedAt() !== null,
$this->mergeWhen($this->isCurrentUser(), fn () => [
'has_pending_email_change' => $this->getPendingEmail() !== null,
/** @var bool */
Expand Down Expand Up @@ -66,6 +70,12 @@ private function isCurrentUser(): bool
return auth()->id() !== null && (int) auth()->id() === $this->getId();
}

private function isPendingInvitationOfAnotherUser(): bool
{
return ! $this->isCurrentUser()
&& $this->getCurrentAccountUser()?->getStatus() === UserStatus::INVITED->name;
}

private function accessSummary(): array
{
$access = app(AccountUserAccessService::class)->forAccountUser($this->getCurrentAccountUser());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,9 @@ private function getExistingUser(CreateAccountDTO $accountData): ?UserDomainObje
'is_account_owner' => true,
]);

if ($existingOwner !== null) {
$passwordMatches = $this->passwordMatches($accountData, $existingUser);

if ($existingOwner !== null || ! $passwordMatches) {
throw new EmailAlreadyExists(
__('There is already an account associated with this email. Please log in instead.')
);
Expand All @@ -182,6 +184,13 @@ private function getExistingUser(CreateAccountDTO $accountData): ?UserDomainObje
return $existingUser;
}

private function passwordMatches(CreateAccountDTO $accountData, UserDomainObject $existingUser): bool
{
return $accountData->password !== null
&& $existingUser->getPassword() !== null
&& $this->hashManager->check($accountData->password, $existingUser->getPassword());
}

/**
* @throws AccountConfigurationDoesNotExist
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
use HiEvents\Services\Application\Handlers\Order\DTO\OrderQuestionsDTO;
use HiEvents\Services\Domain\Order\CheckoutSmsOptInService;
use HiEvents\Services\Domain\Order\OccurrenceStatusValidator;
use HiEvents\Services\Domain\Order\OrderReservationLapseGuard;
use HiEvents\Services\Domain\Product\ProductQuantityUpdateService;
use HiEvents\Services\Domain\Question\QuestionVisibilityService;
use HiEvents\Services\Infrastructure\DomainEvents\DomainEventDispatcherService;
Expand Down Expand Up @@ -82,6 +83,7 @@ public function __construct(
private readonly QuestionVisibilityService $questionVisibilityService,
private readonly PhoneNumberNormalizer $phoneNumberNormalizer,
private readonly CheckoutSmsOptInService $checkoutSmsOptInService,
private readonly OrderReservationLapseGuard $reservationLapseGuard,
) {}

/**
Expand All @@ -99,7 +101,11 @@ public function handle(string $orderShortId, CompleteOrderDTO $orderData): Order

$this->transactionLockService->lockOrder($orderShortId);

$order = $this->getOrder($orderShortId);
$order = $this->getOrder($orderShortId, $orderData->event_id);

if (! $order->isPaymentRequired()) {
$this->reservationLapseGuard->assertReservationHeldUnderEventLock($order);
}

$this->occurrenceStatusValidator->assertOrderOccurrencesArePurchasable($order);

Expand Down Expand Up @@ -420,7 +426,7 @@ private function validateOrder(OrderDomainObject $order): void
/**
* @throws ResourceConflictException
*/
private function getOrder(string $orderShortId): OrderDomainObject
private function getOrder(string $orderShortId, int $eventId): OrderDomainObject
{
$order = $this->orderRepository
->loadRelation(
Expand All @@ -430,7 +436,7 @@ private function getOrder(string $orderShortId): OrderDomainObject
))
->findByShortId($orderShortId);

if ($order === null) {
if ($order === null || $order->getEventId() !== $eventId) {
throw new ResourceNotFoundException(__('Order not found'));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use HiEvents\Services\Application\Handlers\Order\DTO\RefundOrderDTO;
use HiEvents\Services\Domain\Order\OfflineOrderRefundService;
use HiEvents\Services\Domain\Order\OrderCancelService;
use HiEvents\Services\Infrastructure\Lock\TransactionLockService;
use HiEvents\Values\MoneyValue;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Database\DatabaseManager;
Expand All @@ -29,6 +30,7 @@ public function __construct(
private readonly OrderCancelService $orderCancelService,
private readonly OfflineOrderRefundService $offlineOrderRefundService,
private readonly DatabaseManager $databaseManager,
private readonly TransactionLockService $transactionLockService,
) {}

/**
Expand All @@ -45,6 +47,8 @@ public function handle(RefundOrderDTO $refundOrderDTO): OrderDomainObject
*/
private function refundOrder(RefundOrderDTO $refundOrderDTO): OrderDomainObject
{
$this->transactionLockService->lockEvent($refundOrderDTO->event_id);

$order = $this->fetchOrder($refundOrderDTO->event_id, $refundOrderDTO->order_id);

$this->validateRefundability($order, $refundOrderDTO->amount);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use HiEvents\Repository\Interfaces\OrderRepositoryInterface;
use HiEvents\Services\Application\Handlers\Order\DTO\TransitionOrderToOfflinePaymentPublicDTO;
use HiEvents\Services\Domain\Order\OccurrenceStatusValidator;
use HiEvents\Services\Domain\Order\OrderReservationLapseGuard;
use HiEvents\Services\Domain\Order\PaymentLink\OrderCheckoutAccessService;
use HiEvents\Services\Domain\Product\ProductQuantityUpdateService;
use HiEvents\Services\Domain\TicketResale\ResaleClaimService;
Expand All @@ -39,6 +40,7 @@ public function __construct(
private readonly SeatedOrderCompletionGuard $seatedOrderCompletionGuard,
private readonly TransactionLockService $transactionLockService,
private readonly ResaleClaimService $resaleClaimService,
private readonly OrderReservationLapseGuard $reservationLapseGuard,
) {}

public function handle(TransitionOrderToOfflinePaymentPublicDTO $dto): OrderDomainObject
Expand Down Expand Up @@ -68,6 +70,8 @@ public function handle(TransitionOrderToOfflinePaymentPublicDTO $dto): OrderDoma

$this->validateOfflinePayment($order, $eventSettings);

$this->reservationLapseGuard->assertReservationHeldUnderEventLock($order);

$this->resaleClaimService->assertPaidOnlineNow($order->getId());

$this->occurrenceStatusValidator->assertOrderOccurrencesArePurchasable($order);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ private function updateUser(UpdateUserDTO $updateUserData): UserDomainObject
));
}

if ($accountUser->getRole() === Role::SUPERADMIN->name && $this->changesRoleStatusOrAccess($updateUserData)) {
throw new CannotUpdateResourceException(__(
'You cannot change the role, status or access of a Super Admin'
));
}

if ($updateUserData->status !== null && $accountUser->getStatus() === UserStatus::INVITED->name) {
throw new CannotUpdateResourceException(__(
'An invitation becomes active only when it is accepted'
Expand Down Expand Up @@ -135,4 +141,11 @@ private function updateUser(UpdateUserDTO $updateUserData): UserDomainObject
accountId: $updateUserData->account_id
);
}

private function changesRoleStatusOrAccess(UpdateUserDTO $updateUserData): bool
{
return ($updateUserData->role !== null && $updateUserData->role !== Role::SUPERADMIN)
|| ($updateUserData->status !== null && $updateUserData->status !== UserStatus::ACTIVE)
|| $updateUserData->access !== null;
}
}
5 changes: 5 additions & 0 deletions backend/app/Services/Domain/Auth/AuthUserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ public function isApiKeyRequest(): bool
return $this->currentApiKey() !== null;
}

public function isOAuthAccessTokenRequest(): bool
{
return $this->currentApiKey()?->getAttribute('oauth_connection_id') !== null;
}

public function apiKeyCanWrite(): bool
{
$apiKey = $this->currentApiKey();
Expand Down
Loading
Loading