mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-23 14:17:06 +00:00
feat(auth): debug app sessions that act as a user in one app (#4629)
Adds a `debug_app` session kind and AuthService.createDebugAppToken, which mints an app-under-user token on its own session row instead of the user's app session. The row has a hard expiry that activity never slides, its calls record no user activity, it is hidden from the user's session list, and a password reset revokes it. SessionStore.deleteExpiredDebugAppSessions purges expired rows. Migrations add the kind to the sessions constraint on sqlite, mysql and postgres.
This commit is contained in:
1 parent
c253b7e05e
commit
4ad53899da
9 files changed
+355
-3
No files matched your search
@@ -27,7 +27,7 @@ import { DatabaseClientFactory } from './index.js';
|
||||
import { SqliteDatabaseClient } from './SqliteDatabaseClient.js';
|
||||
|
||||
/** Highest schema version the migration table can reach. */
|
||||
const CURRENT_SCHEMA_VERSION = 100;
|
||||
const CURRENT_SCHEMA_VERSION = 101;
|
||||
|
||||
/**
|
||||
* These suites migrate real files on disk. Idle they finish in well under a
|
||||
|
||||
@@ -139,6 +139,7 @@ const AVAILABLE_MIGRATIONS: [number, string[]][] = [
|
||||
[97, ['0102_notification-scope-id-index.sql']],
|
||||
[98, ['0103_share-entry-owner-backfill.sql']],
|
||||
[99, ['0104_signup-tls-fingerprint.sql']],
|
||||
[100, ['0105_sessions_kind_debug_app.sql']],
|
||||
];
|
||||
|
||||
export class SqliteDatabaseClient extends AbstractDatabaseClient {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
-- Copyright (C) 2024-present Puter Technologies Inc.
|
||||
--
|
||||
-- This file is part of Puter.
|
||||
--
|
||||
-- Puter is free software: you can redistribute it and/or modify
|
||||
-- it under the terms of the GNU Affero General Public License as published
|
||||
-- by the Free Software Foundation, either version 3 of the License, or
|
||||
-- (at your option) any later version.
|
||||
--
|
||||
-- This program is distributed in the hope that it will be useful,
|
||||
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
-- GNU Affero General Public License for more details.
|
||||
--
|
||||
-- You should have received a copy of the GNU Affero General Public License
|
||||
-- along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
-- Add 'debug_app' to the `sessions.kind` ENUM: a short-lived app session an
|
||||
-- operator creates on a user's behalf. Mirrors SQLite migration 0105.
|
||||
--
|
||||
-- Idempotent: guarded against COLUMN_TYPE so re-running the directory is a
|
||||
-- no-op once 'debug_app' is in the ENUM.
|
||||
|
||||
DROP PROCEDURE IF EXISTS _puter_sessions_kind_debug_app;
|
||||
DELIMITER //
|
||||
CREATE PROCEDURE _puter_sessions_kind_debug_app()
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'sessions'
|
||||
AND COLUMN_NAME = 'kind'
|
||||
AND FIND_IN_SET('debug_app', REPLACE(REPLACE(REPLACE(COLUMN_TYPE, 'enum(', ''), ')', ''), '''', '')) > 0
|
||||
) THEN
|
||||
ALTER TABLE `sessions`
|
||||
MODIFY COLUMN `kind`
|
||||
ENUM('web', 'app', 'access_token', 'asset', 'worker', 'debug_app')
|
||||
NOT NULL DEFAULT 'web',
|
||||
ALGORITHM=INSTANT;
|
||||
END IF;
|
||||
END//
|
||||
DELIMITER ;
|
||||
|
||||
CALL _puter_sessions_kind_debug_app();
|
||||
|
||||
DROP PROCEDURE IF EXISTS _puter_sessions_kind_debug_app;
|
||||
@@ -0,0 +1,24 @@
|
||||
-- Copyright (C) 2024-present Puter Technologies Inc.
|
||||
--
|
||||
-- This file is part of Puter.
|
||||
--
|
||||
-- Puter is free software: you can redistribute it and/or modify
|
||||
-- it under the terms of the GNU Affero General Public License as published
|
||||
-- by the Free Software Foundation, either version 3 of the License, or
|
||||
-- (at your option) any later version.
|
||||
--
|
||||
-- This program is distributed in the hope that it will be useful,
|
||||
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
-- GNU Affero General Public License for more details.
|
||||
--
|
||||
-- You should have received a copy of the GNU Affero General Public License
|
||||
-- along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
-- Add 'debug_app' to the `sessions.kind` CHECK constraint: a short-lived app
|
||||
-- session an operator creates on a user's behalf. Mirrors SQLite migration
|
||||
-- 0105. Drop-then-add keeps it idempotent across directory replays.
|
||||
|
||||
ALTER TABLE sessions DROP CONSTRAINT IF EXISTS sessions_kind_check;
|
||||
ALTER TABLE sessions ADD CONSTRAINT sessions_kind_check
|
||||
CHECK (kind IN ('web', 'app', 'access_token', 'asset', 'worker', 'debug_app'));
|
||||
@@ -0,0 +1,89 @@
|
||||
-- Copyright (C) 2024-present Puter Technologies Inc.
|
||||
--
|
||||
-- This file is part of Puter.
|
||||
--
|
||||
-- Puter is free software: you can redistribute it and/or modify
|
||||
-- it under the terms of the GNU Affero General Public License as published
|
||||
-- by the Free Software Foundation, either version 3 of the License, or
|
||||
-- (at your option) any later version.
|
||||
--
|
||||
-- This program is distributed in the hope that it will be useful,
|
||||
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
-- GNU Affero General Public License for more details.
|
||||
--
|
||||
-- You should have received a copy of the GNU Affero General Public License
|
||||
-- along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
-- Add 'debug_app' to the `kind` CHECK constraint on `sessions`. Mirrors the
|
||||
-- MySQL ENUM extension in mysql_mig_59.
|
||||
--
|
||||
-- SQLite cannot ALTER a CHECK constraint in place, so we follow the same
|
||||
-- table-rebuild as migration 0056: create `sessions_new` with the corrected
|
||||
-- constraint, copy rows, drop the old table, rename, then recreate every
|
||||
-- index that lived on the original.
|
||||
|
||||
CREATE TABLE `sessions_new` (
|
||||
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
"user_id" INTEGER NOT NULL,
|
||||
"uuid" TEXT NOT NULL,
|
||||
"meta" JSON DEFAULT NULL,
|
||||
"created_at" INTEGER DEFAULT 0,
|
||||
"last_activity" INTEGER DEFAULT 0,
|
||||
"kind" TEXT NOT NULL DEFAULT 'web'
|
||||
CHECK (`kind` IN ('web', 'app', 'access_token', 'asset', 'worker', 'debug_app')),
|
||||
"label" TEXT,
|
||||
"parent_session_id" TEXT,
|
||||
"last_ip" TEXT,
|
||||
"last_user_agent" TEXT,
|
||||
"revoked_at" INTEGER,
|
||||
"expires_at" INTEGER,
|
||||
"app_uid" TEXT,
|
||||
"legacy_token_uid" TEXT,
|
||||
"created_via" TEXT,
|
||||
"auth_id" TEXT,
|
||||
"access_token_uid" TEXT,
|
||||
FOREIGN KEY("user_id") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
INSERT INTO `sessions_new` (
|
||||
`id`, `user_id`, `uuid`, `meta`, `created_at`, `last_activity`,
|
||||
`kind`, `label`, `parent_session_id`, `last_ip`, `last_user_agent`,
|
||||
`revoked_at`, `expires_at`, `app_uid`, `legacy_token_uid`,
|
||||
`created_via`, `auth_id`, `access_token_uid`
|
||||
)
|
||||
SELECT
|
||||
`id`, `user_id`, `uuid`, `meta`, `created_at`, `last_activity`,
|
||||
`kind`, `label`, `parent_session_id`, `last_ip`, `last_user_agent`,
|
||||
`revoked_at`, `expires_at`, `app_uid`, `legacy_token_uid`,
|
||||
`created_via`, `auth_id`, `access_token_uid`
|
||||
FROM `sessions`;
|
||||
|
||||
DROP TABLE `sessions`;
|
||||
|
||||
ALTER TABLE `sessions_new` RENAME TO `sessions`;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS `idx_sessions_user_revoked`
|
||||
ON `sessions` (`user_id`, `revoked_at`);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS `idx_sessions_parent`
|
||||
ON `sessions` (`parent_session_id`);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS `idx_sessions_user_app_active`
|
||||
ON `sessions` (`user_id`, `app_uid`)
|
||||
WHERE `kind` = 'app' AND `revoked_at` IS NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS `idx_sessions_legacy_token_active`
|
||||
ON `sessions` (`legacy_token_uid`)
|
||||
WHERE `legacy_token_uid` IS NOT NULL AND `revoked_at` IS NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS `idx_sessions_kind_user`
|
||||
ON `sessions` (`kind`, `user_id`);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS `idx_sessions_access_token_uid`
|
||||
ON `sessions` (`access_token_uid`)
|
||||
WHERE `access_token_uid` IS NOT NULL;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS `idx_sessions_user_worker_active`
|
||||
ON `sessions` (`user_id`, IFNULL(`app_uid`, ''), json_extract(`meta`, '$.worker_name'))
|
||||
WHERE `kind` = 'worker' AND `revoked_at` IS NULL;
|
||||
@@ -124,6 +124,106 @@ describe('AuthService (integration)', () => {
|
||||
return u;
|
||||
};
|
||||
|
||||
const makeDebugApp = async (): Promise<string> => {
|
||||
const uid = `app-${uuidv4()}`;
|
||||
await server.clients.db.write(
|
||||
'INSERT INTO `apps` (`uid`, `name`, `title`, `index_url`, `owner_user_id`) VALUES (?, ?, ?, ?, ?)',
|
||||
[uid, `n-${uid}`, `t-${uid}`, `https://${uid}.example/`, 1],
|
||||
);
|
||||
return uid;
|
||||
};
|
||||
|
||||
describe('createDebugAppToken', () => {
|
||||
it('mints an app-under-user token on its own expiring, hidden session', async () => {
|
||||
const user = await makeUser();
|
||||
const appUid = await makeDebugApp();
|
||||
const { token, sessionUuid, expiresAt } =
|
||||
await authService.createDebugAppToken(
|
||||
user as never,
|
||||
{ uid: appUid },
|
||||
{
|
||||
ttlSeconds: 3600,
|
||||
label: 'debug',
|
||||
meta: { debug_admin_username: 'op' },
|
||||
},
|
||||
);
|
||||
|
||||
// Its own dedicated row, not reusing a kind='app' session.
|
||||
const row = (
|
||||
(await server.clients.db.read(
|
||||
'SELECT `kind`, `app_uid`, `expires_at` FROM `sessions` WHERE `uuid` = ?',
|
||||
[sessionUuid],
|
||||
)) as Array<Record<string, unknown>>
|
||||
)[0];
|
||||
expect(row?.kind).toBe('debug_app');
|
||||
expect(row?.app_uid).toBe(appUid);
|
||||
expect(Number(row?.expires_at)).toBeGreaterThan(
|
||||
Math.floor(Date.now() / 1000) + 3500,
|
||||
);
|
||||
expect(expiresAt).toBeGreaterThan(Date.now() + 3500 * 1000);
|
||||
|
||||
// Authenticates as the user acting in the app.
|
||||
const { actor } = await authService.authenticate(token);
|
||||
expect(actor?.user.uuid).toBe(user.uuid);
|
||||
expect(actor?.app?.uid).toBe(appUid);
|
||||
|
||||
// Hidden from the user's own session list.
|
||||
const listed = await authService.listSessions({
|
||||
user: { id: user.id },
|
||||
} as Actor);
|
||||
expect(listed.some((s) => s.uuid === sessionUuid)).toBe(false);
|
||||
});
|
||||
|
||||
it('carries an exp, so the token lapses on its own', async () => {
|
||||
const user = await makeUser();
|
||||
const appUid = await makeDebugApp();
|
||||
const { token } = await authService.createDebugAppToken(
|
||||
user as never,
|
||||
{ uid: appUid },
|
||||
{ ttlSeconds: 1234 },
|
||||
);
|
||||
const claims = server.services.token.verify('auth', token) as {
|
||||
iat: number;
|
||||
exp: number;
|
||||
};
|
||||
expect(claims.exp - claims.iat).toBe(1234);
|
||||
});
|
||||
|
||||
it('records no activity for the user', async () => {
|
||||
const user = await makeUser();
|
||||
const appUid = await makeDebugApp();
|
||||
const { token } = await authService.createDebugAppToken(
|
||||
user as never,
|
||||
{ uid: appUid },
|
||||
{ ttlSeconds: 600 },
|
||||
);
|
||||
const touch = vi.spyOn(server.stores.session, 'touch');
|
||||
try {
|
||||
const ctx = { ip: '9.9.9.9', userAgent: 'debug' };
|
||||
expect(
|
||||
(await authService.authenticate(token, ctx)).actor,
|
||||
).toBeTruthy();
|
||||
expect(touch).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
touch.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('is evicted by a password reset', async () => {
|
||||
const user = await makeUser();
|
||||
const appUid = await makeDebugApp();
|
||||
const { token } = await authService.createDebugAppToken(
|
||||
user as never,
|
||||
{ uid: appUid },
|
||||
{ ttlSeconds: 600 },
|
||||
);
|
||||
await authService.revokeInteractiveSessionsForUserId(user.id);
|
||||
const result = await authService.authenticate(token);
|
||||
expect(result.actor).toBeUndefined();
|
||||
expect(result.reauth).toEqual({ reason: 'session_revoked' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('authenticateFromToken', () => {
|
||||
it('returns null for a malformed/unverifiable token', async () => {
|
||||
const actor = await authService.authenticateFromToken('not-a-jwt');
|
||||
|
||||
@@ -31,6 +31,7 @@ import { awaitLater } from '../../util/concurrency.js';
|
||||
import { appGenerationStart } from '../../util/appGeneration.js';
|
||||
import {
|
||||
ASSET_WINDOW_SECONDS,
|
||||
DEBUG_APP_SESSION_KIND,
|
||||
GODMODE_TOKEN_MAX_AGE_SECONDS,
|
||||
GODMODE_TOKEN_WINDOW_SECONDS,
|
||||
WEB_WINDOW_SECONDS,
|
||||
@@ -787,6 +788,8 @@ export class AuthService extends PuterService {
|
||||
const visible = [...live.values()].filter(
|
||||
(row) =>
|
||||
row.kind !== 'asset' &&
|
||||
// Operator-created debug sessions are never the user's own.
|
||||
row.kind !== DEBUG_APP_SESSION_KIND &&
|
||||
(row.kind !== 'access_token' ||
|
||||
!row.parent_session_id ||
|
||||
live.has(row.parent_session_id)),
|
||||
@@ -1075,7 +1078,12 @@ export class AuthService extends PuterService {
|
||||
});
|
||||
await this.#revokeCascades(
|
||||
rows
|
||||
.filter((row) => row.kind === 'web' || row.kind === 'app')
|
||||
.filter(
|
||||
(row) =>
|
||||
row.kind === 'web' ||
|
||||
row.kind === 'app' ||
|
||||
row.kind === DEBUG_APP_SESSION_KIND,
|
||||
)
|
||||
.map((row) => row.uuid as string),
|
||||
);
|
||||
}
|
||||
@@ -1858,6 +1866,49 @@ export class AuthService extends PuterService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* An app token acting as `user` in `app` on its own `debug_app` session,
|
||||
* which expires after `ttlSeconds` and never touches the user's real
|
||||
* sessions. The caller authorizes who may ask; `meta` lands on the row.
|
||||
*/
|
||||
async createDebugAppToken(
|
||||
user: UserRow,
|
||||
app: { uid: string },
|
||||
opts: {
|
||||
ttlSeconds: number;
|
||||
label?: string | null;
|
||||
meta?: Record<string, unknown>;
|
||||
},
|
||||
): Promise<{ token: string; sessionUuid: string; expiresAt: number }> {
|
||||
const authId = this.#authIdFor(user);
|
||||
const expiresAtSeconds = nowSeconds() + opts.ttlSeconds;
|
||||
const session = await this.stores.session.create(user.id as number, {
|
||||
kind: DEBUG_APP_SESSION_KIND,
|
||||
app_uid: app.uid,
|
||||
expires_at: expiresAtSeconds,
|
||||
auth_id: authId,
|
||||
label: opts.label ?? null,
|
||||
meta: opts.meta ?? {},
|
||||
});
|
||||
const token = this.services.token.sign(
|
||||
'auth',
|
||||
{
|
||||
type: 'app-under-user',
|
||||
version: '2',
|
||||
user_uid: user.uuid,
|
||||
app_uid: app.uid,
|
||||
session_uid: session.uuid,
|
||||
auth_id: authId,
|
||||
},
|
||||
{ expiresIn: opts.ttlSeconds },
|
||||
);
|
||||
return {
|
||||
token,
|
||||
sessionUuid: session.uuid as string,
|
||||
expiresAt: expiresAtSeconds * 1000,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Mint the full-access token a godmode app runs on. Only the desktop's own
|
||||
* web session may ask, and only asking extends it: using the token never
|
||||
@@ -2760,7 +2811,11 @@ export class AuthService extends PuterService {
|
||||
|
||||
// An events handler's calls are background work, not the user being
|
||||
// active, and its session never expires, so they record no activity.
|
||||
if (decoded.worker_name !== EVENTS_WORKER_SESSION_NAME)
|
||||
// Nor do calls on a debug session, which aren't the user's own.
|
||||
if (
|
||||
decoded.worker_name !== EVENTS_WORKER_SESSION_NAME &&
|
||||
session.kind !== DEBUG_APP_SESSION_KIND
|
||||
)
|
||||
void this.#touchSession(session.uuid, user.id, ctx);
|
||||
|
||||
const actor = this.#buildAppUnderUserActor(user, app, session);
|
||||
|
||||
@@ -60,6 +60,9 @@ export const APP_WINDOW_SECONDS = 365 * 24 * 60 * 60; // 1y
|
||||
export const WORKER_WINDOW_SECONDS = 99 * 365 * 24 * 60 * 60; // 99y (virtually infinite);
|
||||
|
||||
export const ASSET_WINDOW_SECONDS = 7 * 24 * 60 * 60; // 7 days
|
||||
// An app session created on a user's behalf for debugging: hard expiry, never
|
||||
// slid, and hidden from the user's own session list.
|
||||
export const DEBUG_APP_SESSION_KIND = 'debug_app';
|
||||
// A godmode app's token lapses at most this long after the desktop last asked
|
||||
// for it, so a closed desktop's tokens die on their own. A token past the max
|
||||
// age is never renewed again; the next ask replaces it and revokes the old one.
|
||||
@@ -1004,6 +1007,18 @@ export class SessionStore extends PuterStore {
|
||||
return result?.affectedRows ?? result?.changes ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard-delete debug app sessions that expired before `cutoff` (unix
|
||||
* seconds). Cached copies still read as expired, so need no invalidation.
|
||||
*/
|
||||
async deleteExpiredDebugAppSessions(cutoff) {
|
||||
const result = await this.clients.db.write(
|
||||
'DELETE FROM `sessions` WHERE `kind` = ? AND `expires_at` IS NOT NULL AND `expires_at` < ?',
|
||||
[DEBUG_APP_SESSION_KIND, cutoff],
|
||||
);
|
||||
return result?.affectedRows ?? result?.changes ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bump `last_activity` and slide `expires_at` per the row's kind in a
|
||||
* single UPDATE. Sliding kinds (web/app/asset) get their `expires_at`
|
||||
|
||||
@@ -357,6 +357,28 @@ describe('SessionStore', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteExpiredDebugAppSessions', () => {
|
||||
it('deletes only expired debug_app rows', async () => {
|
||||
const user = await makeUser();
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const mk = async (kind: string, expiresAt: number | null) => {
|
||||
const { uuid } = await target.create(user.id, {
|
||||
kind,
|
||||
expires_at: expiresAt,
|
||||
});
|
||||
return uuid;
|
||||
};
|
||||
const expired = await mk('debug_app', now - 10);
|
||||
const live = await mk('debug_app', now + 3600);
|
||||
const otherKind = await mk('app', now - 10);
|
||||
|
||||
expect(await target.deleteExpiredDebugAppSessions(now)).toBe(1);
|
||||
expect(await rawRow(expired)).toBeNull();
|
||||
expect(await rawRow(live)).not.toBeNull();
|
||||
expect(await rawRow(otherKind)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('revokeCascade', () => {
|
||||
it('revokes the root session and all child sessions', async () => {
|
||||
const user = await makeUser();
|
||||
|
||||
Reference in new issue
Block a user