* feat: add OIDC/SSO database schema and models (Phase 1) Add database foundation for OpenID Connect authentication: Database Migrations: - Create oidc_identities table (links users to OIDC accounts) - Create oidc_state_nonces table (OAuth state/nonce for CSRF protection) - Create auth_audit_log table (security event logging) - Make password_digest nullable in users table (allow OIDC-only users) Models: - OIDCIdentity: Links users to external OIDC providers - OIDCStateNonce: Temporary OAuth state management - AuthAuditLog: Authentication event audit trail Changes: - Updated User model to allow null password_digest - Added model associations in models/index.js - All migrations tested and verified Related to #977 * feat: add OIDC core services (Phase 2) - Install openid-client@^6.2.0 for OIDC protocol support - Implement providerConfig.js for loading providers from .env - Support single provider or numbered providers (OIDC_PROVIDER_1_*, etc.) - Auto-provision and admin email domain configuration - Provider caching for performance - Implement stateManager.js for OAuth state/nonce management - CSRF protection with 10-minute TTL - One-time use state consumption - Automatic cleanup of expired states - Implement auditService.js for authentication event logging - Track login success/failure, logout, OIDC linking/unlinking - Store IP address, user agent, and metadata - Support for event queries and retention cleanup - Add comprehensive unit tests (60 tests, all passing) - providerConfig: 36 tests for env parsing and validation - stateManager: 12 tests for state lifecycle and security - auditService: 12 tests for event logging and queries Phase 2 completes the backend core services needed for OIDC authentication. * feat: implement OIDC authentication flow (Phase 3) Core OIDC Flow (service.js): - Provider discovery with issuer caching - Authorization URL generation with state/nonce - OAuth callback handling and token exchange - ID token validation using openid-client - Token refresh functionality JIT User Provisioning (provisioningService.js): - Auto-create users from OIDC claims - Link existing email accounts to OIDC identities - Admin role assignment based on email domain rules - Automatic username generation from email - Transaction-safe identity creation Identity Management (oidcIdentityService.js): - List user's linked OIDC identities - Link additional providers to existing accounts - Unlink identities with safety checks - Prevent unlinking last auth method - Update identity claims on login HTTP Layer (controller.js + routes.js): - GET /api/oidc/providers - List configured providers - GET /api/oidc/auth/:slug - Initiate OIDC flow - GET /api/oidc/callback/:slug - Handle OAuth callback - POST /api/oidc/link/:slug - Link provider to current user - DELETE /api/oidc/unlink/:id - Unlink identity - GET /api/oidc/identities - Get user's identities Integration: - Register OIDC routes in Express app (public + authenticated) - Update auth service to reject password login for OIDC-only users - Audit logging for all OIDC operations - Session creation on successful authentication Security: - State/nonce CSRF protection - One-time use state consumption - Transaction-safe user provisioning - Foreign key constraints enforced * feat: implement OIDC frontend login flow (Phase 4) - Created OIDCProviderButtons component for SSO login options - Created OIDCCallback component for OAuth callback handling - Updated Login page to fetch and display OIDC providers - Added /auth/callback/:provider route to App.tsx - Added i18n translations for OIDC UI elements - Downgraded openid-client to v5.7.0 (CommonJS compatibility) - Fixed linting issues in backend OIDC modules Phase 4 completes the frontend login flow for OIDC/SSO authentication. Users can now see configured SSO providers on the login page. * feat: implement OIDC account linking UI (Phase 5) Add Connected Accounts section to Profile Security tab allowing users to: - View linked OIDC provider accounts - Link new SSO providers to their account - Unlink OIDC identities with validation - Prevent unlinking last authentication method Backend changes: - Add has_password virtual field to User model - Include has_password in profile API response - Track whether user has password set for validation Frontend changes: - Create oidcService for OIDC API operations - Create ConnectedAccounts component with link/unlink flows - Add confirmation dialog before unlinking accounts - Validate that users cannot unlink their last auth method - Show warning if user has no password set - Integrate Connected Accounts into SecurityTab User experience: - View all linked SSO provider accounts with email and link date - Link additional providers via "Link Provider" buttons - Unlink with two-step confirmation to prevent accidents - Clear error messages when unlinking would leave no auth method - Warning message suggesting password setup for OIDC-only users Fixes #977 * feat: complete OIDC documentation and UI improvements (Phase 6) This commit completes Phase 6 of the OIDC/SSO implementation with comprehensive documentation, bug fixes, and UI reorganization. Documentation: - Add comprehensive user guide at docs/10-oidc-sso.md with: - Setup guides for 6 major providers (Google, Okta, Keycloak, Authentik, PocketID, Azure AD) - Configuration examples for single and multiple providers - User features documentation (login, account linking, management) - Advanced topics (auto-provisioning, admin role assignment, hybrid auth) - Comprehensive troubleshooting section - Security considerations and best practices - Update README.md with OIDC/SSO section and quick setup examples Internationalization: - Add i18n support to OIDCProviderButtons component - Add translation keys for all OIDC UI text - Update English translations with "sign_in_with" key Bug Fixes: - Fix oidcService.ts to correctly unwrap API responses - Backend returns {providers: [...]} and {identities: [...]} - Frontend was expecting plain arrays, causing "map is not a function" error - Fix initiateOIDCLink to properly handle POST response UI Improvements: - Move OIDC/SSO to dedicated tab in profile settings - Create new OIDCTab component with green LinkIcon - Remove ConnectedAccounts from SecurityTab - Add OIDC tab between Security and API Keys tabs - Update ProfileSettings with new tab configuration - Security tab now focuses solely on password management Testing: - All linting passes - All tests pass (82 suites, 1223 tests) Related to #977 * feat: add OIDC/SSO translations for all 24 languages Add i18n support for OIDC/SSO features across all supported languages: - "Sign in with {{provider}}" button text - "OIDC/SSO" tab label in profile settings - OIDC authentication flow messages Translations added for: Arabic, Bulgarian, Danish, German, Greek, Spanish, Finnish, French, Indonesian, Italian, Japanese, Korean, Dutch, Norwegian, Polish, Portuguese, Romanian, Russian, Slovenian, Swedish, Turkish, Ukrainian, Vietnamese, and Chinese. * fix: resolve 13 CodeQL security alerts This commit addresses critical security vulnerabilities identified by CodeQL scanning: **Security Configuration (2 fixes)** - Fix insecure Helmet configuration - enable CSP and HSTS in production - Fix clear text cookie transmission - enable secure cookies in production **Path Injection (3 fixes)** - Add path validation in users/controller.js to prevent arbitrary file deletion - Add path validation in users/service.js for avatar operations - Add path sanitization in attachment-utils.js deleteFileFromDisk function **Cross-Site Scripting (1 fix)** - Fix XSS vulnerability in GeneralTab.tsx avatar URL handling - Add URL sanitization to prevent javascript: protocol attacks **URL Security (2 fixes)** - Fix double escaping in url/service.js HTML entity decoding - Fix incomplete URL sanitization for YouTube domain validation **Denial of Service (1 fix)** - Add loop bound protection in inboxProcessingService.js (10k char limit) **Rate Limiting (3 fixes)** - Add rate limiting to auth routes (register, verify-email) - Add rate limiting to task attachment upload/delete endpoints - Add rate limiting to user avatar upload/delete endpoints **GitHub Actions Security (1 fix)** - Add explicit read-only permissions to CI workflow Note: CSRF middleware (#10) requires frontend changes and is tracked separately. Relates to PR #1008 * fix: allow test files in path validation for tests * fix: format long condition in attachment-utils for Prettier compliance Break the path validation condition across multiple lines to meet Prettier formatting requirements and fix CI linting failure. * fix: resolve CodeQL security alerts - Add rate limiting to OIDC authentication routes using authLimiter and authenticatedApiLimiter - Implement CSRF protection middleware using csrf-sync (skips for API tokens and test environment) - Add CSRF token endpoint at /api/csrf-token - Fix incomplete URL scheme validation in GeneralTab to block all dangerous schemes (javascript:, data:, vbscript:, file:) This addresses 5 high-severity CodeQL security vulnerabilities: - Missing rate limiting on OIDC auth routes - Missing CSRF middleware protection - Incomplete URL sanitization in avatar handling All 1223 tests passing. * fix: implement CSRF protection with lusca for CodeQL compliance Add CSRF protection using lusca.csrf (CodeQL's recommended library) to protect session-based authentication while supporting hybrid auth patterns. Implementation: - Pre-check middleware marks exempt requests (test env, Bearer tokens) - Lusca CSRF middleware applied with exemption flag check - Session-based requests require valid x-csrf-token header - Bearer token requests exempt (don't use cookies) - Test environment exempt for test execution This addresses CodeQL security alert js/missing-token-validation while maintaining support for both cookie-based and token-based authentication. Related: #977 (OIDC/SSO authentication feature)
302 lines
9.6 KiB
JavaScript
302 lines
9.6 KiB
JavaScript
const express = require('express');
|
|
const multer = require('multer');
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
const { getConfig } = require('../../config/config');
|
|
const config = getConfig();
|
|
const { TaskAttachment, Task } = require('../../models');
|
|
const { uid } = require('../../utils/uid');
|
|
const { logError } = require('../../services/logService');
|
|
const {
|
|
validateFileType,
|
|
deleteFileFromDisk,
|
|
getFileUrl,
|
|
} = require('../../utils/attachment-utils');
|
|
const { getAuthenticatedUserId } = require('../../utils/request-utils');
|
|
const permissionsService = require('../../services/permissionsService');
|
|
const { createResourceLimiter } = require('../../middleware/rateLimiter');
|
|
|
|
const router = express.Router();
|
|
|
|
// Ensure authenticated
|
|
router.use((req, res, next) => {
|
|
const userId = getAuthenticatedUserId(req);
|
|
if (!userId) {
|
|
return res.status(401).json({ error: 'Authentication required' });
|
|
}
|
|
req.authUserId = userId;
|
|
next();
|
|
});
|
|
|
|
// Configure multer for file uploads
|
|
const storage = multer.diskStorage({
|
|
destination: function (req, file, cb) {
|
|
const uploadDir = path.join(config.uploadPath, 'tasks');
|
|
if (!fs.existsSync(uploadDir)) {
|
|
fs.mkdirSync(uploadDir, { recursive: true });
|
|
}
|
|
cb(null, uploadDir);
|
|
},
|
|
filename: function (req, file, cb) {
|
|
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
|
|
cb(null, 'task-' + uniqueSuffix + path.extname(file.originalname));
|
|
},
|
|
});
|
|
|
|
const upload = multer({
|
|
storage: storage,
|
|
limits: {
|
|
fileSize: 10 * 1024 * 1024, // 10MB limit
|
|
},
|
|
fileFilter: function (req, file, cb) {
|
|
if (validateFileType(file.mimetype)) {
|
|
return cb(null, true);
|
|
} else {
|
|
cb(new Error('File type not allowed'));
|
|
}
|
|
},
|
|
});
|
|
|
|
// Upload attachment to task
|
|
router.post(
|
|
'/upload/task-attachment',
|
|
createResourceLimiter,
|
|
upload.single('file'),
|
|
async (req, res) => {
|
|
try {
|
|
const { taskUid } = req.body;
|
|
const userId = req.authUserId;
|
|
|
|
if (!taskUid) {
|
|
// Clean up uploaded file
|
|
if (req.file) {
|
|
await deleteFileFromDisk(req.file.path);
|
|
}
|
|
return res.status(400).json({ error: 'Task UID is required' });
|
|
}
|
|
|
|
// Find task
|
|
const task = await Task.findOne({ where: { uid: taskUid } });
|
|
if (!task) {
|
|
// Clean up uploaded file
|
|
if (req.file) {
|
|
await deleteFileFromDisk(req.file.path);
|
|
}
|
|
return res.status(404).json({ error: 'Task not found' });
|
|
}
|
|
|
|
// Check if user has write access to the task (includes shared projects)
|
|
const access = await permissionsService.getAccess(
|
|
userId,
|
|
'task',
|
|
taskUid
|
|
);
|
|
const LEVELS = { none: 0, ro: 1, rw: 2, admin: 3 };
|
|
if (LEVELS[access] < LEVELS.rw) {
|
|
// Clean up uploaded file
|
|
if (req.file) {
|
|
await deleteFileFromDisk(req.file.path);
|
|
}
|
|
return res
|
|
.status(403)
|
|
.json({ error: 'Not authorized to upload to this task' });
|
|
}
|
|
|
|
// Check attachment count limit (20 max)
|
|
const attachmentCount = await TaskAttachment.count({
|
|
where: { task_id: task.id },
|
|
});
|
|
|
|
if (attachmentCount >= 20) {
|
|
// Clean up uploaded file
|
|
if (req.file) {
|
|
await deleteFileFromDisk(req.file.path);
|
|
}
|
|
return res.status(400).json({
|
|
error: 'Maximum 20 attachments allowed per task',
|
|
});
|
|
}
|
|
|
|
if (!req.file) {
|
|
return res.status(400).json({ error: 'No file uploaded' });
|
|
}
|
|
|
|
// Create attachment record
|
|
const attachment = await TaskAttachment.create({
|
|
uid: uid(),
|
|
task_id: task.id,
|
|
user_id: userId,
|
|
original_filename: req.file.originalname,
|
|
stored_filename: req.file.filename,
|
|
file_size: req.file.size,
|
|
mime_type: req.file.mimetype,
|
|
file_path: `tasks/${req.file.filename}`,
|
|
});
|
|
|
|
// Return attachment with file URL
|
|
const attachmentData = {
|
|
...attachment.toJSON(),
|
|
file_url: getFileUrl(req.file.filename),
|
|
};
|
|
|
|
res.status(201).json(attachmentData);
|
|
} catch (error) {
|
|
logError('Error uploading attachment:', error);
|
|
|
|
// Clean up uploaded file on error
|
|
if (req.file) {
|
|
await deleteFileFromDisk(req.file.path);
|
|
}
|
|
|
|
res.status(500).json({
|
|
error: 'Failed to upload attachment',
|
|
details: error.message,
|
|
});
|
|
}
|
|
}
|
|
);
|
|
|
|
// Get all attachments for a task
|
|
router.get('/tasks/:taskUid/attachments', async (req, res) => {
|
|
try {
|
|
const { taskUid } = req.params;
|
|
const userId = req.authUserId;
|
|
|
|
// Find task
|
|
const task = await Task.findOne({ where: { uid: taskUid } });
|
|
if (!task) {
|
|
return res.status(404).json({ error: 'Task not found' });
|
|
}
|
|
|
|
// Check if user has read access to the task (includes shared projects)
|
|
const access = await permissionsService.getAccess(
|
|
userId,
|
|
'task',
|
|
taskUid
|
|
);
|
|
const LEVELS = { none: 0, ro: 1, rw: 2, admin: 3 };
|
|
if (LEVELS[access] < LEVELS.ro) {
|
|
return res
|
|
.status(403)
|
|
.json({ error: 'Not authorized to view this task' });
|
|
}
|
|
|
|
// Get attachments
|
|
const attachments = await TaskAttachment.findAll({
|
|
where: { task_id: task.id },
|
|
order: [['created_at', 'ASC']],
|
|
});
|
|
|
|
// Add file URLs
|
|
const attachmentsWithUrls = attachments.map((att) => ({
|
|
...att.toJSON(),
|
|
file_url: getFileUrl(att.stored_filename),
|
|
}));
|
|
|
|
res.json(attachmentsWithUrls);
|
|
} catch (error) {
|
|
logError('Error fetching attachments:', error);
|
|
res.status(500).json({
|
|
error: 'Failed to fetch attachments',
|
|
details: error.message,
|
|
});
|
|
}
|
|
});
|
|
|
|
// Delete an attachment
|
|
router.delete(
|
|
'/tasks/:taskUid/attachments/:attachmentUid',
|
|
createResourceLimiter,
|
|
async (req, res) => {
|
|
try {
|
|
const { taskUid, attachmentUid } = req.params;
|
|
const userId = req.authUserId;
|
|
|
|
// Find task
|
|
const task = await Task.findOne({ where: { uid: taskUid } });
|
|
if (!task) {
|
|
return res.status(404).json({ error: 'Task not found' });
|
|
}
|
|
|
|
// Check if user has write access to the task (includes shared projects)
|
|
const access = await permissionsService.getAccess(
|
|
userId,
|
|
'task',
|
|
taskUid
|
|
);
|
|
const LEVELS = { none: 0, ro: 1, rw: 2, admin: 3 };
|
|
if (LEVELS[access] < LEVELS.rw) {
|
|
return res
|
|
.status(403)
|
|
.json({ error: 'Not authorized to modify this task' });
|
|
}
|
|
|
|
// Find attachment
|
|
const attachment = await TaskAttachment.findOne({
|
|
where: { uid: attachmentUid, task_id: task.id },
|
|
});
|
|
|
|
if (!attachment) {
|
|
return res.status(404).json({ error: 'Attachment not found' });
|
|
}
|
|
|
|
// Delete file from disk
|
|
const filePath = path.join(config.uploadPath, attachment.file_path);
|
|
await deleteFileFromDisk(filePath);
|
|
|
|
// Delete database record
|
|
await attachment.destroy();
|
|
|
|
res.json({ message: 'Attachment deleted successfully' });
|
|
} catch (error) {
|
|
logError('Error deleting attachment:', error);
|
|
res.status(500).json({
|
|
error: 'Failed to delete attachment',
|
|
details: error.message,
|
|
});
|
|
}
|
|
}
|
|
);
|
|
|
|
// Download an attachment
|
|
router.get('/attachments/:attachmentUid/download', async (req, res) => {
|
|
try {
|
|
const { attachmentUid } = req.params;
|
|
const userId = req.authUserId;
|
|
|
|
// Find attachment
|
|
const attachment = await TaskAttachment.findOne({
|
|
where: { uid: attachmentUid },
|
|
include: [{ model: Task, required: true }],
|
|
});
|
|
|
|
if (!attachment) {
|
|
return res.status(404).json({ error: 'Attachment not found' });
|
|
}
|
|
|
|
// Check if user has read access to the task (includes shared projects)
|
|
const access = await permissionsService.getAccess(
|
|
userId,
|
|
'task',
|
|
attachment.Task.uid
|
|
);
|
|
const LEVELS = { none: 0, ro: 1, rw: 2, admin: 3 };
|
|
if (LEVELS[access] < LEVELS.ro) {
|
|
return res
|
|
.status(403)
|
|
.json({ error: 'Not authorized to download this file' });
|
|
}
|
|
|
|
// Send file
|
|
const filePath = path.join(config.uploadPath, attachment.file_path);
|
|
res.download(filePath, attachment.original_filename);
|
|
} catch (error) {
|
|
logError('Error downloading attachment:', error);
|
|
res.status(500).json({
|
|
error: 'Failed to download attachment',
|
|
details: error.message,
|
|
});
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|