Skip to main content

ironflow_api/
actor.rs

1//! Mapping from an authenticated caller to a persisted run author.
2
3use ironflow_auth::extractor::{AuthMethod, Authenticated};
4use ironflow_store::models::RunActor;
5
6/// Build the [`RunActor`] to persist for a run created by `auth`.
7///
8/// An API key run records both the key and its owner, so filtering runs by user
9/// also matches the runs triggered by that user's keys.
10///
11/// # Examples
12///
13/// ```no_run
14/// use ironflow_api::actor::run_actor_of;
15/// use ironflow_auth::extractor::Authenticated;
16///
17/// fn example(auth: &Authenticated) {
18///     let actor = run_actor_of(auth);
19///     println!("{:?}", actor);
20/// }
21/// ```
22pub fn run_actor_of(auth: &Authenticated) -> RunActor {
23    match auth.method {
24        AuthMethod::Jwt { .. } => RunActor::User {
25            user_id: auth.user_id,
26        },
27        AuthMethod::ApiKey { key_id, .. } => RunActor::ApiKey {
28            api_key_id: key_id,
29            user_id: auth.user_id,
30        },
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use ironflow_store::entities::ApiKeyScope;
37    use uuid::Uuid;
38
39    use super::*;
40
41    #[test]
42    fn jwt_caller_maps_to_a_user_actor() {
43        let user_id = Uuid::now_v7();
44        let auth = Authenticated {
45            user_id,
46            method: AuthMethod::Jwt {
47                username: "alice".to_string(),
48                is_admin: true,
49            },
50        };
51
52        assert_eq!(run_actor_of(&auth), RunActor::User { user_id });
53    }
54
55    #[test]
56    fn api_key_caller_maps_to_an_api_key_actor_carrying_its_owner() {
57        let user_id = Uuid::now_v7();
58        let key_id = Uuid::now_v7();
59        let auth = Authenticated {
60            user_id,
61            method: AuthMethod::ApiKey {
62                key_id,
63                key_name: "ci-deploy".to_string(),
64                scopes: vec![ApiKeyScope::RunsWrite],
65                owner_is_admin: true,
66            },
67        };
68
69        assert_eq!(
70            run_actor_of(&auth),
71            RunActor::ApiKey {
72                api_key_id: key_id,
73                user_id,
74            }
75        );
76    }
77}