1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
use crate::database::migrations::RustMigration;
use crate::database::{FromSqlxError, ToSqlxType, ToVoid};
use ockam_core::{async_trait, Result};
use sqlx::*;

/// This migration moves policies attached to resource types from
/// table "resource_policy" to "resource_type_policy"
#[derive(Debug)]
pub struct SplitPolicies;

#[async_trait]
impl RustMigration for SplitPolicies {
    fn name(&self) -> &str {
        Self::name()
    }

    fn version(&self) -> i64 {
        Self::version()
    }

    async fn migrate(&self, connection: &mut SqliteConnection) -> Result<bool> {
        Self::migrate_policies(connection).await
    }
}

impl SplitPolicies {
    /// Migration version
    pub fn version() -> i64 {
        20240212100000
    }

    /// Migration name
    pub fn name() -> &'static str {
        "migration_20240212100000_migrate_policies"
    }

    pub(crate) async fn migrate_policies(connection: &mut SqliteConnection) -> Result<bool> {
        let mut transaction = sqlx::Connection::begin(&mut *connection)
            .await
            .into_core()?;

        let query_policies =
            query_as("SELECT resource_name, action, expression, node_name FROM resource_policy");
        let rows: Vec<ResourcePolicyRow> = query_policies
            .fetch_all(&mut *transaction)
            .await
            .into_core()?;
        // Copy resource type policies to table "resource_type_policy"
        for row in rows {
            if row.resource_name == "tcp-outlet" || row.resource_name == "tcp-inlet" {
                query("INSERT INTO resource_type_policy (resource_type, action, expression, node_name) VALUES (?, ?, ?, ?)")
                    .bind(row.resource_name.to_sql())
                    .bind(row.action.to_sql())
                    .bind(row.expression.to_sql())
                    .bind(row.node_name.to_sql())
                    .execute(&mut *transaction)
                    .await
                    .void()?;
            }
        }
        // Remove policies from table "resource_policy" where resource is "tcp-outlet" or "tcp-inlet"
        query(
            "DELETE FROM resource_policy WHERE resource_name = 'tcp-outlet' OR resource_name = 'tcp-inlet'",
        )
        .execute(&mut *transaction)
        .await
        .void()?;

        // Commit
        transaction.commit().await.void()?;

        Ok(true)
    }
}

#[derive(FromRow)]
struct ResourcePolicyRow {
    resource_name: String,
    action: String,
    expression: String,
    node_name: String,
}

#[cfg(test)]
mod test {
    use crate::database::migrations::node_migration_set::NodeMigrationSet;
    use crate::database::{MigrationSet, SqlxDatabase};
    use ockam_core::compat::rand::random_string;
    use sqlx::query::Query;
    use sqlx::sqlite::SqliteArguments;
    use tempfile::NamedTempFile;

    use super::*;

    #[tokio::test]
    async fn test_migration() -> Result<()> {
        // create the database pool and migrate the tables
        let db_file = NamedTempFile::new().unwrap();

        let pool = SqlxDatabase::create_connection_pool(db_file.path()).await?;

        let mut connection = pool.acquire().await.into_core()?;

        NodeMigrationSet
            .create_migrator()?
            .migrate_up_to_skip_last_rust_migration(&pool, SplitPolicies::version())
            .await?;

        // insert some policies
        let policy1 = insert_policy("tcp-outlet");
        let policy2 = insert_policy("tcp-inlet");
        let policy3 = insert_policy("my_outlet_1");
        let policy4 = insert_policy("my_outlet_2");
        let policy5 = insert_policy("my_inlet_1");

        policy1.execute(&mut *connection).await.void()?;
        policy2.execute(&mut *connection).await.void()?;
        policy3.execute(&mut *connection).await.void()?;
        policy4.execute(&mut *connection).await.void()?;
        policy5.execute(&mut *connection).await.void()?;

        // apply migrations
        NodeMigrationSet
            .create_migrator()?
            .migrate_up_to(&pool, SplitPolicies::version())
            .await?;

        // check that the "tcp-inlet" and "tcp-outlet" policies are moved to the new table
        let rows: Vec<ResourceTypePolicyRow> = query_as(
            "SELECT resource_type, action, expression, node_name FROM resource_type_policy",
        )
        .fetch_all(&mut *connection)
        .await
        .into_core()?;
        assert_eq!(rows.len(), 2);
        rows.iter()
            .find(|r| r.resource_type == "tcp-outlet")
            .unwrap();
        rows.iter()
            .find(|r| r.resource_type == "tcp-inlet")
            .unwrap();

        // check that they are not in the resource_policy table and that we kept the other policies
        let rows: Vec<ResourcePolicyRow> =
            query_as("SELECT resource_name, action, expression, node_name FROM resource_policy")
                .fetch_all(&mut *connection)
                .await
                .into_core()?;
        assert_eq!(rows.len(), 3);
        rows.iter()
            .find(|r| r.resource_name == "my_outlet_1")
            .unwrap();
        rows.iter()
            .find(|r| r.resource_name == "my_outlet_2")
            .unwrap();
        rows.iter()
            .find(|r| r.resource_name == "my_inlet_1")
            .unwrap();

        Ok(())
    }

    #[derive(FromRow)]
    #[allow(dead_code)]
    struct ResourceTypePolicyRow {
        resource_type: String,
        action: String,
        expression: String,
        node_name: String,
    }

    /// HELPERS
    fn insert_policy(resource: &str) -> Query<'static, Sqlite, SqliteArguments<'static>> {
        let action = "handle_message";
        let expression = random_string();
        let node_name = random_string();
        query("INSERT INTO resource_policy (resource_name, action, expression, node_name) VALUES (?, ?, ?, ?)")
            .bind(resource.to_sql())
            .bind(action.to_sql())
            .bind(expression.to_sql())
            .bind(node_name.to_sql())
    }
}