blindplane-access 0.1.0

Signed enterprise access grants, capability policies, revocation and encrypted audit events for Blindplane
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
//! Signed tenant capability policies.

use blindplane_crypto::Sha256;

use crate::AccessError;
use crate::codec::{AccessValidationPolicy, Cursor, push_header, push_string, validate_identifier};
use crate::principal::TrustedIssuer;
#[cfg(feature = "client")]
use crate::principal::{AccessIssuer, Principal};
#[cfg(feature = "client")]
use crate::signed::sign;
use crate::signed::verify;

const POLICY_TAG: u8 = 2;
const POLICY_SIGNATURE_DOMAIN: &[u8] = b"blindplane/access/policy/v1";

/// Capability namespace interpreted by an embedding adapter.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum CapabilityKind {
    /// A complete MCP server name.
    Mcp,
    /// An exact tool name.
    Tool,
    /// An exact skill name.
    Skill,
    /// The local command-line capability.
    Cli,
}

impl CapabilityKind {
    const fn code(self) -> u8 {
        match self {
            Self::Mcp => 1,
            Self::Tool => 2,
            Self::Skill => 3,
            Self::Cli => 4,
        }
    }

    fn from_code(code: u8) -> Result<Self, AccessError> {
        match code {
            1 => Ok(Self::Mcp),
            2 => Ok(Self::Tool),
            3 => Ok(Self::Skill),
            4 => Ok(Self::Cli),
            _ => Err(AccessError::WrongObjectType),
        }
    }
}

/// Signed rule effect.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum Effect {
    /// Permit the exact capability.
    Allow,
    /// Refuse the exact capability.
    Deny,
}

impl Effect {
    const fn code(self) -> u8 {
        match self {
            Self::Allow => 1,
            Self::Deny => 2,
        }
    }

    fn from_code(code: u8) -> Result<Self, AccessError> {
        match code {
            1 => Ok(Self::Allow),
            2 => Ok(Self::Deny),
            _ => Err(AccessError::WrongObjectType),
        }
    }
}

/// Result of evaluating a verified capability policy.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Decision {
    /// The policy permits the capability.
    Allow,
    /// The policy refuses the capability.
    Deny,
}

/// One exact capability rule.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CapabilityRule {
    kind: CapabilityKind,
    name: String,
    effect: Effect,
}

impl CapabilityRule {
    /// Construct a bounded exact-name rule.
    pub fn new(
        kind: CapabilityKind,
        name: impl Into<String>,
        effect: Effect,
    ) -> Result<Self, AccessError> {
        let name = name.into();
        validate_identifier(
            &name,
            AccessValidationPolicy::default().max_identifier_bytes,
        )?;
        Ok(Self { kind, name, effect })
    }

    /// Rule namespace.
    pub const fn kind(&self) -> CapabilityKind {
        self.kind
    }

    /// Exact case-sensitive capability name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Rule effect.
    pub const fn effect(&self) -> Effect {
        self.effect
    }
}

/// Inputs signed into one tenant policy.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PolicySpec {
    /// Monotonic subject-policy revision.
    pub revision: u64,
    /// Hash of the preceding policy, or zero for revision one.
    pub previous_hash: [u8; 32],
    /// Current authorization epoch.
    pub authorization_epoch: u64,
    /// Issuance time in Unix seconds.
    pub issued_at: u64,
    /// First valid Unix second.
    pub not_before: u64,
    /// Last valid Unix second.
    pub not_after: u64,
    /// Exact capability rules.
    pub rules: Vec<CapabilityRule>,
}

/// Canonical administrator-signed capability policy for one subject.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TenantPolicy {
    tenant_id: String,
    subject_id: String,
    subject_key_id: [u8; 32],
    revision: u64,
    previous_hash: [u8; 32],
    authorization_epoch: u64,
    issued_at: u64,
    not_before: u64,
    not_after: u64,
    default_effect: Effect,
    rules: Vec<CapabilityRule>,
    issuer_id: String,
    issuer_key_id: [u8; 32],
    issuer_public_key: [u8; 32],
    signature: [u8; 64],
}

