Skip to main content

auth_framework/migrations/
mod.rs

1//! Database migration system for auth-framework.
2//! This module provides tools for managing database schema changes
3//! and ensuring proper setup of authentication-related tables.
4#[cfg(any(feature = "cli", feature = "postgres-storage"))]
5use tokio_postgres::{Client, Error as PgError};
6
7/// Migration manager for database schema changes
8#[cfg(any(feature = "cli", feature = "postgres-storage"))]
9pub struct MigrationManager {
10    client: Client,
11}
12
13#[cfg(any(feature = "cli", feature = "postgres-storage"))]
14#[derive(Debug, Clone)]
15pub struct Migration {
16    pub version: i64,
17    pub name: String,
18    pub sql: String,
19}
20
21#[cfg(any(feature = "cli", feature = "postgres-storage"))]
22impl MigrationManager {
23    pub fn new(client: Client) -> Self {
24        Self { client }
25    }
26
27    /// Run all pending migrations
28    pub async fn migrate(&mut self) -> Result<(), MigrationError> {
29        // Ensure migrations table exists
30        self.ensure_migrations_table().await?;
31
32        let applied = self.get_applied_migrations().await?;
33        let available = self.get_available_migrations();
34
35        for migration in available {
36            if !applied.contains(&migration.version) {
37                println!("Applying migration: {}", migration.name);
38                self.apply_migration(&migration).await?;
39            }
40        }
41
42        Ok(())
43    }
44
45    async fn ensure_migrations_table(&self) -> Result<(), PgError> {
46        self.client
47            .execute(
48                r#"
49            CREATE TABLE IF NOT EXISTS _auth_migrations (
50                version BIGINT PRIMARY KEY,
51                name VARCHAR(255) NOT NULL,
52                applied_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
53            )
54            "#,
55                &[],
56            )
57            .await?;
58        Ok(())
59    }
60
61    async fn get_applied_migrations(&self) -> Result<Vec<i64>, PgError> {
62        let rows = self
63            .client
64            .query("SELECT version FROM _auth_migrations ORDER BY version", &[])
65            .await?;
66
67        Ok(rows.iter().map(|row| row.get(0)).collect())
68    }
69
70    fn get_available_migrations(&self) -> Vec<Migration> {
71        vec![
72            Migration {
73                version: 1,
74                name: "create_users_table".to_string(),
75                sql: r#"
76                    CREATE TABLE IF NOT EXISTS users (
77                        id VARCHAR(36) PRIMARY KEY,
78                        username VARCHAR(255) UNIQUE NOT NULL,
79                        password_hash VARCHAR(255) NOT NULL,
80                        email VARCHAR(255) UNIQUE,
81                        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
82                        updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
83                        is_active BOOLEAN DEFAULT true,
84                        last_login TIMESTAMP WITH TIME ZONE
85                    );
86                    CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
87                    CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
88                "#.to_string(),
89            },
90            Migration {
91                version: 2,
92                name: "create_roles_permissions".to_string(),
93                sql: r#"
94                    CREATE TABLE IF NOT EXISTS roles (
95                        id VARCHAR(36) PRIMARY KEY,
96                        name VARCHAR(100) UNIQUE NOT NULL,
97                        description TEXT,
98                        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
99                    );
100
101                    CREATE TABLE IF NOT EXISTS permissions (
102                        id VARCHAR(36) PRIMARY KEY,
103                        action VARCHAR(100) NOT NULL,
104                        resource VARCHAR(100) NOT NULL,
105                        instance VARCHAR(100),
106                        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
107                    );
108
109                    CREATE TABLE IF NOT EXISTS user_roles (
110                        user_id VARCHAR(36) REFERENCES users(id),
111                        role_id VARCHAR(36) REFERENCES roles(id),
112                        PRIMARY KEY (user_id, role_id)
113                    );
114
115                    CREATE TABLE IF NOT EXISTS role_permissions (
116                        role_id VARCHAR(36) REFERENCES roles(id),
117                        permission_id VARCHAR(36) REFERENCES permissions(id),
118                        PRIMARY KEY (role_id, permission_id)
119                    );
120                "#.to_string(),
121            },
122            Migration {
123                version: 3,
124                name: "create_sessions_table".to_string(),
125                sql: r#"
126                    CREATE TABLE IF NOT EXISTS sessions (
127                        id VARCHAR(36) PRIMARY KEY,
128                        user_id VARCHAR(36) REFERENCES users(id),
129                        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
130                        last_accessed TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
131                        expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
132                        state VARCHAR(20) DEFAULT 'active',
133                        device_fingerprint TEXT,
134                        ip_address INET,
135                        user_agent TEXT,
136                        security_flags TEXT[]
137                    );
138                    CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
139                    CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at);
140                "#.to_string(),
141            },
142            Migration {
143                version: 4,
144                name: "create_audit_logs".to_string(),
145                sql: r#"
146                    CREATE TABLE IF NOT EXISTS audit_logs (
147                        id VARCHAR(36) PRIMARY KEY,
148                        event_type VARCHAR(50) NOT NULL,
149                        timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
150                        user_id VARCHAR(36),
151                        session_id VARCHAR(36),
152                        resource VARCHAR(100),
153                        action VARCHAR(100),
154                        success BOOLEAN NOT NULL,
155                        ip_address INET,
156                        user_agent TEXT,
157                        details JSONB
158                    );
159                    CREATE INDEX IF NOT EXISTS idx_audit_logs_timestamp ON audit_logs(timestamp);
160                    CREATE INDEX IF NOT EXISTS idx_audit_logs_user_id ON audit_logs(user_id);
161                    CREATE INDEX IF NOT EXISTS idx_audit_logs_event_type ON audit_logs(event_type);
162                "#.to_string(),
163            },
164            Migration {
165                version: 5,
166                name: "create_mfa_table".to_string(),
167                sql: r#"
168                    CREATE TABLE IF NOT EXISTS mfa_secrets (
169                        user_id VARCHAR(36) PRIMARY KEY REFERENCES users(id),
170                        totp_secret VARCHAR(255),
171                        backup_codes TEXT[],
172                        phone_number VARCHAR(20),
173                        email_verified BOOLEAN DEFAULT false,
174                        phone_verified BOOLEAN DEFAULT false,
175                        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
176                    );
177
178                    CREATE TABLE IF NOT EXISTS mfa_challenges (
179                        id VARCHAR(36) PRIMARY KEY,
180                        user_id VARCHAR(36) REFERENCES users(id),
181                        challenge_type VARCHAR(20) NOT NULL,
182                        challenge_data TEXT,
183                        expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
184                        created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
185                    );
186                    CREATE INDEX IF NOT EXISTS idx_mfa_challenges_expires_at ON mfa_challenges(expires_at);
187                "#.to_string(),
188            },
189        ]
190    }
191
192    async fn apply_migration(&mut self, migration: &Migration) -> Result<(), MigrationError> {
193        let tx = self.client.transaction().await?;
194
195        // Execute migration SQL
196        tx.batch_execute(&migration.sql).await?;
197
198        // Record migration
199        use tokio_postgres::types::ToSql;
200        tx.execute(
201            "INSERT INTO _auth_migrations (version, name) VALUES ($1, $2)",
202            &[
203                &migration.version as &(dyn ToSql + Sync),
204                &migration.name.as_str() as &(dyn ToSql + Sync),
205            ],
206        )
207        .await?;
208
209        tx.commit().await?;
210        Ok(())
211    }
212
213    /// Check migration status
214    pub async fn status(&self) -> Result<MigrationStatus, MigrationError> {
215        let applied = self
216            .get_applied_migrations()
217            .await
218            .map_err(MigrationError::Database)?;
219        let available = self.get_available_migrations();
220
221        let pending: Vec<_> = available
222            .iter()
223            .filter(|m| !applied.contains(&m.version))
224            .collect();
225
226        Ok(MigrationStatus {
227            applied_count: applied.len(),
228            pending_count: pending.len(),
229            latest_applied: applied.last().copied(),
230            next_pending: pending.first().map(|m| m.version),
231        })
232    }
233
234    /// Create a new migration (for external use)
235    pub fn create_migration(version: i64, name: String, sql: String) -> Migration {
236        Migration { version, name, sql }
237    }
238
239    /// Get list of available migrations
240    pub fn list_available_migrations(&self) -> Vec<Migration> {
241        // Return cloned migrations to avoid lifetime issues
242        self.get_available_migrations()
243    }
244}
245
246#[derive(Debug)]
247pub struct MigrationStatus {
248    pub applied_count: usize,
249    pub pending_count: usize,
250    pub latest_applied: Option<i64>,
251    pub next_pending: Option<i64>,
252}
253
254#[cfg(any(feature = "cli", feature = "postgres-storage"))]
255#[derive(Debug, thiserror::Error)]
256pub enum MigrationError {
257    #[error("Database error: {0}")]
258    Database(PgError),
259    #[error("Migration not found: {0}")]
260    NotFound(i64),
261    #[error("Invalid migration order")]
262    InvalidOrder,
263}
264
265#[cfg(any(feature = "cli", feature = "postgres-storage"))]
266impl From<PgError> for MigrationError {
267    fn from(e: PgError) -> Self {
268        MigrationError::Database(e)
269    }
270}
271
272#[cfg(any(feature = "cli", feature = "postgres-storage"))]
273/// CLI tool for running migrations
274pub struct MigrationCli;
275
276#[cfg(any(feature = "cli", feature = "postgres-storage"))]
277impl MigrationCli {
278    pub async fn run(database_url: &str, command: &str) -> Result<(), Box<dyn std::error::Error>> {
279        let (client, connection) =
280            tokio_postgres::connect(database_url, tokio_postgres::NoTls).await?;
281        tokio::spawn(async move {
282            if let Err(e) = connection.await {
283                eprintln!("Connection error: {}", e);
284            }
285        });
286        let mut manager = MigrationManager::new(client);
287
288        match command {
289            "migrate" => {
290                manager.migrate().await?;
291                println!("Migrations completed successfully");
292            }
293            "status" => {
294                let status = manager.status().await?;
295                println!("Migration Status:");
296                println!("  Applied: {}", status.applied_count);
297                println!("  Pending: {}", status.pending_count);
298                if let Some(latest) = status.latest_applied {
299                    println!("  Latest Applied: {}", latest);
300                }
301                if let Some(next) = status.next_pending {
302                    println!("  Next Pending: {}", next);
303                }
304            }
305            _ => {
306                eprintln!("Unknown command: {}", command);
307                eprintln!("Available commands: migrate, status");
308            }
309        }
310
311        Ok(())
312    }
313}