Skip to main content

ironflow_api/entities/
created_by.rs

1//! [`CreatedBy`] — public representation of a run's author.
2
3use ironflow_store::models::{Run, RunActor, TriggerKind};
4use serde::{Deserialize, Serialize};
5use uuid::Uuid;
6
7/// Number of leading UUID characters kept in a fallback label.
8const ID_PREFIX_LEN: usize = 8;
9
10/// What kind of principal triggered a run.
11#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum CreatedByKind {
15    /// A user authenticated via JWT.
16    User,
17    /// An API key.
18    ApiKey,
19    /// No authenticated caller: cron, webhook, or a programmatic trigger.
20    System,
21}
22
23/// The author of a run, as exposed by the API.
24///
25/// Always present on a [`RunResponse`](crate::entities::RunResponse): a run with
26/// no recorded author (including every run created before authorship tracking)
27/// reports [`CreatedByKind::System`] with a label derived from its trigger, so
28/// clients never have to handle a missing value.
29///
30/// # Examples
31///
32/// ```
33/// use ironflow_api::entities::{CreatedBy, CreatedByKind};
34///
35/// // Built from a Run via `CreatedBy::from(&run)`.
36/// let system = CreatedBy {
37///     kind: CreatedByKind::System,
38///     id: None,
39///     label: "manual".to_string(),
40/// };
41/// assert_eq!(system.id, None);
42/// ```
43#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
45pub struct CreatedBy {
46    /// What kind of principal triggered the run.
47    pub kind: CreatedByKind,
48    /// Identifier of the principal: the user ID, the API key ID, or `None` for
49    /// [`CreatedByKind::System`].
50    pub id: Option<Uuid>,
51    /// Human-readable label. Never empty.
52    ///
53    /// The username for a user, `"key-name (username)"` for an API key, and the
54    /// trigger description for a system run.
55    pub label: String,
56}
57
58/// Shorten a UUID to its leading characters for a fallback label.
59fn short_id(id: Uuid) -> String {
60    let text = id.to_string();
61    text[..ID_PREFIX_LEN.min(text.len())].to_string()
62}
63
64/// Describe an unauthenticated trigger.
65fn trigger_label(trigger: &TriggerKind) -> String {
66    match trigger {
67        TriggerKind::Manual => "manual".to_string(),
68        TriggerKind::Api => "api".to_string(),
69        TriggerKind::Workflow => "workflow".to_string(),
70        TriggerKind::Retry { .. } => "retry".to_string(),
71        TriggerKind::Replay { .. } => "replay".to_string(),
72        TriggerKind::Webhook { path } => path.clone(),
73        TriggerKind::Cron { schedule } => schedule.clone(),
74        TriggerKind::Nats { subject } => format!("nats:{subject}"),
75        TriggerKind::RunEvent { event_kind, .. } => format!("event:{event_kind}"),
76        TriggerKind::Polling { probe } => format!("polling:{probe}"),
77    }
78}
79
80impl From<&Run> for CreatedBy {
81    fn from(run: &Run) -> Self {
82        match run.created_by {
83            None => CreatedBy {
84                kind: CreatedByKind::System,
85                id: None,
86                label: trigger_label(&run.trigger),
87            },
88            Some(RunActor::User { user_id }) => CreatedBy {
89                kind: CreatedByKind::User,
90                id: Some(user_id),
91                label: run
92                    .created_by_label
93                    .clone()
94                    .unwrap_or_else(|| format!("user {}", short_id(user_id))),
95            },
96            Some(RunActor::ApiKey { api_key_id, .. }) => CreatedBy {
97                kind: CreatedByKind::ApiKey,
98                id: Some(api_key_id),
99                label: run
100                    .created_by_label
101                    .clone()
102                    .unwrap_or_else(|| format!("key {}", short_id(api_key_id))),
103            },
104        }
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use std::collections::HashMap;
111
112    use ironflow_store::api_key_store::ApiKeyStore;
113    use ironflow_store::memory::InMemoryStore;
114    use ironflow_store::models::{ApiKeyScope, NewApiKey, NewRun, NewUser};
115    use ironflow_store::store::RunStore;
116    use ironflow_store::user_store::UserStore;
117    use serde_json::json;
118
119    use super::*;
120
121    /// Build a run through the real store, so `created_by_label` is resolved the
122    /// same way the API sees it at runtime.
123    async fn run_with(
124        store: &InMemoryStore,
125        trigger: TriggerKind,
126        created_by: Option<RunActor>,
127    ) -> Run {
128        store
129            .create_run(NewRun {
130                workflow_name: "deploy".to_string(),
131                trigger,
132                payload: json!({}),
133                max_retries: 0,
134                handler_version: None,
135                labels: HashMap::new(),
136                scheduled_at: None,
137                created_by,
138                idempotency_key: None,
139                max_cost_usd: None,
140            })
141            .await
142            .expect("create run")
143            .into_run()
144    }
145
146    async fn seed_user(store: &InMemoryStore, username: &str) -> Uuid {
147        store
148            .create_user(NewUser {
149                email: format!("{username}@example.com"),
150                username: username.to_string(),
151                password_hash: "hash".to_string(),
152                is_admin: Some(false),
153            })
154            .await
155            .expect("create user")
156            .id
157    }
158
159    async fn seed_api_key(store: &InMemoryStore, user_id: Uuid, name: &str) -> Uuid {
160        store
161            .create_api_key(NewApiKey {
162                user_id,
163                name: name.to_string(),
164                key_hash: "hash".to_string(),
165                key_prefix: "irfl_0000".to_string(),
166                scopes: vec![ApiKeyScope::RunsWrite],
167                expires_at: None,
168                rate_limit_override: None,
169            })
170            .await
171            .expect("create api key")
172            .id
173    }
174
175    #[tokio::test]
176    async fn user_actor_uses_the_resolved_username() {
177        let store = InMemoryStore::new();
178        let user_id = seed_user(&store, "alice").await;
179        let run = run_with(&store, TriggerKind::Api, Some(RunActor::User { user_id })).await;
180
181        let created_by = CreatedBy::from(&run);
182        assert_eq!(created_by.kind, CreatedByKind::User);
183        assert_eq!(created_by.id, Some(user_id));
184        assert_eq!(created_by.label, "alice");
185    }
186
187    #[tokio::test]
188    async fn user_actor_falls_back_to_a_short_id() {
189        let store = InMemoryStore::new();
190        let user_id = Uuid::now_v7();
191        let run = run_with(&store, TriggerKind::Api, Some(RunActor::User { user_id })).await;
192
193        let created_by = CreatedBy::from(&run);
194        assert_eq!(created_by.kind, CreatedByKind::User);
195        assert_eq!(created_by.id, Some(user_id));
196        assert_eq!(created_by.label, format!("user {}", short_id(user_id)));
197    }
198
199    #[tokio::test]
200    async fn api_key_actor_exposes_the_key_id_and_a_combined_label() {
201        let store = InMemoryStore::new();
202        let user_id = seed_user(&store, "alice").await;
203        let api_key_id = seed_api_key(&store, user_id, "ci-deploy").await;
204        let run = run_with(
205            &store,
206            TriggerKind::Api,
207            Some(RunActor::ApiKey {
208                api_key_id,
209                user_id,
210            }),
211        )
212        .await;
213
214        let created_by = CreatedBy::from(&run);
215        assert_eq!(created_by.kind, CreatedByKind::ApiKey);
216        assert_eq!(created_by.id, Some(api_key_id));
217        assert_eq!(created_by.label, "ci-deploy (alice)");
218    }
219
220    #[tokio::test]
221    async fn api_key_actor_falls_back_to_a_short_id() {
222        let store = InMemoryStore::new();
223        let api_key_id = Uuid::now_v7();
224        let run = run_with(
225            &store,
226            TriggerKind::Api,
227            Some(RunActor::ApiKey {
228                api_key_id,
229                user_id: Uuid::now_v7(),
230            }),
231        )
232        .await;
233
234        let created_by = CreatedBy::from(&run);
235        assert_eq!(created_by.kind, CreatedByKind::ApiKey);
236        assert_eq!(created_by.label, format!("key {}", short_id(api_key_id)));
237    }
238
239    #[tokio::test]
240    async fn system_label_is_derived_from_every_trigger() {
241        let store = InMemoryStore::new();
242        let cases = [
243            (TriggerKind::Manual, "manual"),
244            (TriggerKind::Api, "api"),
245            (TriggerKind::Workflow, "workflow"),
246            (
247                TriggerKind::Retry {
248                    parent_run_id: Uuid::now_v7(),
249                },
250                "retry",
251            ),
252            (
253                TriggerKind::Replay {
254                    original_run_id: Uuid::now_v7(),
255                },
256                "replay",
257            ),
258            (
259                TriggerKind::Webhook {
260                    path: "/hooks/github".to_string(),
261                },
262                "/hooks/github",
263            ),
264            (
265                TriggerKind::Cron {
266                    schedule: "0 */5 * * * *".to_string(),
267                },
268                "0 */5 * * * *",
269            ),
270            (
271                TriggerKind::Nats {
272                    subject: "orders.created".to_string(),
273                },
274                "nats:orders.created",
275            ),
276            (
277                TriggerKind::RunEvent {
278                    source_run_id: Uuid::now_v7(),
279                    event_kind: "completed".to_string(),
280                },
281                "event:completed",
282            ),
283            (
284                TriggerKind::Polling {
285                    probe: "http".to_string(),
286                },
287                "polling:http",
288            ),
289        ];
290
291        for (trigger, expected) in cases {
292            let run = run_with(&store, trigger, None).await;
293            let created_by = CreatedBy::from(&run);
294
295            assert_eq!(created_by.kind, CreatedByKind::System);
296            assert_eq!(created_by.id, None);
297            assert_eq!(created_by.label, expected);
298        }
299    }
300
301    #[tokio::test]
302    async fn a_pre_migration_run_reports_a_system_author() {
303        let store = InMemoryStore::new();
304        // A run predating authorship tracking has both columns NULL.
305        let run = run_with(&store, TriggerKind::Manual, None).await;
306
307        let created_by = CreatedBy::from(&run);
308        assert_eq!(created_by.kind, CreatedByKind::System);
309        assert_eq!(created_by.id, None);
310        assert_eq!(created_by.label, "manual");
311    }
312
313    #[tokio::test]
314    async fn label_is_never_empty() {
315        let store = InMemoryStore::new();
316        let run = run_with(
317            &store,
318            TriggerKind::Webhook {
319                path: "/h".to_string(),
320            },
321            None,
322        )
323        .await;
324
325        assert!(!CreatedBy::from(&run).label.is_empty());
326    }
327
328    #[test]
329    fn short_id_keeps_eight_characters() {
330        let id = Uuid::now_v7();
331        assert_eq!(short_id(id).len(), ID_PREFIX_LEN);
332        assert!(id.to_string().starts_with(&short_id(id)));
333    }
334
335    #[test]
336    fn serde_uses_snake_case_kinds() {
337        let created_by = CreatedBy {
338            kind: CreatedByKind::ApiKey,
339            id: Some(Uuid::now_v7()),
340            label: "ci (alice)".to_string(),
341        };
342
343        let json = serde_json::to_value(&created_by).expect("serialize");
344        assert_eq!(json["kind"], "api_key");
345
346        let back: CreatedBy = serde_json::from_value(json).expect("deserialize");
347        assert_eq!(back, created_by);
348    }
349}