impl TenantPolicy {
    /// Issue and sign a canonical default-deny policy.
    #[cfg(feature = "client")]
    pub fn issue(
        issuer: &AccessIssuer,
        subject: &Principal,
        mut spec: PolicySpec,
    ) -> Result<Self, AccessError> {
        spec.rules.sort_by(|left, right| {
            (left.kind, left.name.as_str(), left.effect).cmp(&(
                right.kind,
                right.name.as_str(),
                right.effect,
            ))
        });
        let mut policy = Self {
            tenant_id: subject.tenant_id().to_owned(),
            subject_id: subject.principal_id().to_owned(),
            subject_key_id: subject.key_id(),
            revision: spec.revision,
            previous_hash: spec.previous_hash,
            authorization_epoch: spec.authorization_epoch,
            issued_at: spec.issued_at,
            not_before: spec.not_before,
            not_after: spec.not_after,
            default_effect: Effect::Deny,
            rules: spec.rules,
            issuer_id: issuer.issuer_id().to_owned(),
            issuer_key_id: issuer.key_id(),
            issuer_public_key: issuer.public_key(),
            signature: [0; 64],
        };
        policy.validate_structure(&AccessValidationPolicy::default())?;
        policy.signature = sign(
            POLICY_SIGNATURE_DOMAIN,
            issuer.signing_key(),
            &policy.unsigned_bytes(),
        );
        Ok(policy)
    }

    /// Tenant identifier authenticated by the signature.
    pub fn tenant_id(&self) -> &str {
        &self.tenant_id
    }

    /// Subject identifier authenticated by the signature.
    pub fn subject_id(&self) -> &str {
        &self.subject_id
    }

    /// Monotonic policy revision.
    pub const fn revision(&self) -> u64 {
        self.revision
    }

    /// Authorization epoch carried by this policy.
    pub const fn authorization_epoch(&self) -> u64 {
        self.authorization_epoch
    }

    /// Canonical encoded and signed policy.
    pub fn encode(&self) -> Vec<u8> {
        let mut out = self.unsigned_bytes();
        out.extend_from_slice(&self.signature);
        out
    }

    /// Domain-separated hash used to link policy revisions.
    pub fn policy_hash(&self) -> [u8; 32] {
        let encoded = self.encode();
        let mut input = Vec::with_capacity(POLICY_SIGNATURE_DOMAIN.len() + encoded.len());
        input.extend_from_slice(POLICY_SIGNATURE_DOMAIN);
        input.extend_from_slice(&encoded);
        Sha256::digest(&input)
    }

    /// Decode, structurally validate, and verify signature math.
    pub fn decode(bytes: &[u8], limits: &AccessValidationPolicy) -> Result<Self, AccessError> {
        let mut cursor = Cursor::new(bytes);
        cursor.take_header(POLICY_TAG)?;
        let tenant_id = cursor.take_string(limits.max_identifier_bytes)?;
        let subject_id = cursor.take_string(limits.max_identifier_bytes)?;
        let subject_key_id = cursor.take_array32()?;
        let revision = cursor.take_u64()?;
        let previous_hash = cursor.take_array32()?;
        let authorization_epoch = cursor.take_u64()?;
        let issued_at = cursor.take_u64()?;
        let not_before = cursor.take_u64()?;
        let not_after = cursor.take_u64()?;
        let default_effect = Effect::from_code(cursor.take_u8()?)?;
        let rule_count = cursor.take_len(limits.max_rules)?;
        let mut rules = Vec::with_capacity(rule_count);
        for _ in 0..rule_count {
            rules.push(CapabilityRule {
                kind: CapabilityKind::from_code(cursor.take_u8()?)?,
                name: cursor.take_string(limits.max_identifier_bytes)?,
                effect: Effect::from_code(cursor.take_u8()?)?,
            });
        }
        let issuer_id = cursor.take_string(limits.max_identifier_bytes)?;
        let issuer_key_id = cursor.take_array32()?;
        let issuer_public_key = cursor.take_array32()?;
        let signature = cursor.take_array64()?;
        if !cursor.is_empty() {
            return Err(AccessError::TrailingBytes);
        }
        let policy = Self {
            tenant_id,
            subject_id,
            subject_key_id,
            revision,
            previous_hash,
            authorization_epoch,
            issued_at,
            not_before,
            not_after,
            default_effect,
            rules,
            issuer_id,
            issuer_key_id,
            issuer_public_key,
            signature,
        };
        policy.validate_structure(limits)?;
        verify(
            POLICY_SIGNATURE_DOMAIN,
            &policy.issuer_public_key,
            &policy.unsigned_bytes(),
            &policy.signature,
        )?;
        if policy.encode() != bytes {
            return Err(AccessError::NonCanonicalEncoding);
        }
        Ok(policy)
    }

