edda-core 0.2.1

Core event model, hash chain, and schema for Edda
Documentation
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Governance policy types and RBAC evaluation.
//!
//! Shared between `edda-cli` (draft approval workflow) and `edda-serve` (authz API).

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;

// ── Policy v2 data model ──

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PolicyV2Config {
    pub version: u32,
    #[serde(default)]
    pub roles: Vec<String>,
    #[serde(default)]
    pub rules: Vec<PolicyRule>,
    /// RBAC permissions (optional, additive to v2 schema).
    #[serde(default)]
    pub permissions: Option<PermissionsConfig>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PolicyRule {
    pub id: String,
    #[serde(default)]
    pub when: PolicyWhen,
    #[serde(default)]
    pub stages: Vec<PolicyStageDef>,
}

#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct PolicyWhen {
    #[serde(default)]
    pub default: Option<bool>,
    #[serde(default)]
    pub labels_any: Option<Vec<String>>,
    #[serde(default)]
    pub failed_cmd: Option<bool>,
    #[serde(default)]
    pub evidence_count_gte: Option<usize>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PolicyStageDef {
    pub stage_id: String,
    pub role: String,
    #[serde(default = "default_one")]
    pub min_approvals: usize,
    #[serde(default = "default_two")]
    pub max_assignees: usize,
}

fn default_one() -> usize {
    1
}
fn default_two() -> usize {
    2
}

// ── Actors config ──

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ActorsConfig {
    pub version: u32,
    #[serde(default)]
    pub actors: BTreeMap<String, ActorDef>,
}

/// Actor kind: distinguishes human users from automated agents.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum ActorKind {
    #[default]
    User,
    Agent,
}

impl std::fmt::Display for ActorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ActorKind::User => write!(f, "user"),
            ActorKind::Agent => write!(f, "agent"),
        }
    }
}

