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                concurrency_key: None,
140                concurrency_limits: Vec::new(),
141                max_cost_usd: None,
142                worker_tags: Vec::new(),
143            })
144            .await
145            .expect("create run")
146            .into_run()
147    }
148
149    async fn seed_user(store: &InMemoryStore, username: &str) -> Uuid {
150        store
151            .create_user(NewUser {
152                email: format!("{username}@example.com"),
153                username: username.to_string(),
154                password_hash: "hash".to_string(),
155                is_admin: Some(false),
156            })
157            .await
158            .expect("create user")
159            .id
160    }
161
162    async fn seed_api_key(store: &InMemoryStore, user_id: Uuid, name: &str) -> Uuid {
163        store
164            .create_api_key(NewApiKey {
165                user_id,
166                name: name.to_string(),
167                key_hash: "hash".to_string(),
168                key_prefix: "irfl_0000".to_string(),
169                scopes: vec![ApiKeyScope::RunsWrite],
170                expires_at: None,
171                rate_limit_override: None,
172            })
173            .await
174            .expect("create api key")
175            .id
176    }
177
178    #[tokio::test]
179    async fn user_actor_uses_the_resolved_username() {
180        let store = InMemoryStore::new();
181        let user_id = seed_user(&store, "alice").await;
182        let run = run_with(&store, TriggerKind::Api, Some(RunActor::User { user_id })).await;
183
184        let created_by = CreatedBy::from(&run);
185        assert_eq!(created_by.kind, CreatedByKind::User);
186        assert_eq!(created_by.id, Some(user_id));
187        assert_eq!(created_by.label, "alice");
188    }
189
190    #[tokio::test]
191    async fn user_actor_falls_back_to_a_short_id() {
192        let store = InMemoryStore::new();
193        let user_id = Uuid::now_v7();
194        let run = run_with(&store, TriggerKind::Api, Some(RunActor::User { user_id })).await;
195
196        let created_by = CreatedBy::from(&run);
197        assert_eq!(created_by.kind, CreatedByKind::User);
198        assert_eq!(created_by.id, Some(user_id));
199        assert_eq!(created_by.label, format!("user {}", short_id(user_id)));
200    }
201
202    #[tokio::test]
203    async fn api_key_actor_exposes_the_key_id_and_a_combined_label() {
204        let store = InMemoryStore::new();
205        let user_id = seed_user(&store, "alice").await;
206        let api_key_id = seed_api_key(&store, user_id, "ci-deploy").await;
207        let run = run_with(
208            &store,
209            TriggerKind::Api,
210            Some(RunActor::ApiKey {
211                api_key_id,
212                user_id,
213            }),
214        )
215        .await;
216
217        let created_by = CreatedBy::from(&run);
218        assert_eq!(created_by.kind, CreatedByKind::ApiKey);
219        assert_eq!(created_by.id, Some(api_key_id));
220        assert_eq!(created_by.label, "ci-deploy (alice)");
221    }
222
223    #[tokio::test]
224    async fn api_key_actor_falls_back_to_a_short_id() {
225        let store = InMemoryStore::new();
226        let api_key_id = Uuid::now_v7();
227        let run = run_with(
228            &store,
229            TriggerKind::Api,
230            Some(RunActor::ApiKey {
231                api_key_id,
232                user_id: Uuid::now_v7(),
233            }),
234        )
235        .await;
236
237        let created_by = CreatedBy::from(&run);
238        assert_eq!(created_by.kind, CreatedByKind::ApiKey);
239        assert_eq!(created_by.label, format!("key {}", short_id(api_key_id)));
240    }
241
242    #[tokio::test]
243    async fn system_label_is_derived_from_every_trigger() {
244        let store = InMemoryStore::new();
245        let cases = [
246            (TriggerKind::Manual, "manual"),
247            (TriggerKind::Api, "api"),
248            (TriggerKind::Workflow, "workflow"),
249            (
250                TriggerKind::Retry {
251                    parent_run_id: Uuid::now_v7(),
252                },
253                "retry",
254            ),
255            (
256                TriggerKind::Replay {
257                    original_run_id: Uuid::now_v7(),
258                },
259                "replay",
260            ),
261            (
262                TriggerKind::Webhook {
263                    path: "/hooks/github".to_string(),
264                },
265                "/hooks/github",
266            ),
267            (
268                TriggerKind::Cron {
269                    schedule: "0 */5 * * * *".to_string(),
270                },
271                "0 */5 * * * *",
272            ),
273            (
274                TriggerKind::Nats {
275                    subject: "orders.created".to_string(),
276                },
277                "nats:orders.created",
278            ),
279            (
280                TriggerKind::RunEvent {
281                    source_run_id: Uuid::now_v7(),
282                    event_kind: "completed".to_string(),
283                },
284                "event:completed",
285            ),
286            (
287                TriggerKind::Polling {
288                    probe: "http".to_string(),
289                },
290                "polling:http",
291            ),
292        ];
293
294        for (trigger, expected) in cases {
295            let run = run_with(&store, trigger, None).await;
296            let created_by = CreatedBy::from(&run);
297
298            assert_eq!(created_by.kind, CreatedByKind::System);
299            assert_eq!(created_by.id, None);
300            assert_eq!(created_by.label, expected);
301        }
302    }
303
304    #[tokio::test]
305    async fn a_pre_migration_run_reports_a_system_author() {
306        let store = InMemoryStore::new();
307        // A run predating authorship tracking has both columns NULL.
308        let run = run_with(&store, TriggerKind::Manual, None).await;
309
310        let created_by = CreatedBy::from(&run);
311        assert_eq!(created_by.kind, CreatedByKind::System);
312        assert_eq!(created_by.id, None);
313        assert_eq!(created_by.label, "manual");
314    }
315
316    #[tokio::test]
317    async fn label_is_never_empty() {
318        let store = InMemoryStore::new();
319        let run = run_with(
320            &store,
321            TriggerKind::Webhook {
322                path: "/h".to_string(),
323            },
324            None,
325        )
326        .await;
327
328        assert!(!CreatedBy::from(&run).label.is_empty());
329    }
330
331    #[test]
332    fn short_id_keeps_eight_characters() {
333        let id = Uuid::now_v7();
334        assert_eq!(short_id(id).len(), ID_PREFIX_LEN);
335        assert!(id.to_string().starts_with(&short_id(id)));
336    }
337
338    #[test]
339    fn serde_uses_snake_case_kinds() {
340        let created_by = CreatedBy {
341            kind: CreatedByKind::ApiKey,
342            id: Some(Uuid::now_v7()),
343            label: "ci (alice)".to_string(),
344        };
345
346        let json = serde_json::to_value(&created_by).expect("serialize");
347        assert_eq!(json["kind"], "api_key");
348
349        let back: CreatedBy = serde_json::from_value(json).expect("deserialize");
350        assert_eq!(back, created_by);
351    }
352}