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
4 changes: 3 additions & 1 deletion packages/core/src/sentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ export async function initSentry() {

Sentry.init({
dsn: sentryDsn,
sendDefaultPii: true,
// Do not ship IP/cookies/headers by default — user content and identifiers
// travel through this stack and Sentry has no scrubbing for our schema.
sendDefaultPii: false,
profileSessionSampleRate: 1.0,
tracesSampleRate: 1.0, // Capture 100% of traces for better visibility
integrations: [
Expand Down
158 changes: 158 additions & 0 deletions packages/gateway/src/__tests__/agent-ownership.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import { describe, expect, test } from "bun:test";
import type { SettingsTokenPayload } from "../auth/settings/token-service";
import { verifyOwnedAgentAccess } from "../routes/shared/agent-ownership";

const makeSession = (
overrides: Partial<SettingsTokenPayload> = {}
): SettingsTokenPayload => ({
userId: "user-owner",
oauthUserId: "user-owner",
platform: "telegram",
exp: Date.now() + 60_000,
...overrides,
});

const stubUserAgentsStore = (owner: {
platform: string;
userId: string;
agentId: string;
}) => ({
async ownsAgent(platform: string, userId: string, agentId: string) {
return (
platform === owner.platform &&
userId === owner.userId &&
agentId === owner.agentId
);
},
async addAgent() {
// no-op: only used for best-effort reconciliation in verifyOwnedAgentAccess
},
});

const stubAgentMetadataStore = (
owner: { platform: string; userId: string } | null
) => ({
async getMetadata(_agentId: string) {
return owner
? { owner: { platform: owner.platform, userId: owner.userId } }
: null;
},
});

describe("verifyOwnedAgentAccess (cross-tenant ownership)", () => {
test("owner sees their own agent", async () => {
const session = makeSession();
const result = await verifyOwnedAgentAccess(session, "agent-1", {
userAgentsStore: stubUserAgentsStore({
platform: "telegram",
userId: "user-owner",
agentId: "agent-1",
}) as any,
agentMetadataStore: stubAgentMetadataStore({
platform: "telegram",
userId: "user-owner",
}) as any,
});
expect(result.authorized).toBe(true);
});

test("cross-tenant user on same platform is rejected", async () => {
const session = makeSession({
userId: "user-attacker",
oauthUserId: "user-attacker",
});
const result = await verifyOwnedAgentAccess(session, "agent-1", {
userAgentsStore: stubUserAgentsStore({
platform: "telegram",
userId: "user-owner",
agentId: "agent-1",
}) as any,
agentMetadataStore: stubAgentMetadataStore({
platform: "telegram",
userId: "user-owner",
}) as any,
});
expect(result.authorized).toBe(false);
});

test("cross-platform user with the same userId is rejected", async () => {
const session = makeSession({ platform: "slack" });
const result = await verifyOwnedAgentAccess(session, "agent-1", {
userAgentsStore: stubUserAgentsStore({
platform: "telegram",
userId: "user-owner",
agentId: "agent-1",
}) as any,
agentMetadataStore: stubAgentMetadataStore({
platform: "telegram",
userId: "user-owner",
}) as any,
});
expect(result.authorized).toBe(false);
});

test("agent-scoped session cannot access a different agent", async () => {
const session = makeSession({ agentId: "agent-1" });
const result = await verifyOwnedAgentAccess(session, "agent-2", {
userAgentsStore: stubUserAgentsStore({
platform: "telegram",
userId: "user-owner",
agentId: "agent-2",
}) as any,
agentMetadataStore: stubAgentMetadataStore({
platform: "telegram",
userId: "user-owner",
}) as any,
});
expect(result.authorized).toBe(false);
});

test("admin session bypasses ownership", async () => {
const session = makeSession({ isAdmin: true, userId: "any" });
const result = await verifyOwnedAgentAccess(session, "agent-1", {
userAgentsStore: stubUserAgentsStore({
platform: "telegram",
userId: "user-owner",
agentId: "agent-1",
}) as any,
agentMetadataStore: stubAgentMetadataStore(null) as any,
});
expect(result.authorized).toBe(true);
});

test("unknown agent (no metadata) is rejected for non-admin", async () => {
const session = makeSession({
userId: "user-attacker",
oauthUserId: "user-attacker",
});
const result = await verifyOwnedAgentAccess(session, "agent-unknown", {
userAgentsStore: stubUserAgentsStore({
platform: "telegram",
userId: "user-owner",
agentId: "agent-1",
}) as any,
agentMetadataStore: stubAgentMetadataStore(null) as any,
});
expect(result.authorized).toBe(false);
});

test("external session with mismatched oauthUserId is rejected", async () => {
const session = makeSession({
platform: "external",
userId: "u1",
oauthUserId: "attacker-oauth",
});
const result = await verifyOwnedAgentAccess(session, "agent-1", {
userAgentsStore: stubUserAgentsStore({
platform: "external",
userId: "owner-oauth",
agentId: "agent-1",
}) as any,
agentMetadataStore: stubAgentMetadataStore({
platform: "telegram",
userId: "owner-oauth",
}) as any,
});
expect(result.authorized).toBe(false);
});
});
17 changes: 11 additions & 6 deletions packages/gateway/src/connections/slack-instruction-provider.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import type { InstructionContext, InstructionProvider } from "@lobu/core";
import type { InstructionContext } from "@lobu/core";
import { BaseInstructionProvider } from "../services/instruction-service";
import type { ChatInstanceManager } from "./chat-instance-manager";

export class SlackInstructionProvider implements InstructionProvider {
name = "slack-identity";
priority = 20;
export class SlackInstructionProvider extends BaseInstructionProvider {
readonly name = "slack-identity";
readonly priority = 20;

constructor(private readonly manager: ChatInstanceManager) {}
constructor(private readonly manager: ChatInstanceManager) {
super();
}

async getInstructions(context: InstructionContext): Promise<string> {
protected async buildInstructions(
context: InstructionContext
): Promise<string> {
const connections = await this.manager.listConnections({
platform: "slack",
templateAgentId: context.agentId,
Expand Down
2 changes: 1 addition & 1 deletion packages/gateway/src/services/instruction-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ interface SessionContextData {
* assembly. This removes the identical boilerplate each subclass used to
* declare.
*/
abstract class BaseInstructionProvider implements InstructionProvider {
export abstract class BaseInstructionProvider implements InstructionProvider {
abstract readonly name: string;
abstract readonly priority: number;

Expand Down
37 changes: 37 additions & 0 deletions packages/owletto-backend/src/__tests__/unit/csp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { describe, expect, it } from 'bun:test';
import { isValidFrameAncestor } from '../../utils/csp';

describe('isValidFrameAncestor', () => {
it('accepts well-formed host-sources', () => {
expect(isValidFrameAncestor('https://lobu.ai')).toBe(true);
expect(isValidFrameAncestor('https://*.lobu.ai')).toBe(true);
expect(isValidFrameAncestor('https://app.lobu.ai:8080')).toBe(true);
expect(isValidFrameAncestor('http://localhost:3000')).toBe(true);
});

it('accepts scheme-only sources', () => {
expect(isValidFrameAncestor('https:')).toBe(true);
expect(isValidFrameAncestor('wss:')).toBe(true);
});

it('rejects entries with embedded whitespace', () => {
expect(isValidFrameAncestor('https:// lobu.ai')).toBe(false);
expect(isValidFrameAncestor('https://lobu .ai')).toBe(false);
expect(isValidFrameAncestor(' https://lobu.ai')).toBe(false);
});

it('rejects entries with paths or queries', () => {
expect(isValidFrameAncestor('https://lobu.ai/embed')).toBe(false);
expect(isValidFrameAncestor('https://lobu.ai?x=1')).toBe(false);
expect(isValidFrameAncestor('https://lobu.ai#f')).toBe(false);
});

it('rejects malformed or suspicious entries', () => {
expect(isValidFrameAncestor('')).toBe(false);
expect(isValidFrameAncestor('lobu.ai')).toBe(false); // no scheme
expect(isValidFrameAncestor("'self'")).toBe(false); // keyword already added separately
expect(isValidFrameAncestor('javascript:alert(1)')).toBe(false);
expect(isValidFrameAncestor('https://')).toBe(false);
expect(isValidFrameAncestor('https://lobu.ai attacker.com')).toBe(false);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { describe, expect, it } from 'bun:test';
import { stripMemberEmailsFromRows } from '../../utils/member-redaction';

describe('stripMemberEmailsFromRows ($member traversal redaction)', () => {
it('strips emailField from $member rows surfaced via template data', () => {
const input = {
members: [
{
entity_type: '$member',
name: 'Alice',
metadata: { email: 'alice@example.com', role: 'member' },
},
{
entity_type: '$member',
name: 'Bob',
metadata: { email: 'bob@example.com', role: 'admin' },
},
],
};
const out = stripMemberEmailsFromRows(input, 'email');
expect(out).not.toBeNull();
const rows = out!.members as Array<{ metadata: Record<string, unknown> }>;
expect(rows[0]!.metadata).toEqual({ role: 'member' });
expect(rows[1]!.metadata).toEqual({ role: 'admin' });
});

it('also strips top-level email columns (e.g. SELECT metadata->> email AS email)', () => {
const input = {
members: [
{
entity_type: '$member',
name: 'Alice',
email: 'alice@example.com',
},
],
};
const out = stripMemberEmailsFromRows(input, 'email');
const rows = out!.members as Array<Record<string, unknown>>;
expect('email' in rows[0]!).toBe(false);
expect(rows[0]!.name).toBe('Alice');
});

it('leaves non-member rows untouched', () => {
const input = {
companies: [
{
entity_type: 'company',
name: 'Acme',
metadata: { email: 'hello@acme.example', website: 'acme.example' },
},
],
};
const out = stripMemberEmailsFromRows(input, 'email');
expect(out!.companies).toEqual(input.companies);
});

it('passes through nullish or malformed rows', () => {
expect(stripMemberEmailsFromRows(null, 'email')).toBeNull();
const out = stripMemberEmailsFromRows(
{ mixed: [null, 'string', 42, { entity_type: '$member', metadata: {} }] },
'email'
);
expect(out!.mixed).toEqual([
null,
'string',
42,
{ entity_type: '$member', metadata: {} },
]);
});

it('no-ops when emailField is empty', () => {
const input = {
members: [
{ entity_type: '$member', metadata: { email: 'a@b' } },
],
};
const out = stripMemberEmailsFromRows(input, '');
expect(out).toEqual(input);
});
});
16 changes: 8 additions & 8 deletions packages/owletto-backend/src/auth/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
updateMemberEntityAccess,
updateMemberEntityStatus,
} from '../utils/member-entity';
import { getConfiguredPublicOrigin } from '../utils/public-origin';
import { getConfiguredPublicOrigin, normalizeHost } from '../utils/public-origin';
import { TtlCache } from '../utils/ttl-cache';
import { resolveBaseUrl, safeParseUrl } from './base-url';
import {
Expand Down Expand Up @@ -133,13 +133,13 @@ export async function createAuth(env: Env, request?: Request) {

// When AUTH_COOKIE_DOMAIN is set (e.g. ".lobu.ai"), trust all subdomains so
// session cookies travel across {org}.lobu.ai → lobu.ai cross-origin requests.
const cookieDomain = process.env.AUTH_COOKIE_DOMAIN?.trim();
if (cookieDomain) {
const normalized = cookieDomain.startsWith('.') ? cookieDomain.slice(1) : cookieDomain;
if (normalized) {
trustedOriginSet.add(`https://*.${normalized}`);
trustedOriginSet.add(`https://${normalized}`);
}
// Normalize via normalizeHost so IDN/uppercase/trailing-dot variants of the
// env value cannot silently mismatch the ASCII-lowercased origin BetterAuth
// sees from the browser.
const normalizedCookieZone = normalizeHost(process.env.AUTH_COOKIE_DOMAIN);
if (normalizedCookieZone) {
trustedOriginSet.add(`https://*.${normalizedCookieZone}`);
trustedOriginSet.add(`https://${normalizedCookieZone}`);
}

const auth = betterAuth({
Expand Down
3 changes: 2 additions & 1 deletion packages/owletto-backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import {
restUpdateContentClassification,
} from './rest-api';
import { entityLinkMatchSql } from './utils/content-search';
import { isValidFrameAncestor } from './utils/csp';
import { errorMessage } from './utils/errors';
import logger from './utils/logger';
import { generateOpenAPISpec } from './utils/openapi-generator';
Expand Down Expand Up @@ -298,7 +299,7 @@ app.use('/*', async (c, next) => {
? rawFrameAncestors
.split(/[\s,]+/)
.map((entry) => entry.trim())
.filter(Boolean)
.filter((entry) => isValidFrameAncestor(entry))
.join(' ')
: 'https://lobu.ai https://*.lobu.ai';
c.header(
Expand Down
14 changes: 14 additions & 0 deletions packages/owletto-backend/src/tools/organizations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { type Static, Type } from '@sinclair/typebox';
import { getDb } from '../db/client';
import type { Env } from '../index';
import { getRateLimiter, RateLimitPresets } from '../utils/rate-limiter';
import { buildWorkspaceInstructions } from '../utils/workspace-instructions';
import { getWorkspaceProvider } from '../workspace';
import { joinPublicOrganization } from '../workspace/join-public';
Expand Down Expand Up @@ -118,6 +119,19 @@ export async function joinOrganization(
org: { slug: string; name: string; id: string; role: string };
note?: string;
}> {
// Match the REST endpoint's 10/hour cap (keyed on userId here since MCP tool
// calls don't carry a client IP).
const rateLimit = getRateLimiter().checkLimit(
`rate:join-public-org:user:${ctx.userId}`,
RateLimitPresets.JOIN_PUBLIC_ORG_PER_IP_HOUR
);
if (!rateLimit.allowed) {
throw new Error(
rateLimit.errorMessage ??
'Join rate limit exceeded. Maximum 10 join attempts per hour.'
);
}

let slug = args.organization_slug ?? null;
if (!slug) {
if (!ctx.currentOrgId) {
Expand Down
Loading
Loading