impl std::str::FromStr for ActorKind {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "user" => Ok(ActorKind::User),
            "agent" => Ok(ActorKind::Agent),
            other => anyhow::bail!("Actor kind must be 'user' or 'agent', got: {other}"),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ActorDef {
    #[serde(default)]
    pub roles: Vec<String>,
    /// Actor kind: "user" or "agent". Defaults to User for v1 compat.
    #[serde(default)]
    pub kind: ActorKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    /// For agent actors: runtime platform (e.g. "claude", "opencode").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime: Option<String>,
}

impl Default for ActorsConfig {
    fn default() -> Self {
        Self {
            version: 1,
            actors: BTreeMap::new(),
        }
    }
}

// ── RBAC Permissions ──

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionsConfig {
    /// "deny" or "allow" — what happens when no grant matches.
    #[serde(default = "default_deny")]
    pub default: String,
    #[serde(default)]
    pub grants: Vec<PermissionGrant>,
}

fn default_deny() -> String {
    "deny".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionGrant {
    pub actions: Vec<String>,
    pub roles: Vec<String>,
}

// ── Authz request / result ──

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthzRequest {
    pub actor: String,
    pub action: String,
    #[serde(default)]
    pub resource: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthzResult {
    pub allowed: bool,
    pub actor_roles: Vec<String>,
    pub matched_grant: Option<PermissionGrant>,
    pub policy_default: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

// ── Evaluation ──

/// Evaluate whether an actor is allowed to perform an action.
///
/// Logic:
/// 1. Look up actor's roles from `actors`.
/// 2. Find a matching grant in `policy.permissions.grants` where the action
///    matches AND at least one of the actor's roles (or `"*"`) is listed.
/// 3. If no grant matches, fall back to `permissions.default`.
pub fn evaluate_authz(
    req: &AuthzRequest,
    policy: &PolicyV2Config,
    actors: &ActorsConfig,
) -> AuthzResult {
    let actor_roles: Vec<String> = actors
        .actors
        .get(&req.actor)
        .map(|a| a.roles.clone())
        .unwrap_or_default();

    let permissions = match &policy.permissions {
        Some(p) => p,
        None => {
            // No permissions section → use default deny
            return AuthzResult {
                allowed: false,
                actor_roles,
                matched_grant: None,
                policy_default: "deny".to_string(),
                reason: Some("no permissions section in policy".to_string()),
            };
        }
    };

    let policy_default = &permissions.default;

    // Search for a matching grant
    for grant in &permissions.grants {
        if !grant.actions.contains(&req.action) {
            continue;
        }
        // Check if any of actor's roles match the grant's roles
        let role_match = grant
            .roles
            .iter()
            .any(|r| r == "*" || actor_roles.iter().any(|ar| ar == r));
        if role_match {
            return AuthzResult {
                allowed: true,
                actor_roles,
                matched_grant: Some(grant.clone()),
                policy_default: policy_default.clone(),
                reason: None,
            };
        }
    }

    // No grant matched — apply default
    let allowed = policy_default == "allow";
    let reason = if allowed {
        None
    } else {
        Some(format!(
            "no grant matches action '{}' for roles {:?}",
            req.action, actor_roles
        ))
    };

    AuthzResult {
        allowed,
        actor_roles,
        matched_grant: None,
        policy_default: policy_default.clone(),
        reason,
    }
}

// ── File loading helpers ──

/// Load policy.yaml from a directory containing `.edda/`.
pub fn load_policy_from_dir(edda_dir: &Path) -> anyhow::Result<PolicyV2Config> {
    let path = edda_dir.join("policy.yaml");
    if !path.exists() {
        return Ok(PolicyV2Config {
            version: 2,
            roles: vec![],
            rules: vec![PolicyRule {
                id: "default".to_string(),
                when: PolicyWhen {
                    default: Some(true),
                    ..Default::default()
                },
                stages: vec![],
            }],
            permissions: None,
        });
    }
    let content = std::fs::read(&path)?;
    let v2: PolicyV2Config = serde_yaml::from_slice(&content)?;
    Ok(v2)
}

/// Load actors.yaml from a directory containing `.edda/`.
pub fn load_actors_from_dir(edda_dir: &Path) -> anyhow::Result<ActorsConfig> {
    let path = edda_dir.join("actors.yaml");
    if !path.exists() {
        return Ok(ActorsConfig::default());
    }
    let content = std::fs::read(&path)?;
    let cfg: ActorsConfig = serde_yaml::from_slice(&content)?;
    Ok(cfg)
}

/// Save actors.yaml to the `.edda/` directory.
pub fn save_actors_to_dir(edda_dir: &Path, cfg: &ActorsConfig) -> anyhow::Result<()> {
    let path = edda_dir.join("actors.yaml");
    let yaml = serde_yaml::to_string(cfg)?;
    std::fs::write(&path, yaml.as_bytes())?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_policy(default: &str) -> PolicyV2Config {
        PolicyV2Config {
            version: 2,
            roles: vec!["lead".into(), "reviewer".into(), "operator".into()],
            rules: vec![],
            permissions: Some(PermissionsConfig {
                default: default.to_string(),
                grants: vec![
                    PermissionGrant {
                        actions: vec!["deploy".into(), "rollback".into()],
                        roles: vec!["lead".into(), "operator".into()],
                    },
                    PermissionGrant {
                        actions: vec!["merge".into(), "approve".into()],
                        roles: vec!["lead".into(), "reviewer".into()],
                    },
                    PermissionGrant {
                        actions: vec!["read".into()],
                        roles: vec!["*".into()],
                    },
                ],
            }),
        }
    }

    fn actors_with(name: &str, roles: &[&str]) -> ActorsConfig {
        let mut actors = BTreeMap::new();
        actors.insert(
            name.to_string(),
            ActorDef {
                roles: roles.iter().map(|s| s.to_string()).collect(),
                kind: ActorKind::User,
                email: None,
                display_name: None,
                runtime: None,
            },
        );
        ActorsConfig { version: 1, actors }
    }

    #[test]
    fn test_evaluate_authz_allow() {
        let policy = sample_policy("deny");
        let actors = actors_with("alice", &["operator"]);
        let req = AuthzRequest {
            actor: "alice".into(),
            action: "deploy".into(),
            resource: None,
        };
        let result = evaluate_authz(&req, &policy, &actors);
        assert!(result.allowed);
        assert!(result.matched_grant.is_some());
        assert_eq!(result.actor_roles, vec!["operator"]);
    }

    #[test]
    fn test_evaluate_authz_deny_no_role() {
        let policy = sample_policy("deny");
        let actors = actors_with("bob", &["reviewer"]);
        let req = AuthzRequest {
            actor: "bob".into(),
            action: "deploy".into(),
            resource: None,
        };
        let result = evaluate_authz(&req, &policy, &actors);
        assert!(!result.allowed);
        assert!(result.matched_grant.is_none());
        assert!(result.reason.is_some());
    }

    #[test]
    fn test_evaluate_authz_default_deny() {
        let policy = sample_policy("deny");
        let actors = actors_with("alice", &["operator"]);
        let req = AuthzRequest {
            actor: "alice".into(),
            action: "unknown_action".into(),
            resource: None,
        };
        let result = evaluate_authz(&req, &policy, &actors);
        assert!(!result.allowed);
        assert_eq!(result.policy_default, "deny");
    }

    #[test]
    fn test_evaluate_authz_default_allow() {
        let policy = sample_policy("allow");
        let actors = actors_with("alice", &["operator"]);
        let req = AuthzRequest {
            actor: "alice".into(),
            action: "unknown_action".into(),
            resource: None,
        };
        let result = evaluate_authz(&req, &policy, &actors);
        assert!(result.allowed);
        assert_eq!(result.policy_default, "allow");
    }

    #[test]
    fn test_evaluate_authz_wildcard_role() {
        let policy = sample_policy("deny");
        let actors = actors_with("charlie", &["intern"]);
        let req = AuthzRequest {
            actor: "charlie".into(),
            action: "read".into(),
            resource: None,
        };
        let result = evaluate_authz(&req, &policy, &actors);
        assert!(result.allowed, "wildcard '*' should match any role");
    }

    #[test]
    fn test_evaluate_authz_unknown_actor() {
        let policy = sample_policy("deny");
        let actors = ActorsConfig::default();
        let req = AuthzRequest {
            actor: "nobody".into(),
            action: "deploy".into(),
            resource: None,
        };
        let result = evaluate_authz(&req, &policy, &actors);
        assert!(!result.allowed);
        assert!(result.actor_roles.is_empty());
    }

    #[test]
    fn test_evaluate_authz_unknown_actor_wildcard_grant() {
        let policy = sample_policy("deny");
        // Actor not in actors.yaml but action has wildcard role
        let actors = ActorsConfig::default();
        let req = AuthzRequest {
            actor: "nobody".into(),
            action: "read".into(),
            resource: None,
        };
        let result = evaluate_authz(&req, &policy, &actors);
        // Wildcard matches even with empty roles
        assert!(result.allowed);
    }

    #[test]
    fn test_policy_v2_backward_compat() {
        let yaml = r#"
version: 2
roles:
  - lead
rules:
  - id: default
    when:
      default: true
    stages: []
"#;
        let config: PolicyV2Config = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.version, 2);
        assert!(config.permissions.is_none());
    }

    #[test]
    fn test_policy_v2_with_permissions() {
        let yaml = r#"
version: 2
roles:
  - lead
  - operator
rules: []
permissions:
  default: deny
  grants:
    - actions: [deploy]
      roles: [lead, operator]
    - actions: [read]
      roles: ["*"]
"#;
        let config: PolicyV2Config = serde_yaml::from_str(yaml).unwrap();
        assert!(config.permissions.is_some());
        let perms = config.permissions.unwrap();
        assert_eq!(perms.default, "deny");
        assert_eq!(perms.grants.len(), 2);
        assert_eq!(perms.grants[0].actions, vec!["deploy"]);
    }

    #[test]
    fn test_actors_v1_backward_compat() {
        let yaml = r#"
version: 1
actors:
  alice:
    roles: [lead, reviewer]
"#;
        let cfg: ActorsConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(cfg.version, 1);
        let alice = cfg.actors.get("alice").unwrap();
        assert_eq!(alice.roles, vec!["lead", "reviewer"]);
        assert_eq!(alice.kind, ActorKind::User); // default
        assert!(alice.email.is_none());
        assert!(alice.display_name.is_none());
        assert!(alice.runtime.is_none());
    }

    #[test]
    fn test_actors_v2_full_fields() {
        let yaml = r#"
version: 2
actors:
  alice:
    kind: user
    roles: [lead, reviewer]
    email: alice@example.com
    display_name: Alice Chen
  claude-agent-1:
    kind: agent
    roles: [operator]
    runtime: claude
"#;
        let cfg: ActorsConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(cfg.version, 2);

        let alice = cfg.actors.get("alice").unwrap();
        assert_eq!(alice.kind, ActorKind::User);
        assert_eq!(alice.email.as_deref(), Some("alice@example.com"));
        assert_eq!(alice.display_name.as_deref(), Some("Alice Chen"));
        assert!(alice.runtime.is_none());

        let agent = cfg.actors.get("claude-agent-1").unwrap();
        assert_eq!(agent.kind, ActorKind::Agent);
        assert_eq!(agent.roles, vec!["operator"]);
        assert_eq!(agent.runtime.as_deref(), Some("claude"));
        assert!(agent.email.is_none());
    }

    #[test]
    fn test_no_permissions_section_defaults_deny() {
        let policy = PolicyV2Config {
            version: 2,
            roles: vec![],
            rules: vec![],
            permissions: None,
        };
        let actors = actors_with("alice", &["lead"]);
        let req = AuthzRequest {
            actor: "alice".into(),
            action: "deploy".into(),
            resource: None,
        };
        let result = evaluate_authz(&req, &policy, &actors);
        assert!(!result.allowed);
        assert!(result
            .reason
            .as_ref()
            .unwrap()
            .contains("no permissions section"));
    }
}