    /// Verify trust, routing, freshness, and time before policy evaluation.
    pub fn verify<'a>(
        &'a self,
        trusted: &TrustedIssuer,
        expected_tenant: &str,
        expected_subject: &str,
        now: u64,
        minimum_revision: u64,
        minimum_authorization_epoch: u64,
    ) -> Result<VerifiedPolicy<'a>, AccessError> {
        verify(
            POLICY_SIGNATURE_DOMAIN,
            &self.issuer_public_key,
            &self.unsigned_bytes(),
            &self.signature,
        )?;
        if self.issuer_id != trusted.issuer_id()
            || self.issuer_key_id != trusted.key_id()
            || self.issuer_public_key != trusted.public_key()
        {
            return Err(AccessError::UntrustedIssuer);
        }
        if self.tenant_id != expected_tenant || self.subject_id != expected_subject {
            return Err(AccessError::SubjectMismatch);
        }
        if now < self.not_before {
            return Err(AccessError::NotYetValid);
        }
        if now > self.not_after {
            return Err(AccessError::Expired);
        }
        if self.revision < minimum_revision {
            return Err(AccessError::StaleRevision);
        }
        if self.authorization_epoch < minimum_authorization_epoch {
            return Err(AccessError::Revoked);
        }
        Ok(VerifiedPolicy { policy: self })
    }

    fn validate_structure(&self, limits: &AccessValidationPolicy) -> Result<(), AccessError> {
        validate_identifier(&self.tenant_id, limits.max_identifier_bytes)?;
        validate_identifier(&self.subject_id, limits.max_identifier_bytes)?;
        validate_identifier(&self.issuer_id, limits.max_identifier_bytes)?;
        if self.revision == 0
            || self.authorization_epoch == 0
            || self.not_before > self.not_after
            || self.issued_at > self.not_after
            || (self.revision == 1 && self.previous_hash != [0; 32])
            || (self.revision > 1 && self.previous_hash == [0; 32])
        {
            return Err(AccessError::InvalidEpoch);
        }
        if self.default_effect != Effect::Deny || self.rules.len() > limits.max_rules {
            return Err(AccessError::LengthLimit(self.rules.len()));
        }
        for rule in &self.rules {
            validate_identifier(&rule.name, limits.max_identifier_bytes)?;
        }
        for pair in self.rules.windows(2) {
            let left = (pair[0].kind, pair[0].name.as_str());
            let right = (pair[1].kind, pair[1].name.as_str());
            if left >= right {
                return Err(AccessError::DuplicateRule);
            }
        }
        Ok(())
    }

    fn unsigned_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(256 + self.rules.len() * 32);
        push_header(&mut out, POLICY_TAG);
        push_string(&mut out, &self.tenant_id);
        push_string(&mut out, &self.subject_id);
        out.extend_from_slice(&self.subject_key_id);
        out.extend_from_slice(&self.revision.to_be_bytes());
        out.extend_from_slice(&self.previous_hash);
        out.extend_from_slice(&self.authorization_epoch.to_be_bytes());
        out.extend_from_slice(&self.issued_at.to_be_bytes());
        out.extend_from_slice(&self.not_before.to_be_bytes());
        out.extend_from_slice(&self.not_after.to_be_bytes());
        out.push(self.default_effect.code());
        out.extend_from_slice(
            &u32::try_from(self.rules.len())
                .expect("policy rules are bounded")
                .to_be_bytes(),
        );
        for rule in &self.rules {
            out.push(rule.kind.code());
            push_string(&mut out, &rule.name);
            out.push(rule.effect.code());
        }
        push_string(&mut out, &self.issuer_id);
        out.extend_from_slice(&self.issuer_key_id);
        out.extend_from_slice(&self.issuer_public_key);
        out
    }
}

/// A policy that passed trust, routing, freshness, epoch, and time checks.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct VerifiedPolicy<'a> {
    policy: &'a TenantPolicy,
}

impl VerifiedPolicy<'_> {
    /// Evaluate one exact capability name. Version one is default-deny.
    pub fn decision(&self, kind: CapabilityKind, name: &str) -> Decision {
        self.policy
            .rules
            .iter()
            .find(|rule| rule.kind == kind && rule.name == name)
            .map_or(Decision::Deny, |rule| match rule.effect {
                Effect::Allow => Decision::Allow,
                Effect::Deny => Decision::Deny,
            })
    }
}